File size: 2,455 Bytes
61e8d5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0efc9e6
61e8d5c
 
 
 
 
 
 
 
 
0efc9e6
 
61e8d5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)