File size: 34,986 Bytes
ec26866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f86a65
 
 
ec26866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f86a65
ec26866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import json
import math
import os
import csv
import random
from pathlib import Path
import re
import argparse
import soundfile as sf
import numpy as np
import torch
import torchaudio
from tqdm import tqdm
import pandas as pd
from whisper_normalizer.english import EnglishTextNormalizer
import re

# -------------------------
# Helpers
# -------------------------
def load_mono_resampled(path, sr):
    wav_np, fs = sf.read(path, always_2d=True)   # [T, C]
    wav = torch.from_numpy(wav_np).float().T     # [C, T]

    if wav.shape[0] > 1:
        wav = wav.mean(dim=0, keepdim=True)
    else:
        wav = wav[:1]

    if fs != sr:
        wav = torchaudio.functional.resample(wav, fs, sr)
        
    # Remove DC offsets
    wav = torchaudio.functional.highpass_biquad(wav, sample_rate=sr, cutoff_freq=20.0)

    peak = wav.abs().max(dim=1, keepdim=True).values.clamp_min(1e-8)
    wav = 0.95 * wav / peak                    # peak normalize to [-0.95, 0.95]
    return wav  # [1, T]

pattern = re.compile(r"\$(\d+(?:\.\d+)?)")

def transform_money(text: str) -> str:
    def repl(match):
        value = float(match.group(1))
        doubled = value * 2
        # Remove trailing .0 for integers
        if doubled.is_integer():
            doubled = int(doubled)
        return f"{doubled} dollars"
    return pattern.sub(repl, text)

def normalize_punct(text, english_normalizer):
    parts = re.split(r'\.{3}|[.!?;]', text)
    parts = [p.strip() for p in parts if p.strip()]
    normalized_text = ""
    for part in parts:
        norm_part = english_normalizer(part)
        normalized_text += norm_part + " , "
    normalized_text += " . "
    normalized_text = normalized_text.replace(" ,  . ", " . ")
    return normalized_text
        

def process_manifest(manifest_dir, wav_root, samples, args):
    manifest_csv = pd.read_csv(manifest_dir)
    wav_dirs = manifest_csv["audio_path"].values
    audio_id = manifest_csv["audio_id"].values 
    texts = manifest_csv["synthetic_text"].values
    conversation_ids = manifest_csv["conversation_id"].values
    utterance_indexes = manifest_csv["utterance_index"].values
    role = manifest_csv["speaker"].values
    split = manifest_csv["split"].values
    english_normalizer = EnglishTextNormalizer()
    for entry_idx in range(len(wav_dirs)):
        if role[entry_idx] == "user":
            result = {
                "wav_dir": f'{wav_root}/{wav_dirs[entry_idx]}',
                "text": texts[entry_idx],
                "dialog_id": conversation_ids[entry_idx],
                "turn_id": utterance_indexes[entry_idx],
                "split": split[entry_idx],
                "audio_id": audio_id[entry_idx]
            }
            
            if args.normalize_text:
                if args.keep_punct:
                    result['text'] = normalize_punct(result['text'], english_normalizer) #english_normalizer(result['text'])
                else:
                    result['text'] = english_normalizer(result['text'])
            
            if args.custom_dollar_normalisation:
                result['text'] = transform_money(result['text'])
                
            samples.append(result)

    return samples

def rms(x, eps=1e-12):
    return torch.sqrt(torch.mean(x**2) + eps)

def fit_noise_length(noise, target_len):
    n = noise.shape[1]
    if n == target_len:
        return noise
    elif n > target_len:
        start = random.randint(0, n - target_len)
        return noise[:, start:start + target_len]
    else:
        repeat = (target_len + n - 1) // n
        noise_rep = noise.repeat(1, repeat)
        return noise_rep[:, :target_len]

