forked from LsNatan/NICE
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaudio_dataset.py
381 lines (307 loc) · 15.3 KB
/
audio_dataset.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import os
import os.path
import numpy as np
from random import randint, uniform
import torch.utils.data as data
# from PIL import Image
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import h5py
import deep_isp_utils as utils
from preprocess_audio.preprocess_audio import combine_two_wavs, create_spectogram
import soundfile as sf
import librosa
from tqdm import tqdm
# Dataset using h5 file with all the data needed (train and test)
class AudioDataset(data.Dataset):
"""`MSR Demosaicing <https://www.microsoft.com/en-us/download/details.aspx?id=52535>`_ Dataset.
Args:
root (string): Root directory of dataset where directory ``Dataset_LINEAR_with_noise`` exists.
train (bool, optional): If True, creates dataset from training set, otherwise
creates from test set.
transform (callable, optional): A function/transform that takes in a pair of PIL images
and returns a transformed version. E.g, ``transforms.RandomCrop``
"""
"""
def read_pair_imgs(self, gt_dir, input_dir, file_name, train=True):
if train:
file_gt_path = os.path.join(gt_dir, 'label_' + file_name)
file_input_path = os.path.join(input_dir, 'train_' + file_name)
else:
file_gt_path = os.path.join(gt_dir, 'test_sounds_' + file_name)
file_input_path = os.path.join(input_dir, 'test_combined_' + file_name)
gt = plt.imread(file_gt_path)[:, :, :3]
gt = np.transpose(gt, (2, 0, 1))
input = plt.imread(file_input_path)[:, :, :3]
input = np.transpose(input, (2, 0, 1))
return input, gt
"""
def read_pair_from_h5(self, gt_group, input_group, file_name):
gt = np.array(gt_group.get(file_name))
gt = np.expand_dims(gt, axis=0)
input = np.array(input_group.get(file_name))
input = np.expand_dims(input, axis=0)
return input, gt
def __init__(self, data_h5_path, add_rpm=False, train=True, validation=False, validation_part=0.1, transform=None):
assert (not (train and validation))
self.data_h5_path = data_h5_path
self.transform = transform
self.train = train # training set or test set
self.validation = validation # validation set
# if not self._check_integrity():
# raise RuntimeError('Dataset not found or corrupted.')
hf = h5py.File(self.data_h5_path, 'r')
# now load the picked numpy arrays
if self.train or self.validation:
train_sub = hf.get('train')
input_sub = train_sub.get('input')
gt_sub = train_sub.get('gt')
self.train_filenames = list(input_sub.keys())
self.train_data = []
self.train_labels = []
for f in self.train_filenames:
im, gt = self.read_pair_from_h5(gt_sub, input_sub, f)
# add rpm as channel
if add_rpm:
rpm = f.split("_")[-2]
rpm_channel = np.full_like(im, rpm)
im = np.append(im, rpm_channel, 0)
self.train_data.append(im)
self.train_labels.append(gt)
self.train_data, self.val_data, self.train_labels, self.val_labels = train_test_split(
self.train_data,
self.train_labels,
test_size=validation_part,
random_state=32)
else:
test_sub = hf.get('test')
input_sub = test_sub.get('input')
gt_sub = test_sub.get('gt')
self.test_filenames = list(input_sub.keys())
self.test_data = []
self.test_labels = []
for f in self.test_filenames:
im, gt = self.read_pair_from_h5(gt_sub, input_sub, f)
# add rpm as channel
if add_rpm:
rpm = f.split("_")[-2]
rpm_channel = np.full_like(im, rpm)
im = np.append(im, rpm_channel, 0)
self.test_data.append(im)
self.test_labels.append(gt)
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
if self.train:
img, target = self.train_data[index], self.train_labels[index]
filename = 0
elif self.validation:
img, target = self.val_data[index], self.val_labels[index]
filename = 0
else:
img, target, filename = self.test_data[index], self.test_labels[index], self.test_filenames[index]
if self.transform is not None:
img, target = self.transform(img, target)
return img, target, filename
def __len__(self):
if self.train:
return len(self.train_data)
elif self.validation:
return len(self.val_data)
else:
return len(self.test_data)
# Dataset using a directory with the following subdirectories: train, test, rotor
# train and test directories contain only gt sounds (without noise)
# Audio and rotors are randomly sampled from the files
#
class AudioGenDataset(data.Dataset):
"""`MSR Demosaicing <https://www.microsoft.com/en-us/download/details.aspx?id=52535>`_ Dataset.
Args:
root (string): Root directory of dataset where directory ``Dataset_LINEAR_with_noise`` exists.
train (bool, optional): If True, creates dataset from training set, otherwise
creates from test set.
transform (callable, optional): A function/transform that takes in a pair of PIL images
and returns a transformed version. E.g, ``transforms.RandomCrop``
"""
"""
def read_pair_imgs(self, gt_dir, input_dir, file_name, train=True):
if train:
file_gt_path = os.path.join(gt_dir, 'label_' + file_name)
file_input_path = os.path.join(input_dir, 'train_' + file_name)
else:
file_gt_path = os.path.join(gt_dir, 'test_sounds_' + file_name)
file_input_path = os.path.join(input_dir, 'test_combined_' + file_name)
gt = plt.imread(file_gt_path)[:, :, :3]
gt = np.transpose(gt, (2, 0, 1))
input = plt.imread(file_input_path)[:, :, :3]
input = np.transpose(input, (2, 0, 1))
return input, gt
"""
# def read_pair_from_h5(self, gt_group, input_group, file_name):
# gt = np.array(gt_group.get(file_name))
# gt = np.expand_dims(gt, axis=0)
# input = np.array(input_group.get(file_name))
# input = np.expand_dims(input, axis=0)
# return input, gt
def __init__(self, dataset_dir, add_rpm=False, train=True, validation=False, validation_part=0.1, transform=None, dataset_size=100, sample_length=1):
assert (not (train and validation))
self.dataset_dir = dataset_dir
self.dataset_size = dataset_size
self.rotor_dir = os.path.join(self.dataset_dir, 'rotor')
self.transform = transform
self.train = train # training set or test set
self.validation = validation # validation set
self.sample_length = 1
N_FFT = 1024
# now load the picked numpy arrays
if self.train or self.validation:
self.data_dir = os.path.join(self.dataset_dir, 'train')
self.train_filenames = os.listdir(self.data_dir)
self.rotor_filenames = os.listdir(self.rotor_dir)
self.train_data = []
self.train_labels = []
print("Building dataset")
for idx in tqdm(np.random.randint(0, len(self.train_filenames), self.dataset_size),0):
file_path = os.path.join(self.data_dir, self.train_filenames[idx])
file_name, ext = os.path.splitext(file_path)
while True:
try:
gt, sr = sf.read(file_path)
if (len(gt) / sr) < self.sample_length:
raise Exception("sample too short")
# pick random location in file
sample_start = randint(0, len(gt) - (sr * self.sample_length))
gt = gt[sample_start: sample_start + (sr * self.sample_length)]
if (gt.max()) < 0.45:
raise Exception("sample too silent")
except Exception as e:
# tqdm.write("Exception: {}".format(e))
idx = randint(0, len(self.train_filenames)-1)
file_path = os.path.join(self.data_dir, self.train_filenames[idx])
continue
break
if(gt.shape[0] == 2):
gt = librosa.core.to_mono(np.swapaxes(gt, 0, 1))
# pick random rotor rpm
rotor_file_path = os.path.join(self.rotor_dir, self.rotor_filenames[randint(0, len(self.rotor_filenames)-1)])
rotor_sound, r_sr = sf.read(rotor_file_path)
rotor_sound = librosa.core.resample(rotor_sound, r_sr, 22050)
gt = librosa.core.resample(gt, sr, 22050)
# theoretically take random sample of sample_size seconds from rotor file
# equalize scale ranges to [0,1]
# rotor_sound *= gt.max()
# # combine sound and rotor
# volume_rotor = 0.4
# im = combine_two_wavs(rotor_sound, gt, volume1=volume_rotor)
# combine sound and rotor
volume_rotors = uniform(0.1, 0.3)
im = combine_two_wavs(rotor_sound, gt, volume1=volume_rotors)
# convert wav to spectogram
im, _ = create_spectogram(im, N_FFT)
gt, _ = create_spectogram(gt, N_FFT)
gt = np.expand_dims(gt, axis=0)
im = np.expand_dims(im, axis=0)
# add rpm as channel
if add_rpm:
rpm = os.path.basename(rotor_file_path)
rpm = float(rpm.split(".")[0]) / float(max(self.rotor_filenames).split(".")[0])
rpm_channel = np.full_like(im, rpm)
im = np.append(im, rpm_channel, 0)
self.train_data.append(im)
self.train_labels.append(gt)
self.train_data, self.val_data, self.train_labels, self.val_labels = train_test_split(
self.train_data,
self.train_labels,
test_size=validation_part,
random_state=32)
else:
# test_sub = hf.get('test')
# input_sub = test_sub.get('input')
# gt_sub = test_sub.get('gt')
# self.test_filenames = list(input_sub.keys())
# self.test_data = []
# self.test_labels = []
# for f in self.test_filenames:
# im, gt = self.read_pair_from_h5(gt_sub, input_sub, f)
# # add rpm as channel
# if add_rpm:
# rpm = f.split("_")[-2]
# rpm_channel = np.full_like(im, rpm)
# im = np.append(im, rpm_channel, 0)
#####################################################
self.data_dir = os.path.join(self.dataset_dir, 'test')
self.test_filenames = os.listdir(self.data_dir)
self.rotor_filenames = os.listdir(self.rotor_dir)
self.test_data = []
self.test_labels = []
for idx in np.random.randint(0, len(self.test_filenames), self.dataset_size):
file_path = os.path.join(self.data_dir, self.test_filenames[idx])
file_name, ext = os.path.splitext(file_path)
while True:
try:
gt, sr = sf.read(file_path)
if (len(gt) / sr) < sample_length:
raise Exception("sample too short")
except Exception as e:
print("Exception: ", e)
idx = randint(0, len(self.train_filenames))
file_path = os.path.join(self.data_dir, self.train_filenames[idx])
continue
break
# pick random location in file
sample_start = randint(0, len(gt) - (sr * sample_length) - 1)
gt = gt[sample_start: sample_start + (sr * sample_length)]
gt = librosa.core.to_mono(np.swapaxes(gt, 0, 1))
# pick random rotor rpm
rotor_file_path = os.path.join(self.rotor_dir, self.rotor_filenames[randint(0, len(self.rotor_filenames)-1)])
rotor_sound, r_sr = sf.read(rotor_file_path)
rotor_sound = librosa.core.resample(rotor_sound, r_sr, 22050)
gt = librosa.core.resample(gt, sr, 22050)
# theoretically take random sample of sample_size seconds from rotor file
# equalize scale ranges to [0,1]
# rotor_sound *= gt.max()
# combine sound and rotor
volume_rotor = 0.2
im = combine_two_wavs(rotor_sound, gt, volume1=volume_rotor)
# convert wav to spectogram
im, _ = create_spectogram(im, N_FFT)
gt, _ = create_spectogram(gt, N_FFT)
gt = np.expand_dims(gt, axis=0)
im = np.expand_dims(im, axis=0)
# add rpm as channel
if add_rpm:
rpm = os.path.basename(rotor_file_path)
rpm = float(rpm.split(".")[0]) / float(max(self.rotor_filenames).split(".")[0])
rpm_channel = np.full_like(im, rpm)
im = np.append(im, rpm_channel, 0)
self.test_data.append(im)
self.test_labels.append(gt)
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
if self.train:
img, target = self.train_data[index], self.train_labels[index]
filename = 0
elif self.validation:
img, target = self.val_data[index], self.val_labels[index]
filename = 0
else:
img, target, filename = self.test_data[index], self.test_labels[index], self.test_filenames[index]
if self.transform is not None:
img, target = self.transform(img, target)
return img, target, filename
def __len__(self):
if self.train:
return len(self.train_data)
elif self.validation:
return len(self.val_data)
else:
return len(self.test_data)