-
Notifications
You must be signed in to change notification settings - Fork 1
/
codebook_creator.py
64 lines (51 loc) · 1.62 KB
/
codebook_creator.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
"""
This module detects the word given the audio file using HMM techniques
"""
import os
import pickle
import numpy as np
from scipy.io import wavfile
from python_speech_features import mfcc, logfbank
from scipy.cluster.vq import vq, kmeans, whiten
BASE_DATAPATH = "data"
STOP_PATH = "data\stop"
DOWN_PATH = "data\down"
GO_PATH = "data\go"
def collect_training_data(label, num_files):
paths = {
"go": GO_PATH,
"down": DOWN_PATH,
"stop": STOP_PATH,
}
mypath = paths[label]
myfiles = [os.path.join(mypath, name) for name in os.listdir(mypath)]
return myfiles[:num_files]
def get_mfcc_vectors(myfiles):
vecs = []
for myfile in myfiles:
frequency_sampling, audio_signal = wavfile.read(myfile)
# print(frequency_sampling, audio_signal)
features_mfcc = mfcc(audio_signal, frequency_sampling) # n x 13
vecs.extend(features_mfcc)
vecs = np.array(vecs)
return vecs
def create_mfcc_dataset_for_codebook(num_files=1000):
labels = ["go", "down", "stop"]
vecs = []
for label in labels:
myfiles = collect_training_data(label, num_files)
vecs1 = get_mfcc_vectors(myfiles)
vecs.extend(vecs1)
return vecs
def get_codebook(vecs, size=64):
whitened = whiten(np.array(vecs))
codebook, distortion = kmeans(whitened, size)
return codebook
if __name__ == '__main__':
vecs = create_mfcc_dataset_for_codebook()
book = get_codebook(vecs)
print(book.shape)
pickle.dump(book, open("book.p", "wb"))
# book = pickle.load(open("book.p", "rb"))
# codes = vq(np.array(vecs), book)[0]
# print(codes[200:400])