def mix_with_snr(clean, noise, snr_db):
    clean_rms = rms(clean)
    noise_rms = rms(noise)
    noise_rms_target = clean_rms / (10 ** (snr_db / 20))
    scale = noise_rms_target / (noise_rms + 1e-12)
    noisy = clean + scale * noise
    return torch.clamp(noisy, -1.0, 1.0)

def vad_labels_from_interval(
    num_samples: int,
    sr: int,
    speech_start: float,
    speech_end: float,
    intermediate_silences: list,
    frame_hop_s: float = 0.01,
    frame_len_s: float = 0.025,
) -> torch.Tensor:
    total_dur = num_samples / sr
    num_frames = int(math.ceil(total_dur / frame_hop_s))
    labels = torch.zeros(num_frames, dtype=torch.float32)
        
    for i in range(num_frames):
        center_t = i * frame_hop_s + 0.5 * frame_len_s
        is_intermediate_silence = False
        for silence in intermediate_silences:
            if silence[0] <= center_t < silence[1]:
                if silence[0] - speech_start - 0.032 < 0.001:
                    if labels[i] != 0.0:
                        labels[i] = 0.0
                    if labels[i-1] != 0.0:
                        labels[i-1] = 0.0
                    if labels[i-2] != 0.0:
                        labels[i-2] = 0.0
                    is_intermediate_silence = True
                    break
                else:
                    if i+1 < num_frames:
                        labels[i+1] = 3.0
                    labels[i] = 3.0

                    is_intermediate_silence = True
                    break
        if not is_intermediate_silence:
            if speech_start <= center_t < speech_end:
                labels[i] = 1.0
            elif center_t > speech_end:
                labels[i] = 2.0

    # Change intermediate silences followed by endpoint to endpoint
    for i in range(num_frames-2, -1, -1):
        if labels[i+1] == 0.0:
            labels[i] = 2.0
        if labels[i+1] == 2.0 and labels[i] == 3.0:
            labels[i] = 2.0
        elif labels[i] == 1.0:
            break
    
    # Remove speech less than 100ms before between intermediate silence E.P.
    labels = fix_prev_values(labels)
    
    # Change intermediate silences followed by endpoint to E.P. again
    for i in range(num_frames-2, -1, -1):
        if labels[i+1] == 0.0:
            labels[i] = 2.0
        if labels[i+1] == 2.0 and labels[i] == 3.0:
            labels[i] = 2.0
        elif labels[i] == 1.0:
            break
        
    labels = torch.cat((torch.zeros(1,), labels))
    labels = labels[:-1]
    eot_idx = torch.where(labels == 2.0)[0]
    start_eot_idx = eot_idx[0].item()
    return labels, start_eot_idx

