Martin 10 lat temu
rodzic
commit
d1beaef950

+ 49 - 0
clips.py

@@ -0,0 +1,49 @@
+import os
+import time
+import wave
+import pyaudio
+
+_CLIP_FOLDER = os.path.join('resources', 'clips')
+_CLIP_DATA_CACHE = {}
+
+class Clips(object):
+    SUCCESS = 'ding.wav'
+    FAILURE = 'dong.wav'
+
+    DING = 'ding.wav'
+    DONG = 'dong.wav'
+
+def play(clip):
+    """Simple callback function to play a wave file. By default it plays
+    a Ding sound.
+
+    :param str fname: wave file name
+    :return: None
+    """
+
+    audio = pyaudio.PyAudio()
+
+    if clip not in _CLIP_DATA_CACHE:
+        fname = os.path.join(_CLIP_FOLDER, clip)
+        f = wave.open(fname, 'rb')
+
+        data = f.readframes(f.getnframes())
+        n_channels = f.getnchannels()
+        width = f.getsampwidth()
+        framerate = f.getframerate()
+
+        _CLIP_DATA_CACHE[clip] = (data, n_channels, width, framerate)
+
+    data, n_channels, width, framerate = _CLIP_DATA_CACHE[clip]
+
+    audio = pyaudio.PyAudio()
+    stream_out = audio.open(
+        format=audio.get_format_from_width(width),
+        channels=n_channels,
+        rate=framerate, input=False, output=True)
+    stream_out.start_stream()
+    stream_out.write(data)
+    time.sleep(0.2)
+    stream_out.stop_stream()
+    stream_out.close()
+    audio.terminate()

+ 3 - 0
dependencies.txt

@@ -0,0 +1,3 @@
+PortAudio: http://portaudio.com/download.html
+  download, configure, make, make install
+

+ 110 - 0
ears.py

