-
Notifications
You must be signed in to change notification settings - Fork 10
/
common.py
297 lines (246 loc) · 11.2 KB
/
common.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
########################################################################
# import python-library
########################################################################
# default
import glob
import argparse
import sys
import os
import itertools
import re
# additional
import numpy as np
import librosa
import librosa.core
import librosa.feature
import yaml
########################################################################
########################################################################
# setup STD I/O
########################################################################
"""
Standard output is logged in "baseline.log".
"""
import logging
logging.basicConfig(level=logging.DEBUG, filename="baseline.log")
logger = logging.getLogger(' ')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
########################################################################
########################################################################
# version
########################################################################
__versions__ = "1.0.0"
########################################################################
########################################################################
# argparse
########################################################################
def command_line_chk():
parser = argparse.ArgumentParser(description='Without option argument, it will not run properly.')
parser.add_argument('-v', '--version', action='store_true', help="show application version")
parser.add_argument('-d', '--dev', action='store_true', help="run mode Development")
parser.add_argument('-e', '--eval', action='store_true', help="run mode Evaluation")
args = parser.parse_args()
if args.version:
print("===============================")
print("DCASE 2021 task 2 baseline\nversion {}".format(__versions__))
print("===============================\n")
if args.dev:
flag = True
elif args.eval:
flag = False
else:
flag = None
print("incorrect argument")
print("please set option argument '--dev' or '--eval'")
return flag
########################################################################
########################################################################
# load parameter.yaml
########################################################################
def yaml_load():
with open("baseline.yaml") as stream:
param = yaml.safe_load(stream)
return param
########################################################################
########################################################################
# file I/O
########################################################################
# wav file input
def file_load(wav_name, mono=False):
"""
load .wav file.
wav_name : str
target .wav file
mono : boolean
When load a multi channels file and this param True, the returned data will be merged for mono data
return : numpy.array( float )
"""
try:
return librosa.load(wav_name, sr=None, mono=mono)
except:
logger.error("file_broken or not exists!! : {}".format(wav_name))
########################################################################
########################################################################
# feature extractor
########################################################################
def file_to_vectors(file_name,
n_mels=64,
n_frames=5,
n_fft=1024,
hop_length=512,
power=2.0):
"""
convert file_name to a vector array.
file_name : str
target .wav file
return : numpy.array( numpy.array( float ) )
vector array
* dataset.shape = (dataset_size, feature_vector_length)
"""
# calculate the number of dimensions
dims = n_mels * n_frames
# generate melspectrogram using librosa
y, sr = file_load(file_name, mono=True)
mel_spectrogram = librosa.feature.melspectrogram(y=y,
sr=sr,
n_fft=n_fft,
hop_length=hop_length,
n_mels=n_mels,
power=power)
# convert melspectrogram to log mel energies
log_mel_spectrogram = 20.0 / power * np.log10(np.maximum(mel_spectrogram, sys.float_info.epsilon))
# calculate total vector size
n_vectors = len(log_mel_spectrogram[0, :]) - n_frames + 1
# skip too short clips
if n_vectors < 1:
return np.empty((0, dims))
# generate feature vectors by concatenating multiframes
vectors = np.zeros((n_vectors, dims))
for t in range(n_frames):
vectors[:, n_mels * t : n_mels * (t + 1)] = log_mel_spectrogram[:, t : t + n_vectors].T
return vectors
########################################################################
########################################################################
# get directory paths according to mode
########################################################################
def select_dirs(param, mode):
"""
param : dict
baseline.yaml data
return :
if active type the development :
dirs : list [ str ]
load base directory list of dev_data
if active type the evaluation :
dirs : list [ str ]
load base directory list of eval_data
"""
if mode:
logger.info("load_directory <- development")
query = os.path.abspath("{base}/*".format(base=param["dev_directory"]))
else:
logger.info("load_directory <- evaluation")
query = os.path.abspath("{base}/*".format(base=param["eval_directory"]))
dirs = sorted(glob.glob(query))
dirs = [f for f in dirs if os.path.isdir(f)]
return dirs
########################################################################
########################################################################
# get machine IDs
########################################################################
def get_section_names(target_dir,
dir_name,
ext="wav"):
"""
target_dir : str
base directory path
dir_name : str
sub directory name
ext : str (default="wav)
file extension of audio files
return :
section_names : list [ str ]
list of section names extracted from the names of audio files
"""
# create test files
query = os.path.abspath("{target_dir}/{dir_name}/*.{ext}".format(target_dir=target_dir, dir_name=dir_name, ext=ext))
file_paths = sorted(glob.glob(query))
# extract section names
section_names = sorted(list(set(itertools.chain.from_iterable(
[re.findall('section_[0-9][0-9]', ext_id) for ext_id in file_paths]))))
return section_names
########################################################################
########################################################################
# get the list of wave file paths
########################################################################
def file_list_generator(target_dir,
section_name,
dir_name,
mode,
prefix_normal="normal",
prefix_anomaly="anomaly",
ext="wav"):
"""
target_dir : str
base directory path
section_name : str
section name of audio file in <<dir_name>> directory
dir_name : str
sub directory name
prefix_normal : str (default="normal")
normal directory name
prefix_anomaly : str (default="anomaly")
anomaly directory name
ext : str (default="wav")
file extension of audio files
return :
if the mode is "development":
files : list [ str ]
audio file list
labels : list [ boolean ]
label info. list
* normal/anomaly = 0/1
if the mode is "evaluation":
files : list [ str ]
audio file list
"""
logger.info("target_dir : {}".format(target_dir + "_" + section_name))
# development
if mode:
query = os.path.abspath("{target_dir}/{dir_name}/{section_name}_*_{prefix_normal}_*.{ext}".format(target_dir=target_dir,
dir_name=dir_name,
section_name=section_name,
prefix_normal=prefix_normal,
ext=ext))
normal_files = sorted(glob.glob(query))
normal_labels = np.zeros(len(normal_files))
query = os.path.abspath("{target_dir}/{dir_name}/{section_name}_*_{prefix_normal}_*.{ext}".format(target_dir=target_dir,
dir_name=dir_name,
section_name=section_name,
prefix_normal=prefix_anomaly,
ext=ext))
anomaly_files = sorted(glob.glob(query))
anomaly_labels = np.ones(len(anomaly_files))
files = np.concatenate((normal_files, anomaly_files), axis=0)
labels = np.concatenate((normal_labels, anomaly_labels), axis=0)
logger.info("#files : {num}".format(num=len(files)))
if len(files) == 0:
logger.exception("no_wav_file!!")
print("\n========================================")
# evaluation
else:
query = os.path.abspath("{target_dir}/{dir_name}/{section_name}_*.{ext}".format(target_dir=target_dir,
dir_name=dir_name,
section_name=section_name,
ext=ext))
files = sorted(glob.glob(query))
labels = None
logger.info("#files : {num}".format(num=len(files)))
if len(files) == 0:
logger.exception("no_wav_file!!")
print("\n=========================================")
return files, labels
########################################################################