Explorar o código

#15 wip: move towards a token stream approach

Martin %!s(int64=10) %!d(string=hai) anos
pai
achega
8122f3b834

+ 1 - 8
voice_control/ears.py

@@ -104,11 +104,4 @@ def listen(pause_threshold=5, tokenize=False, return_all=False, language='en-GB'
         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'
+    return _speech_to_text(audio, recognizer, tokenize, return_all, language, preferred_phrases)

+ 31 - 0
voice_control/functions/__init__.py

@@ -0,0 +1,31 @@
+import threading
+import email_mailgun
+import todo_wunderlist
+import input_sources
+import output
+
+def _get_services():
+    return {
+        'email': email_mailgun.Email(),
+        'food': todo_wunderlist.Wunderlist(True, 'food'),
+        'todo': todo_wunderlist.Wunderlist(False),
+        #'play': music.Music(),
+    }
+
+def launch_services(interrupted):
+    services = _get_services()
+
+    for s in services.values():
+        if not s.initialized:
+            t = threading.Thread(target=s.init)
+            t.start()
+
+    output.text('Ready.')
+
+    while not interrupted():
+        t = input_sources.get_token(5)
+        if t is not None and t in services and services[t].initialized:
+            output.text('Entering %s' % t)
+            services[t].call()
+        elif t is not None:
+            output.failure()

+ 9 - 20
voice_control/functions/email_mailgun.py

@@ -1,8 +1,7 @@
-import logging
 import requests
 import requests.exceptions
-import ears
 import base
+import input_sources
 import output
 
 _RECIPIENTS = {
@@ -34,34 +33,24 @@ class Email(base.BaseFunction):
         return _RECIPIENTS.keys()
 
     def _send(self, recipient):
-        logging.info('email _send: %s', recipient)
-
-        output.text(recipient)
-
-        lines, terminator = ears.listen_until_terminated()
+        output.text('email _send: %s' % recipient)
+        tokens, terminator = input_sources.get_until_terminated()
 
         if terminator == 'done':
-            body = '\n'.join(lines)
-            logging.info('Sending email: %s: %s', _RECIPIENTS[recipient], lines)
+            body = ' '.join(tokens)
             try:
                 _send_by_sendgrid(_RECIPIENTS[recipient], 'snowbody email', body)
                 output.success()
             except requests.exceptions.HTTPError, e:
-                output.failure()
-                logging.error(e)
+                output.failure(str(e))
 
         else:
             output.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
-
+    def call(self):
         output.text('to whom?')
-        recipient = ears.listen(pause_threshold=1, preferred_phrases=self.preferred_phrases())
+        recipient = input_sources.get_token(preferred_phrases=self.preferred_phrases())
         if recipient in _RECIPIENTS:
             self._send(recipient)
+        else:
+            output.failure('Could not find an email recipient "%s".' % recipient)

+ 14 - 10
voice_control/functions/todo_wunderlist.py

@@ -1,7 +1,7 @@
 import logging
 import base
-import ears
 import requests
+import input_sources
 import output
 
 _LISTEN_TIMEOUT = 600
@@ -44,7 +44,6 @@ class Wunderlist(base.BaseFunction):
 
     def __init__(self, multiple_tasks, list_name=None):
         self.client = _WunderlistClient(_WUNDERLIST_CLIENT_ID, _WUNDERLIST_ACCESS_TOKEN)
-
         self.multiple_tasks = multiple_tasks
         self.list_name = list_name
         self.initialized = False
@@ -61,7 +60,10 @@ class Wunderlist(base.BaseFunction):
             return self.list_name
         
         else:
-            list_name = ears.listen(pause_threshold=1, preferred_phrases=self.client.lists.keys()).lower()
+            if not input_sources.token_available():
+                output.text('Select list.')
+            list_name = input_sources.get_token(preferred_phrases=self.client.lists.keys())
+            output.text('Selected list: %s' % list_name)
             if list_name in self.client.lists:
                 return list_name
             else:
@@ -75,18 +77,20 @@ class Wunderlist(base.BaseFunction):
 
         tasks = []
         if self.multiple_tasks:
-            lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
+            t = input_sources.get_token(120)
+            output.text('Specify tasks:')
+
+            while t not in ['done', 'cancel', None]:
+                tasks.append(t)
+                t = input_sources.get_token(120)
 
-            if terminator == 'cancel':
+            if t in ['cancel', None]:
                 output.cancelled()
                 return
-
-            else:
-                for line in lines:
-                    tasks.extend([t.strip() for t in line.split(' and ') if t.strip()])
         
         else:
-            task = ears.listen(pause_threshold=3)
+            output.text('Specify task:')
+            task = input_sources.get_line()
             if task == 'cancel': 
                 output.cancelled()
                 return

+ 51 - 0
voice_control/input_sources/__init__.py

@@ -0,0 +1,51 @@
+import Queue
+import threading
+import console_input
+
+_TOKEN_STREAM = None
+
+class TokenStream(object):
+    def __init__(self):
+        self.preferred_phrases = None
+        self.buffer = Queue.Queue()
+    
+    def add_token(self, token):
+        self.buffer.put(token)
+    
+    def get_token(self, timeout):
+        try:
+            return self.buffer.get(timeout=timeout).strip()
+        except Queue.Empty:
+            return None
+
+    def get_line(self, timeout):
+        return self.get_token(timeout)
+
+def launch_input_sources(interrupted):
+    global _TOKEN_STREAM
+    _TOKEN_STREAM = TokenStream()
+
+    services = [
+        console_input.ConsoleInput(_TOKEN_STREAM, interrupted)
+    ]
+
+    for s in services:
+        t = threading.Thread(target=s.run)
+        t.start()
+
+def get_token(timeout=120, preferred_phrases=None):
+    return _TOKEN_STREAM.get_token(timeout)
+
+def get_line(timeout=120, preferred_phrases=None):
+    return _TOKEN_STREAM.get_line(timeout)
+
+def token_available():
+    return not _TOKEN_STREAM.buffer.empty()
+
+def get_until_terminated(timeout=120, terminators=['done', 'cancel'], preferred_phrases=None):
+    res = []
+    t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
+    while t not in terminators:
+        res.append(t)
+        t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
+    return res, t

+ 15 - 0
voice_control/input_sources/console_input.py

@@ -0,0 +1,15 @@
+class ConsoleInput(object):
+    def __init__(self, token_stream, interrupted):
+        self.stream = token_stream
+        self.interrupted = interrupted
+    
+    def run(self):
+        while not self.interrupted():
+            try:
+                cmd = raw_input('> ')
+                for token in cmd.split(' '):
+                    token = token.strip()
+                    if token:
+                        self.stream.add_token(token)
+            except EOFError:
+                return

+ 22 - 27
voice_control/main.py

@@ -1,35 +1,30 @@
 import logging
 import sys
-import threading
-import trigger
-import functions.todo_wunderlist
-import functions.email_mailgun
-import functions.music
+import signal
+import input_sources
+import functions
 
-def init():
-    logging.basicConfig(stream=sys.stdout)
-    logging.getLogger().setLevel(logging.INFO)
+_INTERRUPTED = False
 
-def init_all(services):
-    for s in services:
-        if not s.initialized:
-            t = threading.Thread(target=s.init)
-            t.start()
+def _signal_handler(*_):
+    global _INTERRUPTED
+    _INTERRUPTED = True
 
-_AUDIO_SERVICES = [{
-    'model': '/home/martin/workspaces/visual-code/voice_control/resources/snowboy/alexa.umdl',
-    'callbacks': {
-        'email': functions.email_mailgun.Email(),
-        'food': functions.todo_wunderlist.Wunderlist(True, 'food'),
-        'todo': functions.todo_wunderlist.Wunderlist(False),
-        #'play': functions.music.Music(),
-    }
-}]
+def _interrupt_callback():
+    global _INTERRUPTED
+    return _INTERRUPTED
+
+def _init_logging():
+    logging.basicConfig(stream=sys.stdout)
+    logging.getLogger().setLevel(logging.INFO)
+    signal.signal(signal.SIGINT, _signal_handler)
 
 if __name__ == "__main__":
-    init()
-    init_all(_AUDIO_SERVICES[0]['callbacks'].values())
-    trigger.start(_AUDIO_SERVICES)
-    #trigger.loop_model(_AUDIO_SERVICES[0])
+    _init_logging()
+    input_sources.launch_input_sources(_interrupt_callback)
+    functions.launch_services(_interrupt_callback)
 
-    #trigger._callback(_AUDIO_SERVICES[0])
+    #init_all(_AUDIO_SERVICES[0]['callbacks'].values())
+    #trigger.start(_AUDIO_SERVICES)
+    #trigger.loop_model(_AUDIO_SERVICES[0])
+    #trigger._callback(_AUDIO_SERVICES[0])

+ 15 - 3
voice_control/output/__init__.py

@@ -1,13 +1,25 @@
 import audio_output
+import logging
 
 def success():
     audio_output.play_clip(audio_output.Clips.SUCCESS)
+    logging.info('OK.')
 
-def failure():
+def failure(s=None):
     audio_output.play_clip(audio_output.Clips.FAILURE)
+    if s:
+        logging.info('Failed.')
+    else:
+        logging.info(s)
 
 def cancelled():
-    audio_output.tts('cancelled')
+    tts('cancelled')
+    logging.info('Cancelled.')
+
+def tts(s):
+    audio_output.tts(s)
+    logging.info(s)
 
 def text(s):
-    audio_output.tts(s)
+    audio_output.tts(s)
+    logging.info(s)