# -------------------------
# Argparse
# -------------------------
def parse_args():
    parser = argparse.ArgumentParser(description="Augment Taskmaster with start / end silences and optional noise.")

    parser.add_argument("--target-sr", type=int, default=16000)
    parser.add_argument("--silence-min-start", type=float, default=0.0, help="Minimum silence duration (seconds) for start and end silences")
    parser.add_argument("--silence-max-start", type=float, default=0.0, help="Maximum silence duration (seconds) for start and end silences")
    parser.add_argument("--silence-min-end", type=float, default=0.0, help="Minimum silence duration (seconds) for start and end silences")
    parser.add_argument("--silence-max-end", type=float, default=3.0, help="Maximum silence duration (seconds) for start and end silences")
    parser.add_argument("--silence-insertion-min-s", type=float, default=0.05, help="Minimum silence duration (seconds) for silence insertions")
    parser.add_argument("--silence-insertion-max-s", type=float, default=2.0, help="Maximum silence duration (seconds) for silence insertions")
    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.")
    
    parser.add_argument("--lam", type=float, default=0.003, help="Lam for exponential silence duration sampling")
    parser.add_argument("--max-initial-silence-duration", type=float, default=1.5, help="Maximum silence duration (seconds) for silence insertions")
    
    parser.add_argument("--snr-min-db", type=float, default=10)
    parser.add_argument("--snr-max-db", type=float, default=21)
    parser.add_argument("--frame-hop-s", type=float, default=0.01 * 4)
    parser.add_argument("--frame-len-s", type=float, default=0.032 * 4)

    parser.add_argument("--normalize-text", action="store_true")
    parser.add_argument("--keep-punct", action="store_true")
    parser.add_argument("--custom-dollar-normalisation", action="store_true", help="replace $10 to 10 dollars")
    parser.add_argument("--silence-insertion", action="store_true")
    
    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.")
    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.")
    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.")
    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.")

    parser.add_argument("--taskmaster-root-dir", type=str, required=True, help="The root leading to the manifest.csv and the audios.")
    parser.add_argument("--manifest-dir", type=str, required=True, help="The manifest to use to build the new TurnMaster version.")
    parser.add_argument("--aug-dataset-save-dir", type=str, required=True, help="The directory to save the dataset version.")
    
    parser.add_argument("--add-white-noise", action="store_true", help="Required only if SNR args are provided.")
    parser.add_argument("--add-bg-noise", action="store_true", help="Required only if SNR args are provided.")
    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.")

    parser.add_argument(
        "--splits",
        nargs="+",
        default=["train", "dev", "test"],
        choices=["train", "dev", "test"],
        help="Which splits to process"
    )

    parser.add_argument("--seed", type=int, default=3265)

    return parser.parse_args()

def save_args_json(args, path="args.json"):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(vars(args), f, indent=2, ensure_ascii=False)

def detect_silence_segments(
    waveform,
    frame_length=1024,
    hop_length=512,
    energy_threshold=0.01,
    min_silence_frames=3
):
    """
    Detect silence regions in an audio waveform using short-time energy.

    Args:
        waveform (np.ndarray): 1D audio signal, or 2D with shape (channels, samples) / (samples, channels).
        frame_length (int): Number of samples per frame.
        hop_length (int): Step size between frames.
        energy_threshold (float): Frames with RMS energy below this are considered silent.
        min_silence_frames (int): Minimum consecutive silent frames to keep.

    Returns:
        List[Tuple[int, int]]: List of (start_frame, end_frame) silence intervals (inclusive).
    """
    waveform = np.asarray(waveform)

    # Robustly convert to 1D mono
    if waveform.ndim == 2:
        # If (channels, samples), average over channels
        if waveform.shape[0] <= waveform.shape[1]:
            waveform = waveform.mean(axis=0)
        else:
            # If (samples, channels), average over channels
            waveform = waveform.mean(axis=1)
    elif waveform.ndim != 1:
        raise ValueError("waveform must be 1D or 2D")

    waveform = waveform.astype(np.float32, copy=False)

    n_samples = len(waveform)
    if n_samples < frame_length:
        return []

    # Number of complete frames
    n_frames = 1 + (n_samples - frame_length) // hop_length

    # Frame-wise RMS energy
    energies = np.empty(n_frames, dtype=np.float32)
    for i in range(n_frames):
        start = i * hop_length
        frame = waveform[start:start + frame_length]
        energies[i] = np.sqrt(np.mean(frame * frame) + 1e-12)

    # Silent mask
    silent = energies < energy_threshold

    # Group consecutive silent frames
    silence_segments = []
    in_segment = False
    seg_start = 0

    for i, is_silent in enumerate(silent):
        if is_silent and not in_segment:
            in_segment = True
            seg_start = i
        elif not is_silent and in_segment:
            seg_end = i - 1
            if (seg_end - seg_start + 1) >= min_silence_frames:
                silence_segments.append((seg_start, seg_end))
            in_segment = False

    # If segment reaches last frame
    if in_segment:
        seg_end = n_frames - 1
        if (seg_end - seg_start + 1) >= min_silence_frames:
            silence_segments.append((seg_start, seg_end))

    return silence_segments


