-
Notifications
You must be signed in to change notification settings - Fork 65
/
data_generator.py
310 lines (284 loc) · 11.4 KB
/
data_generator.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# Ke Chen
# HTS-AT: A HIERARCHICAL TOKEN-SEMANTIC AUDIO TRANSFORMER FOR SOUND CLASSIFICATION AND DETECTION
# Dataset Collections
import numpy as np
import torch
import logging
import os
import sys
import h5py
import csv
import time
import random
import json
from datetime import datetime
from torch.utils.data import Dataset
from utils import int16_to_float32
# For AudioSet
class SEDDataset(Dataset):
def __init__(self, index_path, idc, config, eval_mode = False):
"""
Args:
index_path: the link to each audio
idc: npy file, the number of samples in each class, computed in main
config: the config.py module
eval_model (bool): to indicate if the dataset is a testing dataset
"""
self.config = config
self.fp = h5py.File(index_path, "r")
self.idc = idc
self.total_size = len(self.fp["audio_name"])
self.classes_num = config.classes_num
self.eval_mode = eval_mode
self.shift_max = config.shift_max
if (config.enable_label_enhance) and (not eval_mode):
self.class_map = np.load(config.class_map_path, allow_pickle = True)
if not eval_mode:
self.generate_queue()
else:
if self.config.debug:
self.total_size = 1000
self.queue = []
for i in range(self.total_size):
target = self.fp["target"][i]
if np.sum(target) > 0:
self.queue.append(i)
self.total_size = len(self.queue)
logging.info("total dataset size: %d" %(self.total_size))
logging.info("class num: %d" %(self.classes_num))
def time_shifting(self, x):
frame_num = len(x)
shift_len = random.randint(0, self.shift_max - 1)
new_sample = np.concatenate([x[shift_len:], x[:shift_len]], axis = 0)
return new_sample
def generate_queue(self):
self.queue = []
if self.config.debug:
self.total_size = 1000
if self.config.balanced_data:
if self.config.enable_token_label:
while len(self.queue) < self.total_size * 2:
if self.config.class_filter is not None:
class_set = self.config.class_filter[:]
else:
class_set = [*range(self.classes_num)]
random.shuffle(class_set)
self.queue += [self.idc[d][random.randint(0, len(self.idc[d]) - 1)] for d in class_set]
self.queue = self.queue[:self.total_size * 2]
self.queue = [[self.queue[i],self.queue[i+1]] for i in range(0, self.total_size * 2, 2)]
assert len(self.queue) == self.total_size, "generate data error!!"
else:
while len(self.queue) < self.total_size:
if self.config.class_filter is not None:
class_set = self.config.class_filter[:]
else:
class_set = [*range(self.classes_num)]
random.shuffle(class_set)
self.queue += [self.idc[d][random.randint(0, len(self.idc[d]) - 1)] for d in class_set]
self.queue = self.queue[:self.total_size]
else:
self.queue = [*range(self.total_size)]
random.shuffle(self.queue)
logging.info("queue regenerated:%s" %(self.queue[-5:]))
def crop_wav(self, x):
crop_size = self.config.crop_size
crop_pos = random.randint(0, len(x) - crop_size - 1)
return x[crop_pos:crop_pos + crop_size]
def __getitem__(self, index):
"""Load waveform and target of an audio clip.
Args:
index: the index number
Return: {
"hdf5_path": str,
"index_in_hdf5": int,
"audio_name": str,
"waveform": (clip_samples,),
"target": (classes_num,)
}
"""
s_index = self.queue[index]
if (not self.eval_mode) and (self.config.enable_token_label):
audio_name = self.fp["audio_name"][s_index[0]].decode()
hdf5_path = [
self.fp["hdf5_path"][s_index[0]],
self.fp["hdf5_path"][s_index[1]]
]
r_idx = [
self.fp["index_in_hdf5"][s_index[0]],
self.fp["index_in_hdf5"][s_index[1]]
]
target = [
self.fp["target"][s_index[0]].astype(np.float32),
self.fp["target"][s_index[1]].astype(np.float32)
]
waveform = []
with h5py.File(hdf5_path, "r") as f:
waveform.append(int16_to_float32(f["waveform"][r_idx[0]]))
with h5py.File(hdf5_path, "r") as f:
waveform.append(int16_to_float32(f["waveform"][r_idx[1]]))
mix_sample = int(len(waveform[1]) * random.uniform(self.config.token_label_range[0],self.config.token_label_range[1]))
mix_position = random.randint(0, len(waveform[1]) - mix_sample - 1)
mix_waveform = np.concatenate(
[waveform[0][:mix_position],
waveform[1][mix_position:mix_position+mix_sample],
waveform[0][mix_position+mix_sample:]],
axis=0
)
mix_target = np.concatenate([
np.tile(target[0],(mix_position,1)),
np.tile(target[1], (mix_sample, 1)),
np.tile(target[0], (len(waveform[0]) - mix_position - mix_sample, 1))],
axis=0
)
assert len(mix_waveform) == len(waveform[0]),"length of the mix waveform error!!"
data_dict = {
"audio_name": audio_name,
"waveform": mix_waveform,
"target": mix_target
}
else:
audio_name = self.fp["audio_name"][s_index].decode()
hdf5_path = self.fp["hdf5_path"][s_index].decode()
# replace("/home/tiger/DB/knut/data/audioset", self.config.dataset_path)
r_idx = self.fp["index_in_hdf5"][s_index]
target = self.fp["target"][s_index].astype(np.float32)
with h5py.File(hdf5_path, "r") as f:
waveform = int16_to_float32(f["waveform"][r_idx])
# Time shift
if (self.config.enable_time_shift) and (not self.eval_mode):
waveform = self.time_shifting(waveform)
# Label Enhance
if (self.config.crop_size is not None) and (not self.eval_mode):
waveform = self.crop_wav(waveform)
# the label enhance rate is fixed 0.5
if (self.config.enable_label_enhance) and (not self.eval_mode) and random.random() < 0.5:
kidx = np.where(target)[0]
for k in kidx:
for add_key in self.class_map[k][1]:
target[add_key] = 1.0
if len(self.class_map[k][2]) > 0:
add_key = random.choice(self.class_map[k][2])
target[add_key] = 1.0
data_dict = {
"hdf5_path": hdf5_path,
"index_in_hdf5": r_idx,
"audio_name": audio_name,
"waveform": waveform,
"target": target
}
return data_dict
def __len__(self):
return self.total_size
# For ESC dataset
class ESC_Dataset(Dataset):
def __init__(self, dataset, config, eval_mode = False):
self.dataset = dataset
self.config = config
self.eval_mode = eval_mode
if self.eval_mode:
self.dataset = self.dataset[self.config.esc_fold]
else:
temp = []
for i in range(len(self.dataset)):
if i != config.esc_fold:
temp += list(self.dataset[i])
self.dataset = temp
self.total_size = len(self.dataset)
self.queue = [*range(self.total_size)]
logging.info("total dataset size: %d" %(self.total_size))
if not eval_mode:
self.generate_queue()
def generate_queue(self):
random.shuffle(self.queue)
logging.info("queue regenerated:%s" %(self.queue[-5:]))
def __getitem__(self, index):
"""Load waveform and target of an audio clip.
Args:
index: the index number
Return: {
"audio_name": str,
"waveform": (clip_samples,),
"target": (classes_num,)
}
"""
p = self.queue[index]
data_dict = {
"audio_name": self.dataset[p]["name"],
"waveform": np.concatenate((self.dataset[p]["waveform"],self.dataset[p]["waveform"])),
"real_len": len(self.dataset[p]["waveform"]) * 2,
"target": self.dataset[p]["target"]
}
return data_dict
def __len__(self):
return self.total_size
# For Speech Command V2 dataset
class SCV2_Dataset(Dataset):
def __init__(self, dataset, config, eval_mode = False):
self.dataset = dataset
self.config = config
self.eval_mode = eval_mode
self.total_size = len(self.dataset)
self.queue = [*range(self.total_size)]
logging.info("total dataset size: %d" %(self.total_size))
if not eval_mode:
self.generate_queue()
def generate_queue(self):
random.shuffle(self.queue)
logging.info("queue regenerated:%s" %(self.queue[-5:]))
def __getitem__(self, index):
"""Load waveform and target of an audio clip.
Args:
index: the index number
Return: {
"audio_name": str,
"waveform": (clip_samples,),
"target": (classes_num,)
}
"""
p = self.queue[index]
waveform = self.dataset[p]["waveform"]
while len(waveform) < self.config.clip_samples:
waveform = np.concatenate((waveform, waveform))
waveform = waveform[:self.config.clip_samples]
target = np.zeros(self.config.classes_num).astype(np.float32)
target[int(self.dataset[p]["target"])] = 1.
data_dict = {
"audio_name": self.dataset[p]["name"],
"waveform": waveform,
"real_len": len(waveform),
"target": target
}
return data_dict
def __len__(self):
return self.total_size
# For DeSED dataset in DACASE 2020/2021
class DESED_Dataset(Dataset):
def __init__(self, dataset, config):
self.dataset = dataset
self.config = config
self.total_size = len(dataset)
logging.info("total dataset size: %d" %(self.total_size))
def __getitem__(self, index):
"""Load waveform and target of an audio clip.
Args:
index: the index number
Return: {
"audio_name": str,
"waveform": (clip_samples,),
}
"""
real_len = len(self.dataset[index]["waveform"])
if real_len < self.config.clip_samples:
zero_pad = np.zeros(self.config.clip_samples - real_len)
waveform = np.concatenate([self.dataset[index]["waveform"], zero_pad])
else:
waveform = self.dataset[index]["waveform"][:self.config.clip_samples]
data_dict = {
"audio_name": self.dataset[index]["audio_name"],
"waveform": int16_to_float32(waveform),
"real_len": real_len
}
return data_dict
def __len__(self):
return self.total_size