@@ -0,0 +1,110 @@
+import logging
+import speech_recognition as sr
+import conf
+import time
+import clips
+
+def _get_recognizer(pause_threshold):
+    recognizer = sr.Recognizer()
+    recognizer.pause_threshold = pause_threshold
+    recognizer.dynamic_energy_threshold = False
+
+    return recognizer    
+
+class TextCollector(object):
+    def __init__(self, terminators):
+        self.res = []
+        self.done = None
+        self.terminators = [t.lower() for t in terminators]
+    
+    def call(self, text_or_tokens):
+        for t in self.terminators:
+            if isinstance(text_or_tokens, list) and text_or_tokens[-1].lower() == t:
+                self.done = t
+                text_or_tokens = text_or_tokens[:-1]
+                break
+
+            elif isinstance(text_or_tokens, basestring) and text_or_tokens.lower().endswith(t):
+                self.done = t
+                text_or_tokens = text_or_tokens[:-len(t)].strip()
+                break
+        
+        if text_or_tokens:
+            self.res.append(text_or_tokens)
+
+def listen_until_terminated(terminators=['done', 'cancel'], timeout=300, pause_threshold=5, tokenize=False, return_all=False, language='en-GB', preferred_phrases=None):
+    if preferred_phrases is None:
+        preferred_phrases = terminators
+    else:
+        preferred_phrases.extend(terminators)
+
+    c = TextCollector(terminators)
+
+    stopper = _listen_in_background(c.call, pause_threshold=pause_threshold, tokenize=tokenize, return_all=return_all, language=language, preferred_phrases=preferred_phrases)
+
+    start_t = time.time()
+    while not c.done and time.time() < start_t + timeout:
+        time.sleep(0.1)
+
+    stopper()
+
+    return c.res, c.done
+
+
+def _listen_in_background(callback, pause_threshold=5, tokenize=False, return_all=False, language='en-GB', preferred_phrases=None):
+    source = sr.Microphone()
+    recognizer = _get_recognizer(pause_threshold)
+
+    def _background_callback(recognizer, audio):
+        text = _speech_to_text(audio, recognizer, tokenize, return_all, language, preferred_phrases)
+        if text is not None:
+            callback(text)
+
+    return recognizer.listen_in_background(source, _background_callback)
+
+def _speech_to_text(audio, recognizer, tokenize, return_all, language, preferred_phrases):
+    res = None
+    logging.info('Calling recognition APIs (preferred_phrases: %s)...', preferred_phrases)
+    try:
+        t = time.time()
+        res = recognizer.recognize_google_cloud(audio, language=language, show_all=return_all, preferred_phrases=preferred_phrases)
+        logging.info('Google cloud speech: %s (%.2f s)', res, time.time() - t)
+    except sr.UnknownValueError:
+        logging.error('Google Cloud Speech Recognition could not understand audio')
+    except sr.RequestError, e:
+        logging.error("Could not request results from Google Cloud Speech Recognition service: %s", e)
+    
+    try:
+        t = time.time()
+        alt = recognizer.recognize_google(audio, language=language, show_all=return_all)
+        res = res or alt
+        logging.info('Google speech: %s (%.2f s)', res, time.time() - t)
+    except sr.UnknownValueError:
+        logging.error('Google Speech Recognition could not understand audio')
+    except sr.RequestError, e:
+        logging.error("Could not request results from Google Speech Recognition service: %s", e)
+
+    if res and res.strip():
+        clips.play(clips.Clips.SUCCESS)
+        return [t.strip() for t in res.split(' ') if t.strip()] if tokenize else res.strip() 
+
+    else:
+        clips.play(clips.Clips.FAILURE)
+        return None
+
+def listen(pause_threshold=5, tokenize=False, return_all=False, language='en-GB', preferred_phrases=None):
+    # obtain audio from the microphone
+    recognizer = _get_recognizer(pause_threshold)
+
+    with sr.Microphone() as source:
+        logging.info('listening...')
+        audio = recognizer.listen(source)
+
+    return _speech_to_text(audio, recognizer, tokenize, return_all, language, preferred_phrases)
+
+if __name__ == "__main__":
+    import main
+    main.init()
+    while True:
+        listen()
+        print '\n\n\n'

+ 0 - 0
functions/__init__.py


+ 5 - 0
functions/base.py

@@ -0,0 +1,5 @@
+class BaseFunction(object):
+    def init(self):
+        pass
+    def preferred_phrases(self):
+        return []

+ 67 - 0
functions/email.py

@@ -0,0 +1,67 @@
+import logging
+import requests
+import requests.exceptions
+import tts
+import ears
+import base
+
+_RECIPIENTS = {
+    'martin': 'martin@gerner.co',
+    'pointy': 'martin@pointy.com',
+    'georgina': 'georgina@pointy.com',
+}
+
+_MAILGUN_API_URL = 'https://api.mailgun.net/v3/mg.gerner.co'
+_MAILGUN_API_KEY = 'key-80245476ae35aa626d782556419280f9'
+_MAILGUN_SENDER_EMAIL = 'noreply@mg.gerner.co'
+
+def _send_by_sendgrid(recipient, subject, email_body):
+    auth = ('api', _MAILGUN_API_KEY)
+    body = {
+        'from': _MAILGUN_SENDER_EMAIL,
+        'to': recipient,
+        'subject': subject,
+        'text': email_body
+    }
+
+    resp = requests.post(_MAILGUN_API_URL + '/messages', data=body, auth=auth)
+
+    if resp.status_code != 200:
+        resp.raise_for_status()
+
+class Email(base.BaseFunction):
+    def preferred_phrases(self):
+        return _RECIPIENTS.keys()
+
+    def _send(self, recipient):
+        logging.info('email _send: %s', recipient)
+
+        tts.tts(recipient)
+
+        lines, terminator = ears.listen_until_terminated()
+
+        if terminator == 'done':
+            body = '\n'.join(lines)
+            logging.info('Sending email: %s: %s', _RECIPIENTS[recipient], lines)
+            try:
+                _send_by_sendgrid(_RECIPIENTS[recipient], 'snowbody email', body)
+                tts.tts('done')
+            except requests.exceptions.HTTPError, e:
+                tts.tts('error')
+                logging.error(e)
+
+        else:
+            tts.tts('cancelled')
+
+    def call(self, additional_tokens=None, **_):
+        logging.info('email: %s', additional_tokens)
+        for t in additional_tokens:
+            t = t.lower()
+            if t in _RECIPIENTS:
+                self._send(t)
+                return
+
+        tts.tts('to whom?')
+        recipient = ears.listen(pause_threshold=1, preferred_phrases=self.preferred_phrases())
+        if recipient in _RECIPIENTS:
+            self._send(recipient)

