turnmaster commited on
Commit
732ec72
·
verified ·
1 Parent(s): ccf829c

Delete augment_taskmaster.py

Browse files
Files changed (1) hide show
  1. augment_taskmaster.py +0 -809
augment_taskmaster.py DELETED
@@ -1,809 +0,0 @@
1
- import json
2
- import math
3
- import os
4
- import csv
5
- import random
6
- from pathlib import Path
7
- import re
8
- import argparse
9
- import soundfile as sf
10
- import numpy as np
11
- import torch
12
- import torchaudio
13
- from tqdm import tqdm
14
- import pandas as pd
15
- from whisper_normalizer.english import EnglishTextNormalizer
16
- import re
17
-
18
- # -------------------------
19
- # Helpers
20
- # -------------------------
21
- def load_mono_resampled(path, sr):
22
- wav_np, fs = sf.read(path, always_2d=True) # [T, C]
23
- wav = torch.from_numpy(wav_np).float().T # [C, T]
24
-
25
- if wav.shape[0] > 1:
26
- wav = wav.mean(dim=0, keepdim=True)
27
- else:
28
- wav = wav[:1]
29
-
30
- if fs != sr:
31
- wav = torchaudio.functional.resample(wav, fs, sr)
32
-
33
- # Remove DC offsets
34
- wav = torchaudio.functional.highpass_biquad(wav, sample_rate=sr, cutoff_freq=20.0)
35
-
36
- peak = wav.abs().max(dim=1, keepdim=True).values.clamp_min(1e-8)
37
- wav = 0.95 * wav / peak # peak normalize to [-0.95, 0.95]
38
- return wav # [1, T]
39
-
40
- pattern = re.compile(r"\$(\d+(?:\.\d+)?)")
41
-
42
- def transform_money(text: str) -> str:
43
- def repl(match):
44
- value = float(match.group(1))
45
- doubled = value * 2
46
- # Remove trailing .0 for integers
47
- if doubled.is_integer():
48
- doubled = int(doubled)
49
- return f"{doubled} dollars"
50
- return pattern.sub(repl, text)
51
-
52
- def normalize_punct(text, english_normalizer):
53
- parts = re.split(r'\.{3}|[.!?;]', text)
54
- parts = [p.strip() for p in parts if p.strip()]
55
- normalized_text = ""
56
- for part in parts:
57
- norm_part = english_normalizer(part)
58
- normalized_text += norm_part + " , "
59
- normalized_text += " . "
60
- normalized_text = normalized_text.replace(" , . ", " . ")
61
- return normalized_text
62
-
63
-
64
- def process_manifest(manifest_dir, wav_root, samples, args):
65
- manifest_csv = pd.read_csv(manifest_dir)
66
- wav_dirs = manifest_csv["audio_path"].values
67
- audio_id = manifest_csv["audio_id"].values
68
- texts = manifest_csv["synthetic_text"].values
69
- conversation_ids = manifest_csv["conversation_id"].values
70
- utterance_indexes = manifest_csv["utterance_index"].values
71
- role = manifest_csv["speaker"].values
72
- split = manifest_csv["split"].values
73
- english_normalizer = EnglishTextNormalizer()
74
- for entry_idx in range(len(wav_dirs)):
75
- if role[entry_idx] == "user":
76
- result = {
77
- "wav_dir": f'{wav_root}/{wav_dirs[entry_idx]}',
78
- "text": texts[entry_idx],
79
- "dialog_id": conversation_ids[entry_idx],
80
- "turn_id": utterance_indexes[entry_idx],
81
- "split": split[entry_idx],
82
- "audio_id": audio_id[entry_idx]
83
- }
84
-
85
- if args.normalize_text:
86
- if args.keep_punct:
87
- result['text'] = normalize_punct(result['text'], english_normalizer) #english_normalizer(result['text'])
88
- else:
89
- result['text'] = english_normalizer(result['text'])
90
-
91
- if args.custom_dollar_normalisation:
92
- result['text'] = transform_money(result['text'])
93
-
94
- samples.append(result)
95
-
96
- return samples
97
-
98
- def rms(x, eps=1e-12):
99
- return torch.sqrt(torch.mean(x**2) + eps)
100
-
101
- def fit_noise_length(noise, target_len):
102
- n = noise.shape[1]
103
- if n == target_len:
104
- return noise
105
- elif n > target_len:
106
- start = random.randint(0, n - target_len)
107
- return noise[:, start:start + target_len]
108
- else:
109
- repeat = (target_len + n - 1) // n
110
- noise_rep = noise.repeat(1, repeat)
111
- return noise_rep[:, :target_len]
112
-
113
- def mix_with_snr(clean, noise, snr_db):
114
- clean_rms = rms(clean)
115
- noise_rms = rms(noise)
116
- noise_rms_target = clean_rms / (10 ** (snr_db / 20))
117
- scale = noise_rms_target / (noise_rms + 1e-12)
118
- noisy = clean + scale * noise
119
- return torch.clamp(noisy, -1.0, 1.0)
120
-
121
- def vad_labels_from_interval(
122
- num_samples: int,
123
- sr: int,
124
- speech_start: float,
125
- speech_end: float,
126
- intermediate_silences: list,
127
- frame_hop_s: float = 0.01,
128
- frame_len_s: float = 0.025,
129
- ) -> torch.Tensor:
130
- total_dur = num_samples / sr
131
- num_frames = int(math.ceil(total_dur / frame_hop_s))
132
- labels = torch.zeros(num_frames, dtype=torch.float32)
133
-
134
- for i in range(num_frames):
135
- center_t = i * frame_hop_s + 0.5 * frame_len_s
136
- is_intermediate_silence = False
137
- for silence in intermediate_silences:
138
- if silence[0] <= center_t < silence[1]:
139
- if silence[0] - speech_start - 0.032 < 0.001:
140
- if labels[i] != 0.0:
141
- labels[i] = 0.0
142
- if labels[i-1] != 0.0:
143
- labels[i-1] = 0.0
144
- if labels[i-2] != 0.0:
145
- labels[i-2] = 0.0
146
- is_intermediate_silence = True
147
- break
148
- else:
149
- if i+1 < num_frames:
150
- labels[i+1] = 3.0
151
- labels[i] = 3.0
152
-
153
- is_intermediate_silence = True
154
- break
155
- if not is_intermediate_silence:
156
- if speech_start <= center_t < speech_end:
157
- labels[i] = 1.0
158
- elif center_t > speech_end:
159
- labels[i] = 2.0
160
-
161
- # Change intermediate silences followed by endpoint to endpoint
162
- for i in range(num_frames-2, -1, -1):
163
- if labels[i+1] == 0.0:
164
- labels[i] = 2.0
165
- if labels[i+1] == 2.0 and labels[i] == 3.0:
166
- labels[i] = 2.0
167
- elif labels[i] == 1.0:
168
- break
169
-
170
- # Remove speech less than 100ms before between intermediate silence E.P.
171
- labels = fix_prev_values(labels)
172
-
173
- # Change intermediate silences followed by endpoint to E.P. again
174
- for i in range(num_frames-2, -1, -1):
175
- if labels[i+1] == 0.0:
176
- labels[i] = 2.0
177
- if labels[i+1] == 2.0 and labels[i] == 3.0:
178
- labels[i] = 2.0
179
- elif labels[i] == 1.0:
180
- break
181
-
182
- labels = torch.cat((torch.zeros(1,), labels))
183
- labels = labels[:-1]
184
- eot_idx = torch.where(labels == 2.0)[0]
185
- start_eot_idx = eot_idx[0].item()
186
- return labels, start_eot_idx
187
-
188
- # -------------------------
189
- # Argparse
190
- # -------------------------
191
- def parse_args():
192
- parser = argparse.ArgumentParser(description="Augment Taskmaster with start / end silences and optional noise.")
193
-
194
- parser.add_argument("--target-sr", type=int, default=16000)
195
- parser.add_argument("--silence-min-start", type=float, default=0.0, help="Minimum silence duration (seconds) for start and end silences")
196
- parser.add_argument("--silence-max-start", type=float, default=0.0, help="Maximum silence duration (seconds) for start and end silences")
197
- parser.add_argument("--silence-min-end", type=float, default=0.0, help="Minimum silence duration (seconds) for start and end silences")
198
- parser.add_argument("--silence-max-end", type=float, default=3.0, help="Maximum silence duration (seconds) for start and end silences")
199
- parser.add_argument("--silence-insertion-min-s", type=float, default=0.05, help="Minimum silence duration (seconds) for silence insertions")
200
- parser.add_argument("--silence-insertion-max-s", type=float, default=2.0, help="Maximum silence duration (seconds) for silence insertions")
201
- parser.add_argument("--pause-per-second-ratio", type=float, default=0.7, help="Maximum ratio of silence per audio duration allowed. Ex if audio duration = 10s and --pause-per-second-ratio 0.5 the maximum of number of silences to be inserted is 5.")
202
-
203
- parser.add_argument("--lam", type=float, default=0.003, help="Lam for exponential silence duration sampling")
204
- parser.add_argument("--max-initial-silence-duration", type=float, default=1.5, help="Maximum silence duration (seconds) for silence insertions")
205
-
206
- parser.add_argument("--snr-min-db", type=float, default=10)
207
- parser.add_argument("--snr-max-db", type=float, default=21)
208
- parser.add_argument("--frame-hop-s", type=float, default=0.01 * 4)
209
- parser.add_argument("--frame-len-s", type=float, default=0.032 * 4)
210
-
211
- parser.add_argument("--normalize-text", action="store_true")
212
- parser.add_argument("--keep-punct", action="store_true")
213
- parser.add_argument("--custom-dollar-normalisation", action="store_true", help="replace $10 to 10 dollars")
214
- parser.add_argument("--silence-insertion", action="store_true")
215
-
216
- parser.add_argument("--VAD-hop-length", type=int, default=256, help="Hop length used by the energy based VAD for speech segmentation before silence insertion.")
217
- parser.add_argument("--VAD-frame-length", type=int, default=512, help="Frame length used by the energy based VAD for speech segmentation before silence insertion.")
218
- parser.add_argument("--VAD-energy-threshold", type=float, default=0.01, help="Energy threshold used by the energy based VAD for speech segmentation before silence insertion.")
219
- parser.add_argument("--VAD-min-silence-frames", type=int, default=3, help="Min silence frame used by the energy based VAD for speech segmentation before silence insertion.")
220
-
221
- parser.add_argument("--taskmaster-root-dir", type=str, default="/opt/marcel-c3/workdir/clws3842/datasets/Taskmaster/original_clean", help="The root leading to the manifest.csv and the audios")
222
- parser.add_argument("--aug-dataset-save-dir", type=str, required=True)
223
-
224
- parser.add_argument("--add-white-noise", action="store_true", help="Required only if SNR args are provided.")
225
- parser.add_argument("--add-bg-noise", action="store_true", help="Required only if SNR args are provided.")
226
- parser.add_argument("--input-noise-dir", type=str, default="/opt/marcel-c3/workdir/clws3842/datasets/musan/musan", help="Required only if SNR args are provided.")
227
-
228
- parser.add_argument(
229
- "--splits",
230
- nargs="+",
231
- default=["train", "dev", "test"],
232
- choices=["train", "dev", "test"],
233
- help="Which splits to process"
234
- )
235
-
236
- parser.add_argument("--seed", type=int, default=3265)
237
-
238
- return parser.parse_args()
239
-
240
- def save_args_json(args, path="args.json"):
241
- path = Path(path)
242
- path.parent.mkdir(parents=True, exist_ok=True)
243
- with open(path, "w", encoding="utf-8") as f:
244
- json.dump(vars(args), f, indent=2, ensure_ascii=False)
245
-
246
- def detect_silence_segments(
247
- waveform,
248
- frame_length=1024,
249
- hop_length=512,
250
- energy_threshold=0.01,
251
- min_silence_frames=3
252
- ):
253
- """
254
- Detect silence regions in an audio waveform using short-time energy.
255
-
256
- Args:
257
- waveform (np.ndarray): 1D audio signal, or 2D with shape (channels, samples) / (samples, channels).
258
- frame_length (int): Number of samples per frame.
259
- hop_length (int): Step size between frames.
260
- energy_threshold (float): Frames with RMS energy below this are considered silent.
261
- min_silence_frames (int): Minimum consecutive silent frames to keep.
262
-
263
- Returns:
264
- List[Tuple[int, int]]: List of (start_frame, end_frame) silence intervals (inclusive).
265
- """
266
- waveform = np.asarray(waveform)
267
-
268
- # Robustly convert to 1D mono
269
- if waveform.ndim == 2:
270
- # If (channels, samples), average over channels
271
- if waveform.shape[0] <= waveform.shape[1]:
272
- waveform = waveform.mean(axis=0)
273
- else:
274
- # If (samples, channels), average over channels
275
- waveform = waveform.mean(axis=1)
276
- elif waveform.ndim != 1:
277
- raise ValueError("waveform must be 1D or 2D")
278
-
279
- waveform = waveform.astype(np.float32, copy=False)
280
-
281
- n_samples = len(waveform)
282
- if n_samples < frame_length:
283
- return []
284
-
285
- # Number of complete frames
286
- n_frames = 1 + (n_samples - frame_length) // hop_length
287
-
288
- # Frame-wise RMS energy
289
- energies = np.empty(n_frames, dtype=np.float32)
290
- for i in range(n_frames):
291
- start = i * hop_length
292
- frame = waveform[start:start + frame_length]
293
- energies[i] = np.sqrt(np.mean(frame * frame) + 1e-12)
294
-
295
- # Silent mask
296
- silent = energies < energy_threshold
297
-
298
- # Group consecutive silent frames
299
- silence_segments = []
300
- in_segment = False
301
- seg_start = 0
302
-
303
- for i, is_silent in enumerate(silent):
304
- if is_silent and not in_segment:
305
- in_segment = True
306
- seg_start = i
307
- elif not is_silent and in_segment:
308
- seg_end = i - 1
309
- if (seg_end - seg_start + 1) >= min_silence_frames:
310
- silence_segments.append((seg_start, seg_end))
311
- in_segment = False
312
-
313
- # If segment reaches last frame
314
- if in_segment:
315
- seg_end = n_frames - 1
316
- if (seg_end - seg_start + 1) >= min_silence_frames:
317
- silence_segments.append((seg_start, seg_end))
318
-
319
- return silence_segments
320
-
321
-
322
- def fix_prev_values(x: torch.Tensor, n: int = 3) -> torch.Tensor:
323
- """
324
- x: 1D tensor with values in [0, 3]
325
- n: number of values before first '2' to check
326
-
327
- Finds first index i where x[i] == 2.
328
- Checks slice x[max(0, i-n):i].
329
- If all are 1 -> keep unchanged.
330
- Otherwise sets that whole slice to 2.
331
- """
332
- x = x.clone() # avoid modifying original tensor
333
-
334
- # Find first index where value == 2
335
- idx = torch.where(x == 2.0)[0]
336
- if idx.numel() == 0:
337
- return x # no '2' found, nothing to do
338
-
339
- i = idx[0].item()
340
- start = max(0, i - n)
341
-
342
- prev_slice = x[start:i]
343
- if prev_slice.numel() > 0 and not torch.all(prev_slice == 1):
344
- x[start:i] = 2.0
345
-
346
- return x
347
-
348
-
349
- def sample_truncated_exponential(
350
- lower=500,
351
- upper=1500,
352
- decay_rate=0.005
353
- ):
354
- """
355
- Return one sample from a truncated exponential distribution
356
- between lower and upper.
357
- """
358
-
359
- if lower >= upper:
360
- raise ValueError("lower must be less than upper")
361
-
362
- if decay_rate < 0:
363
- raise ValueError("decay_rate must be non-negative")
364
-
365
- if decay_rate == 0:
366
- return random.uniform(lower, upper)
367
-
368
- u = random.random()
369
-
370
- return lower - math.log(
371
- 1 - u * (1 - math.exp(-decay_rate * (upper - lower)))
372
- ) / decay_rate
373
-
374
-
375
- def add_silence(waveform, sr, args):
376
- """
377
- Insert random silent chunks at detected silence starts.
378
-
379
- Args:
380
- waveform (np.ndarray): 1D waveform (or 2D, will be converted to mono).
381
- sr (int): Sample rate used for insertion duration and timestamps.
382
- args: object with at least `target_sr` (optional; if missing, `sr` is used).
383
-
384
- Returns:
385
- waveform_torch (torch.Tensor): shape (1, num_samples)
386
- silence_infos (str): "start_sec|end_sec;..." for all detected silences
387
- intermediate_silences (list): List of [start_sec, end_sec] for all silences
388
- """
389
- # Ensure 1D mono float32
390
- waveform = np.asarray(waveform)
391
- if waveform.ndim == 2:
392
- if waveform.shape[0] <= waveform.shape[1]:
393
- waveform = waveform.mean(axis=0)
394
- else:
395
- waveform = waveform.mean(axis=1)
396
- elif waveform.ndim != 1:
397
- raise ValueError("waveform must be 1D or 2D")
398
- waveform = waveform.astype(np.float32, copy=False)
399
-
400
- frame_length = args.VAD_frame_length
401
- hop_length = args.VAD_hop_length
402
-
403
- silences = detect_silence_segments(
404
- waveform,
405
- frame_length=frame_length,
406
- hop_length=hop_length,
407
- energy_threshold=args.VAD_energy_threshold,
408
- min_silence_frames=args.VAD_min_silence_frames
409
- )
410
-
411
- num_frames_waveform = len(waveform)
412
-
413
- # Exclude segments touching first/last frame (correct unit: frames)
414
- if silences:
415
- n_frames = 1 + (num_frames_waveform - frame_length) // hop_length if num_frames_waveform >= frame_length else 0
416
-
417
- used_sr = getattr(args, "target_sr", sr)
418
-
419
- silence_infos = "["
420
- intermediate_silences = []
421
-
422
- if len(silences) > 0:
423
- silences_idx_correct = [x for x in range(len(silences)) if (silences[x][1] * hop_length / sr) - (silences[x][0] * hop_length / sr) < args.max_initial_silence_duration]
424
- max_sil_insertion = max(1, int(num_frames_waveform / sr * args.pause_per_second_ratio))
425
-
426
- rand_num_silence = np.random.randint(0, min(max_sil_insertion, len(silences_idx_correct) + 1))
427
-
428
- elongate_indices = set()
429
- if rand_num_silence > 0 and args.silence_insertion == True:
430
- idx = np.random.choice(len(silences_idx_correct), replace=False, size=rand_num_silence)
431
- elongate_indices = set(idx)
432
-
433
- silences_to_elongate = [(i, silences[i]) for i in elongate_indices
434
- if silences[i][0] != 0 and silences[i][1] != (n_frames - 1)]
435
- silences_to_elongate = sorted(silences_to_elongate, key=lambda x: x[1][0], reverse=False)
436
-
437
- added_duration = 0
438
- elongated_map = {}
439
-
440
- for silence_idx, silence in silences_to_elongate:
441
- # Calculate the original silence boundaries in samples
442
- silence_start_sample = silence[0] * hop_length
443
- silence_end_sample = (silence[1] + 1) * hop_length
444
- sample_silence_duration = silence_end_sample - silence_start_sample
445
-
446
- # Calculate insertion point: end of silence - 2 frames
447
- insert_sample = silence_end_sample - (2 * hop_length) + added_duration
448
-
449
- if args.lam > 0:
450
- # Generate exp random silence duration
451
- silence_duration = sample_truncated_exponential(
452
- int(args.silence_insertion_min_s * 1000),
453
- int(args.silence_insertion_max_s * 1000),
454
- args.lam
455
- )
456
- silence_duration = int(silence_duration / 1000 * sr)
457
- else:
458
- # Generate uniform random silence duration
459
- silence_duration = int(np.random.randint(
460
- sr * args.silence_insertion_min_s,
461
- sr * args.silence_insertion_max_s)
462
- )
463
- silence_insert = np.zeros((silence_duration,), dtype=waveform.dtype)
464
-
465
- # Insert at end - 2 frames of the silence
466
- waveform = np.insert(waveform, insert_sample, silence_insert)
467
-
468
- # ═══════════════════════════════════════════════════════════════
469
- # FIX: Store the original start sample for correct timestamp calculation
470
- # ═══════════════════════════════════════════════════════════════
471
- elongated_map[silence_idx] = (added_duration, silence_duration, sample_silence_duration, silence_start_sample)
472
- added_duration += silence_duration
473
-
474
- cumulative_added = 0
475
- for silence_idx in range(len(silences)):
476
- silence = silences[silence_idx]
477
-
478
- if silence_idx in elongated_map:
479
- # ═══════════════════════════════════════════════════════════════
480
- # FIX: Calculate timestamps correctly for elongated silences
481
- # ═══════════════════════════════════════════════════════════════
482
- # The silence now spans from its original start to its original end + inserted duration
483
- added_at_this_point, silence_duration, sample_silence_duration, silence_start_sample = elongated_map[silence_idx]
484
-
485
- # Start remains at the original silence start (adjusted for previous insertions)
486
- start_sample = silence_start_sample + added_at_this_point
487
- # End is original end + inserted silence duration (adjusted for previous insertions)
488
- end_sample = start_sample + sample_silence_duration + silence_duration
489
-
490
- start_t = start_sample / used_sr
491
- end_t = end_sample / used_sr
492
-
493
- silence_infos += f"{start_t:.4f}|{end_t:.4f};"
494
- intermediate_silences.append([start_t, end_t])
495
-
496
- cumulative_added = added_at_this_point + silence_duration
497
- else:
498
- # Non-elongated silences
499
- start_sample = silence[0] * hop_length + cumulative_added
500
- end_sample = (silence[1] + 1) * hop_length + cumulative_added
501
-
502
- start_t = start_sample / used_sr
503
- end_t = end_sample / used_sr
504
-
505
- silence_infos += f"{start_t:.4f}|{end_t:.4f};"
506
- intermediate_silences.append([start_t, end_t])
507
-
508
- silence_infos += "]"
509
-
510
- waveform = torch.from_numpy(waveform.astype(np.float32, copy=False)).unsqueeze(0)
511
- return waveform, silence_infos, intermediate_silences
512
-
513
-
514
-
515
- def add_silence_deprecated(waveform, sr, args):
516
- """
517
- Insert random silent chunks at detected silence starts.
518
-
519
- Args:
520
- waveform (np.ndarray): 1D waveform (or 2D, will be converted to mono).
521
- sr (int): Sample rate used for insertion duration and timestamps.
522
- args: object with at least `target_sr` (optional; if missing, `sr` is used).
523
-
524
- Returns:
525
- waveform_torch (torch.Tensor): shape (1, num_samples)
526
- silence_infos (str): "start_sec-end_sec$..." for inserted chunks
527
- """
528
- # Ensure 1D mono float32
529
- waveform = np.asarray(waveform)
530
- if waveform.ndim == 2:
531
- if waveform.shape[0] <= waveform.shape[1]:
532
- waveform = waveform.mean(axis=0)
533
- else:
534
- waveform = waveform.mean(axis=1)
535
- elif waveform.ndim != 1:
536
- raise ValueError("waveform must be 1D or 2D")
537
- waveform = waveform.astype(np.float32, copy=False)
538
-
539
- frame_length = args.VAD_frame_length
540
- hop_length = args.VAD_hop_length
541
-
542
- silences = detect_silence_segments(
543
- waveform,
544
- frame_length=frame_length,
545
- hop_length=hop_length,
546
- energy_threshold=args.VAD_energy_threshold,
547
- min_silence_frames=args.VAD_min_silence_frames
548
- )
549
-
550
- # Exclude segments touching first/last frame (correct unit: frames)
551
- num_frames_waveform = len(waveform)
552
- if silences:
553
- n_frames = 1 + (num_frames_waveform - frame_length) // hop_length if num_frames_waveform >= frame_length else 0
554
-
555
- used_sr = getattr(args, "target_sr", sr)
556
- print(len(silences))
557
-
558
- silence_infos = "["
559
- intermediate_silences = []
560
- if len(silences) > 0:
561
- pause_per_second_ration = 0.75
562
- max_sil_insertion = max(1, int(num_frames_waveform / sr * pause_per_second_ration))
563
- print(max_sil_insertion, num_frames_waveform / sr)
564
- rand_num_silence = np.random.randint(0, min(max_sil_insertion, len(silences) + 1))
565
- if rand_num_silence > 0 and args.silence_insertion == True:
566
- idx = np.random.choice(len(silences), replace=False, size=rand_num_silence)
567
- random_silences = [silences[i] for i in idx]
568
- # descending so earlier insertions don't shift later indices
569
- random_silences = sorted(random_silences, key=lambda x: x[0], reverse=True)
570
- added_duration = 0
571
- for silence_idx in range(len(silences)):
572
- if silence_idx in idx and silences[silence_idx][0] != 0 and silences[silence_idx][1] != (n_frames - 1):
573
- # Convert frame index -> sample index
574
- silence = silences[silence_idx]
575
- insert_sample = (silence[0] + 2) * hop_length + added_duration # +2 to account for frame length
576
- sample_silence_duration = (silence[1] + 1) * hop_length - silence[0] * hop_length # +1 to account for strict exclusion
577
-
578
- silence_duration = int(np.random.randint(sr * args.silence_insertion_min_s, sr * args.silence_insertion_max_s))
579
- silence_insert = np.zeros((silence_duration,), dtype=waveform.dtype)
580
-
581
- waveform = np.insert(waveform, insert_sample, silence_insert)
582
-
583
- start_t = insert_sample / used_sr
584
- end_t = (insert_sample + silence_duration) / used_sr
585
- silence_infos += f"{start_t:.6f}|{end_t:.6f};"
586
- intermediate_silences.append([insert_sample, (insert_sample + silence_duration + sample_silence_duration)])
587
- added_duration += silence_duration
588
- else:
589
- start_t, end_t = (silences[silence_idx][0] + 2) * hop_length + added_duration, (silences[silence_idx][1] + 2) * hop_length + added_duration
590
- intermediate_silences.append([start_t, end_t])
591
- else:
592
- for silence_idx in range(len(silences)):
593
- start_t, end_t = (silences[silence_idx][0] + 2) * hop_length, (silences[silence_idx][1] + 2) * hop_length
594
- intermediate_silences.append([start_t, end_t])
595
-
596
- intermediate_silences = [[x[0] / used_sr, x[1] / used_sr] for x in intermediate_silences]
597
- silence_infos += "]"
598
-
599
- waveform = torch.from_numpy(waveform.astype(np.float32, copy=False)).unsqueeze(0)
600
- return waveform, silence_infos, intermediate_silences
601
-
602
-
603
- def is_sample_in_split(split, sample_split):
604
- if split == "train":
605
- if sample_split == "train":
606
- return True
607
- else:
608
- False
609
- elif split == "dev":
610
- if sample_split == "dev":
611
- return True
612
- else:
613
- False
614
-
615
- elif split == "test":
616
- if sample_split == "test":
617
- return True
618
- else:
619
- False
620
- else:
621
- raise(f"{split} does not exist in the list of dataset splits to process")
622
-
623
- def main():
624
- print("Starting dataset augmentation.")
625
- args = parse_args()
626
- save_args_json(args, f'{args.aug_dataset_save_dir}/run_config.json')
627
-
628
- os.makedirs(f'{args.aug_dataset_save_dir}/figs', exist_ok=True)
629
-
630
- if args.seed is not None:
631
- random.seed(args.seed)
632
- np.random.seed(args.seed)
633
- torch.manual_seed(args.seed)
634
-
635
- if (args.snr_min_db is None) ^ (args.snr_max_db is None):
636
- raise ValueError("Provide both --snr-min-db and --snr-max-db, or neither.")
637
-
638
- for split in args.splits:
639
-
640
- out_audio_dir_tts = f'{args.aug_dataset_save_dir}/{split}/wav'
641
- out_vad_dir_tts = f'{args.aug_dataset_save_dir}/{split}/vad_labels'
642
- out_csv_path = f'{args.aug_dataset_save_dir}/{split}.csv'
643
-
644
- os.makedirs(out_audio_dir_tts, exist_ok=True)
645
- os.makedirs(out_vad_dir_tts, exist_ok=True)
646
- os.makedirs(Path(out_csv_path).parent, exist_ok=True)
647
-
648
- noise_files = []
649
- use_noise = args.add_bg_noise
650
- if use_noise:
651
- noise_files = sorted([
652
- str(p) for p in Path(args.input_noise_dir).glob("**/*")
653
- if p.suffix.lower() in [".wav", ".flac", ".mp3", ".ogg"]
654
- and "speech" not in str(p)
655
- ])
656
- if len(noise_files) == 0:
657
- raise RuntimeError("No noise files found.")
658
-
659
- speech_files = []
660
- manifest_dir = f'{args.taskmaster_root_dir}/manifest_filtered_1_18_02.csv'
661
- speech_files = process_manifest(manifest_dir, args.taskmaster_root_dir, speech_files, args)
662
-
663
- rows = []
664
- for i, speech_sample in enumerate(tqdm(speech_files, desc=f"Processing {split}", unit="file")):
665
- if is_sample_in_split(split, speech_sample["split"]):
666
- speech_path = speech_sample["wav_dir"]
667
- base = Path(speech_path).stem
668
- out_audio_path = os.path.join(out_audio_dir_tts, f"{i:06d}_aug_{base}.wav")
669
-
670
- if os.path.exists(out_audio_path):
671
- print("already exist")
672
- continue
673
-
674
- speech = load_mono_resampled(speech_path, args.target_sr)
675
- speech, silence_infos, intermediate_silences = add_silence(speech, args.target_sr, args)
676
-
677
- T_speech = speech.shape[1]
678
-
679
- start_sil_s = random.uniform(args.silence_min_start, args.silence_max_start)
680
- end_sil_s = random.uniform(args.silence_min_end, args.silence_max_end)
681
- intermediate_silences = [[intermediate_silences[x][0] + start_sil_s, intermediate_silences[x][1] + start_sil_s] for x in range(len(intermediate_silences))]
682
-
683
- T_start = int(round(start_sil_s * args.target_sr))
684
- T_end = int(round(end_sil_s * args.target_sr))
685
-
686
- start_sil = torch.zeros((1, T_start), dtype=speech.dtype)
687
- end_sil = torch.zeros((1, T_end), dtype=speech.dtype)
688
-
689
- clean_aug = torch.cat([start_sil, speech, end_sil], dim=1)
690
- T_total = clean_aug.shape[1]
691
-
692
- vad_label, start_eot_idx = vad_labels_from_interval(
693
- num_samples=T_total,
694
- sr=args.target_sr,
695
- speech_start=T_start / args.target_sr,
696
- speech_end=(T_start + T_speech) / args.target_sr,
697
- frame_hop_s=args.frame_hop_s,
698
- frame_len_s=args.frame_len_s,
699
- intermediate_silences=intermediate_silences,
700
- )
701
-
702
- is_syntethic = 1 if "tts" in speech_path or "train" in speech_path else 0
703
-
704
- base = Path(speech_path).stem
705
- out_audio_path = os.path.join(out_audio_dir_tts, f"aug_{i:06d}_{base}.wav")
706
- out_audio_noise_path = os.path.join(out_audio_dir_tts, f"aug_{i:06d}_{base}_noise.wav")
707
- out_vad_path = os.path.join(out_vad_dir_tts, f"aug_{i:06d}_{base}_vad.pt")
708
-
709
-
710
- noisy_aug = clean_aug.clone()
711
- noise_path = None
712
- if args.add_bg_noise and split != "train":
713
- noise_path = random.choice(noise_files)
714
- noise = load_mono_resampled(noise_path, args.target_sr)
715
- noise = fit_noise_length(noise, T_total)
716
-
717
- snr_db = random.uniform(args.snr_min_db, args.snr_max_db)
718
- noisy_aug = mix_with_snr(noisy_aug, noise, snr_db)
719
-
720
- if args.add_white_noise and split != "train":
721
-
722
- snr_db = random.uniform(args.snr_min_db, args.snr_max_db)
723
- white = torch.randn_like(clean_aug)
724
-
725
- noisy_aug = mix_with_snr(clean_aug, white, snr_db)
726
-
727
- if args.add_white_noise or args.add_bg_noise:
728
- if split != "train":
729
- noisy_np = noisy_aug.squeeze(0).cpu().numpy().astype(np.float32)
730
- sf.write(out_audio_noise_path, noisy_np, args.target_sr)
731
-
732
- rows.append({
733
- "ID": f"aug_{i:06d}_{base}_noise",
734
- "orig_speech_path": speech_path,
735
- "noise_path": noise_path,
736
- "wav": out_audio_noise_path,
737
- "vad": out_vad_path,
738
- "sample_rate": args.target_sr,
739
- "speech_num_samples": T_speech,
740
- "start_eot": start_eot_idx,
741
- "start_eot_time": start_eot_idx * 0.04,
742
- "start_silence_s": start_sil_s,
743
- "end_silence_s": end_sil_s,
744
- "start_silence_samples": T_start,
745
- "end_silence_samples": T_end,
746
- "total_num_samples": T_total,
747
- "duration": T_total / args.target_sr,
748
- "snr_db": snr_db,
749
- "speech_start_sample": T_start,
750
- "speech_end_sample_exclusive": T_start + T_speech,
751
- "wrd": speech_sample["text"],
752
- "dialog_id": speech_sample["dialog_id"],
753
- "turn_id": speech_sample["turn_id"],
754
- "split": speech_sample["split"],
755
- "audio_id": speech_sample["audio_id"],
756
- "is_syntethic": is_syntethic,
757
- "silence_infos": silence_infos,
758
- "white_noise": args.add_white_noise,
759
- "bg_noise": args.add_bg_noise
760
- })
761
-
762
- noise_path = None
763
- snr_db = None
764
- clean_aug_np = clean_aug.squeeze(0).cpu().numpy().astype(np.float32)
765
- sf.write(out_audio_path, clean_aug_np, args.target_sr)
766
- rows.append({
767
- "ID": f"aug_{i:06d}_{base}",
768
- "orig_speech_path": speech_path,
769
- "noise_path": noise_path,
770
- "wav": out_audio_path,
771
- "vad": out_vad_path,
772
- "sample_rate": args.target_sr,
773
- "speech_num_samples": T_speech,
774
- "start_eot": start_eot_idx,
775
- "start_eot_time": start_eot_idx * 0.04,
776
- "start_silence_s": start_sil_s,
777
- "end_silence_s": end_sil_s,
778
- "start_silence_samples": T_start,
779
- "end_silence_samples": T_end,
780
- "total_num_samples": T_total,
781
- "duration": T_total / args.target_sr,
782
- "snr_db": None,
783
- "speech_start_sample": T_start,
784
- "speech_end_sample_exclusive": T_start + T_speech,
785
- "wrd": speech_sample["text"],
786
- "dialog_id": speech_sample["dialog_id"],
787
- "turn_id": speech_sample["turn_id"],
788
- "split": speech_sample["split"],
789
- "audio_id": speech_sample["audio_id"],
790
- "is_syntethic": is_syntethic,
791
- "silence_infos": silence_infos,
792
- "white_noise": False,
793
- "bg_noise": False
794
- })
795
-
796
- torch.save(vad_label, out_vad_path)
797
-
798
- fieldnames = list(rows[0].keys()) if rows else []
799
- with open(out_csv_path, "w", newline="", encoding="utf-8") as f:
800
- writer = csv.DictWriter(f, fieldnames=fieldnames)
801
- writer.writeheader()
802
- writer.writerows(rows)
803
-
804
- print(f"[{split}] Done. Processed {len(rows)} files.")
805
- print(f"[{split}] Metadata CSV: {out_csv_path}")
806
-
807
-
808
- if __name__ == "__main__":
809
- main()