File size: 27,628 Bytes
132e1cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

# 3️⃣ Initalize a pipeline
from kokoro import KPipeline
from IPython.display import display, Audio
import soundfile as sf
import torch
import numpy as np
from scipy import signal
import os
import json
from pathlib import Path
from tqdm import tqdm
# 🇺🇸 'a' => American English, 🇬🇧 'b' => British English
# 🇪🇸 'e' => Spanish es
# 🇫🇷 'f' => French fr-fr
# 🇮🇳 'h' => Hindi hi
# 🇮🇹 'i' => Italian it
# 🇯🇵 'j' => Japanese: pip install misaki[ja]
# 🇧🇷 'p' => Brazilian Portuguese pt-br
# 🇨🇳 'z' => Mandarin Chinese: pip install misaki[zh]


# Create random generators for RIR and white noise files
import random
random.seed(42)


def get_random_rir_generator(simulated_rirs_dict):
    """Generator that yields random RIR file paths from the simulated_rirs_dict"""
    rir_paths = list(simulated_rirs_dict.keys())
    while True:
        yield random.choice(rir_paths)

def get_random_white_noise_generator(white_noise_dict):
    """Generator that yields random white noise file paths from the white_noise_dict"""
    white_noise_paths = list(white_noise_dict.keys())
    while True:
        yield random.choice(white_noise_paths)


def load_manifest_file(manifest_path):
    """
    Load a JSONL manifest file into a dictionary.
    
    Args:
        manifest_path (str): Path to the JSONL manifest file
    
    Returns:
        dict: Dictionary with audio filepath as key and metadata as value
    """
    manifest_dict = {}
    
    try:
        with open(manifest_path, 'r') as f:
            for line_num, line in enumerate(f, 1):
                line = line.strip()
                if line:  # Skip empty lines
                    try:
                        entry = json.loads(line)
                        audio_filepath = entry.get('audio_filepath')
                        if audio_filepath:
                            manifest_dict[audio_filepath] = entry
                        else:
                            print(f"Warning: Line {line_num} missing audio_filepath")
                    except json.JSONDecodeError as e:
                        print(f"Warning: Invalid JSON on line {line_num}: {e}")
                        continue
        
        print(f"Successfully loaded {len(manifest_dict)} entries from {manifest_path}")
        return manifest_dict
    
    except FileNotFoundError:
        print(f"Error: Manifest file not found: {manifest_path}")
        return {}
    except Exception as e:
        print(f"Error loading manifest file {manifest_path}: {e}")
        return {}

def load_rirs_manifests(simulated_rirs_path="/disk_a_nvd/datasets/RIRS_NOISES/simulated_rirs.json", 
                        white_noise_path="/disk_a_nvd/datasets/RIRS_NOISES/white_noise.json"
                        ):
    """
    Load both RIRS_NOISES manifest files into dictionaries.
    
    Args:
        simulated_rirs_path (str): Path to the simulated RIRs manifest file
        white_noise_path (str): Path to the white noise manifest file
    
    Returns:
        tuple: (simulated_rirs_dict, white_noise_dict)
    """
    simulated_rirs_dict = load_manifest_file(simulated_rirs_path)
    white_noise_dict = load_manifest_file(white_noise_path)
    
    return simulated_rirs_dict, white_noise_dict