+ 58 - 0
functions/music.py

@@ -0,0 +1,58 @@
+import subprocess
+import os
+import logging
+import base
+import tts
+import ears
+
+_FOLDER = '/mnt/nas/music/albums'
+
+class Music(base.BaseFunction):
+    folders = None
+    current_process = None
+
+    def _initialize(self):
+        logging.info('initializing...')
+
+        folders = [unicode(os.path.join(_FOLDER, f).decode('utf-8')) for f in os.listdir(_FOLDER)]
+        folders = [f for f in folders if os.path.isdir(f)]
+        self.folders = {os.path.basename(f).lower(): f for f in folders}
+        logging.info(sorted(self.folders.keys()))
+        logging.info('done.')
+
+    def _search(self, tokens):
+        if not tokens:
+            return
+
+        eligible = self.folders
+        for t in tokens:
+            t = t.lower()
+            eligible = {f: v for f, v in eligible.iteritems() if t in f}
+        
+        logging.info('tokens: %s; eligible: %s', tokens, eligible.keys())
+        if eligible:
+            return eligible[eligible.keys()[0]]
+
+    def stop(self):
+        if self.current_process:
+            self.current_process.terminate()
+            self.current_process = None
+
+    def call(self, additional_tokens=None, **_):
+        if self.folders is None:
+            self._initialize()
+
+        f = None
+        if additional_tokens:
+            f = self._search(additional_tokens)
+        if not f:
+            tts.tts('ready')
+            tokens = ears.listen(pause_threshold=3, preferred_phrases=self.folders.keys()[:300])
+            f = self._search(tokens)
+
+        if f:
+            tts.tts('playing %s' % f)
+            self.current_process = subprocess.Popen(['cvlc', '-Z', f, ]) 
+
+        else:
+            tts.tts('failed')

+ 35 - 0
functions/todo.py

@@ -0,0 +1,35 @@
+import logging
+import base
+import tts
+import clips
+import ears
+
+_LISTEN_TIMEOUT = 600
+_GROCERIES = ['milk', 'bread']
+
+class WunderbarTodo(base.BaseFunction):
+    def _groceries(self):
+        tts.tts('ready')
+
+        lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
+
+        if terminator == 'cancel':
+            tts.tts('cancelled')
+            return
+
+        else:
+            items = []
+            for line in lines:
+                items.extend([t.strip() for t in line.split(' and ') if t.strip()])
+
+            logging.info(items)
+
+            tts.tts('ok')
+
+
+    def call(self, trigger=None, **_):
+        if trigger == 'food':
+            self._groceries()
+        else:
+            tts.tts('Bad trigger')
+

+ 12 - 0
gcloud-key.json

