File size: 1,365 Bytes
662ec82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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()