shrutilipi / data /preprocess.py
amithm3's picture
Create preprocess.py
662ec82 verified
import csv
import os
import tarfile
from hashlib import sha1
def hexdigest(string):
return sha1(string.encode()).hexdigest()
def read_fairseq(root, subset):
with open(f"{root}/{subset}/train.tsv", 'r') as tsv, open(f"{root}/{subset}/train.wrd", 'r') as wrd:
audio = map(lambda x: x[0], csv.reader(tsv, delimiter='\t'))
transcriptions = map(lambda x: x.strip(), wrd.readlines())
metadata = [[path, hexdigest(transcription), transcription]
for path, transcription in zip(audio, transcriptions)]
return metadata[1:]
def shard_wav_files(file_paths, shard_size_limit, output_dir, arcnames=None):
shard_index = 1
current_shard_size = 0
current_tar = None
for i, file_path in enumerate(file_paths):
file_size = os.path.getsize(file_path)
if not current_tar or current_shard_size + file_size > shard_size_limit:
if current_tar: current_tar.close()
shard_name = f"shard_{shard_index}.tar"
shard_path = os.path.join(output_dir, shard_name)
current_tar = tarfile.open(shard_path, "w")
shard_index += 1
current_shard_size = 0
current_tar.add(file_path, arcname=arcnames[i] if arcnames else os.path.basename(file_path))
current_shard_size += file_size
if current_tar: current_tar.close()