@@ -0,0 +1,12 @@
+{
+  "type": "service_account",
+  "project_id": "backup-storage-142717",
+  "private_key_id": "a618da1c7d9d4532f2d03c025f71bae73576085d",
+  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5omuTMxXySTOo\n3KURO9l57zM6sKCoUZ6lmqmdLZzNaORfO8RwL1OBeI/GMo3NLnd6nsojNVDkgurc\ndoh9m6/ExPTwQB7OA68yCOsu3KvqRJvW5ZrwJBqul2GAIzc6obKnxYtBI8FxUQAH\nGJWuYvBkgo0fVBmMClhJKLF35hm5yogdqbwxot44Gx5kFUneODBjRdXXUTiZUnLJ\nQrqCys2DIhNzmGf3FrQ5M04FFeEtpvAPGVe+ZBW5632FRmFUu2AoQzhTemvku0eI\nlxXBjxO7u3xgIYVDkfbohNdewrHNxnfLlo5H5T3tBYC7Ytng/o2o/JX/TlTKxJAW\n+jqJv7P5AgMBAAECggEAV7nM8qxSs8QqOKPFEibheIE1CYhM9B5WRdaYT2It1ti6\nC9NX2thSsz3BXB2p64wJBJaj2g2pI8RGr1cI26tGXkvhoOP8aslM8u1KD0RTrgss\nRlsNZGz7ewSpHAAIapndrvFpBKicEyv/Qls46UdyaV1UybhZtldxL2merJW+FJE1\nbeDMtkENbfTLu6XQVKlT3wcj5WVKrL7gPzG1DnaNbhkVT1NfxgbikGDJ6AWKSpA9\n+5vw11FqlEqAaTXMr4hdjNQD/pQ3juYoSiotbJLFvN0Vp3lwNOoGTsZXmExUA7td\nUUoKa/gSySaqHKe2Mudb9UG/Ew/AYhoqFx5NtM32zQKBgQD0V5ZCpqah4zRZNT+i\n/KCBUHaXEtN4SmgbZrGtERN2/8dneGJSwBe6fkSjR4vxRilzDWfflUeqq65C0mAa\nkhVlD7QxMBlNUQsWYTXLYro7oU0A940GwQVwKdqK+GppTl7BbafwYs506vn76ja8\ncJ7NAjmvcOwefF5o/T4EBqx3UwKBgQDCfcX0CIc2DLCIXAtBePVnxQ+19LZa1Cns\nAwGQgVmazLvTGZUY7l4E3s2NRCCJkIeTilgSMQtGmPz5M/n5g4OHP8qxHpEiYvBd\nuGhpJ4G+2q/tJkeCWcN5vG+1GOt2HbmeJIoqOSXnxXxtbBditaMFT2+FUaXjiKTB\nnFkbg9i6AwKBgEhZCs/PYnV6vcxQPPh4jtnbRlHzLBRpC6xZWvCgpr/MenGDrrFL\n2XrJ2m7yR1h4att7M697Fw5M6Ts16WjUqmsTHEqYMFW5Umwc+n2vTO9NEmzf360J\nSB/u9JvDdFab8uiZHGnMB8+Mp9pUfkKLoimXqBbve6qHLrktishMZZKrAoGARvyA\n88DpGOEozZxKv2rWpzlVsqPOqvglFO9D8upDOizfoP0FXkQiLMTlYVosRglqcn9c\nBcfAxdOxAYPnCRrnNsYhxOPTNSnHcW2NLlQtFuvaqkP+daUto5ETdJXT2xieVwof\nI6oYG7AI6ic5od2J0rZbjd1vHs0Q1VmrbE+DGuECgYEAgSCptjBF/74sC00oNb4J\nVs1BQl/wy1GQQFhxig55TY/C3u4flx22xWd3PfY66WP3k/nI47/N2N785M+xXSxy\nupiFY83OYXFfEeST+4gDPwVOuPB0yBfgN+G5vjMkubFNH2EpY8ZjPVCrRjLiU79Q\nJ4gN80P37zXfcRJ/MA1XaKY=\n-----END PRIVATE KEY-----\n",
+  "client_email": "speech-api-acc@backup-storage-142717.iam.gserviceaccount.com",
+  "client_id": "112814405749362055241",
+  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+  "token_uri": "https://accounts.google.com/o/oauth2/token",
+  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
+  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/speech-api-acc%40backup-storage-142717.iam.gserviceaccount.com"
+}

