import csv as csv_module import json from pathlib import Path import tqdm ROOT = "./labels" ANNOTATION_FREQ = 100 # ms per frame LABEL_MAPPING = { "0": "Female speech", "1": "Male speech", "2": "Clapping", "3": "Telephone", "4": "Laughter", "5": "Domestic sounds", "6": "Footsteps", "7": "Door", "8": "Music", "9": "Musical instrument", "10": "Water tap", "11": "Bell", "12": "Knock", } def get_csvs(root): metadata_root = Path(root) assert metadata_root.exists(), "Metadata root does not exist" metadata_files = list(sorted(metadata_root.glob("*/*.csv"))) splits = {} for file in metadata_files: file = str(file.absolute()) file_name, folder = file.split("/")[-1].replace(".csv", ""), file.split("/")[-2] splits.setdefault(folder, []).append(file_name) assert len(metadata_files) > 0, "Folder does not contain any csv files" return metadata_files, splits def process_csv(csv_path): path = Path(csv_path) assert path.exists(), f"CSV Path {csv_path} does not exist" # Load all rows from CSV and group by label (ignoring source) data = [] with open(path, newline='') as csvfile: reader = csv_module.reader(csvfile, delimiter=',') for row in reader: if len(row) >= 2: # At minimum we need frame and class frame_idx = int(row[0]) class_idx = int(row[1]) label = LABEL_MAPPING[str(class_idx)] data.append({ "label": label, "start": float(frame_idx * ANNOTATION_FREQ), "end": float((frame_idx + 1) * ANNOTATION_FREQ) }) return data def map_to_splits(audios, fold_to_split): fold_data = {k : {} for k in fold_to_split} for k, file_names in fold_to_split.items(): for file_name in file_names: fold_data[k][file_name + ".wav"] = audios[file_name] return fold_data if __name__ == "__main__": csvs, splits = get_csvs(ROOT) folds = {} for i in tqdm.tqdm(csvs): file_name = i.stem folds[file_name] = process_csv(i) json_files = map_to_splits(folds, splits) done = set() for data in splits.keys(): if data in done: continue with open(data + ".json", "w") as js_file: json.dump(json_files[data], js_file, indent=4) done.add(data)