/
vd.py
235 lines (168 loc) · 5.91 KB
/
vd.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
#!/usr/bin/env python
# encoding: utf-8
import wavio
import sys
from glob import glob
from scipy.signal import decimate
from features import mfcc
import bisect
import random
import numpy as np
from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
from sklearn import svm
class LabelTeller():
"""docstring for LabelTeller"""
def __init__(self, firstLabel, blockLimits):
self._firstLabel = firstLabel
self._blockLimits = blockLimits
self._secondLabel = 'sing' if 'nosing' == self._firstLabel else 'nosing'
def tell(self, noOfBlock):
index = bisect.bisect_left(self._blockLimits, noOfBlock)
return self._firstLabel if 0 == (index % 2) else self._secondLabel
def tellNoOfAllBlocks(self):
return self._blockLimits[-1] + 1
class Loader():
"""docstring for Loader"""
def __init__(self, labelDir, blockLength, overlap):
# labelDir should end with /
# blockLength is in ms
self._labelDir = labelDir
self._blockLength = blockLength / 1000.0
self._overlap = overlap / 1000.0
self._firstLabel = ''
self._blockLimits = []
def loadLabelsForSoundfile(self, soundFilename):
self._blockLimits = []
labelFilePath = self._labelDir+ "../jamendo_lab/"+ soundFilename.replace('.wav', '.lab')
with open(labelFilePath, 'r') as f:
intervalLimits = self.parse(f)
self.transformTimeIntervalsToBlocks(intervalLimits)
return LabelTeller(self._firstLabel, self._blockLimits)
def parse(self, labelFile):
intervalLimits = []
line = labelFile.readline().split(' ')
self._firstLabel = line[2].rstrip()
intervalLimits.append(float(line[1]))
for line in labelFile:
intervalEnd = line.split(' ')[1]
intervalLimits.append(float(intervalEnd))
return intervalLimits
def transformTimeIntervalsToBlocks(self, intervalLimits):
for limit in intervalLimits:
blockLimit = int(limit / (self._blockLength - self._overlap)) - 1
# int not round because decimal is related to half of block
self._blockLimits.append(blockLimit)
class Dataset(object):
"""Docstring for Data. """
def __init__(self, directory):
self.directory = directory
def validationTracks(self):
for filename in glob(self.directory+"/valid" + "/*.wav"):
yield filename
def trainTracks(self):
for filename in glob(self.directory+"/train" + "/*.wav"):
yield filename
def testTracks(self):
for filename in glob(self.directory+"/test" + "/*.wav"):
yield filename
def adnotations(self):
for filename in glob(self.directory+"/jamendo_lab" + "/*.lab"):
yield filename
#def windows(self,track, rate, width, overlap):
# wav = wavio.read(track)
# signal = decimate(wav.data[:, 0], wav.rate / rate)
# print wav.rate
#for start in xrange(0, signal.shape[0] - width + overlap, overlap):
#if start > overlap:
# start -= overlap
# yield signal[start:(start+width)]
class VocalDetector(object):
"""Docstring for VocalDetector. """
def __init__(self):
self.classifier = svm.SVC(cache_size=2000)
def main(path):
ds = Dataset(path)
loader = Loader(path+"/train/", 32,16)
X = []
y=[]
Z= []
ii = 0
for p in ds.trainTracks():
f=p.split("/")
name = f[len(f)-1]
labelTeller = loader.loadLabelsForSoundfile(name)
[Fs, x] = audioBasicIO.readAudioFile(p)
F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.032*Fs, 0.016*Fs);
G = zip(*F)
N = 0
if(len(G)>labelTeller.tellNoOfAllBlocks()):
N = labelTeller.tellNoOfAllBlocks()
else:
N = len(G)
for i in range(N):
Z.append([G[i],labelTeller.tell(i)])
#i = 0
#for w in ds.windows(x,44100, 1410, 705):
# mf = mfcc(w)
#row = [i]
# Z.append([mf[0],labelTeller.tell(i)])
# i = i+1
print p +" "+ str(ii)+"/61"
ii = ii +1
print "shuffle"
random.shuffle(Z)
Z = zip(*Z)
NN = 20000
L = NN
R = NN
FINAL =[[],[]]
for i in range(len(Z[0])):
if(Z[1][i] == 'sing' and L>0 ):
L = L - 1
FINAL[0].append(Z[0][i])
FINAL[1].append(Z[1][i])
if(Z[1][i] == 'nosing' and R>0 ):
R = R - 1
FINAL[0].append(Z[0][i])
FINAL[1].append(Z[1][i])
clf = svm.SVC(cache_size=2000)
print "######### " + str(len(Z[0]))
clf.fit(FINAL[0], FINAL[1])
loader = Loader(path+"/test/", 32,16)
print "Loading test"
for p in ds.validationTracks():
X = []
y=[]
f=p.split("/")
name = f[len(f)-1]
labelTeller = loader.loadLabelsForSoundfile(name)
i = 0
[Fs, x] = audioBasicIO.readAudioFile(p)
F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.032*Fs, 0.016*Fs);
G = zip(*F)
N = 0
if(len(G)>labelTeller.tellNoOfAllBlocks()):
N = labelTeller.tellNoOfAllBlocks()
else:
N = len(G)
for i in range(N):
X.append(G[i])
y.append(labelTeller.tell(i))
print "Starting prediction "+p
Y= clf.predict(X)
ok = 0
al = 0
for i in range(len(y)):
if(y[i]==Y[i]):
ok = ok +1
al = al +1
print ok/float(al)
#for w in ds.windows(x,44100, 1410, 705):
# mf = mfcc(w)
# #row = [i]
# X.append(mf[0])
# y.append(labelTeller.tell(i))
# i = i+1
if __name__ == '__main__':
main(sys.argv[1])