def apply_perturb(input_wav_file_path, rir_wav_path, noise_wav_path, noise_scale_factor=3.0, output_sr=16000):
    """
    Apply Room Impulse Response (RIR) and optionally noise to an audio file.
    
    Args:
        input_wav_file_path (str): Path to the input audio file
        rir_wav_path (str): Path to the RIR file
        noise_wav_path (str, optional): Path to the noise file
    
    Returns:
        str: Path to the output file with RIR and noise applied
    """
    # Load input audio and use first channel if multichannel
    input_audio, input_sr = sf.read(input_wav_file_path)
    if len(input_audio.shape) > 1:
        input_audio = input_audio[:, 0]
    
    # Load RIR and use first channel if multichannel
    rir_audio, rir_sr = sf.read(rir_wav_path)
    if len(rir_audio.shape) > 1:
        rir_audio = rir_audio[:, 0]
    
    # Ensure both audio files have the same sample rate
    if input_sr != rir_sr:
        print(f"Warning: Sample rate mismatch. Input: {input_sr}Hz, RIR: {rir_sr}Hz")
        # Resample RIR to match input sample rate if needed
        if rir_sr != input_sr:
            # Simple resampling - in production you might want to use librosa.resample
            rir_audio = signal.resample(rir_audio, int(len(rir_audio) * input_sr / rir_sr))
    
    # Apply RIR convolution
    output_audio = signal.convolve(input_audio, rir_audio, mode='full')
    
    # Apply noise if provided
    if noise_wav_path is not None:
        try:
            # Load noise audio and use first channel if multichannel
            noise_audio, noise_sr = sf.read(noise_wav_path)
            if len(noise_audio.shape) > 1:
                noise_audio = noise_audio[:, 0]
            
            # Resample noise if needed
            if noise_sr != input_sr:
                noise_audio = signal.resample(noise_audio, int(len(noise_audio) * input_sr / noise_sr))
            
            # Ensure noise is the same length as output_audio
            if len(noise_audio) < len(output_audio):
                # Repeat noise if it's shorter
                repeats_needed = int(np.ceil(len(output_audio) / len(noise_audio)))
                noise_audio = np.tile(noise_audio, repeats_needed)
            
            # Trim noise to match output_audio length
            noise_audio = noise_audio[:len(output_audio)]
            
            # Add noise to output audio
            noise_scale = noise_scale_factor * np.max(np.abs(output_audio))
            output_audio += noise_scale * noise_audio
            
            
        except Exception as e:
            raise SyntaxError(f"Error: Could not apply noise from {noise_wav_path}: {e}")
    
    # Normalize the output audio
    max_val = np.max(np.abs(output_audio))
    if max_val > 0:
        output_audio = output_audio / max_val * 0.95  # Scale to 95% to avoid clipping
    
    # Create output filename with RIR and noise information
    input_path = Path(input_wav_file_path)
    rir_path = Path(rir_wav_path)
    rir_name = rir_path.stem  # Get filename without extension
    
    if noise_wav_path is not None:
        noise_path = Path(noise_wav_path)
        noise_name = "_".join(noise_path.stem.split("_")[-2:])
        output_filename = f"{input_path.stem}_R_{rir_name}_N_{noise_name}{input_path.suffix}"
    else:
        output_filename = f"{input_path.stem}_R_{rir_name}{input_path.suffix}"


    # Make this absolute path
    output_path = f"{input_path.parent}/{output_filename}"
    output_path = os.path.abspath(output_path)
    
    # Save the processed audio
    # Resample to output_sr
    output_audio = signal.resample(output_audio, int(len(output_audio) * output_sr / input_sr))
    sf.write(str(output_path), output_audio, output_sr)
    
    # print(f"Perturbation applied successfully. Output saved as: {output_path}")

    return output_audio, str(output_path)


def concat_with_fo_fi(audio1, audio2, sr=16000, transition_time=0.2):
    """
    Concatenate two audio arrays with fade out on the first and fade in on the second.
    
    Args:
        audio1 (np.array): First audio array
        audio2 (np.array): Second audio array
        sr (int): Sample rate
        transition_time (float): Transition time in seconds
    
    Returns:
        np.array: Concatenated audio with smooth transition
    """
    # Calculate transition samples
    transition_samples = int(transition_time * sr)
    
    # Ensure transition_samples doesn't exceed audio length
    transition_samples = min(transition_samples, len(audio1), len(audio2))
    
    # Create fade out for audio1 (last transition_samples)
    fade_out = np.linspace(1.0, 0.0, transition_samples)
    audio1_faded = audio1.copy()
    audio1_faded[-transition_samples:] *= fade_out
    
    # Create fade in for audio2 (first transition_samples)
    fade_in = np.linspace(0.0, 1.0, transition_samples)
    audio2_faded = audio2.copy()
    audio2_faded[:transition_samples] *= fade_in
    
    # Concatenate the audio
    # audio1 without the last transition_samples + audio2 without the first transition_samples
    audio1_part = audio1_faded[:-transition_samples]
    audio2_part = audio2_faded[transition_samples:]
    
    # Concatenate
    concatenated = np.concatenate([audio1_part, audio2_part])
    
    return concatenated


