ashishkblink commited on
Commit
9ed490b
·
verified ·
1 Parent(s): e1e29b4

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

Browse files
f5_tts/train/datasets/prepare_csvs_wavs_v2.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("/home/tts/ttsteam/repos/F5-TTS/ckpts/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 audio_path_text_pairs}
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
+ sub_result.append(result[0])
64
+ durations.append(result[1])
65
+ vocab_set.update(list(result[0]['text']))
66
+
67
+ return sub_result, durations, vocab_set
68
+
69
+
70
+ def get_audio_duration(audio_path):
71
+ audio, sample_rate = torchaudio.load(audio_path)
72
+ return audio.shape[1] / sample_rate
73
+
74
+
75
+ def read_audio_text_pairs(csv_file_path):
76
+ audio_text_pairs = []
77
+
78
+ parent = Path(csv_file_path).parent
79
+ with open(csv_file_path, mode="r", newline="", encoding="utf-8-sig") as csvfile:
80
+ reader = csv.reader(csvfile, delimiter="|")
81
+ next(reader) # Skip the header row
82
+ for row in reader:
83
+ if len(row) == 2: # Only if len == 2, else skip the row as could be noisy. IN22 texts could use '|' as a delimiter
84
+ audio_file = row[0].strip() # First column: audio file path
85
+ text = row[1].strip() # Second column: text
86
+ # audio_file_path = parent / audio_file
87
+ audio_file_path = audio_file
88
+ audio_text_pairs.append((Path(audio_file_path).as_posix(), text))
89
+ return audio_text_pairs
90
+
91
+
92
+ def save_prepped_dataset(out_dir, result, duration_list, text_vocab_set, is_finetune):
93
+ out_dir = Path(out_dir)
94
+ # save preprocessed dataset to disk
95
+ out_dir.mkdir(exist_ok=True, parents=True)
96
+ print(f"\nSaving to {out_dir} ...")
97
+
98
+ # dataset = Dataset.from_dict({"audio_path": audio_path_list, "text": text_list, "duration": duration_list}) # oom
99
+ # dataset.save_to_disk(f"{out_dir}/raw", max_shard_size="2GB")
100
+ raw_arrow_path = out_dir / "raw.arrow"
101
+ with ArrowWriter(path=raw_arrow_path.as_posix(), writer_batch_size=1) as writer:
102
+ for line in tqdm(result, desc="Writing to raw.arrow ..."):
103
+ writer.write(line)
104
+
105
+ # dup a json separately saving duration in case for DynamicBatchSampler ease
106
+ dur_json_path = out_dir / "duration.json"
107
+ with open(dur_json_path.as_posix(), "w", encoding="utf-8") as f:
108
+ json.dump({"duration": duration_list}, f, ensure_ascii=False)
109
+
110
+ # vocab map, i.e. tokenizer
111
+ # add alphabets and symbols (optional, if plan to ft on de/fr etc.)
112
+ # if tokenizer == "pinyin":
113
+ # text_vocab_set.update([chr(i) for i in range(32, 127)] + [chr(i) for i in range(192, 256)])
114
+ voca_out_path = out_dir / "vocab.txt"
115
+ with open(voca_out_path.as_posix(), "w") as f:
116
+ for vocab in sorted(text_vocab_set):
117
+ f.write(vocab + "\n")
118
+
119
+ voca_out_path = out_dir / "new_vocab.txt"
120
+ with open(voca_out_path.as_posix(), "w") as f:
121
+ for vocab in sorted(text_vocab_set):
122
+ f.write(vocab + "\n")
123
+
124
+ if is_finetune:
125
+ file_vocab_finetune = PRETRAINED_VOCAB_PATH.as_posix()
126
+ shutil.copy2(file_vocab_finetune, voca_out_path)
127
+ else:
128
+ with open(voca_out_path, "w") as f:
129
+ for vocab in sorted(text_vocab_set):
130
+ f.write(vocab + "\n")
131
+
132
+ dataset_name = out_dir.stem
133
+ print(f"\nFor {dataset_name}, sample count: {len(result)}")
134
+ print(f"For {dataset_name}, vocab size is: {len(text_vocab_set)}")
135
+ print(f"For {dataset_name}, total {sum(duration_list)/3600:.2f} hours")
136
+
137
+
138
+ def prepare_and_save_set(inp_dir, out_dir, is_finetune: bool = True):
139
+ if is_finetune:
140
+ print("Inside finetuning ...")
141
+ assert PRETRAINED_VOCAB_PATH.exists(), f"pretrained vocab.txt not found: {PRETRAINED_VOCAB_PATH}"
142
+ sub_result, durations, vocab_set = prepare_csv_wavs_dir(inp_dir)
143
+ save_prepped_dataset(out_dir, sub_result, durations, vocab_set, is_finetune)
144
+
145
+
146
+ def cli():
147
+ # finetune: python scripts/prepare_csv_wavs.py /path/to/input_dir /path/to/output_dir_pinyin
148
+ # pretrain: python scripts/prepare_csv_wavs.py /path/to/output_dir_pinyin --pretrain
149
+ parser = argparse.ArgumentParser(description="Prepare and save dataset.")
150
+ parser.add_argument("inp_dir", type=str, help="Input directory containing the data.")
151
+ parser.add_argument("out_dir", type=str, help="Output directory to save the prepared data.")
152
+ parser.add_argument("--pretrain", action="store_true", help="Enable for new pretrain, otherwise is a fine-tune")
153
+
154
+ args = parser.parse_args()
155
+
156
+ prepare_and_save_set(args.inp_dir, args.out_dir, is_finetune=not args.pretrain)
157
+
158
+
159
+ if __name__ == "__main__":
160
+ cli()