def fix_prev_values(x: torch.Tensor, n: int = 3) -> torch.Tensor:
    """
    x: 1D tensor with values in [0, 3]
    n: number of values before first '2' to check
    
    Finds first index i where x[i] == 2.
    Checks slice x[max(0, i-n):i].
    If all are 1 -> keep unchanged.
    Otherwise sets that whole slice to 2.
    """
    x = x.clone()  # avoid modifying original tensor

    # Find first index where value == 2
    idx = torch.where(x == 2.0)[0]
    if idx.numel() == 0:
        return x  # no '2' found, nothing to do

    i = idx[0].item()
    start = max(0, i - n)

    prev_slice = x[start:i]
    if prev_slice.numel() > 0 and not torch.all(prev_slice == 1):
        x[start:i] = 2.0

    return x


def sample_truncated_exponential(
    lower=500,
    upper=1500,
    decay_rate=0.005
):
    """
    Return one sample from a truncated exponential distribution
    between lower and upper.
    """

    if lower >= upper:
        raise ValueError("lower must be less than upper")

    if decay_rate < 0:
        raise ValueError("decay_rate must be non-negative")

    if decay_rate == 0:
        return random.uniform(lower, upper)

    u = random.random()

    return lower - math.log(
        1 - u * (1 - math.exp(-decay_rate * (upper - lower)))
    ) / decay_rate