def get_manifest_entry(audio_filepath, text, label="infer", num_speakers=1, rttm_filepath=None, uem_filepath=None, ctm_filepath=None):
    # {"audio_filepath": "/disk_a_nvd/datasets/RIRS_NOISES/real_rirs_isotropic_noises/RVB2014_type1_noise_largeroom1_3.wav", "offset": 0, "duration": null, "label": "infer", "text": "-", "num_speakers": null, "rttm_filepath": null, "uem_filepath": null, "ctm_filepath": null}
    # Get the duration of the audio file
    audio_duration = sf.SoundFile(audio_filepath).frames / sf.SoundFile(audio_filepath).samplerate
    duration_in_seconds = round(audio_duration, 2)


    # make all the paths absolute
    audio_filepath = os.path.abspath(audio_filepath)
    rttm_filepath = os.path.abspath(rttm_filepath)

    return {
        "audio_filepath": audio_filepath,
        "offset": 0,
        "duration": duration_in_seconds,
        "label": label,
        "text": text,
        "num_speakers": num_speakers,
        "rttm_filepath": rttm_filepath,
        "uem_filepath": uem_filepath,
        "ctm_filepath": ctm_filepath,
        "source_lang": "en",
        "target_lang": "en",
        "pnc": "no",
        "timestamp": "no",
    }

def make_single_speaker_rttm(uniq_id, audio_filepath, rttm_filepath, speaker_name):
    """
    SPEAKER {uniq_id} 0 {duration:.3f} <NA> <NA> {speaker_name} <NA> <NA>
    """ 
    # Load audio file
    audio, sr = sf.read(audio_filepath)
    duration = len(audio) / sr

    # Create RTTM file
    with open(rttm_filepath, 'w') as f:
        f.write(f"SPEAKER {uniq_id} 0.0 {duration:.3f} <NA> <NA> {speaker_name} <NA> <NA>\n")

def make_two_speaker_rttm(uniq_id, audio_filepath_A, audio_filepath_B, rttm_filepath, speaker_A, speaker_B):
    """
    # SPEAKER iapb 0 0 3.26 <NA> <NA> speaker_A <NA> <NA>
    # SPEAKER iapb 0 3.26 0.42 <NA> <NA> speaker_B <NA> <NA>
    """ 
    # Load audio file
    audio_A, sr = sf.read(audio_filepath_A)
    duration_A = len(audio_A) / sr
    
    audio_B, sr = sf.read(audio_filepath_B)
    duration_B = len(audio_B) / sr

    # Create RTTM file
    with open(rttm_filepath, 'w') as f:
        # for i in range(num_speakers):
        f.write(f"SPEAKER {uniq_id} 1 0.0 {duration_A:.3f} <NA> <NA> {speaker_A} <NA> <NA>\n")
        f.write(f"SPEAKER {uniq_id} 1 {duration_A:.3f} {duration_B:.3f} <NA> <NA> {speaker_B} <NA> <NA>\n")


pipeline = KPipeline(lang_code='a') # <= make sure lang_code matches voice, reference above.

# This text is for demonstration purposes only, unseen during training
# text = '''
# The sky above the port was the color of television, tuned to a dead channel.
# "It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd around the door of the Chat. "It's like my body's developed this massive drug deficiency."
# It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates; you could drink there for a week and never hear two words in Japanese.

# These were to have an enormous impact, not only because they were associated with Constantine, but also because, as in so many other areas, the decisions taken by Constantine (or in his name) were to have great significance for centuries to come. One of the main issues was the shape that Christian churches were to take, since there was not, apparently, a tradition of monumental church buildings when Constantine decided to help the Christian church build a series of truly spectacular structures. The main form that these churches took was that of the basilica, a multipurpose rectangular structure, based ultimately on the earlier Greek stoa, which could be found in most of the great cities of the empire. Christianity, unlike classical polytheism, needed a large interior space for the celebration of its religious services, and the basilica aptly filled that need. We naturally do not know the degree to which the emperor was involved in the design of new churches, but it is tempting to connect this with the secular basilica that Constantine completed in the Roman forum (the so-called Basilica of Maxentius) and the one he probably built in Trier, in connection with his residence in the city at a time when he was still caesar.

