ashishkblink commited on
Commit
ac92a73
·
verified ·
1 Parent(s): 31d2662

Upload f5_tts/train/datasets/prepare_csv_wavs.py with huggingface_hub

Browse files
f5_tts/train/datasets/prepare_csv_wavs.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ sys.path.append(os.getcwd())
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import shutil
10
+ from importlib.resources import files
11
+ from pathlib import Path
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+
14
+ import torchaudio
15
+ from tqdm import tqdm
16
+ from datasets.arrow_writer import ArrowWriter
17
+
18
+ from f5_tts.model.utils import (
19
+ convert_char_to_pinyin,
20
+ )
21
+
22
+
23
+ # Increase the field size limit
24
+ csv.field_size_limit(sys.maxsize)
25
+
26
+ # PRETRAINED_VOCAB_PATH = files("f5_tts").joinpath("../../data/Emilia_ZH_EN_pinyin/vocab.txt")
27
+ PRETRAINED_VOCAB_PATH = Path("/home/tts/ttsteam/repos/F5-TTS/ckpts/vocab.txt")
28
+
29
+
30
+ def is_csv_wavs_format(input_dataset_dir):
31
+
32
+ # import pdb;pdb.set_trace()
33
+
34
+ fpath = Path(input_dataset_dir)
35
+ metadata = fpath / "metadata.csv"
36
+ wavs = fpath / "wavs"
37
+ return metadata.exists() and metadata.is_file() and wavs.exists() and wavs.is_dir()
38
+
39
+
40
+ def prepare_csv_wavs_dir(input_dir, num_threads=16): # Added num_threads parameter
41
+ print("Inside prepare csv wavs dir!")
42
+ # assert is_csv_wavs_format(input_dir), f"not csv_wavs format: {input_dir}"
43
+ input_dir = Path(input_dir)
44
+ metadata_path = input_dir / "metadata.csv"
45
+ audio_path_text_pairs = read_audio_text_pairs(metadata_path.as_posix())
46
+
47
+ sub_result, durations = [], []
48
+ vocab_set = set()
49
+ polyphone = True
50
+
51
+ def process_audio(audio_path_text):
52
+ audio_path, text = audio_path_text
53
+ if not Path(audio_path).exists():
54
+ print(f"audio {audio_path} not found, skipping")
55
+ return None
56
+ audio_duration = get_audio_duration(audio_path)
57
+ text = convert_char_to_pinyin([text], polyphone=polyphone)[0]
58
+ return {"audio_path": audio_path, "text": text, "duration": audio_duration}, audio_duration
59
+
60
+ with ThreadPoolExecutor(max_workers=num_threads) as executor: # Set max_workers
61
+ futures = {executor.submit(process_audio, pair): pair for pair in audio_path_text_pairs}
62
+
63
+ # Use tqdm to track progress
64
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Processing audio files"):
65
+ result = future.result()
66
+ if result is not None:
67
+ # print("result is: ", result)
68
+ sub_result.append(result[0])
69
+ durations.append(result[1])
70
+ vocab_set.update(list(result[0]['text']))
71
+
72
+ return sub_result, durations, vocab_set
73
+
74
+
75
+ def get_audio_duration(audio_path):
76
+ audio, sample_rate = torchaudio.load(audio_path)
77
+ return audio.shape[1] / sample_rate
78
+
79
+
80
+ def read_audio_text_pairs(csv_file_path):
81
+ audio_text_pairs = []
82
+
83
+ parent = Path(csv_file_path).parent
84
+ with open(csv_file_path, mode="r", newline="", encoding="utf-8-sig") as csvfile:
85
+ reader = csv.reader(csvfile, delimiter="|")
86
+ next(reader) # Skip the header row
87
+ for row in reader:
88
+ if len(row) >= 2:
89
+ audio_file = row[0].strip() # First column: audio file path
90
+ text = row[1].strip() # Second column: text
91
+ # audio_file_path = parent / audio_file
92
+ audio_file_path = audio_file
93
+ audio_text_pairs.append((Path(audio_file_path).as_posix(), text))
94
+
95
+ return audio_text_pairs
96
+
97
+
98
+ def save_prepped_dataset(out_dir, result, duration_list, text_vocab_set, is_finetune):
99
+ out_dir = Path(out_dir)
100
+ # save preprocessed dataset to disk
101
+ out_dir.mkdir(exist_ok=True, parents=True)
102
+ print(f"\nSaving to {out_dir} ...")
103
+
104
+ # dataset = Dataset.from_dict({"audio_path": audio_path_list, "text": text_list, "duration": duration_list}) # oom
105
+ # dataset.save_to_disk(f"{out_dir}/raw", max_shard_size="2GB")
106
+ raw_arrow_path = out_dir / "raw.arrow"
107
+ with ArrowWriter(path=raw_arrow_path.as_posix(), writer_batch_size=1) as writer:
108
+ for line in tqdm(result, desc="Writing to raw.arrow ..."):
109
+ writer.write(line)
110
+
111
+ # dup a json separately saving duration in case for DynamicBatchSampler ease
112
+ dur_json_path = out_dir / "duration.json"
113
+ with open(dur_json_path.as_posix(), "w", encoding="utf-8") as f:
114
+ json.dump({"duration": duration_list}, f, ensure_ascii=False)
115
+
116
+ # vocab map, i.e. tokenizer
117
+ # add alphabets and symbols (optional, if plan to ft on de/fr etc.)
118
+ # if tokenizer == "pinyin":
119
+ # text_vocab_set.update([chr(i) for i in range(32, 127)] + [chr(i) for i in range(192, 256)])
120
+ voca_out_path = out_dir / "vocab.txt"
121
+ with open(voca_out_path.as_posix(), "w") as f:
122
+ for vocab in sorted(text_vocab_set):
123
+ f.write(vocab + "\n")
124
+
125
+ voca_out_path = out_dir / "new_vocab.txt"
126
+ with open(voca_out_path.as_posix(), "w") as f:
127
+ for vocab in sorted(text_vocab_set):
128
+ f.write(vocab + "\n")
129
+
130
+ if is_finetune:
131
+ file_vocab_finetune = PRETRAINED_VOCAB_PATH.as_posix()
132
+ shutil.copy2(file_vocab_finetune, voca_out_path)
133
+ else:
134
+ with open(voca_out_path, "w") as f:
135
+ for vocab in sorted(text_vocab_set):
136
+ f.write(vocab + "\n")
137
+
138
+ dataset_name = out_dir.stem
139
+ print(f"\nFor {dataset_name}, sample count: {len(result)}")
140
+ print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
141
+ print(f"For {dataset_name}, total {sum(duration_list)/3600:.2f} hours")
142
+
143
+
144
+ def prepare_and_save_set(inp_dir, out_dir, is_finetune: bool = True):
145
+ if is_finetune:
146
+ print("Inside finetuning ...")
147
+ assert PRETRAINED_VOCAB_PATH.exists(), f"pretrained vocab.txt not found: {PRETRAINED_VOCAB_PATH}"
148
+ sub_result, durations, vocab_set = prepare_csv_wavs_dir(inp_dir)
149
+ save_prepped_dataset(out_dir, sub_result, durations, vocab_set, is_finetune)
150
+
151
+
152
+ def cli():
153
+ # finetune: python scripts/prepare_csv_wavs.py /path/to/input_dir /path/to/output_dir_pinyin
154
+ # pretrain: python scripts/prepare_csv_wavs.py /path/to/output_dir_pinyin --pretrain
155
+ parser = argparse.ArgumentParser(description="Prepare and save dataset.")
156
+ parser.add_argument("inp_dir", type=str, help="Input directory containing the data.")
157
+ parser.add_argument("out_dir", type=str, help="Output directory to save the prepared data.")
158
+ parser.add_argument("--pretrain", action="store_true", help="Enable for new pretrain, otherwise is a fine-tune")
159
+
160
+ args = parser.parse_args()
161
+
162
+ prepare_and_save_set(args.inp_dir, args.out_dir, is_finetune=not args.pretrain)
163
+
164
+
165
+ if __name__ == "__main__":
166
+ cli()