-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel_feature_extraction.py
191 lines (158 loc) · 6.72 KB
/
parallel_feature_extraction.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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# NOTE: librosa dependencies apparently require specific versions of numpy, try numpy==1.21.4
import librosa
import librosa.display
import os
import scipy
from joblib import Parallel, delayed
# Data should be placed in the "large_data/" directory, which is not staged in the git repo
metadata = pd.read_csv('./large_data/UrbanSound8K/metadata/UrbanSound8K.csv')
# metadata.info()
# Function to load wav file with librosa, given a row from metadata table
def load_data(meta_row):
filename = meta_row['slice_file_name']
filepath = f'large_data/UrbanSound8K/audio/fold{meta_row["fold"]}/'
return librosa.load(filepath+filename,sr=None)
def write_csv_line(filenm, eq_cutoffs, row_ind):
file = open(filenm+"_"+str(os.getpid())+".csv",'a+')
row = metadata.loc[row_ind]
y,sr = load_data(metadata.loc[row_ind])
## get the class and fold
classifier = metadata['class'][row_ind]
foldinfo = metadata['fold'][row_ind]
## get timing info
t = round(row["end"]-row["start"],3)
dt = t/len(y)
k = np.fft.fftfreq(len(y), d=dt)
# k = k[:len(k)//2]
## get salience
sal = row["salience"]
## hilbert transform filtering for "room noise"
hil = np.abs(scipy.signal.hilbert(y))
hilk = np.fft.fft(hil)
hilk *= np.exp(-k*k / (2*10**2))
hil2 = np.fft.ifft(hilk)
hil2 = np.abs(hil2)
hil2 *= hil.max() / hil2.max()
filt_y = y * hil2/np.sqrt((y*y).mean())
filt_y *= y.max() / filt_y.max()
y_sq = filt_y*filt_y
## get crest factor
Cr = filt_y.max() / np.sqrt(y_sq.mean())
yk = np.fft.fft(filt_y)
mag_yk = np.abs(yk)
mag_yk = mag_yk[:len(mag_yk)//2]
## seperate into harmonic and percussive components
D = librosa.stft(filt_y / filt_y.max())
y_harmonic, y_percussive = librosa.decompose.hpss(D,margin=16.0)
y_p = librosa.istft(y_percussive, length=len(filt_y))
y_h = librosa.istft(y_harmonic, length=len(filt_y))
Ptot = (filt_y**2).mean()
ynorm = filt_y / np.sqrt(Ptot)
Pnorm = (ynorm**2).mean()
P_p = (y_p**2).mean()
P_h = (y_h**2).mean()
Anorm = np.sqrt(Pnorm/(P_h+P_p))
y_p *= Anorm
y_h *= Anorm
y_percussive = librosa.stft(y_p)
y_harmonic = librosa.stft(y_h)
## generate the MIDI range and corresponding frequencies
st_k = np.fft.fftfreq(np.size(y_harmonic,0), d=dt)
fbins = []
keypitch = []
midi = []
maxlen=np.size(y_harmonic,0)
p = -69
kmin = 440*2**((p - 0.5)/12)
kmax = 440*2**((p+0.5)/12)
while kmax <= 20000:
kmin = 440*2**((p - 0.5)/12)
kmax = 440*2**((p+0.5)/12)
keypitch.append(440*2**(p/12))
midi.append(p+69)
p += 1
## sum up the number of 3rds, 5ths, and chords
harmonicality = 0
for tm in range(np.size(y_harmonic,1)):
p = -69
kmin = 440*2**((p - 0.5)/12)
kmax = 440*2**((p+0.5)/12)
while kmax <= 20000:
kmin = 440*2**((p - 0.5)/12)
kmax = 440*2**((p+0.5)/12)
if (len(np.abs(y_harmonic[(st_k[:maxlen] <= kmax) & (st_k[:maxlen] > kmin),tm])) != 0) :
sumbin = np.abs(y_harmonic[(st_k[:maxlen] <= kmax) & (st_k[:maxlen] > kmin),tm]).sum() / len(np.abs(y_harmonic[(st_k[:maxlen] <= kmax) & (st_k[:maxlen] > kmin),tm]))
else:
sumbin = 0
fbins.append(sumbin)
p += 1
peaks = librosa.util.localmax(np.asarray(fbins))
maj3 = []
min3 = []
maj5 = []
majchord = []
fbins2 = np.asarray(fbins)
if len(fbins2[fbins2 > 0] > 0):
favg = fbins2[fbins2 > 0].max()
else:
favg = 1
for i in range(len(fbins)-4):
maj3.append(peaks[i]*peaks[i+4]*(fbins[i] + fbins[i+4])/favg)
for i in range(len(fbins)-3):
min3.append(peaks[i]*peaks[i+3]*(fbins[i] + fbins[i+3])/favg)
for i in range(len(fbins)-7):
maj5.append(peaks[i]*peaks[i+7]*(fbins[i] + fbins[i+7])/favg)
majchord.append(peaks[i]*peaks[i+4]*peaks[i+7]*(fbins[i] + fbins[i+4] + fbins[i+7])/favg)
maj3 = np.asarray(maj3)
min3 = np.asarray(min3)
maj5 = np.asarray(maj5)
majchord = np.asarray(majchord)
maj3 = len(maj3[np.log10(maj3 + 1e-12)>=-0.5])
min3 = len(min3[np.log10(min3 + 1e-12)>=-0.5])
maj5 = len(maj5[np.log10(maj5 + 1e-12)>=-0.5])
majchord = len(majchord[np.log10(majchord + 1e-12)>=-0.5])
harmonicality += maj3 + min3 + maj5 + majchord
## divide by the number of time slices to get mean harmonicality
harmrate = harmonicality / np.size(y_harmonic,1)
## from the percussive component get the onsets for number of percussive hits
y_out = librosa.istft(y_percussive, length=len(filt_y))
onset_env = librosa.onset.onset_strength(y=y_out, sr=sr,
max_size=5,
aggregate=np.median)
perc_peaks = librosa.util.peak_pick(onset_env, pre_max=3, post_max=3, pre_avg=3, post_avg=5, delta=0.5, wait=0)
perc_rate = len(perc_peaks) #/ t
## generate equilizer values from fourier transform
equilizer = np.zeros(len(eq_cutoffs))
index = 0
for i in range(len(equilizer)):
num = 0
while ((index < len(mag_yk)) & (k[index] < eq_cutoffs[i])):
equilizer[i] += mag_yk[index]
index += 1
num += 1
equilizer[i] /= num
## write everything to csv
file.write(str(row_ind)+",")
file.write(classifier)
for i in range(len(eq_cutoffs)):
file.write(","+str(equilizer[i]))
file.write(","+str(Cr)+","+str(sal)+","+str(P_h)+","+str(P_p)+","+str(harmrate)+","+str(perc_rate)+","+str(foldinfo)+"\n")
# file.write(","+str(sal))
# file.write(","+str(P_h))
# file.write(","+str(P_p))
# file.write(","+str(harmrate))
# file.write(","+str(perc_rate))
# file.write(","+str(foldinfo)+"\n")
print("preprocessed audio file ", str(row_ind))
file.close()
def make_csv(filenm):
file = open(filenm+"_header.csv",'a+')
file.write("index,class,eq_0,eq_10,eq_20,eq_30,eq_40,eq_60,eq_80,eq_120,eq_160,eq_230,eq_300,eq_450,eq_600,eq_900,eq_1200,eq_1800,eq_2400,eq_3700,eq_5000,eq_7500,eq_10000,eq_15000,eq_20000,crestfactor,salience,harmonic_power,percussive_power,harmonic_hits,percussive_hits,fold\n")
file.close()
eq_cutoffs = [10.0, 20.0, 30.0, 40.0, 60.0, 80.0, 120.0, 160.0, 230.0, 300.0, 450.0, 600.0, 900.0, 1200.0, 1800.0, 2400.0, 3700.0, 5000.0, 7500.0, 10000.0, 15000.0, 20000.0, np.inf]
backend = 'loky'
Parallel(n_jobs=40, backend = backend)(delayed(write_csv_line)(filenm, eq_cutoffs, row_ind) for row_ind in range(len(metadata)))
make_csv('./large_data/eq_with_harmony3')