import logging import snowboy.snowboydecoder import sys import signal import ears import tts # Demo code for listening two hotwords at the same time INTERRUPTED = False DEFAULT_SENSITIVITY = 0.5 def _signal_handler(signal, frame): global INTERRUPTED INTERRUPTED = True def _interrupt_callback(): global INTERRUPTED return INTERRUPTED def _callback(model): logging.info('%s triggered.', model['model'].split('/')[-1]) if 'callback' in model: model['callback'].call() elif 'callbacks' in model: logging.info('waiting for keyword...') preferred_phrases = model['callbacks'].keys() for v in model['callbacks'].itervalues(): preferred_phrases.extend(v.preferred_phrases()) tokens = ears.listen(tokenize=True, preferred_phrases=preferred_phrases, pause_threshold=1) if tokens: keyword = tokens[0].lower() if keyword in model['callbacks']: return model['callbacks'][keyword].call(trigger=keyword, additional_tokens=tokens[1:]) tts.tts('callback failed.') def loop_model(model): signal.signal(signal.SIGINT, _signal_handler) while not INTERRUPTED: raw_input('Press enter to listen.') _callback(model) def start(models): callbacks = [] for m in models: if 'callbacks' in m: m['callbacks'] = {k.lower().strip(): v for k, v in m['callbacks'].iteritems()} def c(): _callback(m) callbacks.append(c) signal.signal(signal.SIGINT, _signal_handler) detector = snowboy.snowboydecoder.HotwordDetector([m['model'] for m in models], sensitivity=[m.get('sensitivity', DEFAULT_SENSITIVITY) for m in models]) detector.start(detected_callback=callbacks, interrupt_check=_interrupt_callback, sleep_time=0.03) detector.terminate()