def add_silence(waveform, sr, args):
    """
    Insert random silent chunks at detected silence starts.

    Args:
        waveform (np.ndarray): 1D waveform (or 2D, will be converted to mono).
        sr (int): Sample rate used for insertion duration and timestamps.
        args: object with at least `target_sr` (optional; if missing, `sr` is used).

    Returns:
        waveform_torch (torch.Tensor): shape (1, num_samples)
        silence_infos (str): "start_sec|end_sec;..." for all detected silences
        intermediate_silences (list): List of [start_sec, end_sec] for all silences
    """
    # Ensure 1D mono float32
    waveform = np.asarray(waveform)
    if waveform.ndim == 2:
        if waveform.shape[0] <= waveform.shape[1]:
            waveform = waveform.mean(axis=0)
        else:
            waveform = waveform.mean(axis=1)
    elif waveform.ndim != 1:
        raise ValueError("waveform must be 1D or 2D")
    waveform = waveform.astype(np.float32, copy=False)
    
    frame_length = args.VAD_frame_length
    hop_length = args.VAD_hop_length
    
    silences = detect_silence_segments(
        waveform,
        frame_length=frame_length,
        hop_length=hop_length,
        energy_threshold=args.VAD_energy_threshold,
        min_silence_frames=args.VAD_min_silence_frames
    )
    
    num_frames_waveform = len(waveform)
    
    # Exclude segments touching first/last frame (correct unit: frames)
    if silences:
        n_frames = 1 + (num_frames_waveform - frame_length) // hop_length if num_frames_waveform >= frame_length else 0
    
    used_sr = getattr(args, "target_sr", sr)
    
    silence_infos = "["
    intermediate_silences = []
    
    if len(silences) > 0:
        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]
        max_sil_insertion = max(1, int(num_frames_waveform / sr * args.pause_per_second_ratio))
        
        rand_num_silence = np.random.randint(0, min(max_sil_insertion, len(silences_idx_correct) + 1))
        
        elongate_indices = set()
        if rand_num_silence > 0 and args.silence_insertion == True:
            idx = np.random.choice(len(silences_idx_correct), replace=False, size=rand_num_silence)
            elongate_indices = set(idx)
        
        silences_to_elongate = [(i, silences[i]) for i in elongate_indices 
                                if silences[i][0] != 0 and silences[i][1] != (n_frames - 1)]
        silences_to_elongate = sorted(silences_to_elongate, key=lambda x: x[1][0], reverse=False)
                
        added_duration = 0
        elongated_map = {}
        
        for silence_idx, silence in silences_to_elongate:
            # Calculate the original silence boundaries in samples
            silence_start_sample = silence[0] * hop_length
            silence_end_sample = (silence[1] + 1) * hop_length
            sample_silence_duration = silence_end_sample - silence_start_sample
            
            # Calculate insertion point: end of silence - 2 frames
            insert_sample = silence_end_sample - (2 * hop_length) + added_duration
            
            if args.lam > 0:
                # Generate exp random silence duration
                silence_duration = sample_truncated_exponential(
                    int(args.silence_insertion_min_s * 1000),
                    int(args.silence_insertion_max_s * 1000),
                    args.lam
                )
                silence_duration = int(silence_duration / 1000 * sr)
            else:
                # Generate uniform random silence duration
                silence_duration = int(np.random.randint(
                    sr * args.silence_insertion_min_s, 
                    sr * args.silence_insertion_max_s)
                )
            silence_insert = np.zeros((silence_duration,), dtype=waveform.dtype)
            
            # Insert at end - 2 frames of the silence
            waveform = np.insert(waveform, insert_sample, silence_insert)
            
            # ═══════════════════════════════════════════════════════════════
            # FIX: Store the original start sample for correct timestamp calculation
            # ═══════════════════════════════════════════════════════════════
            elongated_map[silence_idx] = (added_duration, silence_duration, sample_silence_duration, silence_start_sample)
            added_duration += silence_duration
        
        cumulative_added = 0
        for silence_idx in range(len(silences)):
            silence = silences[silence_idx]
            
            if silence_idx in elongated_map:
                # ═══════════════════════════════════════════════════════════════
                # FIX: Calculate timestamps correctly for elongated silences
                # ═══════════════════════════════════════════════════════════════
                # The silence now spans from its original start to its original end + inserted duration
                added_at_this_point, silence_duration, sample_silence_duration, silence_start_sample = elongated_map[silence_idx]
                
                # Start remains at the original silence start (adjusted for previous insertions)
                start_sample = silence_start_sample + added_at_this_point
                # End is original end + inserted silence duration (adjusted for previous insertions)
                end_sample = start_sample + sample_silence_duration + silence_duration
                
                start_t = start_sample / used_sr
                end_t = end_sample / used_sr
                
                silence_infos += f"{start_t:.4f}|{end_t:.4f};"
                intermediate_silences.append([start_t, end_t])
                
                cumulative_added = added_at_this_point + silence_duration
            else:
                # Non-elongated silences
                start_sample = silence[0] * hop_length + cumulative_added
                end_sample = (silence[1] + 1) * hop_length + cumulative_added
                
                start_t = start_sample / used_sr
                end_t = end_sample / used_sr
                
                silence_infos += f"{start_t:.4f}|{end_t:.4f};"
                intermediate_silences.append([start_t, end_t])
    
    silence_infos += "]"
    
    waveform = torch.from_numpy(waveform.astype(np.float32, copy=False)).unsqueeze(0)
    return waveform, silence_infos, intermediate_silences



