cdminix commited on
Commit
1dc30f0
·
verified ·
1 Parent(s): 940b905

Upload folder using huggingface_hub

Browse files
dataset/mainstream_us_english/female/hesitation/74-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4959261b84a8d979249ee25f1285d99edf306c7bedad421448e444865884e204
3
+ size 998444
dataset/mainstream_us_english/female/hesitation/75-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad2969f77c741c55f0f992b93791e779ef668760f7ae4225fcb33bbf4aaf22ea
3
+ size 925484
dataset/mainstream_us_english/female/hesitation/76-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2a11adc2cd93e142d6e9d6c72d119b3e106f1b509eecd6bd4121cc3f3b8100d
3
+ size 890924
dataset/mainstream_us_english/female/hesitation/77-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5705267134e02b684e7c07c7d459a7821991a47862faa787b3ebff50e9148ab1
3
+ size 1006124
dataset/mainstream_us_english/female/hesitation/78-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddb4e17aea2593ed1641bfec9a932913a75c02c5c9398ea7f8c7553e016ee7d9
3
+ size 937004
dataset/mainstream_us_english/female/hesitation/79-mainstream_us_english-female-1388-hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d870b6b2f10fd2465025bdc8001523841962db5675c089d05eb2c319732a05
3
+ size 890924
dataset/mainstream_us_english/female/no_hesitation/0-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:312c2fcf155098f2f31ffd413f7db5884dcd7273d4cd23d4a74817e1be62ad82
3
+ size 802604
dataset/mainstream_us_english/female/no_hesitation/1-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ab7789cada01007aed17cd45aecd930b090cb2d2c752aeb25c7d236cad3070d
3
+ size 825644
dataset/mainstream_us_english/female/no_hesitation/2-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77ad60c05ae8e8a907ff2cf678ce44d52372bcc9c83b27b85b6fd33cbbefc25c
3
+ size 725804
dataset/mainstream_us_english/female/no_hesitation/3-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a97e614a274beb8a93ff5d60fac9c93c0a1e6e4392d6786ae11f06eef84f4c6c
3
+ size 679724
dataset/mainstream_us_english/female/no_hesitation/4-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f4447a749576352978edeedb0b98cf9f3831e365bade1ce0a8bca8bcb547462
3
+ size 706604
dataset/mainstream_us_english/female/no_hesitation/5-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c4ffcdee198034b2425c21d0421b397d252ceec5ceaf9562fe166ddbf7843a6
3
+ size 963884
dataset/mainstream_us_english/female/no_hesitation/6-mainstream_us_english-female-1388-no_hesitation.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9caa3c801ea7cbecbe833f2d2717b5581dbb5fef71e07be434f8d465b3cad1a1
3
+ size 860204
generate_speech.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Generate speech samples using MegaTTS3 for different accents and genders.
4
+
5
+ This script:
6
+ 1. Loads question metadata from JSON files
7
+ 2. Filters and constructs accent/gender dictionaries
8
+ 3. Generates speech using MegaTTS3 voice cloning
9
+ """
10
+
11
+ import json
12
+ import shutil
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import pandas as pd
17
+ from gradio_client import Client, handle_file
18
+ from tqdm.auto import tqdm
19
+
20
+
21
+ def generate_with_retry(client, speaker_audio_path, text, max_retries=5, initial_delay=1):
22
+ """Generate speech with retry logic and exponential backoff.
23
+
24
+ Args:
25
+ client: Gradio client instance
26
+ speaker_audio_path: Path to reference speaker audio
27
+ text: Text to synthesize
28
+ max_retries: Maximum number of retry attempts (default: 5)
29
+ initial_delay: Initial delay in seconds (default: 1)
30
+
31
+ Returns:
32
+ Path to generated audio file
33
+
34
+ Raises:
35
+ Exception: If all retry attempts fail
36
+ """
37
+ for attempt in range(max_retries):
38
+ try:
39
+ result = client.predict(
40
+ inp_audio=handle_file(speaker_audio_path),
41
+ inp_text=text,
42
+ infer_timestep=32,
43
+ p_w=1.4,
44
+ t_w=3,
45
+ api_name="/generate_speech"
46
+ )
47
+ return result
48
+ except Exception as e:
49
+ if attempt == max_retries - 1:
50
+ # Last attempt failed, raise the exception
51
+ raise
52
+ # Calculate backoff delay: 1s, 2s, 4s, 8s, 16s
53
+ delay = initial_delay * (2 ** attempt)
54
+ print(f"\nRetry {attempt + 1}/{max_retries} after error: {str(e)[:100]}")
55
+ print(f"Waiting {delay}s before retrying...")
56
+ time.sleep(delay)
57
+
58
+
59
+ def build_accent_gender_dicts(questions_dir="questions"):
60
+ """Build accent-gender dictionaries from question JSON files.
61
+
62
+ Args:
63
+ questions_dir: Directory containing question JSON files
64
+
65
+ Returns:
66
+ tuple: (accents_gender, accent_gender_both, final_dict)
67
+ """
68
+ questions_path = Path(questions_dir)
69
+
70
+ # Step 1: Build initial accents_gender dictionary
71
+ print("Building accent-gender mappings...")
72
+ accents_gender = {}
73
+ for item in sorted(questions_path.glob("*.json")):
74
+ with open(item, "r") as f:
75
+ data = json.load(f)
76
+
77
+ # Filter based on text length and other criteria
78
+ if len(data["text"]) > 50:
79
+ # Skip certain US English speakers
80
+ if data["accent"] == "Mainstream US English" and "US English" not in data["l1"]:
81
+ continue
82
+ # Skip specific problematic speaker
83
+ if data["speaker"] == "EDACC-C19-B":
84
+ print(f"Skipping speaker {data['speaker']} - {item.stem}")
85
+ continue
86
+
87
+ accent_gender_key = f"{data['accent']}-{data['gender']}"
88
+ if accent_gender_key not in accents_gender:
89
+ accents_gender[accent_gender_key] = item.stem
90
+
91
+ print(f"Found {len(accents_gender)} accent-gender combinations")
92
+
93
+ # Step 2: Filter to only include accent-gender pairs where both male and female exist
94
+ print("\nFiltering for balanced gender representation...")
95
+ accent_gender_both = {}
96
+ for k in accents_gender:
97
+ if "-male" in k:
98
+ if k.replace("-male", "-female") in accents_gender:
99
+ accent_gender_both[k] = accents_gender[k]
100
+ else:
101
+ print(f"Missing female pair for: {k}")
102
+ elif "-female" in k:
103
+ if k.replace("-female", "-male") in accents_gender:
104
+ accent_gender_both[k] = accents_gender[k]
105
+ else:
106
+ print(f"Missing male pair for: {k}")
107
+
108
+ print(f"Balanced pairs: {len(accent_gender_both)}")
109
+
110
+ # Show unique accents
111
+ unique_accents = set([x.split("-")[0] for x in accent_gender_both.keys()])
112
+ print(f"\nUnique accents: {sorted(unique_accents)}")
113
+
114
+ # Step 3: Filter to specific accents of interest
115
+ keys_to_keep = [
116
+ "Mainstream US",
117
+ "Southern British",
118
+ "Indian",
119
+ "Chinese",
120
+ "Latin American",
121
+ "Eastern European",
122
+ ]
123
+
124
+ final_dict = {}
125
+ for k in accent_gender_both:
126
+ if any(x in k for x in keys_to_keep):
127
+ final_dict[k] = accent_gender_both[k]
128
+
129
+ print(f"\nFinal selection: {len(final_dict)} accent-gender pairs")
130
+ for k, v in sorted(final_dict.items()):
131
+ print(f" {k}: {v}")
132
+
133
+ return accents_gender, accent_gender_both, final_dict
134
+
135
+
136
+ def generate_speech_samples(
137
+ final_dict,
138
+ prompts_csv="tts_prompts.csv",
139
+ output_dir="dataset",
140
+ questions_dir="questions",
141
+ gradio_endpoint="cdminix/MegaTTS3-Voice-Cloning"
142
+ ):
143
+ """Generate speech samples for all accent-gender pairs.
144
+
145
+ Args:
146
+ final_dict: Dictionary mapping accent-gender keys to question IDs
147
+ prompts_csv: Path to CSV file containing prompts
148
+ output_dir: Base directory for output files
149
+ questions_dir: Directory containing reference speaker audio
150
+ gradio_endpoint: Gradio API endpoint for MegaTTS3
151
+ """
152
+ # Initialize MegaTTS3 client
153
+ print(f"\nInitializing MegaTTS3 client: {gradio_endpoint}")
154
+ client = Client(gradio_endpoint)
155
+
156
+ # Load prompts
157
+ df = pd.read_csv(prompts_csv)
158
+ df_hesitation = df[df["has_disfluency"] == True]
159
+ df_no_hesitation = df[df["has_disfluency"] == False]
160
+
161
+ print(f"\nTotal prompts: {len(df)} ({len(df_hesitation)} with hesitation, {len(df_no_hesitation)} without)")
162
+
163
+ result_rows = []
164
+
165
+ # Calculate total number of files to generate
166
+ total_files = len(final_dict.keys()) * (len(df_hesitation) + len(df_no_hesitation))
167
+ print(f"Total files to generate: {total_files}")
168
+
169
+ pbar = tqdm(total=total_files, desc="Generating audio")
170
+
171
+ for k in sorted(final_dict.keys()):
172
+ accent = k.split("-")[0]
173
+ accent = accent.replace(" ", "_").lower()
174
+ gender = k.split("-")[1]
175
+
176
+ # Create output directories
177
+ hesitation_dir = Path(output_dir) / accent / gender / "hesitation"
178
+ no_hesitation_dir = Path(output_dir) / accent / gender / "no_hesitation"
179
+ hesitation_dir.mkdir(parents=True, exist_ok=True)
180
+ no_hesitation_dir.mkdir(parents=True, exist_ok=True)
181
+
182
+ # Get speaker audio path
183
+ speaker_audio_path = Path(questions_dir) / f"{final_dict[k]}.wav"
184
+ speaker_audio_path_corrected = Path(questions_dir) / f"{final_dict[k]}_corrected.wav"
185
+
186
+ # Use corrected version if available, otherwise copy original
187
+ if not speaker_audio_path_corrected.exists():
188
+ if speaker_audio_path.exists():
189
+ shutil.copy(speaker_audio_path, speaker_audio_path_corrected)
190
+
191
+ speaker_audio_path = str(speaker_audio_path_corrected)
192
+
193
+ # Generate hesitation samples
194
+ for idx, row in df_hesitation.iterrows():
195
+ _id = f"{idx}-{accent}-{gender}-{final_dict[k]}-hesitation"
196
+ output_path = hesitation_dir / f"{_id}.wav"
197
+
198
+ if output_path.exists():
199
+ result_rows.append({
200
+ "id": _id,
201
+ "accent": accent,
202
+ "gender": gender,
203
+ "speaker_audio": speaker_audio_path,
204
+ })
205
+ pbar.update(1)
206
+ continue
207
+
208
+ # Generate with retry logic
209
+ result = generate_with_retry(client, speaker_audio_path, row["text"])
210
+
211
+ # Copy the result file to output path
212
+ shutil.copy(result, output_path)
213
+
214
+ result_rows.append({
215
+ "id": _id,
216
+ "accent": accent,
217
+ "gender": gender,
218
+ "speaker_audio": speaker_audio_path,
219
+ })
220
+ pbar.update(1)
221
+
222
+ # Generate no-hesitation samples
223
+ for idx, row in df_no_hesitation.iterrows():
224
+ _id = f"{idx}-{accent}-{gender}-{final_dict[k]}-no_hesitation"
225
+ output_path = no_hesitation_dir / f"{_id}.wav"
226
+
227
+ if output_path.exists():
228
+ result_rows.append({
229
+ "id": _id,
230
+ "accent": accent,
231
+ "gender": gender,
232
+ "speaker_audio": speaker_audio_path,
233
+ })
234
+ pbar.update(1)
235
+ continue
236
+
237
+ # Generate with retry logic
238
+ result = generate_with_retry(client, speaker_audio_path, row["text"])
239
+
240
+ # Copy the result file to output path
241
+ shutil.copy(result, output_path)
242
+
243
+ result_rows.append({
244
+ "id": _id,
245
+ "accent": accent,
246
+ "gender": gender,
247
+ "speaker_audio": speaker_audio_path,
248
+ })
249
+ pbar.update(1)
250
+
251
+ pbar.close()
252
+
253
+ # Save results
254
+ df_result = pd.DataFrame(result_rows)
255
+ df_result.to_csv("tts_prompts_result.csv", index=False)
256
+ print(f"\nCompleted! Generated {len(result_rows)} audio files.")
257
+ print(f"Results saved to: tts_prompts_result.csv")
258
+
259
+
260
+ def main():
261
+ """Main execution function."""
262
+ print("=" * 70)
263
+ print("Speech Generation Pipeline")
264
+ print("=" * 70)
265
+
266
+ # Step 1: Build dictionaries
267
+ accents_gender, accent_gender_both, final_dict = build_accent_gender_dicts()
268
+
269
+ # Step 2: Generate speech samples
270
+ generate_speech_samples(final_dict)
271
+
272
+ print("\n" + "=" * 70)
273
+ print("Pipeline complete!")
274
+ print("=" * 70)
275
+
276
+
277
+ if __name__ == "__main__":
278
+ main()
279
+
requirements.txt CHANGED
@@ -7,4 +7,7 @@ torch
7
  datasets[audio]
8
  torchcodec
9
  python-dotenv
10
- replicate
 
 
 
 
7
  datasets[audio]
8
  torchcodec
9
  python-dotenv
10
+ replicate
11
+ gradio_client
12
+ transformers
13
+ pandas