ashishkblink commited on
Commit
edf6dfe
·
verified ·
1 Parent(s): cdb9ab7

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

Browse files
f5_tts/train/datasets/prepare_csvs_wavs_v3.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = Path("/projects/data/ttsteam/repos/f5/data/in22_5k/vocab.txt")
27
+
28
+
29
+ def is_csv_wavs_format(input_dataset_dir):
30
+ fpath = Path(input_dataset_dir)
31
+ metadata = fpath / "metadata.csv"
32
+ wavs = fpath / "wavs"
33
+ return metadata.exists() and metadata.is_file() and wavs.exists() and wavs.is_dir()
34
+
35
+
36
+ def prepare_csv_wavs_dir(input_dir, num_threads=16): # Added num_threads parameter
37
+ print("Inside prepare csv wavs dir!")
38
+ input_dir = Path(input_dir)
39
+ metadata_path = input_dir / "metadata.csv"
40
+ audio_path_text_pairs = read_audio_text_pairs(metadata_path.as_posix())
41
+
42
+ sub_result, durations = [], []
43
+ vocab_set = set()
44
+ polyphone = True
45
+
46
+ def process_audio(audio_path_text):
47
+ audio_path, text = audio_path_text
48
+ if not Path(audio_path).exists():
49
+ print(f"audio {audio_path} not found, skipping")
50
+ return None
51
+ audio_duration = get_audio_duration(audio_path)
52
+ text = convert_char_to_pinyin([text], polyphone=polyphone)[0]
53
+ return {"audio_path": audio_path, "text": text, "duration": audio_duration}, audio_duration
54
+
55
+ with ThreadPoolExecutor(max_workers=num_threads) as executor: # Set max_workers
56
+ futures = {executor.submit(process_audio, pair): pair for pair in tqdm(audio_path_text_pairs, desc='submit')}
57
+
58
+ # Use tqdm to track progress
59
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Processing audio files"):
60
+ result = future.result()
61
+ if result is not None:
62
+ # print("result is: ", result)
63
+ aud_dur = result[1]
64
+ if aud_dur < 0.1 or aud_dur > 30:
65
+ continue
66
+ sub_result.append(result[0])
67
+ durations.append(result[1])
68
+ vocab_set.update(list(result[0]['text']))
69
+ else:
70
+ print("Result not found: ", futures[future])
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 tqdm(reader):
88
+ if len(row) == 2: # Only if len == 2, else skip the row as could be noisy. IN22 texts could use '|' as a delimiter
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
+ else:
95
+ print("skipped", row)
96
+ return audio_text_pairs
97
+
98
+
99
+ def save_prepped_dataset(out_dir, result, duration_list, text_vocab_set, is_finetune):
100
+ out_dir = Path(out_dir)
101
+ # save preprocessed dataset to disk
102
+ out_dir.mkdir(exist_ok=True, parents=True)
103
+ print(f"\nSaving to {out_dir} ...")
104
+
105
+ # dataset = Dataset.from_dict({"audio_path": audio_path_list, "text": text_list, "duration": duration_list}) # oom
106
+ # dataset.save_to_disk(f"{out_dir}/raw", max_shard_size="2GB")
107
+ raw_arrow_path = out_dir / "raw.arrow"
108
+ with ArrowWriter(path=raw_arrow_path.as_posix(), writer_batch_size=1) as writer:
109
+ for line in tqdm(result, desc="Writing to raw.arrow ..."):
110
+ writer.write(line)
111
+
112
+ # dup a json separately saving duration in case for DynamicBatchSampler ease
113
+ dur_json_path = out_dir / "duration.json"
114
+ with open(dur_json_path.as_posix(), "w", encoding="utf-8") as f:
115
+ json.dump({"duration": duration_list}, f, ensure_ascii=False)
116
+
117
+ # vocab map, i.e. tokenizer
118
+ # add alphabets and symbols (optional, if plan to ft on de/fr etc.)
119
+ # if tokenizer == "pinyin":
120
+ # text_vocab_set.update([chr(i) for i in range(32, 127)] + [chr(i) for i in range(192, 256)])
121
+ voca_out_path = out_dir / "new_vocab.txt"
122
+ with open(voca_out_path.as_posix(), "w") as f:
123
+ for vocab in sorted(text_vocab_set):
124
+ f.write(vocab + "\n")
125
+
126
+ # voca_out_path = out_dir / "new_vocab.txt"
127
+ # with open(voca_out_path.as_posix(), "w") as f:
128
+ # for vocab in sorted(text_vocab_set):
129
+ # f.write(vocab + "\n")
130
+
131
+ voca_out_path = out_dir / "vocab.txt"
132
+ if is_finetune:
133
+ file_vocab_finetune = PRETRAINED_VOCAB_PATH.as_posix()
134
+ shutil.copy2(file_vocab_finetune, voca_out_path)
135
+ else:
136
+ with open(voca_out_path, "w") as f:
137
+ for vocab in sorted(text_vocab_set):
138
+ f.write(vocab + "\n")
139
+
140
+ dataset_name = out_dir.stem
141
+ print(f"\nFor {dataset_name}, sample count: {len(result)}")
142
+ print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
143
+ print(f"For {dataset_name}, total {sum(duration_list)/3600:.2f} hours")
144
+
145
+
146
+ def prepare_and_save_set(inp_dir, out_dir, is_finetune: bool = True):
147
+ if is_finetune:
148
+ print("Inside finetuning ...")
149
+ assert PRETRAINED_VOCAB_PATH.exists(), f"pretrained vocab.txt not found: {PRETRAINED_VOCAB_PATH}"
150
+ sub_result, durations, vocab_set = prepare_csv_wavs_dir(inp_dir)
151
+ save_prepped_dataset(out_dir, sub_result, durations, vocab_set, is_finetune)
152
+
153
+
154
+ def cli():
155
+ # finetune: python scripts/prepare_csv_wavs.py /path/to/input_dir /path/to/output_dir_pinyin
156
+ # pretrain: python scripts/prepare_csv_wavs.py /path/to/output_dir_pinyin --pretrain
157
+ parser = argparse.ArgumentParser(description="Prepare and save dataset.")
158
+ parser.add_argument("inp_dir", type=str, help="Input directory containing the data.")
159
+ parser.add_argument("out_dir", type=str, help="Output directory to save the prepared data.")
160
+ parser.add_argument("--pretrain", action="store_true", help="Enable for new pretrain, otherwise is a fine-tune")
161
+
162
+ args = parser.parse_args()
163
+
164
+ prepare_and_save_set(args.inp_dir, args.out_dir, is_finetune=not args.pretrain)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ cli()