acoustic_context_switching / run_samples_acous.py
Taejin's picture
Adding the first version of data
132e1cd
# 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')