-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain_compute_indices_from_dir
262 lines (204 loc) · 13.3 KB
/
main_compute_indices_from_dir
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
__author__ = 'guyot'
#!/usr/bin/env python
"""
Compute and output acoustic indices from a directory
"""
__author__ = "Patrice Guyot"
__version__ = "0.1"
__credits__ = ["Patrice Guyot"]
__email__ = ["[email protected]"]
__status__ = "Development"
from compute_indice import *
from acoustic_index import *
import yaml
from scipy import signal
from csv import writer
import argparse
import os
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("config_file", help='yaml config file', nargs='?', const='yaml/config_014_butter.yaml', default='yaml/config_014_butter.yaml', type=str)
parser.add_argument("audio_dir", help='audio directory', nargs='?', const='audio_files', default='audio_files', type=str)
parser.add_argument("output_csv_file", help='output csv file', nargs='?', const='dict_all.csv', default='dict_all.csv', type=str)
args =parser.parse_args()
#Set config file
yml_file = args.config_file
print("Config file: ", yml_file)
with open(yml_file, 'r') as stream:
data_config = yaml.load(stream, Loader=yaml.FullLoader)
print("audio directory: ", args.audio_dir)
print("output_csv_file: ", args.output_csv_file)
# Get audio files
all_audio_file_path = []
for path, subdirs, files in os.walk(args.audio_dir):
for name in files :
if name.endswith(".wav") and not name.startswith("."):
all_audio_file_path.append(os.path.join(path, name))
print("-", len(all_audio_file_path), "files found in the directory", args.audio_dir,':\n')
for idx_file, filename in enumerate(all_audio_file_path):
# Read signal -------------------------------------
file = AudioFile(filename, verbose=True)
# Pre-processing -----------------------------------------------------------------------------------
if 'Filtering' in data_config:
if data_config['Filtering']['type'] == 'butterworth':
print('- Pre-processing - High-Pass Filtering:', data_config['Filtering'])
freq_filter = data_config['Filtering']['frequency']
Wn = freq_filter/float(file.niquist)
order = data_config['Filtering']['order']
[b,a] = signal.butter(order, Wn, btype='highpass')
# to plot the frequency response
#w, h = signal.freqz(b, a, worN=2000)
#plt.plot((file.sr * 0.5 / np.pi) * w, abs(h))
#plt.show()
file.process_filtering(signal.filtfilt(b, a, file.sig_float))
elif data_config['Filtering']['type'] == 'windowed_sinc':
print('- Pre-processing - High-Pass Filtering:', data_config['Filtering'])
freq_filter = data_config['Filtering']['frequency']
fc = freq_filter / float(file.sr)
roll_off = data_config['Filtering']['roll_off']
b = roll_off / float(file.sr)
N = int(np.ceil((4 / b)))
if not N % 2: N += 1 # Make sure that N is odd.
n = np.arange(N)
# Compute a low-pass filter.
h = np.sinc(2 * fc * (n - (N - 1) / 2.))
w = np.blackman(N)
h = h * w
h = h / np.sum(h)
# Create a high-pass filter from the low-pass filter through spectral inversion.
h = -h
h[(N - 1) / 2] += 1
file.process_filtering(np.convolve(file.sig_float, h))
# Compute Indices -----------------------------------------------------------------------------------
print('- Compute Indices')
ci = data_config['Indices'] # use to simplify the notation
for index_name in ci: # iterate over the index names (key of dictionary in the yml file)
if index_name == 'Acoustic_Complexity_Index':
print('\tCompute', index_name)
spectro, _ = compute_spectrogram(file, **ci[index_name]['spectro'])
methodToCall = globals().get(ci[index_name]['function'])
j_bin = int(ci[index_name]['arguments']['j_bin'] * file.sr / ci[index_name]['spectro']['windowHop']) # transform j_bin in samples
main_value, temporal_values = methodToCall(spectro, j_bin)
file.indices[index_name] = Index(index_name, temporal_values=temporal_values, main_value=main_value)
elif index_name == 'Acoustic_Diversity_Index':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
freq_band_Hz = ci[index_name]['arguments']['max_freq'] / ci[index_name]['arguments']['freq_step']
windowLength = int(file.sr / freq_band_Hz)
spectro,_ = compute_spectrogram(file, windowLength=windowLength, windowHop= windowLength, scale_audio=True, square=False, windowType='hanning', centered=False, normalized= False )
main_value = methodToCall(spectro, freq_band_Hz, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Acoustic_Evenness_Index':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
freq_band_Hz = ci[index_name]['arguments']['max_freq'] / ci[index_name]['arguments']['freq_step']
windowLength = int(file.sr / freq_band_Hz)
spectro,_ = compute_spectrogram(file, windowLength=windowLength, windowHop= windowLength, scale_audio=True, square=False, windowType='hanning', centered=False, normalized= False )
main_value = methodToCall(spectro, freq_band_Hz, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Bio_acoustic_Index':
print('\tCompute', index_name)
spectro, frequencies = compute_spectrogram(file, **ci[index_name]['spectro'])
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(spectro, frequencies, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Normalized_Difference_Sound_Index':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(file, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'RMS_energy':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
temporal_values = methodToCall(file, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, temporal_values=temporal_values)
elif index_name == 'Spectral_centroid':
print('\tCompute', index_name)
spectro, frequencies = compute_spectrogram(file, **ci[index_name]['spectro'])
methodToCall = globals().get(ci[index_name]['function'])
temporal_values = methodToCall(spectro, frequencies)
file.indices[index_name] = Index(index_name, temporal_values=temporal_values)
elif index_name == 'Spectral_Entropy':
print('\tCompute', index_name)
spectro, _ = compute_spectrogram(file, **ci[index_name]['spectro'])
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(spectro)
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Temporal_Entropy':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(file, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'ZCR':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
temporal_values = methodToCall(file, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, temporal_values=temporal_values)
elif index_name == 'Wave_SNR':
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
values = methodToCall(file, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, values=values)
elif index_name == 'NB_peaks':
print('\tCompute', index_name)
spectro, frequencies = compute_spectrogram(file, **ci[index_name]['spectro'])
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(spectro, frequencies, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Acoustic_Diversity_Index_NR': # Acoustic_Diversity_Index with Noise Removed spectrograms
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
freq_band_Hz = ci[index_name]['arguments']['max_freq'] / ci[index_name]['arguments']['freq_step']
windowLength = int(file.sr / freq_band_Hz)
spectro,_ = compute_spectrogram(file, windowLength=windowLength, windowHop= windowLength, scale_audio=True, square=False, windowType='hanning', centered=False, normalized= False )
spectro_noise_removed = remove_noiseInSpectro(spectro, **ci[index_name]['remove_noiseInSpectro'])
main_value = methodToCall(spectro_noise_removed, freq_band_Hz, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Acoustic_Evenness_Index_NR': # Acoustic_Evenness_Index with Noise Removed spectrograms
print('\tCompute', index_name)
methodToCall = globals().get(ci[index_name]['function'])
freq_band_Hz = ci[index_name]['arguments']['max_freq'] / ci[index_name]['arguments']['freq_step']
windowLength = int(file.sr / freq_band_Hz)
spectro,_ = compute_spectrogram(file, windowLength=windowLength, windowHop= windowLength, scale_audio=True, square=False, windowType='hanning', centered=False, normalized= False )
spectro_noise_removed = remove_noiseInSpectro(spectro, **ci[index_name]['remove_noiseInSpectro'])
main_value = methodToCall(spectro_noise_removed, freq_band_Hz, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Bio_acoustic_Index_NR': # Bio_acoustic_Index with Noise Removed spectrograms
print('\tCompute', index_name)
spectro, frequencies = compute_spectrogram(file, **ci[index_name]['spectro'])
spectro_noise_removed = remove_noiseInSpectro(spectro, **ci[index_name]['remove_noiseInSpectro'])
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(spectro_noise_removed, frequencies, **ci[index_name]['arguments'])
file.indices[index_name] = Index(index_name, main_value=main_value)
elif index_name == 'Spectral_Entropy_NR': # Spectral_Entropy with Noise Removed spectrograms
print('\tCompute', index_name)
spectro, _ = compute_spectrogram(file, **ci[index_name]['spectro'])
spectro_noise_removed = remove_noiseInSpectro(spectro, **ci[index_name]['remove_noiseInSpectro'])
methodToCall = globals().get(ci[index_name]['function'])
main_value = methodToCall(spectro_noise_removed)
file.indices[index_name] = Index(index_name, main_value=main_value)
# Output Indices -----------------------------------------------------------------------------------
if idx_file == 0:
with open(args.output_csv_file, 'w') as f_object:
writer_object = writer(f_object)
keys = ['filename']
values = [file.file_name]
for idx, current_index in file.indices.items():
for key, value in current_index.__dict__.items():
if key != 'name':
keys.append(idx + '__' + key)
values.append(value)
writer_object.writerow(keys)
writer_object.writerow(values)
f_object.close()
else:
with open(args.output_csv_file, 'a') as f_object:
writer_object = writer(f_object)
values = [file.file_name]
for idx, current_index in file.indices.items():
for key, value in current_index.__dict__.items():
if key != 'name':
values.append(value)
writer_object.writerow(values)
f_object.close()
print("\n")