-
Notifications
You must be signed in to change notification settings - Fork 0
/
kws_snowboy.py
113 lines (83 loc) · 2.69 KB
/
kws_snowboy.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
# -*- coding: utf-8 -*-
"""
Keyword spotting using snowboy
"""
import os
import sys
import threading
if sys.version_info[0] < 3:
import Queue as queue
else:
import queue
from snowboy import snowboydetect
from .element import Element
class KWS(Element):
def __init__(self, model='snowboy', sensitivity=0.5, verbose=False):
super(KWS, self).__init__()
self.verbose = verbose
resource_path = os.path.join(os.path.dirname(snowboydetect.__file__), 'resources')
common_resource = os.path.join(resource_path, 'common.res')
for model_path in [resource_path, os.path.join(resource_path, 'models')]:
builtin_model = os.path.join(model_path, '{}.umdl'.format(model))
if os.path.isfile(builtin_model):
model = builtin_model
break
if model == 'alexa':
alexa_model = os.path.join(resource_path, 'alexa', 'alexa_02092017.umdl')
if os.path.isfile(alexa_model):
model = alexa_model
self.detector = snowboydetect.SnowboyDetect(common_resource.encode(), model.encode())
# self.detector.SetAudioGain(1)
# self.detector.ApplyFrontend(True)
self.detector.SetSensitivity(str(sensitivity).encode())
self.queue = queue.Queue()
self.done = False
self.thread = None
self.on_detected = None
def put(self, data):
self.queue.put(data)
def start(self):
self.done = False
self.thread = threading.Thread(target=self.run)
self.thread.daemon = True
self.thread.start()
def stop(self):
self.done = True
if self.thread and self.thread.is_alive():
self.thread.join(timeout=3)
def run(self):
while not self.done:
try:
data = self.queue.get(timeout=1)
except queue.Empty:
break
ans = self.detector.RunDetection(data)
if ans > 0:
if callable(self.on_detected):
self.on_detected(ans)
if self.verbose:
sys.stdout.write(str(ans+2))
sys.stdout.flush()
super(KWS, self).put(data)
def set_callback(self, callback):
self.on_detected = callback
def main():
import time
from voice_engine.source import Source
src = Source()
kws = KWS()
src.link(kws)
def on_detected(keyword):
print('found {}'.format(keyword))
kws.on_detected = on_detected
kws.start()
src.start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
break
kws.stop()
src.stop()
if __name__ == '__main__':
main()