Skip to content

Instantly share code, notes, and snippets.

@DevloperHS
Created December 28, 2021 08:26
Show Gist options
  • Select an option

  • Save DevloperHS/21bded9837752b3fa2bed068940287b3 to your computer and use it in GitHub Desktop.

Select an option

Save DevloperHS/21bded9837752b3fa2bed068940287b3 to your computer and use it in GitHub Desktop.
import csv
import json
import logging
import multiprocessing
import os
import tarfile
from multiprocessing.pool import ThreadPool
from pathlib import Path
from typing import List
import sox
from sox import Transformer
import wget
from tqdm import tqdm
# few parameters
data_root = 'dataset'
manifest_dir = './'
num_workers = 1
sample_rate = 16000
files_to_process = ['test.tsv', 'dev.tsv', 'train.tsv']
version = 'cv-corpus-6.1-2020-12-11'
language = 'hi'
COMMON_VOICE_URL = f"https://voice-prod-bundler-ee1969a6ce8178826482b88e843c335139bd3fb4.s3.amazonaws.com/" \
"{}/{}.tar.gz".format(version, language)
def create_manifest(data: List[tuple], output_name: str, manifest_path: str):
output_file = Path(manifest_path)/output_name
output_file.parent.mkdir(exist_ok=True, parents=True)
with output_file.open(mode='w') as f:
for wav_path,duration,text in tqdm(data,total=len(data)):
f.write(
json.dumps({
'audio_filepath': wav_path,
"duration": duration,
'text': text
}) + '\n'
)
def process_files(csv_file,data_root,num_workers):
wav_dir = os.path.join(data_root,'/wav')
os.makedirs(wav_dir, exist_ok=True)
audio_clips_path = os.path.dirname(csv_file) + '/clips/'
def process(x):
file_path, text = x
file_name = os.path.splitext(os.path.basename(file_path))[0]
text = text.lower().strip()
audio_path = os.path.join(audio_clips_path, file_path)
output_wav_path = os.path.join(wav_dir, file_name + '.wav')
tfm = Transformer()
tfm.rate(samplerate=sample_rate)
tfm.build(
input_filepath=audio_path,
output_filepath=output_wav_path
)
duration = sox.file_info.duration(output_wav_path)
return output_wav_path, duration, text
logging.info('Converting mp3 to wav for {}.'.format(csv_file))
with open(csv_file) as csvfile:
reader = csv.DictReader(csvfile, delimiter='\t')
next(reader, None) # skip the headers
data = [(row['path'], row['sentence']) for row in reader]
with ThreadPool(num_workers) as pool:
data = list(tqdm(pool.imap(process, data), total=len(data)))
return data
def main():
dr = data_root
os.makedirs(dr, exist_ok=True)
target_unpacked_dir = os.path.join(dr, "CV_unpacked")
if os.path.exists(target_unpacked_dir):
logging.info('Find existing folder {}'.format(target_unpacked_dir))
else:
logging.info("Could not find Common Voice, Downloading corpus...")
filename = wget.download(COMMON_VOICE_URL, dr)
target_file = os.path.join(dr, os.path.basename(filename))
os.makedirs(target_unpacked_dir, exist_ok=True)
logging.info("Unpacking corpus to {} ...".format(target_unpacked_dir))
tar = tarfile.open(target_file)
tar.extractall(target_unpacked_dir)
tar.close()
folder_path = os.path.join(target_unpacked_dir, version + f'/{language}/')
for csv_file in files_to_process:
data = process_files(
csv_file=os.path.join(folder_path, csv_file),
data_root=os.path.join(dr, os.path.splitext(csv_file)[0]),
num_workers=num_workers
)
logging.info('Creating manifests...')
create_manifest(
data=data,
output_name=f'commonvoice_{os.path.splitext(csv_file)[0]}_manifest.json',
manifest_path=manifest_dir,
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment