forked from CPJKU/dcase2024_task1_baseline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcase24.py
174 lines (139 loc) · 6.61 KB
/
dcase24.py
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
import pandas as pd
import os
from sklearn import preprocessing
from torch.utils.data import Dataset as TorchDataset
import torch
import torchaudio
from torch.hub import download_url_to_file
import numpy as np
dataset_dir = None
assert dataset_dir is not None, "Specify 'TAU Urban Acoustic Scenes 2022 Mobile dataset' location in variable " \
"'dataset_dir'. The dataset can be downloaded from this URL:" \
" https://zenodo.org/record/6337421"
dataset_config = {
"dataset_name": "tau24",
"meta_csv": os.path.join(dataset_dir, "meta.csv"),
"split_path": "split_setup",
"split_url": "https://github.com/CPJKU/dcase2024_task1_baseline/releases/download/files/",
"test_split_csv": "test.csv",
"eval_dir": os.path.join(dataset_dir, "..", "TAU-urban-acoustic-scenes-2024-mobile-evaluation"),
"eval_fold_csv": os.path.join(dataset_dir, "..", "TAU-urban-acoustic-scenes-2024-mobile-evaluation",
"evaluation_setup", "fold1_test.csv")
}
class BasicDCASE24Dataset(TorchDataset):
"""
Basic DCASE'24 Dataset: loads data from files
"""
def __init__(self, meta_csv):
"""
@param meta_csv: meta csv file for the dataset
return: waveform, file, label, device and city
"""
df = pd.read_csv(meta_csv, sep="\t")
le = preprocessing.LabelEncoder()
self.labels = torch.from_numpy(le.fit_transform(df[['scene_label']].values.reshape(-1)))
self.devices = le.fit_transform(df[['source_label']].values.reshape(-1))
self.cities = le.fit_transform(df['identifier'].apply(lambda loc: loc.split("-")[0]).values.reshape(-1))
self.files = df[['filename']].values.reshape(-1)
def __getitem__(self, index):
sig, _ = torchaudio.load(os.path.join(dataset_dir, self.files[index]))
return sig, self.files[index], self.labels[index], self.devices[index], self.cities[index]
def __len__(self):
return len(self.files)
class SimpleSelectionDataset(TorchDataset):
"""A dataset that selects a subsample from a dataset based on a set of sample ids.
Supporting integer indexing in range from 0 to len(self) exclusive.
"""
def __init__(self, dataset, available_indices):
"""
@param dataset: dataset to load data from
@param available_indices: available indices of samples for different splits
return: waveform, file, label, device, city
"""
self.available_indices = available_indices
self.dataset = dataset
def __getitem__(self, index):
x, file, label, device, city = self.dataset[self.available_indices[index]]
return x, file, label, device, city
def __len__(self):
return len(self.available_indices)
class RollDataset(TorchDataset):
"""A dataset implementing time rolling of waveforms.
"""
def __init__(self, dataset: TorchDataset, shift_range: int, axis=1):
"""
@param dataset: dataset to load data from
@param shift_range: maximum shift range
return: waveform, file, label, device, city
"""
self.dataset = dataset
self.shift_range = shift_range
self.axis = axis
def __getitem__(self, index):
x, file, label, device, city = self.dataset[index]
sf = int(np.random.random_integers(-self.shift_range, self.shift_range))
return x.roll(sf, self.axis), file, label, device, city
def __len__(self):
return len(self.dataset)
def get_training_set(split=100, roll=False):
assert str(split) in ("5", "10", "25", "50", "100"), "Parameters 'split' must be in [5, 10, 25, 50, 100]"
os.makedirs(dataset_config['split_path'], exist_ok=True)
subset_fname = f"split{split}.csv"
subset_split_file = os.path.join(dataset_config['split_path'], subset_fname)
if not os.path.isfile(subset_split_file):
# download split{x}.csv (file containing all audio snippets for respective development-train split)
subset_csv_url = dataset_config['split_url'] + subset_fname
print(f"Downloading file: {subset_fname}")
download_url_to_file(subset_csv_url, subset_split_file)
ds = get_base_training_set(dataset_config['meta_csv'], subset_split_file)
if roll:
ds = RollDataset(ds, shift_range=roll)
return ds
def get_base_training_set(meta_csv, train_files_csv):
meta = pd.read_csv(meta_csv, sep="\t")
train_files = pd.read_csv(train_files_csv, sep='\t')['filename'].values.reshape(-1)
train_subset_indices = list(meta[meta['filename'].isin(train_files)].index)
ds = SimpleSelectionDataset(BasicDCASE24Dataset(meta_csv),
train_subset_indices)
return ds
def get_test_set():
os.makedirs(dataset_config['split_path'], exist_ok=True)
test_split_csv = os.path.join(dataset_config['split_path'], dataset_config['test_split_csv'])
if not os.path.isfile(test_split_csv):
# download test.csv (file containing all audio snippets for development-test split)
test_csv_url = dataset_config['split_url'] + dataset_config['test_split_csv']
print(f"Downloading file: {dataset_config['test_split_csv']}")
download_url_to_file(test_csv_url, test_split_csv)
ds = get_base_test_set(dataset_config['meta_csv'], test_split_csv)
return ds
def get_base_test_set(meta_csv, test_files_csv):
meta = pd.read_csv(meta_csv, sep="\t")
test_files = pd.read_csv(test_files_csv, sep='\t')['filename'].values.reshape(-1)
test_indices = list(meta[meta['filename'].isin(test_files)].index)
ds = SimpleSelectionDataset(BasicDCASE24Dataset(meta_csv), test_indices)
return ds
class BasicDCASE24EvalDataset(TorchDataset):
"""
Basic DCASE'24 Dataset: loads eval data from files
"""
def __init__(self, meta_csv, eval_dir):
"""
@param meta_csv: meta csv file for the dataset
@param eval_dir: directory containing evaluation set
return: waveform, file
"""
df = pd.read_csv(meta_csv, sep="\t")
self.files = df[['filename']].values.reshape(-1)
self.eval_dir = eval_dir
def __getitem__(self, index):
sig, _ = torchaudio.load(os.path.join(self.eval_dir, self.files[index]))
return sig, self.files[index]
def __len__(self):
return len(self.files)
def get_eval_set():
assert os.path.exists(dataset_config['eval_dir']), f"No such folder: {dataset_config['eval_dir']}"
ds = get_base_eval_set(dataset_config['eval_fold_csv'], dataset_config['eval_dir'])
return ds
def get_base_eval_set(meta_csv, eval_dir):
ds = BasicDCASE24EvalDataset(meta_csv, eval_dir)
return ds