+ 29 - 0
main.py

@@ -0,0 +1,29 @@
+import logging
+import sys
+from ears import listen
+from tts import tts
+import trigger
+import functions.todo
+import functions.email
+import functions.music
+
+def init():
+    logging.basicConfig(stream=sys.stdout)
+    logging.getLogger().setLevel(logging.INFO)
+
+MODELS = [{
+    'model': 'resources/snowboy/alexa.umdl',
+    'callbacks': {
+        'email': functions.email.Email(),
+        'food': functions.todo.WunderbarTodo(),
+        'play': functions.music.Music(),
+    }
+}]
+
+if __name__ == "__main__":
+    init()
+    #trigger.start(MODELS)
+    #trigger.loop_model(MODELS[0])
+
+    trigger._callback(MODELS[0])
+    #functions.music.Music().call(['elton'])

BIN
resources/clips/ding.wav


BIN
resources/clips/dong.wav


BIN
resources/snowboy/alexa.umdl


BIN
resources/snowboy/common.res


BIN
resources/snowboy/snowboy.umdl


+ 0 - 0
snowboy/__init__.py


+ 41 - 0
snowboy/demo2.py

@@ -0,0 +1,41 @@
+import snowboydecoder
+import sys
+import signal
+
+# Demo code for listening two hotwords at the same time
+
+interrupted = False
+
+
+def signal_handler(signal, frame):
+    global interrupted
+    interrupted = True
+
+
+def interrupt_callback():
+    global interrupted
+    return interrupted
+
+if len(sys.argv) != 3:
+    print("Error: need to specify 2 model names")
+    print("Usage: python demo.py 1st.model 2nd.model")
+    sys.exit(-1)
+
+models = sys.argv[1:]
+
+# capture SIGINT signal, e.g., Ctrl+C
+signal.signal(signal.SIGINT, signal_handler)
+
+sensitivity = [0.5]*len(models)
+detector = snowboydecoder.HotwordDetector(models, sensitivity=sensitivity)
+callbacks = [lambda: snowboydecoder.play_audio_file(snowboydecoder.DETECT_DING),
+             lambda: snowboydecoder.play_audio_file(snowboydecoder.DETECT_DONG)]
+print('Listening... Press Ctrl+C to exit')
+
+# main loop
+# make sure you have the same numbers of callbacks and models
+detector.start(detected_callback=callbacks,
+               interrupt_check=interrupt_callback,
+               sleep_time=0.03)
+
+detector.terminate()

BIN
snowboy/resources/alexa.umdl


BIN
snowboy/resources/common.res


BIN
snowboy/resources/snowboy.umdl


+ 183 - 0
snowboy/snowboydecoder.py

