-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdatasets.py
334 lines (256 loc) · 15.1 KB
/
datasets.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
# A Wavenet For Source Separation - Francesc Lluis - 25.10.2018
# Datasets.py
import util
import os
import numpy as np
import musdb
import logging
class SingingVoiceMUSDB18Dataset():
def __init__(self, config, model):
self.model = model
self.path = config['dataset']['path']
self.sample_rate = config['dataset']['sample_rate']
self.file_paths = {'train': {'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}, 'val':
{'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}}
self.sequences = {'train': {'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}, 'val':
{'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}}
self.voice_indices = {'train': [], 'val': []}
self.batch_size = config['training']['batch_size']
self.extract_voice_percent = config['dataset']['extract_voice_percentage']
self.in_memory_percentage = config['dataset']['in_memory_percentage']
self.num_sequences_in_memory = 0
self.condition_encode_function = util.get_condition_input_encode_func(config['model']['condition_encoding'])
def load_dataset(self):
print('Loading MUSDB18 dataset for singing voice separation...')
mus = musdb.DB(root_dir=self.path, is_wav=True)
tracks = mus.load_mus_tracks(subsets='train')
np.random.seed(seed=1337)
val_idx = np.random.choice(len(tracks), size=25, replace=False)
train_idx = [i for i in range(len(tracks)) if i not in val_idx]
val_tracks = [tracks[i] for i in val_idx]
train_tracks = [tracks[i] for i in train_idx]
for condition in ['mixture', 'vocals']:
self.file_paths['val'][condition] = [track.path[:-11] + condition + '.wav' for track in val_tracks]
for condition in ['mixture', 'vocals']:
self.file_paths['train'][condition] = [track.path[:-11] + condition + '.wav' for track in train_tracks]
self.load_songs()
return self
def load_songs(self):
for set in ['train', 'val']:
for condition in ['mixture', 'vocals']:
for filepath in self.file_paths[set][condition]:
if condition == 'vocals':
sequence = util.load_wav(filepath, self.sample_rate)
self.sequences[set][condition].append(sequence)
self.num_sequences_in_memory += 1
if self.extract_voice_percent > 0:
self.voice_indices[set].append(util.get_sequence_with_singing_indices(sequence))
else:
if self.in_memory_percentage == 1 or np.random.uniform(0, 1) <= (
self.in_memory_percentage - 0.5) * 2:
sequence = util.load_wav(filepath, self.sample_rate)
self.sequences[set][condition].append(sequence)
self.num_sequences_in_memory += 1
else:
self.sequences[set][condition].append([-1])
def get_num_sequences_in_dataset(self):
return len(self.sequences['train']['vocals']) + len(self.sequences['train']['mixture']) + len(
self.sequences['val']['vocals']) + len(self.sequences['val']['mixture'])
def retrieve_sequence(self, set, condition, sequence_num):
if len(self.sequences[set][condition][sequence_num]) == 1:
sequence = util.load_wav(self.file_paths[set][condition][sequence_num], self.sample_rate)
if (float(self.num_sequences_in_memory) / self.get_num_sequences_in_dataset()) < self.in_memory_percentage:
self.sequences[set][condition][sequence_num] = sequence
self.num_sequences_in_memory += 1
else:
sequence = self.sequences[set][condition][sequence_num]
return np.array(sequence)
def get_random_batch_generator(self, set):
if set not in ['train', 'val']:
raise ValueError("Argument SET must be either 'train' or 'val'")
while True:
sample_indices = np.random.randint(0, len(self.sequences[set]['vocals']), self.batch_size)
batch_inputs = []
batch_outputs_1 = []
batch_outputs_2 = []
for i, sample_i in enumerate(sample_indices):
while True:
starting_index = 0
mixture = self.retrieve_sequence(set, 'mixture', sample_i)
vocals = self.retrieve_sequence(set, 'vocals', sample_i)
accompaniment = mixture - vocals
if np.random.uniform(0, 1) < self.extract_voice_percent:
indices = self.voice_indices[set][sample_i]
vocals_indices, _ = util.get_indices_subsequence(indices)
vocals = vocals[vocals_indices[0]:vocals_indices[1]]
starting_index = vocals_indices[0]
if len(vocals) < self.model.input_length:
sample_i = np.random.randint(0, len(self.sequences[set]['vocals']))
else:
break
offset_1 = np.squeeze(np.random.randint(0, len(vocals) - self.model.input_length + 1, 1))
vocals_fragment = vocals[offset_1:offset_1 + self.model.input_length]
offset_2 = offset_1 + starting_index
accompaniment_fragment = accompaniment[offset_2:offset_2 + self.model.input_length]
input = accompaniment_fragment + vocals_fragment
output_vocals = vocals_fragment
output_accompaniment = accompaniment_fragment
batch_inputs.append(input)
batch_outputs_1.append(output_vocals)
batch_outputs_2.append(output_accompaniment)
batch_inputs = np.array(batch_inputs, dtype='float32')
batch_outputs_1 = np.array(batch_outputs_1, dtype='float32')
batch_outputs_2 = np.array(batch_outputs_2, dtype='float32')
batch_outputs_1 = batch_outputs_1[:, self.model.get_padded_target_field_indices()]
batch_outputs_2 = batch_outputs_2[:, self.model.get_padded_target_field_indices()]
batch = {'data_input': batch_inputs}, {'data_output_1': batch_outputs_1,
'data_output_2': batch_outputs_2}
yield batch
def get_condition_input_encode_func(self, representation):
if representation == 'binary':
return util.binary_encode
else:
return util.one_hot_encode
def get_target_sample_index(self):
return int(np.floor(self.fragment_length / 2.0))
def get_samples_of_interest_indices(self, causal=False):
if causal:
return -1
else:
target_sample_index = self.get_target_sample_index()
return range(target_sample_index - self.half_target_field_length - self.target_padding,
target_sample_index + self.half_target_field_length + self.target_padding + 1)
def get_sample_weight_vector_length(self):
if self.samples_of_interest_only:
return len(self.get_samples_of_interest_indices())
else:
return self.fragment_length
class MultiInstrumentMUSDB18Dataset():
def __init__(self, config, model):
self.model = model
self.path = config['dataset']['path']
self.sample_rate = config['dataset']['sample_rate']
self.file_paths = {'train': {'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}, 'val':
{'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}}
self.sequences = {'train': {'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}, 'val':
{'vocals': [], 'mixture': [], 'drums': [], 'other': [], 'bass': []}}
self.voice_indices = {'train': [], 'val': []}
self.batch_size = config['training']['batch_size']
self.extract_voice_percent = config['dataset']['extract_voice_percentage']
self.in_memory_percentage = config['dataset']['in_memory_percentage']
self.num_sequences_in_memory = 0
self.condition_encode_function = util.get_condition_input_encode_func(config['model']['condition_encoding'])
def load_dataset(self):
print('Loading MUSDB18 dataset for multi-instrument separation...')
mus = musdb.DB(root_dir=self.path, is_wav=True)
tracks = mus.load_mus_tracks(subsets='train')
np.random.seed(seed=1337)
val_idx = np.random.choice(len(tracks), size=25, replace=False)
train_idx = [i for i in range(len(tracks)) if i not in val_idx]
val_tracks = [tracks[i] for i in val_idx]
train_tracks = [tracks[i] for i in train_idx]
for condition in ['mixture', 'vocals', 'drums', 'other', 'bass']:
self.file_paths['val'][condition] = [track.path[:-11] + condition + '.wav' for track in val_tracks]
for condition in ['mixture', 'vocals', 'drums', 'other', 'bass']:
self.file_paths['train'][condition] = [track.path[:-11] + condition + '.wav' for track in train_tracks]
self.load_songs()
return self
def load_songs(self):
for set in ['train', 'val']:
for condition in ['vocals', 'mixture', 'drums', 'other', 'bass']:
for filepath in self.file_paths[set][condition]:
if condition == 'vocals':
sequence = util.load_wav(filepath, self.sample_rate)
self.sequences[set][condition].append(sequence)
self.num_sequences_in_memory += 1
if self.extract_voice_percent > 0:
self.voice_indices[set].append(util.get_sequence_with_singing_indices(sequence))
else:
if self.in_memory_percentage == 1 or np.random.uniform(0, 1) <= (
self.in_memory_percentage - 0.5) * 2:
sequence = util.load_wav(filepath, self.sample_rate)
self.sequences[set][condition].append(sequence)
self.num_sequences_in_memory += 1
else:
self.sequences[set][condition].append([-1])
def get_num_sequences_in_dataset(self):
return len(self.sequences['train']['vocals']) + len(self.sequences['train']['mixture']) + len(
self.sequences['val']['vocals']) + len(self.sequences['val']['mixture'])
def retrieve_sequence(self, set, condition, sequence_num):
if len(self.sequences[set][condition][sequence_num]) == 1:
sequence = util.load_wav(self.file_paths[set][condition][sequence_num], self.sample_rate)
if (float(self.num_sequences_in_memory) / self.get_num_sequences_in_dataset()) < self.in_memory_percentage:
self.sequences[set][condition][sequence_num] = sequence
self.num_sequences_in_memory += 1
else:
sequence = self.sequences[set][condition][sequence_num]
return np.array(sequence)
def get_random_batch_generator(self, set):
if set not in ['train', 'val']:
raise ValueError("Argument SET must be either 'train' or 'val'")
while True:
sample_indices = np.random.randint(0, len(self.sequences[set]['vocals']), self.batch_size)
batch_inputs = []
batch_outputs_1 = []
batch_outputs_2 = []
batch_outputs_3 = []
for i, sample_i in enumerate(sample_indices):
while True:
starting_index = 0
vocals = self.retrieve_sequence(set, 'vocals', sample_i)
bass = self.retrieve_sequence(set, 'bass', sample_i)
drums = self.retrieve_sequence(set, 'drums', sample_i)
other = self.retrieve_sequence(set, 'other', sample_i)
if np.random.uniform(0, 1) < self.extract_voice_percent:
indices = self.voice_indices[set][sample_i]
vocals_indices, _ = util.get_indices_subsequence(indices)
vocals = vocals[vocals_indices[0]:vocals_indices[1]]
starting_index = vocals_indices[0]
if len(vocals) < self.model.input_length:
sample_i = np.random.randint(0, len(self.sequences[set]['vocals']))
else:
break
offset_1 = np.squeeze(np.random.randint(0, len(vocals) - self.model.input_length + 1, 1))
vocals_fragment = vocals[offset_1:offset_1 + self.model.input_length]
offset_2 = offset_1 + starting_index
bass_fragment = bass[offset_2:offset_2 + self.model.input_length]
drums_fragment = drums[offset_2:offset_2 + self.model.input_length]
other_fragment = other[offset_2:offset_2 + self.model.input_length]
input = vocals_fragment + bass_fragment + drums_fragment + other_fragment
output_vocals = vocals_fragment
output_drums = drums_fragment
output_bass = bass_fragment
batch_inputs.append(input)
batch_outputs_1.append(output_vocals)
batch_outputs_2.append(output_drums)
batch_outputs_3.append(output_bass)
batch_inputs = np.array(batch_inputs, dtype='float32')
batch_outputs_1 = np.array(batch_outputs_1, dtype='float32')
batch_outputs_2 = np.array(batch_outputs_2, dtype='float32')
batch_outputs_3 = np.array(batch_outputs_3, dtype='float32')
batch_outputs_1 = batch_outputs_1[:, self.model.get_padded_target_field_indices()]
batch_outputs_2 = batch_outputs_2[:, self.model.get_padded_target_field_indices()]
batch_outputs_3 = batch_outputs_3[:, self.model.get_padded_target_field_indices()]
batch = {'data_input': batch_inputs}, {'data_output_1': batch_outputs_1,
'data_output_2': batch_outputs_2,
'data_output_3': batch_outputs_3}
yield batch
def get_condition_input_encode_func(self, representation):
if representation == 'binary':
return util.binary_encode
else:
return util.one_hot_encode
def get_target_sample_index(self):
return int(np.floor(self.fragment_length / 2.0))
def get_samples_of_interest_indices(self, causal=False):
if causal:
return -1
else:
target_sample_index = self.get_target_sample_index()
return range(target_sample_index - self.half_target_field_length - self.target_padding,
target_sample_index + self.half_target_field_length + self.target_padding + 1)
def get_sample_weight_vector_length(self):
if self.samples_of_interest_only:
return len(self.get_samples_of_interest_indices())
else:
return self.fragment_length