# [Kokoro](/kˈOkəɹO/) is an open-weight TTS model with 82 million parameters. Despite its lightweight architecture, it delivers comparable quality to larger models while being significantly faster and more cost-efficient. With Apache-licensed weights, [Kokoro](/kˈOkəɹO/) can be deployed anywhere from production environments to personal projects.
# '''
# text = '「もしおれがただ偶然、そしてこうしようというつもりでなくここに立っているのなら、ちょっとばかり絶望するところだな」と、そんなことが彼の頭に思い浮かんだ。'
# text = '中國人民不信邪也不怕邪,不惹事也不怕事,任何外國不要指望我們會拿自己的核心利益做交易,不要指望我們會吞下損害我國主權、安全、發展利益的苦果!'
# text = 'Los partidos políticos tradicionales compiten con los populismos y los movimientos asamblearios.'
# text = 'Le dromadaire resplendissant déambulait tranquillement dans les méandres en mastiquant de petites feuilles vernissées.'
# text = 'ट्रांसपोर्टरों की हड़ताल लगातार पांचवें दिन जारी, दिसंबर से इलेक्ट्रॉनिक टोल कलेक्शनल सिस्टम'
# text = "Allora cominciava l'insonnia, o un dormiveglia peggiore dell'insonnia, che talvolta assumeva i caratteri dell'incubo."
# text = 'Elabora relatórios de acompanhamento cronológico para as diferentes unidades do Departamento que propõem contratos.'
text_list_A = [
    "She sells sea shells by the seashore while subtly shifting sapphire souvenirs.",
    "The anthropologist's anecdote about antediluvian artifacts was astonishingly ambiguous.",
    "I scream, you scream, we all scream for ice cream, especially when it's free.",
    "Their heir apparently inherited an eerily empty estate.",
    "Can you can a can as a canner can can a can?",
    "The lead violinist led the lead singer through a leaden performance.",
    "Fred fed Ted bread, and Ted fed Fred bread.",
    "I thought a thought but the thought I thought wasn't the thought I thought I thought.",
    "How can a clam cram in a clean cream can?",
    "Six slippery snails slid slowly seaward.",
    "I slit the sheet, the sheet I slit, and on the slitted sheet I sit.",
    "Lesser leather never weathered wetter weather better."
]
text_list_B = text_list_A[::-1]

# Filtered speaker list - Top 20 speakers with gender balance (10 female, 10 male)
# Selected based on quality grades: A, A-, B, B-, C+
speaker_list = [
    # Female speakers (10) - American English
    "af_heart",    # A grade
    "af_bella",    # A- grade
    "af_nicole",   # B- grade
    "af_aoede",    # C+ grade
    "af_kore",     # C+ grade
    "af_sarah",    # C+ grade
    # Female speakers (2) - British English
    "bf_emma",     # B- grade
    "bf_isabella", # C grade
    # Male speakers (8) - American English
    "am_fenrir",   # C+ grade
    "am_michael",  # C+ grade
    "am_puck",     # C+ grade
    "am_echo",     # D grade (included for balance)
    "am_eric",     # D grade (included for balance)
    "am_liam",     # D grade (included for balance)
    # Male speakers (2) - British English
    "bm_fable",    # B grade
    "bm_george",   # B grade
]


# RIR file path
simulated_rir_manifest_path = "/disk_a_nvd/datasets/RIRS_NOISES/simulated_rirs.json"
white_noise_manifest_path = "/disk_a_nvd/datasets/RIRS_NOISES/white_noise.json"

simulated_rirs_dict, white_noise_dict = load_rirs_manifests(simulated_rir_manifest_path, white_noise_manifest_path)

# Initialize generators
rir_generator = get_random_rir_generator(simulated_rirs_dict)
white_noise_generator = get_random_white_noise_generator(white_noise_dict)

speech_speed = 1.3

base_folder_name = "utt_samples"
shift_left = 15
speaker_list_A = speaker_list
speaker_list_B = speaker_list_A[shift_left:] + speaker_list_A[:shift_left]

# matched_speaker_mode = True
matched_speaker_mode = False
folder_name = base_folder_name + "_matched" if matched_speaker_mode else base_folder_name + "_unmatched"