@@ -0,0 +1,183 @@
+#!/usr/bin/env python
+
+import collections
+import pyaudio
+import snowboydetect
+import time
+import wave
+import os
+import logging
+
+logging.basicConfig()
+logger = logging.getLogger("snowboy")
+logger.setLevel(logging.INFO)
+TOP_DIR = os.path.dirname(os.path.abspath(__file__))
+
+RESOURCE_FILE = os.path.join(TOP_DIR, "resources/common.res")
+DETECT_DING = os.path.join(TOP_DIR, "resources/ding.wav")
+DETECT_DONG = os.path.join(TOP_DIR, "resources/dong.wav")
+
+
+class RingBuffer(object):
+    """Ring buffer to hold audio from PortAudio"""
+    def __init__(self, size = 4096):
+        self._buf = collections.deque(maxlen=size)
+
+    def extend(self, data):
+        """Adds data to the end of buffer"""
+        self._buf.extend(data)
+
+    def get(self):
+        """Retrieves data from the beginning of buffer and clears it"""
+        tmp = bytes(bytearray(self._buf))
+        self._buf.clear()
+        return tmp
+
+
+def play_audio_file(fname=DETECT_DING):
+    """Simple callback function to play a wave file. By default it plays
+    a Ding sound.
+
+    :param str fname: wave file name
+    :return: None
+    """
+    ding_wav = wave.open(fname, 'rb')
+    ding_data = ding_wav.readframes(ding_wav.getnframes())
+    audio = pyaudio.PyAudio()
+    stream_out = audio.open(
+        format=audio.get_format_from_width(ding_wav.getsampwidth()),
+        channels=ding_wav.getnchannels(),
+        rate=ding_wav.getframerate(), input=False, output=True)
+    stream_out.start_stream()
+    stream_out.write(ding_data)
+    time.sleep(0.2)
+    stream_out.stop_stream()
+    stream_out.close()
+    audio.terminate()
+
+
+class HotwordDetector(object):
+    """
+    Snowboy decoder to detect whether a keyword specified by `decoder_model`
+    exists in a microphone input stream.
+
+    :param decoder_model: decoder model file path, a string or a list of strings
+    :param resource: resource file path.
+    :param sensitivity: decoder sensitivity, a float of a list of floats.
+                              The bigger the value, the more senstive the
+                              decoder. If an empty list is provided, then the
+                              default sensitivity in the model will be used.
+    :param audio_gain: multiply input volume by this factor.
+    """
+    def __init__(self, decoder_model,
+                 resource=RESOURCE_FILE,
+                 sensitivity=[],
+                 audio_gain=1):
+
+        def audio_callback(in_data, frame_count, time_info, status):
+            self.ring_buffer.extend(in_data)
+            play_data = chr(0) * len(in_data)
+            return play_data, pyaudio.paContinue
+
+        tm = type(decoder_model)
+        ts = type(sensitivity)
+        if tm is not list:
+            decoder_model = [decoder_model]
+        if ts is not list:
+            sensitivity = [sensitivity]
+        model_str = ",".join(decoder_model)
+
+        self.detector = snowboydetect.SnowboyDetect(
+            resource_filename=resource.encode(), model_str=model_str.encode())
+        self.detector.SetAudioGain(audio_gain)
+        self.num_hotwords = self.detector.NumHotwords()
+
+        if len(decoder_model) > 1 and len(sensitivity) == 1:
+            sensitivity = sensitivity*self.num_hotwords
+        if len(sensitivity) != 0:
+            assert self.num_hotwords == len(sensitivity), \
+                "number of hotwords in decoder_model (%d) and sensitivity " \
+                "(%d) does not match" % (self.num_hotwords, len(sensitivity))
+        sensitivity_str = ",".join([str(t) for t in sensitivity])
+        if len(sensitivity) != 0:
+            self.detector.SetSensitivity(sensitivity_str.encode())
+
+        self.ring_buffer = RingBuffer(
+            self.detector.NumChannels() * self.detector.SampleRate() * 5)
+        self.audio = pyaudio.PyAudio()
+        self.stream_in = self.audio.open(
+            input=True, output=False,
+            format=self.audio.get_format_from_width(
+                self.detector.BitsPerSample() / 8),
+            channels=self.detector.NumChannels(),
+            rate=self.detector.SampleRate(),
+            frames_per_buffer=2048,
+            stream_callback=audio_callback)
+
+
+    def start(self, detected_callback=play_audio_file,
+              interrupt_check=lambda: False,
+              sleep_time=0.03):
+        """
+        Start the voice detector. For every `sleep_time` second it checks the
+        audio buffer for triggering keywords. If detected, then call
+        corresponding function in `detected_callback`, which can be a single
+        function (single model) or a list of callback functions (multiple
+        models). Every loop it also calls `interrupt_check` -- if it returns
+        True, then breaks from the loop and return.
+
+        :param detected_callback: a function or list of functions. The number of
+                                  items must match the number of models in
+                                  `decoder_model`.
+        :param interrupt_check: a function that returns True if the main loop
+                                needs to stop.
+        :param float sleep_time: how much time in second every loop waits.
+        :return: None
+        """
+        if interrupt_check():
+            logger.debug("detect voice return")
+            return
+
+        tc = type(detected_callback)
+        if tc is not list:
+            detected_callback = [detected_callback]
+        if len(detected_callback) == 1 and self.num_hotwords > 1:
+            detected_callback *= self.num_hotwords
+
+        assert self.num_hotwords == len(detected_callback), \
+            "Error: hotwords in your models (%d) do not match the number of " \
+            "callbacks (%d)" % (self.num_hotwords, len(detected_callback))
+
+        logger.debug("detecting...")
+
+        while True:
+            if interrupt_check():
+                logger.debug("detect voice break")
+                break
+            data = self.ring_buffer.get()
+            if len(data) == 0:
+                time.sleep(sleep_time)
+                continue
+
+            ans = self.detector.RunDetection(data)
+            if ans == -1:
+                logger.warning("Error initializing streams or reading audio data")
+            elif ans > 0:
+                message = "Keyword " + str(ans) + " detected at time: "
+                message += time.strftime("%Y-%m-%d %H:%M:%S",
+                                         time.localtime(time.time()))
+                logger.info(message)
+                callback = detected_callback[ans-1]
+                if callback is not None:
+                    callback()
+
+        logger.debug("finished.")
+
+    def terminate(self):
+        """
+        Terminate audio stream. Users cannot call start() again to detect.
+        :return: None
+        """
+        self.stream_in.stop_stream()
+        self.stream_in.close()
+        self.audio.terminate()

