-
Notifications
You must be signed in to change notification settings - Fork 1
/
features.py
467 lines (362 loc) · 14.3 KB
/
features.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], 'utils'))
import numpy as np
import argparse
import h5py
import librosa
from scipy import signal
import matplotlib.pyplot as plt
import time
import math
import pandas as pd
import random
from utilities import (create_folder, read_audio, calculate_scalar_of_tensor,
pad_truncate_sequence)
import config
class LogMelExtractor(object):
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax):
'''Log mel feature extractor.
Args:
sample_rate: int
window_size: int
hop_size: int
mel_bins: int
fmin: int, minimum frequency of mel filter banks
fmax: int, maximum frequency of mel filter banks
'''
self.window_size = window_size
self.hop_size = hop_size
self.window_func = np.hanning(window_size)
self.melW = librosa.filters.mel(
sr=sample_rate,
n_fft=window_size,
n_mels=mel_bins,
fmin=fmin,
fmax=fmax).T
'''(n_fft // 2 + 1, mel_bins)'''
def transform(self, audio):
'''Extract feature of a singlechannel audio file.
Args:
audio: (samples,)
Returns:
feature: (frames_num, freq_bins)
'''
window_size = self.window_size
hop_size = self.hop_size
window_func = self.window_func
# Compute short-time Fourier transform
stft_matrix = librosa.core.stft(
y=audio,
n_fft=window_size,
hop_length=hop_size,
window=window_func,
center=True,
dtype=np.complex64,
pad_mode='reflect').T
'''(N, n_fft // 2 + 1)'''
# Mel spectrogram
mel_spectrogram = np.dot(np.abs(stft_matrix) ** 2, self.melW)
# Log mel spectrogram
logmel_spectrogram = librosa.core.power_to_db(
mel_spectrogram, ref=1.0, amin=1e-10,
top_db=None)
logmel_spectrogram = logmel_spectrogram.astype(np.float32)
return logmel_spectrogram
def read_metadata(metadata_path, data_type, mini_data):
'''Read train validation metadata csv file.
Args:
metadata_path: string
data_type: 'train' | 'validate'
mini_data: bool, set True for debugging on a small part of data
Returns:
meta_dict
'''
fine_labels = config.fine_labels
fine_classes_num = config.fine_classes_num
fine_lb_to_idx = config.fine_lb_to_idx
coarse_labels = config.coarse_labels
coarse_classes_num = config.coarse_classes_num
coarse_lb_to_idx = config.coarse_lb_to_idx
# Read csv data
assert data_type in ['train', 'validate','evaluate']
df = pd.read_csv(metadata_path, sep=',')
df = df[df['split'] == data_type].reset_index()
# Each audio may be annotated by multiple labelers. So remove duplicate
# audio names.
audio_names = np.array(sorted(list(set(df['audio_filename']))))
if mini_data:
random_state = np.random.RandomState(1234)
random_state.shuffle(audio_names)
audio_names = audio_names[0 : 10]
fine_targets = []
coarse_targets = []
for audio_name in audio_names:
# One audio_name may have multiple labelers
indexes = df.index[df['audio_filename'] == audio_name]
fine_target = np.zeros(fine_classes_num)
coarse_target = np.zeros(coarse_classes_num)
# Aggregating annotation of multiple labelers
for index in indexes:
for fine_label in fine_labels:
class_idx = fine_lb_to_idx[fine_label]
label_type = '{}_presence'.format(fine_label)
fine_target[class_idx] += df.iloc[index][label_type]
for coarse_label in coarse_labels:
class_idx = coarse_lb_to_idx[coarse_label]
label_type = '{}_presence'.format(coarse_label)
coarse_target[class_idx] += df.iloc[index][label_type]
# Annotation of an audio is the average annotation of multiple labelrs
fine_target /= len(indexes)
coarse_target /= len(indexes)
fine_targets.append(fine_target)
coarse_targets.append(coarse_target)
fine_targets = np.array(fine_targets)
coarse_targets = np.array(coarse_targets)
meta_dict = {
'audio_name': audio_names,
'fine_target': fine_targets,
'coarse_target': coarse_targets}
return meta_dict
def read_eval_metadata(metadata_path, data_type,mini_data):
'''Read eval metadata csv file.
Args:
metadata_path: string
mini_data: bool, set True for debugging on a small part of data
Returns:
meta_dict
'''
# Read csv data
# assert data_type in ['train', 'validate']
df = pd.read_csv(metadata_path, sep=',')
# df = df[df['split'] == data_type].reset_index()
# Each audio may be annotated by multiple labelers. So remove duplicate
# audio names.
audio_names = np.array(sorted(list(set(df['audio_filename']))))
meta_dict = {
'audio_name': audio_names}
# 'fine_target': fine_targets,
# 'coarse_target': coarse_targets}
return meta_dict
def calculate_feature_for_all_audio_files(args):
'''Calculate feature of audio files and write out features to a hdf5 file.
Args:
dataset_dir: string
data_type: 'train' | 'validate'
workspace: string
mini_data: bool, set True for debugging on a small part of data
'''
# Arguments & parameters
print('!'*10)
print(args)
dataset_dir = args.dataset_dir
data_type = args.data_type
workspace = args.workspace
mini_data = args.mini_data
sample_rate = config.sample_rate
window_size = config.window_size
hop_size = config.hop_size
mel_bins = config.mel_bins
fmin = config.fmin
fmax = config.fmax
frames_per_second = config.frames_per_second
frames_num = config.frames_num
total_samples = config.total_samples
# Paths
if mini_data:
prefix = 'minidata_'
else:
prefix = ''
metadata_path = os.path.join(dataset_dir, 'annotations.csv')
audios_dir = os.path.join(dataset_dir, data_type)
feature_path = os.path.join(workspace, 'features',
'{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins),
'{}.h5'.format(data_type))
create_folder(os.path.dirname(feature_path))
# Feature extractor
feature_extractor = LogMelExtractor(
sample_rate=sample_rate,
window_size=window_size,
hop_size=hop_size,
mel_bins=mel_bins,
fmin=fmin,
fmax=fmax)
# Read metadata
print('Extracting features of all audio files ...')
extract_time = time.time()
meta_dict = read_metadata(metadata_path, data_type, mini_data)
# Hdf5 containing features and targets
hf = h5py.File(feature_path, 'w')
hf.create_dataset(
name='audio_name',
data=[audio_name.encode() for audio_name in meta_dict['audio_name']],
dtype='S32')
if 'fine_target' in meta_dict.keys():
hf.create_dataset(
name='fine_target',
data=meta_dict['fine_target'],
dtype=np.float32)
if 'coarse_target' in meta_dict.keys():
hf.create_dataset(
name='coarse_target',
data=meta_dict['coarse_target'],
dtype=np.float32)
hf.create_dataset(
name='feature',
shape=(0, frames_num, mel_bins),
maxshape=(None, frames_num, mel_bins),
dtype=np.float32)
for (n, audio_name) in enumerate(meta_dict['audio_name']):
audio_path = os.path.join(audios_dir, audio_name)
print(n, audio_path)
# Read audio
(audio, _) = read_audio(
audio_path=audio_path,
target_fs=sample_rate)
# Pad or truncate audio recording
audio = pad_truncate_sequence(audio, total_samples)
# Extract feature
feature = feature_extractor.transform(audio)
# Remove the extra frames caused by padding zero
feature = feature[0 : frames_num]
hf['feature'].resize((n + 1, frames_num, mel_bins))
hf['feature'][n] = feature
hf.close()
print('Write hdf5 file to {} using {:.3f} s'.format(
feature_path, time.time() - extract_time))
def calculate_feature_for_eval_audio_files(args):
'''Calculate eval feature of audio files and write out features to a single hdf5
file.
Args:
dataset_dir: string
workspace: string
data_type: 'train' | 'validate'
mini_data: bool, set True for debugging on a small part of data
'''
# Arguments & parameters
dataset_dir = args.dataset_dir
data_type = args.data_type
workspace = args.workspace
mini_data = args.mini_data
sample_rate = config.sample_rate
window_size = config.window_size
hop_size = config.hop_size
mel_bins = config.mel_bins
fmin = config.fmin
fmax = config.fmax
frames_per_second = config.frames_per_second
frames_num = config.frames_num
total_samples = config.total_samples
# Paths
if mini_data:
prefix = 'minidata_'
else:
prefix = ''
metadata_path = os.path.join(dataset_dir, 'annotations.csv')
audios_dir = os.path.join(dataset_dir, data_type)
feature_path = os.path.join(workspace, 'features',
'{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins),
'{}.h5'.format(data_type))
create_folder(os.path.dirname(feature_path))
# Feature extractor
feature_extractor = LogMelExtractor(
sample_rate=sample_rate,
window_size=window_size,
hop_size=hop_size,
mel_bins=mel_bins,
fmin=fmin,
fmax=fmax)
# Read metadata
print('Extracting features of all audio files ...')
extract_time = time.time()
meta_dict = read_eval_metadata(metadata_path, data_type, mini_data)
# Hdf5 containing features and targets
hf = h5py.File(feature_path, 'w')
hf.create_dataset(
name='audio_name',
data=[audio_name.encode() for audio_name in meta_dict['audio_name']],
dtype='S32')
hf.create_dataset(
name='feature',
shape=(0, frames_num, mel_bins),
maxshape=(None, frames_num, mel_bins),
dtype=np.float32)
for (n, audio_name) in enumerate(meta_dict['audio_name']):
audio_path = os.path.join(audios_dir, audio_name)
print(n, audio_path)
# Read audio
(audio, _) = read_audio(
audio_path=audio_path,
target_fs=sample_rate)
# Pad or truncate audio recording
audio = pad_truncate_sequence(audio, total_samples)
# Extract feature
feature = feature_extractor.transform(audio)
# Remove the extra frames caused by padding zero
feature = feature[0 : frames_num]
hf['feature'].resize((n + 1, frames_num, mel_bins))
hf['feature'][n] = feature
hf.close()
print('Write hdf5 file to {} using {:.3f} s'.format(
feature_path, time.time() - extract_time))
def calculate_scalar(args):
'''Calculate and write out scalar of features.
Args:
data_type: 'train'
workspace: string
mini_data: bool, set True for debugging on a small part of data
'''
# Arguments & parameters
data_type = args.data_type
workspace = args.workspace
mini_data = args.mini_data
mel_bins = config.mel_bins
frames_per_second = config.frames_per_second
# Paths
if mini_data:
prefix = 'minidata_'
else:
prefix = ''
feature_path = os.path.join(workspace, 'features',
'{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins),
'{}.h5'.format(data_type))
scalar_path = os.path.join(workspace, 'scalars',
'{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins),
'{}.h5'.format(data_type))
create_folder(os.path.dirname(scalar_path))
# Load data
load_time = time.time()
with h5py.File(feature_path, 'r') as hf:
features = hf['feature'][:]
# Calculate scalar
features = np.concatenate(features, axis=0)
(mean, std) = calculate_scalar_of_tensor(features)
with h5py.File(scalar_path, 'w') as hf:
hf.create_dataset('mean', data=mean, dtype=np.float32)
hf.create_dataset('std', data=std, dtype=np.float32)
print('All features: {}'.format(features.shape))
print('mean: {}'.format(mean))
print('std: {}'.format(std))
print('Write out scalar to {}'.format(scalar_path))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
subparsers = parser.add_subparsers(dest='mode')
parser_logmel = subparsers.add_parser('calculate_feature_for_all_audio_files')
parser_logmel.add_argument('--dataset_dir', type=str, required=True)
parser_logmel.add_argument('--data_type', type=str, choices=['train', 'validate', 'evaluate'], required=True)
parser_logmel.add_argument('--workspace', type=str, required=True)
parser_logmel.add_argument('--mini_data', action='store_true', default=False)
parser_scalar = subparsers.add_parser('calculate_scalar')
parser_scalar.add_argument('--data_type', type=str, choices=['train','evaluate'], required=True)
parser_scalar.add_argument('--workspace', type=str, required=True)
parser_scalar.add_argument('--mini_data', action='store_true', default=False)
args = parser.parse_args()
print('#'*10)
print(args)
if args.mode == 'calculate_feature_for_all_audio_files':
calculate_feature_for_all_audio_files(args)
elif args.mode == 'calculate_scalar':
calculate_scalar(args)
else:
raise Exception('Incorrect arguments!')
#python features.py calculate_feature_for_all_audio_files --dataset_dir data --data_type evaluate --workspace workspace