def add_silence_deprecated(waveform, sr, args):
    """
    Insert random silent chunks at detected silence starts.

    Args:
        waveform (np.ndarray): 1D waveform (or 2D, will be converted to mono).
        sr (int): Sample rate used for insertion duration and timestamps.
        args: object with at least `target_sr` (optional; if missing, `sr` is used).

    Returns:
        waveform_torch (torch.Tensor): shape (1, num_samples)
        silence_infos (str): "start_sec-end_sec$..." for inserted chunks
    """
    # Ensure 1D mono float32
    waveform = np.asarray(waveform)
    if waveform.ndim == 2:
        if waveform.shape[0] <= waveform.shape[1]:
            waveform = waveform.mean(axis=0)
        else:
            waveform = waveform.mean(axis=1)
    elif waveform.ndim != 1:
        raise ValueError("waveform must be 1D or 2D")
    waveform = waveform.astype(np.float32, copy=False)
    
    frame_length = args.VAD_frame_length
    hop_length = args.VAD_hop_length
    
    silences = detect_silence_segments(
        waveform,
        frame_length=frame_length,
        hop_length=hop_length,
        energy_threshold=args.VAD_energy_threshold,
        min_silence_frames=args.VAD_min_silence_frames
    )
    
    # Exclude segments touching first/last frame (correct unit: frames)
    num_frames_waveform = len(waveform)
    if silences:
        n_frames = 1 + (num_frames_waveform - frame_length) // hop_length if num_frames_waveform >= frame_length else 0
    
    used_sr = getattr(args, "target_sr", sr)
    print(len(silences))
    
    silence_infos = "["
    intermediate_silences = []
    if len(silences) > 0:
        pause_per_second_ration = 0.75
        max_sil_insertion = max(1, int(num_frames_waveform / sr * pause_per_second_ration))
        print(max_sil_insertion, num_frames_waveform / sr)
        rand_num_silence = np.random.randint(0, min(max_sil_insertion, len(silences) + 1))
        if rand_num_silence > 0 and args.silence_insertion == True:
            idx = np.random.choice(len(silences), replace=False, size=rand_num_silence)
            random_silences = [silences[i] for i in idx]
            # descending so earlier insertions don't shift later indices
            random_silences = sorted(random_silences, key=lambda x: x[0], reverse=True)
            added_duration = 0
            for silence_idx in range(len(silences)):
                if silence_idx in idx and silences[silence_idx][0] != 0 and silences[silence_idx][1] != (n_frames - 1):
                    # Convert frame index -> sample index
                    silence = silences[silence_idx]
                    insert_sample = (silence[0] + 2) * hop_length + added_duration # +2 to account for frame length
                    sample_silence_duration = (silence[1] + 1) * hop_length - silence[0] * hop_length # +1 to account for strict exclusion

                    silence_duration = int(np.random.randint(sr * args.silence_insertion_min_s, sr * args.silence_insertion_max_s))
                    silence_insert = np.zeros((silence_duration,), dtype=waveform.dtype)

                    waveform = np.insert(waveform, insert_sample, silence_insert)

                    start_t = insert_sample / used_sr
                    end_t = (insert_sample + silence_duration) / used_sr
                    silence_infos += f"{start_t:.6f}|{end_t:.6f};"
                    intermediate_silences.append([insert_sample, (insert_sample + silence_duration + sample_silence_duration)])
                    added_duration += silence_duration
                else:
                    start_t, end_t = (silences[silence_idx][0] + 2) * hop_length + added_duration, (silences[silence_idx][1] + 2) * hop_length + added_duration
                    intermediate_silences.append([start_t, end_t])
        else:
            for silence_idx in range(len(silences)):
                start_t, end_t = (silences[silence_idx][0] + 2) * hop_length, (silences[silence_idx][1] + 2) * hop_length
                intermediate_silences.append([start_t, end_t])
                    
    intermediate_silences = [[x[0] / used_sr, x[1] / used_sr] for x in intermediate_silences]
    silence_infos += "]"

    waveform = torch.from_numpy(waveform.astype(np.float32, copy=False)).unsqueeze(0)
    return waveform, silence_infos, intermediate_silences


def is_sample_in_split(split, sample_split):
    if split == "train":
        if sample_split == "train":
            return True
        else:
            False
    elif split == "dev":
        if sample_split == "dev":
            return True
        else:
            False
            
    elif split == "test":
        if sample_split == "test":
            return True
        else:
            False
    else:
        raise(f"{split} does not exist in the list of dataset splits to process")

