|
|
import csv as csv_module |
|
|
import json |
|
|
from pathlib import Path |
|
|
import tqdm |
|
|
|
|
|
ROOT = "./labels" |
|
|
ANNOTATION_FREQ = 100 |
|
|
|
|
|
LABEL_MAPPING = { |
|
|
"0": "alarm", |
|
|
"1": "crying baby", |
|
|
"2": "crash", |
|
|
"3": "barking dog", |
|
|
"4": "female scream", |
|
|
"5": "female speech", |
|
|
"6": "footsteps", |
|
|
"7": "knocking on door", |
|
|
"8": "male scream", |
|
|
"9": "male speech", |
|
|
"10": "ringing phone", |
|
|
"11": "piano" |
|
|
} |
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
label_frames = {} |
|
|
with open(path, newline='') as csvfile: |
|
|
reader = csv_module.reader(csvfile, delimiter=',') |
|
|
for row in reader: |
|
|
if len(row) >= 2: |
|
|
frame_idx = int(row[0]) |
|
|
class_idx = int(row[1]) |
|
|
label = LABEL_MAPPING[str(class_idx)] |
|
|
label_frames.setdefault(label, set()).add(frame_idx) |
|
|
|
|
|
if not label_frames: |
|
|
return [] |
|
|
|
|
|
|
|
|
data = [] |
|
|
for label, frames in label_frames.items(): |
|
|
frames = sorted(frames) |
|
|
|
|
|
|
|
|
start_frame = frames[0] |
|
|
prev_frame = frames[0] |
|
|
|
|
|
for frame in frames[1:]: |
|
|
if frame - prev_frame > 1: |
|
|
data.append({ |
|
|
"label": label, |
|
|
"start": float(start_frame * ANNOTATION_FREQ), |
|
|
"end": float((prev_frame + 1) * ANNOTATION_FREQ) |
|
|
}) |
|
|
start_frame = frame |
|
|
prev_frame = frame |
|
|
|
|
|
|
|
|
data.append({ |
|
|
"label": label, |
|
|
"start": float(start_frame * ANNOTATION_FREQ), |
|
|
"end": float((prev_frame + 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) |