-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.py
263 lines (214 loc) · 9.01 KB
/
analyzer.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
import sys
import argparse
import os
from pympler import muppy
from pympler import summary
from yaafelib import *
from aubio import pitch
from aubio import source, pvoc, mfcc
import numpy as numpy
from numpy import array, vstack, zeros
from scipy.io import wavfile
from tqdm import *
from pymongo import MongoClient
from pydub import AudioSegment
def main():
args = parseArgs()
if(args.clear):
clearData()
#processing
if(args.mfcc or args.all):
analyzeAllMFCC()
if(args.pitch or args.all):
analyzeAllPitch()
if(args.energy or args.all):
analyzeAllEnergy()
if(args.shape or args.all):
analyzeAllSpectralShape()
if(args.zcr or args.all):
analyzeAllZeroCrossingRate()
def clearData():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
grains = grainEntries.find({})
print("Clearing " + str(grains.count()) + " grains")
for grain in tqdm(grains):
os.remove(grain["file"])
grainEntries.delete_one({"_id" : grain["_id"]})
client.close()
def extractFile(grain):
return grain["file"];
def analyzePitchSubset(grains):
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "pitch" : { "$exists" : False }, "file" : { "$in" : map(extractFile, grains)}})
print("Analyzing Pitch for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"pitch" : analyzePitch(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeAllPitch():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "pitch" : { "$exists": False }})
print("Analyzing Pitch for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"pitch" : analyzePitch(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzePitch(grain):
s = source(grain["file"], int(grain["sampleRate"]), int(float(grain["frameCount"])))
samplerate = s.samplerate
tolerance = 0.8
pitch_out = pitch("yin", int(float(grain["frameCount"])), int(float(grain["frameCount"])), samplerate)
samples, read = s()
pitchFreq = pitch_out(samples)[0].item()
del s
return pitchFreq
def analyzeZeroCrossingRateSubset(grains):
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "zcr" : { "$exists" : False }, "file" : { "$in" : map(extractFile, grains)}})
print("Analyzing ZCR for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"zcr" : analyzeZeroCrossingRate(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeAllZeroCrossingRate():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "zcr" : { "$exists": False }})
print("Analyzing Zero Crossing Rate for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"zcr" : analyzeZeroCrossingRate(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeZeroCrossingRate(grain):
blockSize = grain["frameCount"]
stepSize = grain["frameCount"]
fp = FeaturePlan(sample_rate=int(grain["sampleRate"]))
fp.addFeature('zcr: ZCR blockSize=' + blockSize + ' stepSize=' + stepSize)
engine = Engine()
engine.load(fp.getDataFlow())
(rate, data) = wavfile.read(grain["file"])
data = numpy.array([data.astype(numpy.float64)]);
feats = engine.processAudio(data)
del data
return feats["zcr"][0][0]
def analyzeAllSpectralShape():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "centroid" : { "$exists": False }})
print("Analyzing Spectral Shape for " + str(query.count()) + " grains")
for grain in tqdm(query):
centroid, spread, skewness, kurtosis = analyzeSpectralShape(grain)
update = {"centroid" : centroid,
"spread" : spread,
"skewness" : skewness,
"kurtosis" : kurtosis}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeSpectralShape(grain):
blockSize = grain["frameCount"]
stepSize = grain["frameCount"]
fp = FeaturePlan(sample_rate=int(grain["sampleRate"]))
fp.addFeature('spectralShape: SpectralShapeStatistics blockSize=' + blockSize + ' stepSize=' + stepSize)
engine = Engine()
engine.load(fp.getDataFlow())
(rate, data) = wavfile.read(grain["file"])
data = numpy.array([data.astype(numpy.float64)]);
feats = engine.processAudio(data)
del data
return (feats["spectralShape"][0][0], feats["spectralShape"][0][1], feats["spectralShape"][0][2], feats["spectralShape"][0][3])
def analyzeEnergySubset(grains):
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "energy" : { "$exists" : False }, "file" : { "$in" : map(extractFile, grains)}})
print("Analyzing Energy for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"energy" : analyzeEnergy(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeAllEnergy():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "energy" : { "$exists": False }})
print("Analyzing Energy for " + str(query.count()) + " grains")
for grain in tqdm(query):
update = {"energy" : analyzeEnergy(grain)}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeEnergy(grain):
blockSize = grain["frameCount"]
stepSize = grain["frameCount"]
fp = FeaturePlan(sample_rate=int(grain["sampleRate"]))
fp.addFeature('energy: Energy blockSize=' + blockSize + ' stepSize=' + stepSize)
engine = Engine()
engine.load(fp.getDataFlow())
(rate, data) = wavfile.read(grain["file"])
data = numpy.array([data.astype(numpy.float64)]);
feats = engine.processAudio(data)
del data
return feats["energy"][0][0]
def analyzeMFCCSubset(grains):
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "mfcc00" : { "$exists" : False }, "file" : { "$in" : map(extractFile, grains)}})
print("Analyzing MFCC for " + str(query.count()) + " grains")
for grain in tqdm(query):
mfccs = analyzeMFCC(grain)
for mfccIndex in range(0, len(mfccs)):
update = {"mfcc" + format(mfccIndex, '02') : mfccs[mfccIndex]}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
client.close()
def analyzeAllMFCC():
client = MongoClient()
db = client.audiograins
grainEntries = db.grains
query = grainEntries.find({ "mfcc00" : { "$exists": False }})
print("Analyzing MFCC for " + str(query.count()) + " grains")
for grain in tqdm(query):
mfccs = analyzeMFCC(grain)
for mfccIndex in range(0, len(mfccs)):
update = {"mfcc" + format(mfccIndex, '02') : mfccs[mfccIndex]}
grainEntries.update_one({"_id": grain["_id"]}, {"$set" : update})
summary.print_(summary.summarize(muppy.get_objects()))
client.close()
def analyzeMFCC(grain):
windowSize = int(float(grain["frameCount"]))
s = source(grain["file"], int(grain["sampleRate"]), windowSize - 1)
sampleRate = s.samplerate
p = pvoc(windowSize, windowSize - 1)
m = mfcc(windowSize, 40, 13, s.samplerate)
samples, read = s()
spec = p(samples)
mfcc_out = m(spec)
mfccs = mfcc_out.tolist()
return mfccs
def parseArgs():
parser = argparse.ArgumentParser(description='Analyze a set of grains to extract features and label them')
parser.add_argument('--clear', dest="clear", action="store_true", help="Delete all grains and clear all grain data.");
parser.add_argument('--mfcc', dest="mfcc", action="store_true", help="Include to not compute Mel Frequency Cepstrum Coefficients");
parser.add_argument('--pitch', dest="pitch", action="store_true", help="Include to not compute pitches");
parser.add_argument('--energy', dest="energy", action="store_true", help="Compute RMS energy for grain");
parser.add_argument('--shape', dest="shape", action="store_true", help="Compute the spectral shape data for grain");
parser.add_argument('--all', dest="all", action="store_true", help="Compute all available features");
parser.add_argument('--zcr', dest="zcr", action="store_true", help="Compute Zero Crossing Rate for grains");
parser.set_defaults(clear=False)
parser.set_defaults(mfcc=False)
parser.set_defaults(shape=False)
parser.set_defaults(zcr=False)
parser.set_defaults(energy=False)
parser.set_defaults(all=False)
return parser.parse_args()
if __name__ == "__main__":
main()