def main():
    print("Starting dataset augmentation.")
    args = parse_args()
    save_args_json(args, f'{args.aug_dataset_save_dir}/run_config.json')
    
    os.makedirs(f'{args.aug_dataset_save_dir}/figs', exist_ok=True)
    
    if args.seed is not None:
        random.seed(args.seed)
        np.random.seed(args.seed)
        torch.manual_seed(args.seed)

    if (args.snr_min_db is None) ^ (args.snr_max_db is None):
        raise ValueError("Provide both --snr-min-db and --snr-max-db, or neither.")

    for split in args.splits:

        out_audio_dir_tts = f'{args.aug_dataset_save_dir}/{split}/wav'
        out_vad_dir_tts = f'{args.aug_dataset_save_dir}/{split}/vad_labels'
        out_csv_path = f'{args.aug_dataset_save_dir}/{split}.csv'

        os.makedirs(out_audio_dir_tts, exist_ok=True)
        os.makedirs(out_vad_dir_tts, exist_ok=True)
        os.makedirs(Path(out_csv_path).parent, exist_ok=True)

        noise_files = []
        use_noise = args.add_bg_noise
        if use_noise:
            noise_files = sorted([
                str(p) for p in Path(args.input_noise_dir).glob("**/*")
                if p.suffix.lower() in [".wav", ".flac", ".mp3", ".ogg"]
                and "speech" not in str(p)
            ])
            if len(noise_files) == 0:
                raise RuntimeError("No noise files found.")

        speech_files = []
        manifest_dir = f'{args.manifest_dir}'
        speech_files = process_manifest(manifest_dir, args.taskmaster_root_dir, speech_files, args)

        rows = []
        for i, speech_sample in enumerate(tqdm(speech_files, desc=f"Processing {split}", unit="file")):
            if is_sample_in_split(split, speech_sample["split"]):
                speech_path = speech_sample["wav_dir"]
                base = Path(speech_path).stem
                out_audio_path = os.path.join(out_audio_dir_tts, f"{i:06d}_aug_{base}.wav")

                if os.path.exists(out_audio_path):
                    print("already exist")
                    continue

                speech = load_mono_resampled(speech_path, args.target_sr)
                speech, silence_infos, intermediate_silences = add_silence(speech, args.target_sr, args)
                
                T_speech = speech.shape[1]

                start_sil_s = random.uniform(args.silence_min_start, args.silence_max_start)
                end_sil_s = random.uniform(args.silence_min_end, args.silence_max_end)
                intermediate_silences = [[intermediate_silences[x][0] + start_sil_s, intermediate_silences[x][1] + start_sil_s] for x in range(len(intermediate_silences))]

                T_start = int(round(start_sil_s * args.target_sr))
                T_end = int(round(end_sil_s * args.target_sr))

                start_sil = torch.zeros((1, T_start), dtype=speech.dtype)
                end_sil = torch.zeros((1, T_end), dtype=speech.dtype)

                clean_aug = torch.cat([start_sil, speech, end_sil], dim=1)
                T_total = clean_aug.shape[1]

                vad_label, start_eot_idx = vad_labels_from_interval(
                    num_samples=T_total,
                    sr=args.target_sr,
                    speech_start=T_start / args.target_sr,
                    speech_end=(T_start + T_speech) / args.target_sr,
                    frame_hop_s=args.frame_hop_s,
                    frame_len_s=args.frame_len_s,
                    intermediate_silences=intermediate_silences,
                )
                
                is_syntethic = 1 if "tts" in speech_path or "train" in speech_path else 0

                base = Path(speech_path).stem
                out_audio_path = os.path.join(out_audio_dir_tts, f"aug_{i:06d}_{base}.wav")
                out_audio_noise_path = os.path.join(out_audio_dir_tts, f"aug_{i:06d}_{base}_noise.wav")
                out_vad_path = os.path.join(out_vad_dir_tts, f"aug_{i:06d}_{base}_vad.pt")


                noisy_aug = clean_aug.clone()
                noise_path = None
                if args.add_bg_noise and split != "train":
                    noise_path = random.choice(noise_files)
                    noise = load_mono_resampled(noise_path, args.target_sr)
                    noise = fit_noise_length(noise, T_total)

                    snr_db = random.uniform(args.snr_min_db, args.snr_max_db)
                    noisy_aug = mix_with_snr(noisy_aug, noise, snr_db)
                    
                if args.add_white_noise and split != "train":

                    snr_db = random.uniform(args.snr_min_db, args.snr_max_db)
                    white = torch.randn_like(clean_aug)
                    
                    noisy_aug = mix_with_snr(clean_aug, white, snr_db)
                                
                if args.add_white_noise or args.add_bg_noise:
                    if split != "train":
                        noisy_np = noisy_aug.squeeze(0).cpu().numpy().astype(np.float32)
                        sf.write(out_audio_noise_path, noisy_np, args.target_sr)
                        
                        rows.append({
                            "ID": f"aug_{i:06d}_{base}_noise",
                            "orig_speech_path": speech_path,
                            "noise_path": noise_path,
                            "wav": out_audio_noise_path,
                            "vad": out_vad_path,
                            "sample_rate": args.target_sr,
                            "speech_num_samples": T_speech,
                            "start_eot": start_eot_idx,
                            "start_eot_time": start_eot_idx * 0.04,
                            "start_silence_s": start_sil_s,
                            "end_silence_s": end_sil_s,
                            "start_silence_samples": T_start,
                            "end_silence_samples": T_end,
                            "total_num_samples": T_total,
                            "duration": T_total / args.target_sr,
                            "snr_db": snr_db,
                            "speech_start_sample": T_start,
                            "speech_end_sample_exclusive": T_start + T_speech,
                            "wrd": speech_sample["text"],
                            "dialog_id": speech_sample["dialog_id"],
                            "turn_id": speech_sample["turn_id"],
                            "split": speech_sample["split"],
                            "audio_id": speech_sample["audio_id"],
                            "is_syntethic": is_syntethic,
                            "silence_infos": silence_infos,
                            "white_noise": args.add_white_noise,
                            "bg_noise": args.add_bg_noise
                        })
                
                noise_path = None
                snr_db = None
                clean_aug_np = clean_aug.squeeze(0).cpu().numpy().astype(np.float32)
                sf.write(out_audio_path, clean_aug_np, args.target_sr)
                rows.append({
                    "ID": f"aug_{i:06d}_{base}",
                    "orig_speech_path": speech_path,
                    "noise_path": noise_path,
                    "wav": out_audio_path,
                    "vad": out_vad_path,
                    "sample_rate": args.target_sr,
                    "speech_num_samples": T_speech,
                    "start_eot": start_eot_idx,
                    "start_eot_time": start_eot_idx * 0.04,
                    "start_silence_s": start_sil_s,
                    "end_silence_s": end_sil_s,
                    "start_silence_samples": T_start,
                    "end_silence_samples": T_end,
                    "total_num_samples": T_total,
                    "duration": T_total / args.target_sr,
                    "snr_db": None,
                    "speech_start_sample": T_start,
                    "speech_end_sample_exclusive": T_start + T_speech,
                    "wrd": speech_sample["text"],
                    "dialog_id": speech_sample["dialog_id"],
                    "turn_id": speech_sample["turn_id"],
                    "split": speech_sample["split"],
                    "audio_id": speech_sample["audio_id"],
                    "is_syntethic": is_syntethic,
                    "silence_infos": silence_infos,
                    "white_noise": False,
                    "bg_noise": False
                })

                torch.save(vad_label, out_vad_path)

        fieldnames = list(rows[0].keys()) if rows else []
        with open(out_csv_path, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(rows)

        print(f"[{split}] Done. Processed {len(rows)} files.")
        print(f"[{split}] Metadata CSV: {out_csv_path}")
    

if __name__ == "__main__":
    main()