# If path does not exist, create it (exists okay)
os.makedirs(folder_name, exist_ok=True)

if matched_speaker_mode:
    num_speakers = 1
else:
    num_speakers = 2


indiv_text_manifest_clean = []
indiv_text_manifest_clean_perturbed = []
indiv_text_manifest_perturbed_clean = []
indiv_text_manifest_perturbed = []
pair_text_manifest_Ac_Bc = []
pair_text_manifest_Ac_Bp = []
pair_text_manifest_Ap_Bc = []
pair_text_manifest_Ap_Bp = []

count = 0
total_speakers = len(speaker_list_A)  # Since we break after count > 2, max is 3
for speaker_A, speaker_B in tqdm(zip(speaker_list_A, speaker_list_B), total=total_speakers, desc="Processing speakers"):

    # if count > 2:
    #     break
    
    count += 1

    if matched_speaker_mode:
        speaker_B = speaker_A

    generator_A = pipeline(
        text_list_A, voice=speaker_A, # <= use current speaker from loop
        speed=speech_speed, split_pattern=r'\n+'
    )
    generator_B = pipeline(
        text_list_B, voice=speaker_B, # <= use current speaker from loop
        speed=speech_speed, split_pattern=r'\n+'
    )
    text_data_size = len(text_list_A)
    text_data_size_B = len(text_list_B)
    assert text_data_size == text_data_size_B, "Text data size mismatch"
    
    for idx, ((gs_text_A, ps_A, audio_A), (gs_text_B, ps_B, audio_B)) in tqdm(enumerate(zip(generator_A, generator_B)), total=text_data_size, desc=f"Processing {speaker_A} vs {speaker_B}", leave=False):

        # zfill the indices to 2 digits
        A_idx = idx
        B_idx = str(text_data_size - A_idx - 1).zfill(2)
        A_idx = str(A_idx).zfill(2)

        # Get random RIR and white noise file paths
        rir_wav_path = next(rir_generator)
        noise_wav_path = next(white_noise_generator)
        
        # print(f"Using RIR: {rir_wav_path}")
        # print(f"Using white noise: {noise_wav_path}")

        sub_folder_name = f"A_text{A_idx}_{speaker_A}_B_text{B_idx}_{speaker_B}"

        os.makedirs(f"{folder_name}/{sub_folder_name}", exist_ok=True)
        
        # Process audio from generator A
        uniq_id_a = f"A_text{A_idx}_{speaker_A}"
        original_filename_A = f'{folder_name}/{sub_folder_name}/{uniq_id_a}.wav'
        # Resample audio to 16000 Hz
        audio_A_16k = signal.resample(audio_A, int(len(audio_A) * 16000 / 24000))
        sf.write(original_filename_A, audio_A_16k, 16000)
        
        # Apply RIR and noise to the generated audio A
        try:
            perturbed_audio_A_16k, perturbed_audio_A_16k_path = apply_perturb(original_filename_A, rir_wav_path, noise_wav_path)
        except Exception as e:
            print(f"Error applying perturbation to {original_filename_A}: {e}")
        
        # Process audio from generator B
        uniq_id_b = f"B_text{B_idx}_{speaker_B}"
        original_filename_B = f'{folder_name}/{sub_folder_name}/{uniq_id_b}.wav'
        audio_B_16k = signal.resample(audio_B, int(len(audio_B) * 16000 / 24000))
        sf.write(original_filename_B, audio_B_16k, 16000)
        
        # Apply RIR and noise to the generated audio B
        try:
            perturbed_audio_B_16k, perturbed_audio_B_16k_path = apply_perturb(original_filename_B, rir_wav_path, noise_wav_path)
        except Exception as e:
            print(f"Error applying perturbation to {original_filename_B}: {e}")

        pair_gt_text = f"{gs_text_A} {gs_text_B}"
        uniq_id_pair = f"{uniq_id_a}_{uniq_id_b}"
        uniq_id_pair_Ac_Bc = f"{uniq_id_a}_Ac_Bc"
        uniq_id_pair_Ac_Bp = f"{uniq_id_a}_Ac_Bp"
        uniq_id_pair_Ap_Bc = f"{uniq_id_a}_Ap_Bc"
        uniq_id_pair_Ap_Bp = f"{uniq_id_a}_Ap_Bp"

        # {"audio_filepath": "/disk_a_nvd/datasets/RIRS_NOISES/real_rirs_isotropic_noises/RVB2014_type1_noise_largeroom1_3.wav", "offset": 0, "duration": null, "label": "infer", "text": "-", "num_speakers": null, "rttm_filepath": null, "uem_filepath": null, "ctm_filepath": null}

        uniq_id_a_perturbed = Path(perturbed_audio_A_16k_path).stem
        uniq_id_b_perturbed = Path(perturbed_audio_B_16k_path).stem

        rttm_path_A = f"{folder_name}/{sub_folder_name}/{uniq_id_a}.rttm"
        rttm_path_B = f"{folder_name}/{sub_folder_name}/{uniq_id_b}.rttm"
        rttm_path_A_perturbed = f"{folder_name}/{sub_folder_name}/{uniq_id_a_perturbed}.rttm"
        rttm_path_B_perturbed = f"{folder_name}/{sub_folder_name}/{uniq_id_b_perturbed}.rttm"

        make_single_speaker_rttm(uniq_id_a, original_filename_A, rttm_path_A, speaker_A)
        make_single_speaker_rttm(uniq_id_b, original_filename_B, rttm_path_B, speaker_B)
        make_single_speaker_rttm(uniq_id_a_perturbed, perturbed_audio_A_16k_path, rttm_path_A_perturbed, speaker_A)
        make_single_speaker_rttm(uniq_id_b_perturbed, perturbed_audio_B_16k_path, rttm_path_B_perturbed, speaker_B)

        rttm_path_pair_Ac_Bc = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ac_Bc.rttm"
        rttm_path_pair_Ac_Bp = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ac_Bp.rttm"
        rttm_path_pair_Ap_Bc = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ap_Bc.rttm"
        rttm_path_pair_Ap_Bp = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ap_Bp.rttm"

        make_two_speaker_rttm(uniq_id_pair_Ac_Bc, original_filename_A, original_filename_B, rttm_path_pair_Ac_Bc, speaker_A, speaker_B)
        make_two_speaker_rttm(uniq_id_pair_Ac_Bp, original_filename_A, perturbed_audio_B_16k_path, rttm_path_pair_Ac_Bp, speaker_A, speaker_B)
        make_two_speaker_rttm(uniq_id_pair_Ap_Bc, perturbed_audio_A_16k_path, original_filename_B, rttm_path_pair_Ap_Bc, speaker_A, speaker_B)
        make_two_speaker_rttm(uniq_id_pair_Ap_Bp, perturbed_audio_A_16k_path, perturbed_audio_B_16k_path, rttm_path_pair_Ap_Bp, speaker_A, speaker_B)

        # Concatenate wav files for 4 different combinations (uniq_id_pair)
        Ac_Bc_filename = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ac_Bc.wav"
        Ac_Bp_filename = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ac_Bp.wav"
        Ap_Bc_filename = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ap_Bc.wav"
        Ap_Bp_filename = f"{folder_name}/{sub_folder_name}/{uniq_id_pair}_Ap_Bp.wav"


        # Concatenate wav files with fade out/fade in transitions
        Ac_Bc_audio = concat_with_fo_fi(audio_A_16k, audio_B_16k)
        Ac_Bp_audio = concat_with_fo_fi(audio_A_16k, perturbed_audio_B_16k)
        Ap_Bc_audio = concat_with_fo_fi(perturbed_audio_A_16k, audio_B_16k)
        Ap_Bp_audio = concat_with_fo_fi(perturbed_audio_A_16k, perturbed_audio_B_16k)

        sf.write(Ac_Bc_filename, Ac_Bc_audio, 16000)
        sf.write(Ac_Bp_filename, Ac_Bp_audio, 16000)
        sf.write(Ap_Bc_filename, Ap_Bc_audio, 16000)
        sf.write(Ap_Bp_filename, Ap_Bp_audio, 16000)

        indiv_text_manifest_clean.append(get_manifest_entry(original_filename_A, text=gs_text_A, num_speakers=1, rttm_filepath=rttm_path_A, uem_filepath=None, ctm_filepath=None))
        indiv_text_manifest_clean.append(get_manifest_entry(original_filename_B, text=gs_text_B, num_speakers=1, rttm_filepath=rttm_path_B, uem_filepath=None, ctm_filepath=None))

        indiv_text_manifest_clean_perturbed.append(get_manifest_entry(original_filename_A, text=gs_text_A, num_speakers=1, rttm_filepath=rttm_path_A, uem_filepath=None, ctm_filepath=None))
        indiv_text_manifest_clean_perturbed.append(get_manifest_entry(perturbed_audio_B_16k_path, text=gs_text_B, num_speakers=1, rttm_filepath=rttm_path_B_perturbed, uem_filepath=None, ctm_filepath=None))

        indiv_text_manifest_perturbed_clean.append(get_manifest_entry(perturbed_audio_A_16k_path, text=gs_text_A, num_speakers=1, rttm_filepath=rttm_path_A_perturbed, uem_filepath=None, ctm_filepath=None))
        indiv_text_manifest_perturbed_clean.append(get_manifest_entry(original_filename_B, text=gs_text_B, num_speakers=1, rttm_filepath=rttm_path_B, uem_filepath=None, ctm_filepath=None))

        indiv_text_manifest_perturbed.append(get_manifest_entry(perturbed_audio_A_16k_path, text=gs_text_A, num_speakers=1, rttm_filepath=rttm_path_A_perturbed, uem_filepath=None, ctm_filepath=None))
        indiv_text_manifest_perturbed.append(get_manifest_entry(perturbed_audio_B_16k_path, text=gs_text_B, num_speakers=1, rttm_filepath=rttm_path_B_perturbed, uem_filepath=None, ctm_filepath=None))
        
        pair_text_manifest_Ac_Bc.append(get_manifest_entry(Ac_Bc_filename, text=pair_gt_text, num_speakers=num_speakers, rttm_filepath=rttm_path_pair_Ac_Bc, uem_filepath=None, ctm_filepath=None))
        pair_text_manifest_Ac_Bp.append(get_manifest_entry(Ac_Bp_filename, text=pair_gt_text, num_speakers=num_speakers, rttm_filepath=rttm_path_pair_Ac_Bp, uem_filepath=None, ctm_filepath=None))
        pair_text_manifest_Ap_Bc.append(get_manifest_entry(Ap_Bc_filename, text=pair_gt_text, num_speakers=num_speakers, rttm_filepath=rttm_path_pair_Ap_Bc, uem_filepath=None, ctm_filepath=None))
        pair_text_manifest_Ap_Bp.append(get_manifest_entry(Ap_Bp_filename, text=pair_gt_text, num_speakers=num_speakers, rttm_filepath=rttm_path_pair_Ap_Bp, uem_filepath=None, ctm_filepath=None))

    # Delete all the json files and overwrite
    for file in os.listdir(folder_name):
        if file.endswith('.json'):
            os.remove(os.path.join(folder_name, file))

    # Write to json files   f'{folder_name}'
    # Overwrite the json files
    with open(f'{folder_name}/indiv_text_manifest_clean.json', 'w') as f:
        for entry in indiv_text_manifest_clean:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/indiv_text_manifest_perturbed.json', 'w') as f:
        for entry in indiv_text_manifest_perturbed:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/indiv_text_manifest_clean_perturbed.json', 'w') as f:
        for entry in indiv_text_manifest_clean_perturbed:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/indiv_text_manifest_perturbed_clean.json', 'w') as f:
        for entry in indiv_text_manifest_perturbed_clean:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/pair_text_manifest_Ac_Bc.json', 'w') as f:
        for entry in pair_text_manifest_Ac_Bc:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/pair_text_manifest_Ac_Bp.json', 'w') as f:
        for entry in pair_text_manifest_Ac_Bp:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/pair_text_manifest_Ap_Bc.json', 'w') as f:
        for entry in pair_text_manifest_Ap_Bc:
            f.write(json.dumps(entry) + '\n')
    with open(f'{folder_name}/pair_text_manifest_Ap_Bp.json', 'w') as f:
        for entry in pair_text_manifest_Ap_Bp:
            f.write(json.dumps(entry) + '\n')