-
Notifications
You must be signed in to change notification settings - Fork 28
/
voice.py
390 lines (287 loc) · 12.2 KB
/
voice.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/uspeech_recognition/bin/env python3
"""
This is a demo for a voice biometrics application
"""
# ------------------------------------------------------------------------------------------------------------------------------------#
# Installing Packages Needed #
# ------------------------------------------------------------------------------------------------------------------------------------#
# This is used to dump the models into an object
import pickle
import datetime
import os # For creating directories
import shutil # For deleting directories
# from collections import defaultdict
import matplotlib.pyplot as plt
import numpy
import scipy.cluster
import scipy.io.wavfile
# For the speech detection alogrithms
import speech_recognition
# For the fuzzy matching algorithms
from fuzzywuzzy import fuzz
# For using the MFCC feature selection
from python_speech_features import mfcc
# For generating random words
from random_words import RandomWords
from sklearn import preprocessing
# For using the Gausian Mixture Models
from sklearn.mixture import GaussianMixture
from watson_developer_cloud import SpeechToTextV1
# Note: Is there a better way to do this?
# This is the file where the credentials are stored
import config
speech_to_text = SpeechToTextV1(
iam_apikey=config.APIKEY,
url=config.URL
)
from flask import Flask, render_template, request, jsonify, url_for, redirect, abort, session, json
PORT = 8080
# Global Variables
random_words = []
random_string = ""
username = ""
user_directory = "Users/Test"
filename = ""
filename_wav = ""
app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return render_template('main.html')
@app.route('/enroll', methods=["GET", "POST"])
def enroll():
global username
global user_directory
if request.method == 'POST':
data = request.get_json()
username = data['username']
password = data['password']
repassword = data['repassword']
user_directory = "Users/" + username + "/"
# Create target directory & all intermediate directories if don't exists
if not os.path.exists(user_directory):
os.makedirs(user_directory)
print("[ * ] Directory ", username, " Created ...")
else:
print("[ * ] Directory ", username, " already exists ...")
print("[ * ] Overwriting existing directory ...")
shutil.rmtree(user_directory, ignore_errors=False, onerror=None)
os.makedirs(user_directory)
print("[ * ] Directory ", username, " Created ...")
return redirect(url_for('voice'))
else:
return render_template('enroll.html')
@app.route('/auth', methods=['POST', 'GET'])
def auth():
global username
global user_directory
global filename
user_exist = False
if request.method == 'POST':
data = request.get_json()
print(data)
user_directory = 'Models/'
username = data['username']
password = data['password']
print("[ DEBUG ] : What is the user directory at auth : ", user_directory)
print("os.fsencode(user_directory : ", os.fsencode(user_directory))
directory = os.fsencode(user_directory)
print("directory : ", os.listdir(directory)[1:])
for file in os.listdir(directory):
print("file : ", file)
filename = os.fsdecode(file)
if filename.startswith(username):
print("filename : ", filename)
user_exist = True
break
else:
pass
if user_exist:
print("[ * ] The user profile exists ...")
return "User exist"
else:
print("[ * ] The user profile does not exists ...")
return "Doesn't exist"
else:
print('its coming here')
return render_template('auth.html')
@app.route('/vad', methods=['GET', 'POST'])
def vad():
if request.method == 'POST':
global random_words
f = open('./static/audio/background_noise.wav', 'wb')
f.write(request.data)
f.close()
background_noise = speech_recognition.AudioFile(
'./static/audio/background_noise.wav')
with background_noise as source:
speech_recognition.Recognizer().adjust_for_ambient_noise(source, duration=5)
print("Voice activity detection complete ...")
random_words = RandomWords().random_words(count=5)
print(random_words)
return " ".join(random_words)
else:
background_noise = speech_recognition.AudioFile(
'./static/audio/background_noise.wav')
with background_noise as source:
speech_recognition.Recognizer().adjust_for_ambient_noise(source, duration=5)
print("Voice activity detection complete ...")
random_words = RandomWords().random_words(count=5)
print(random_words)
return " ".join(random_words)
@app.route('/voice', methods=['GET', 'POST'])
def voice():
global user_directory
global filename_wav
print("[ DEBUG ] : User directory at voice : ", user_directory)
if request.method == 'POST':
# global random_string
global random_words
global username
filename_wav = user_directory + "-".join(random_words) + '.wav'
f = open(filename_wav, 'wb')
f.write(request.data)
f.close()
with open(filename_wav, 'rb') as audio_file:
recognised_words = speech_to_text.recognize(audio_file, content_type='audio/wav').get_result()
recognised_words = str(recognised_words['results'][0]['alternatives'][0]['transcript'])
print("IBM Speech to Text thinks you said : " + recognised_words)
print("IBM Fuzzy partial score : " + str(fuzz.partial_ratio(random_words, recognised_words)))
print("IBM Fuzzy score : " + str(fuzz.ratio(random_words, recognised_words)))
if fuzz.ratio(random_words, recognised_words) < 65:
print(
"\nThe words you have spoken aren't entirely correct. Please try again ...")
os.remove(filename_wav)
return "fail"
else:
pass
return "pass"
else:
return render_template('voice.html')
@app.route('/biometrics', methods=['GET', 'POST'])
def biometrics():
global user_directory
print("[ DEBUG ] : User directory is : ", user_directory)
if request.method == 'POST':
pass
else:
# MFCC
print("Into the biometrics route.")
directory = os.fsencode(user_directory)
features = numpy.asarray(())
for file in os.listdir(directory):
filename_wav = os.fsdecode(file)
if filename_wav.endswith(".wav"):
print("[biometrics] : Reading audio files for processing ...")
(rate, signal) = scipy.io.wavfile.read(user_directory + filename_wav)
extracted_features = extract_features(rate, signal)
if features.size == 0:
features = extracted_features
else:
features = numpy.vstack((features, extracted_features))
else:
continue
# GaussianMixture Model
print("[ * ] Building Gaussian Mixture Model ...")
gmm = GaussianMixture(n_components=16,
max_iter=200,
covariance_type='diag',
n_init=3)
gmm.fit(features)
print("[ * ] Modeling completed for user :" + username +
" with data point = " + str(features.shape))
# dumping the trained gaussian model
# picklefile = path.split("-")[0]+".gmm"
print("[ * ] Saving model object ...")
pickle.dump(gmm, open("Models/" + str(username) +
".gmm", "wb"), protocol=None)
print("[ * ] Object has been successfully written to Models/" +
username + ".gmm ...")
print("\n\n[ * ] User has been successfully enrolled ...")
features = numpy.asarray(())
return "User has been successfully enrolled ...!!"
@app.route("/verify", methods=['GET'])
def verify():
global username
global filename
global user_directory
global filename_wav
print("[ DEBUG ] : user directory : " , user_directory)
print("[ DEBUG ] : filename : " , filename)
print("[ DEBUG ] : filename_wav : " , filename_wav)
# ------------------------------------------------------------------------------------------------------------------------------------#
# LTSD and MFCC #
# ------------------------------------------------------------------------------------------------------------------------------------#
# (rate, signal) = scipy.io.wavfile.read(audio.get_wav_data())
(rate, signal) = scipy.io.wavfile.read(filename_wav)
extracted_features = extract_features(rate, signal)
# ------------------------------------------------------------------------------------------------------------------------------------#
# Loading the Gaussian Models #
# ------------------------------------------------------------------------------------------------------------------------------------#
gmm_models = [os.path.join(user_directory, user)
for user in os.listdir(user_directory)
if user.endswith('.gmm')]
# print("GMM Models : " + str(gmm_models))
# Load the Gaussian user Models
models = [pickle.load(open(user, 'rb')) for user in gmm_models]
user_list = [user.split("/")[-1].split(".gmm")[0]
for user in gmm_models]
log_likelihood = numpy.zeros(len(models))
for i in range(len(models)):
gmm = models[i] # checking with each model one by one
scores = numpy.array(gmm.score(extracted_features))
log_likelihood[i] = scores.sum()
print("Log liklihood : " + str(log_likelihood))
identified_user = numpy.argmax(log_likelihood)
print("[ * ] Identified User : " + str(identified_user) +
" - " + user_list[identified_user])
auth_message = ""
if user_list[identified_user] == username:
print("[ * ] You have been authenticated!")
auth_message = "success"
else:
print("[ * ] Sorry you have not been authenticated")
auth_message = "fail"
return auth_message
def calculate_delta(array):
"""Calculate and returns the delta of given feature vector matrix
(https://appliedmachinelearning.blog/2017/11/14/spoken-speaker-identification-based-on-gaussian-mixture-models-python-implementation/)"""
print("[Delta] : Calculating delta")
rows, cols = array.shape
deltas = numpy.zeros((rows, 20))
N = 2
for i in range(rows):
index = []
j = 1
while j <= N:
if i-j < 0:
first = 0
else:
first = i-j
if i+j > rows - 1:
second = rows - 1
else:
second = i+j
index.append((second, first))
j += 1
deltas[i] = (array[index[0][0]]-array[index[0][1]] +
(2 * (array[index[1][0]]-array[index[1][1]]))) / 10
return deltas
def extract_features(rate, signal):
print("[extract_features] : Exctracting featureses ...")
mfcc_feat = mfcc(signal,
rate,
winlen=0.020, # remove if not requred
preemph=0.95,
numcep=20,
nfft=1024,
ceplifter=15,
highfreq=6000,
nfilt=55,
appendEnergy=False)
mfcc_feat = preprocessing.scale(mfcc_feat)
delta_feat = calculate_delta(mfcc_feat)
combined_features = numpy.hstack((mfcc_feat, delta_feat))
return combined_features
if __name__ == '__main__':
app.run(host='0.0.0.0', port=PORT, debug=True)