-
Notifications
You must be signed in to change notification settings - Fork 27
/
audio_dataset.py
229 lines (201 loc) · 9.44 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
import numpy as np
import os
import torch
from torch.utils.data import Dataset, DataLoader
from utils.preprocess import Preprocess, FeatureTypes
import math
from multiprocessing import Pool
from sortedcontainers import SortedList
class AudioDataset(Dataset):
def __init__(self, config, root_dir='/data/music/chord_recognition', dataset_names=('isophonic',),
featuretype=FeatureTypes.cqt, num_workers=20, train=False, preprocessing=False, resize=None, kfold=4):
super(AudioDataset, self).__init__()
self.config = config
self.root_dir = root_dir
self.dataset_names = dataset_names
self.preprocessor = Preprocess(config, featuretype, dataset_names, self.root_dir)
self.resize = resize
self.train = train
self.ratio = config.experiment['data_ratio']
# preprocessing hyperparameters
# song_hz, n_bins, bins_per_octave, hop_length
mp3_config = config.mp3
feature_config = config.feature
self.mp3_string = "%d_%.1f_%.1f" % \
(mp3_config['song_hz'], mp3_config['inst_len'],
mp3_config['skip_interval'])
self.feature_string = "%s_%d_%d_%d" % \
(featuretype.value, feature_config['n_bins'], feature_config['bins_per_octave'], feature_config['hop_length'])
if feature_config['large_voca'] == True:
# store paths if exists
is_preprocessed = True if os.path.exists(os.path.join(root_dir, 'result', dataset_names[0]+'_voca', self.mp3_string, self.feature_string)) else False
if (not is_preprocessed) | preprocessing:
midi_paths = self.preprocessor.get_all_files()
if num_workers > 1:
num_path_per_process = math.ceil(len(midi_paths) / num_workers)
args = [midi_paths[i * num_path_per_process:(i + 1) * num_path_per_process] for i in range(num_workers)]
# start process
p = Pool(processes=num_workers)
p.map(self.preprocessor.generate_labels_features_voca, args)
p.close()
else:
self.preprocessor.generate_labels_features_voca(midi_paths)
# kfold is 5 fold index ( 0, 1, 2, 3, 4 )
self.song_names, self.paths = self.get_paths_voca(kfold=kfold)
else:
# store paths if exists
is_preprocessed = True if os.path.exists(os.path.join(root_dir, 'result', dataset_names[0], self.mp3_string, self.feature_string)) else False
if (not is_preprocessed) | preprocessing:
midi_paths = self.preprocessor.get_all_files()
if num_workers > 1:
num_path_per_process = math.ceil(len(midi_paths) / num_workers)
args = [midi_paths[i * num_path_per_process:(i + 1) * num_path_per_process]
for i in range(num_workers)]
# start process
p = Pool(processes=num_workers)
p.map(self.preprocessor.generate_labels_features_new, args)
p.close()
else:
self.preprocessor.generate_labels_features_new(midi_paths)
# kfold is 5 fold index ( 0, 1, 2, 3, 4 )
self.song_names, self.paths = self.get_paths(kfold=kfold)
def __len__(self):
return len(self.paths)
def __getitem__(self, idx):
instance_path = self.paths[idx]
res = dict()
data = torch.load(instance_path)
res['feature'] = np.log(np.abs(data['feature']) + 1e-6)
res['chord'] = data['chord']
return res
def get_paths(self, kfold=4):
temp = {}
used_song_names = list()
for name in self.dataset_names:
dataset_path = os.path.join(self.root_dir, "result", name, self.mp3_string, self.feature_string)
song_names = os.listdir(dataset_path)
for song_name in song_names:
paths = []
instance_names = os.listdir(os.path.join(dataset_path, song_name))
if len(instance_names) > 0:
used_song_names.append(song_name)
for instance_name in instance_names:
paths.append(os.path.join(dataset_path, song_name, instance_name))
temp[song_name] = paths
# throw away unused song names
song_names = used_song_names
song_names = SortedList(song_names)
print('Total used song length : %d' %len(song_names))
tmp = []
for i in range(len(song_names)):
tmp += temp[song_names[i]]
print('Total instances (train and valid) : %d' %len(tmp))
# divide train/valid dataset using k fold
result = []
total_fold = 5
quotient = len(song_names) // total_fold
remainder = len(song_names) % total_fold
fold_num = [0]
for i in range(total_fold):
fold_num.append(quotient)
for i in range(remainder):
fold_num[i+1] += 1
for i in range(total_fold):
fold_num[i+1] += fold_num[i]
if self.train:
tmp = []
# get not augmented data
for k in range(total_fold):
if k != kfold:
for i in range(fold_num[k], fold_num[k+1]):
result += temp[song_names[i]]
tmp += song_names[fold_num[k]:fold_num[k + 1]]
song_names = tmp
else:
for i in range(fold_num[kfold], fold_num[kfold+1]):
instances = temp[song_names[i]]
instances = [inst for inst in instances if "1.00_0" in inst]
result += instances
song_names = song_names[fold_num[kfold]:fold_num[kfold+1]]
return song_names, result
def get_paths_voca(self, kfold=4):
temp = {}
used_song_names = list()
for name in self.dataset_names:
dataset_path = os.path.join(self.root_dir, "result", name+'_voca', self.mp3_string, self.feature_string)
song_names = os.listdir(dataset_path)
for song_name in song_names:
paths = []
instance_names = os.listdir(os.path.join(dataset_path, song_name))
if len(instance_names) > 0:
used_song_names.append(song_name)
for instance_name in instance_names:
paths.append(os.path.join(dataset_path, song_name, instance_name))
temp[song_name] = paths
# throw away unused song names
song_names = used_song_names
song_names = SortedList(song_names)
print('Total used song length : %d' %len(song_names))
tmp = []
for i in range(len(song_names)):
tmp += temp[song_names[i]]
print('Total instances (train and valid) : %d' %len(tmp))
# divide train/valid dataset using k fold
result = []
total_fold = 5
quotient = len(song_names) // total_fold
remainder = len(song_names) % total_fold
fold_num = [0]
for i in range(total_fold):
fold_num.append(quotient)
for i in range(remainder):
fold_num[i+1] += 1
for i in range(total_fold):
fold_num[i+1] += fold_num[i]
if self.train:
tmp = []
# get not augmented data
for k in range(total_fold):
if k != kfold:
for i in range(fold_num[k], fold_num[k+1]):
result += temp[song_names[i]]
tmp += song_names[fold_num[k]:fold_num[k + 1]]
song_names = tmp
else:
for i in range(fold_num[kfold], fold_num[kfold+1]):
instances = temp[song_names[i]]
instances = [inst for inst in instances if "1.00_0" in inst]
result += instances
song_names = song_names[fold_num[kfold]:fold_num[kfold+1]]
return song_names, result
def _collate_fn(batch):
batch_size = len(batch)
max_len = batch[0]['feature'].shape[1]
input_percentages = torch.empty(batch_size) # for variable length
chord_lens = torch.empty(batch_size, dtype=torch.int64)
chords = []
collapsed_chords = []
features = []
boundaries = []
for i in range(batch_size):
sample = batch[i]
feature = sample['feature']
chord = sample['chord']
diff = np.diff(chord, axis=0).astype(np.bool)
idx = np.insert(diff, 0, True, axis=0)
chord_lens[i] = np.sum(idx).item(0)
chords.extend(chord)
features.append(feature)
input_percentages[i] = feature.shape[1] / max_len
collapsed_chords.extend(np.array(chord)[idx].tolist())
boundary = np.append([0], diff)
boundaries.extend(boundary.tolist())
features = torch.tensor(features, dtype=torch.float32).unsqueeze(1) # batch_size*1*feature_size*max_len
chords = torch.tensor(chords, dtype=torch.int64) # (batch_size*time_length)
collapsed_chords = torch.tensor(collapsed_chords, dtype=torch.int64) # total_unique_chord_len
boundaries = torch.tensor(boundaries, dtype=torch.uint8) # (batch_size*time_length)
return features, input_percentages, chords, collapsed_chords, chord_lens, boundaries
class AudioDataLoader(DataLoader):
def __init__(self, *args, **kwargs):
super(AudioDataLoader, self).__init__(*args, **kwargs)
self.collate_fn = _collate_fn