+ 143 - 0
snowboy/snowboydetect.py

@@ -0,0 +1,143 @@
+# This file was automatically generated by SWIG (http://www.swig.org).
+# Version 3.0.7
+#
+# Do not make changes to this file unless you know what you are doing--modify
+# the SWIG interface file instead.
+
+
+
+
+
+from sys import version_info
+if version_info >= (2, 6, 0):
+    def swig_import_helper():
+        from os.path import dirname
+        import imp
+        fp = None
+        try:
+            fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
+        except ImportError:
+            import _snowboydetect
+            return _snowboydetect
+        if fp is not None:
+            try:
+                _mod = imp.load_module('_snowboydetect', fp, pathname, description)
+            finally:
+                fp.close()
+            return _mod
+    _snowboydetect = swig_import_helper()
+    del swig_import_helper
+else:
+    import _snowboydetect
+del version_info
+try:
+    _swig_property = property
+except NameError:
+    pass  # Python < 2.2 doesn't have 'property'.
+
+
+def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
+    if (name == "thisown"):
+        return self.this.own(value)
+    if (name == "this"):
+        if type(value).__name__ == 'SwigPyObject':
+            self.__dict__[name] = value
+            return
+    method = class_type.__swig_setmethods__.get(name, None)
+    if method:
+        return method(self, value)
+    if (not static):
+        if _newclass:
+            object.__setattr__(self, name, value)
+        else:
+            self.__dict__[name] = value
+    else:
+        raise AttributeError("You cannot add attributes to %s" % self)
+
+
+def _swig_setattr(self, class_type, name, value):
+    return _swig_setattr_nondynamic(self, class_type, name, value, 0)
+
+
+def _swig_getattr_nondynamic(self, class_type, name, static=1):
+    if (name == "thisown"):
+        return self.this.own()
+    method = class_type.__swig_getmethods__.get(name, None)
+    if method:
+        return method(self)
+    if (not static):
+        return object.__getattr__(self, name)
+    else:
+        raise AttributeError(name)
+
+def _swig_getattr(self, class_type, name):
+    return _swig_getattr_nondynamic(self, class_type, name, 0)
+
+
+def _swig_repr(self):
+    try:
+        strthis = "proxy of " + self.this.__repr__()
+    except:
+        strthis = ""
+    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
+
+try:
+    _object = object
+    _newclass = 1
+except AttributeError:
+    class _object:
+        pass
+    _newclass = 0
+
+
+class SnowboyDetect(_object):
+    __swig_setmethods__ = {}
+    __setattr__ = lambda self, name, value: _swig_setattr(self, SnowboyDetect, name, value)
+    __swig_getmethods__ = {}
+    __getattr__ = lambda self, name: _swig_getattr(self, SnowboyDetect, name)
+    __repr__ = _swig_repr
+
+    def __init__(self, resource_filename, model_str):
+        this = _snowboydetect.new_SnowboyDetect(resource_filename, model_str)
+        try:
+            self.this.append(this)
+        except:
+            self.this = this
+
+    def Reset(self):
+        return _snowboydetect.SnowboyDetect_Reset(self)
+
+    def RunDetection(self, *args):
+        return _snowboydetect.SnowboyDetect_RunDetection(self, *args)
+
+    def SetSensitivity(self, sensitivity_str):
+        return _snowboydetect.SnowboyDetect_SetSensitivity(self, sensitivity_str)
+
+    def GetSensitivity(self):
+        return _snowboydetect.SnowboyDetect_GetSensitivity(self)
+
+    def SetAudioGain(self, audio_gain):
+        return _snowboydetect.SnowboyDetect_SetAudioGain(self, audio_gain)
+
+    def UpdateModel(self):
+        return _snowboydetect.SnowboyDetect_UpdateModel(self)
+
+    def NumHotwords(self):
+        return _snowboydetect.SnowboyDetect_NumHotwords(self)
+
+    def SampleRate(self):
+        return _snowboydetect.SnowboyDetect_SampleRate(self)
+
+    def NumChannels(self):
+        return _snowboydetect.SnowboyDetect_NumChannels(self)
+
+    def BitsPerSample(self):
+        return _snowboydetect.SnowboyDetect_BitsPerSample(self)
+    __swig_destroy__ = _snowboydetect.delete_SnowboyDetect
+    __del__ = lambda self: None
+SnowboyDetect_swigregister = _snowboydetect.SnowboyDetect_swigregister
+SnowboyDetect_swigregister(SnowboyDetect)
+
+# This file is compatible with both classic and new-style classes.
+
+

+ 1 - 0
snowboy/version

@@ -0,0 +1 @@
+1.1.0

+ 60 - 0
trigger.py

@@ -0,0 +1,60 @@
+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()

+ 45 - 0
tts.py

@@ -0,0 +1,45 @@
+import logging
+import os
+import hashlib
+import time
+
+from gtts import gTTS
+import pygame.mixer
+
+if not os.path.isdir('/tmp/snowboy'):
+    os.mkdir('/tmp/snowboy')
+TMP_DIR = '/tmp/snowboy/tts-cache'
+if not os.path.isdir(TMP_DIR):
+    os.mkdir(TMP_DIR)
+
+_SOUND_ENABLED = False
+
+def _play(fname, block):
+    pygame.mixer.init()
+    pygame.mixer.music.load(fname)
+    pygame.mixer.music.play()
+
+    if block:
+        while pygame.mixer.music.get_busy():
+            time.sleep(0.1)
+
+def tts(text, lang='en', block=True):
+    if not text:
+        return
+
+    logging.info('> %s', text)
+
+    if not _SOUND_ENABLED:
+        return
+
+    hash = hashlib.md5(text.lower()).hexdigest()
+    cache_fname = os.path.join(TMP_DIR, hash) + '.mp3'
+    if os.path.isfile(cache_fname):
+        _play(cache_fname, block)
+        return
+
+    tts = gTTS(text=text, lang=lang)
+    with open(cache_fname, 'w') as f:
+        tts.write_to_fp(f)
+
+    _play(cache_fname, block)