Forráskód Böngészése

wunderlist improvements, cleanup, better .init service usage

Martin 10 éve
szülő
commit
50b05c7177

+ 100 - 0
.vscode/.ropeproject/config.py

@@ -0,0 +1,100 @@
+# The default ``config.py``
+# flake8: noqa
+
+
+def set_prefs(prefs):
+    """This function is called before opening the project"""
+
+    # Specify which files and folders to ignore in the project.
+    # Changes to ignored resources are not added to the history and
+    # VCSs.  Also they are not returned in `Project.get_files()`.
+    # Note that ``?`` and ``*`` match all characters but slashes.
+    # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
+    # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
+    # '.svn': matches 'pkg/.svn' and all of its children
+    # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
+    # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
+    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
+                                  '.hg', '.svn', '_svn', '.git', '.tox']
+
+    # Specifies which files should be considered python files.  It is
+    # useful when you have scripts inside your project.  Only files
+    # ending with ``.py`` are considered to be python files by
+    # default.
+    #prefs['python_files'] = ['*.py']
+
+    # Custom source folders:  By default rope searches the project
+    # for finding source folders (folders that should be searched
+    # for finding modules).  You can add paths to that list.  Note
+    # that rope guesses project source folders correctly most of the
+    # time; use this if you have any problems.
+    # The folders should be relative to project root and use '/' for
+    # separating folders regardless of the platform rope is running on.
+    # 'src/my_source_folder' for instance.
+    #prefs.add('source_folders', 'src')
+
+    # You can extend python path for looking up modules
+    #prefs.add('python_path', '~/python/')
+
+    # Should rope save object information or not.
+    prefs['save_objectdb'] = True
+    prefs['compress_objectdb'] = False
+
+    # If `True`, rope analyzes each module when it is being saved.
+    prefs['automatic_soa'] = True
+    # The depth of calls to follow in static object analysis
+    prefs['soa_followed_calls'] = 0
+
+    # If `False` when running modules or unit tests "dynamic object
+    # analysis" is turned off.  This makes them much faster.
+    prefs['perform_doa'] = True
+
+    # Rope can check the validity of its object DB when running.
+    prefs['validate_objectdb'] = True
+
+    # How many undos to hold?
+    prefs['max_history_items'] = 32
+
+    # Shows whether to save history across sessions.
+    prefs['save_history'] = True
+    prefs['compress_history'] = False
+
+    # Set the number spaces used for indenting.  According to
+    # :PEP:`8`, it is best to use 4 spaces.  Since most of rope's
+    # unit-tests use 4 spaces it is more reliable, too.
+    prefs['indent_size'] = 4
+
+    # Builtin and c-extension modules that are allowed to be imported
+    # and inspected by rope.
+    prefs['extension_modules'] = []
+
+    # Add all standard c-extensions to extension_modules list.
+    prefs['import_dynload_stdmods'] = True
+
+    # If `True` modules with syntax errors are considered to be empty.
+    # The default value is `False`; When `False` syntax errors raise
+    # `rope.base.exceptions.ModuleSyntaxError` exception.
+    prefs['ignore_syntax_errors'] = False
+
+    # If `True`, rope ignores unresolvable imports.  Otherwise, they
+    # appear in the importing namespace.
+    prefs['ignore_bad_imports'] = False
+
+    # If `True`, rope will insert new module imports as
+    # `from <package> import <module>` by default.
+    prefs['prefer_module_from_imports'] = False
+
+    # If `True`, rope will transform a comma list of imports into
+    # multiple separate import statements when organizing
+    # imports.
+    prefs['split_imports'] = False
+
+    # If `True`, rope will sort imports alphabetically by module name
+    # instead of alphabetically by import statement, with from imports
+    # after normal imports.
+    prefs['sort_imports_alphabetically'] = False
+
+
+def project_opened(project):
+    """This function is called after opening the project"""
+    # Do whatever you like here!

BIN
.vscode/.ropeproject/objectdb


+ 7 - 0
clips.py

@@ -2,6 +2,7 @@ import os
 import time
 import wave
 import pyaudio
+import tts
 
 _CLIP_FOLDER = os.path.join('resources', 'clips')
 _CLIP_DATA_CACHE = {}
@@ -21,6 +22,11 @@ def play(clip):
     :return: None
     """
 
+    fname = os.path.join(_CLIP_FOLDER, clip)
+    tts._play(fname, False)
+    return
+
+    """
     audio = pyaudio.PyAudio()
 
     if clip not in _CLIP_DATA_CACHE:
@@ -47,3 +53,4 @@ def play(clip):
     stream_out.stop_stream()
     stream_out.close()
     audio.terminate()
+    """

+ 1 - 0
ears.py

@@ -8,6 +8,7 @@ def _get_recognizer(pause_threshold):
     recognizer = sr.Recognizer()
     recognizer.pause_threshold = pause_threshold
     recognizer.dynamic_energy_threshold = False
+    recognizer.energy_threshold = 500
 
     return recognizer    
 

+ 2 - 0
functions/base.py

@@ -1,4 +1,6 @@
 class BaseFunction(object):
+    initialized = True
+    
     def init(self):
         pass
     def preferred_phrases(self):

+ 0 - 0
functions/email.py → functions/email_mailgun.py


+ 4 - 7
functions/music.py

@@ -11,14 +11,14 @@ class Music(base.BaseFunction):
     folders = None
     current_process = None
 
-    def _initialize(self):
-        logging.info('initializing...')
+    def __init__(self):
+        self.initialized = False
 
+    def init(self):
         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.')
+        self.initialized = True
 
     def _search(self, tokens):
         if not tokens:
@@ -39,9 +39,6 @@ class Music(base.BaseFunction):
             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)

+ 21 - 21
functions/todo.py → functions/todo_wunderlist.py

@@ -7,11 +7,10 @@ import requests
 
 _LISTEN_TIMEOUT = 600
 _GROCERIES = ['milk', 'bread']
-
 _WUNDERLIST_CLIENT_ID = '34e0e31945afeb63e1b8'
 _WUNDERLIST_ACCESS_TOKEN = 'a7258e8b6596fdaffc904fc6b65d40c23afe6d2a28bfe7be1a9026d44b59'
 
-class WunderlistClient(object):
+class _WunderlistClient(object):
     lists = None
     
     def __init__(self, client_id, access_token):
@@ -33,24 +32,33 @@ class WunderlistClient(object):
         else:
             raise Exception(resp.content)
 
-    def create_task(self, list_id, title):
+    def create_task(self, list_name, title):
+        list_id = self.lists[list_name]
         self.call('POST', 'https://a.wunderlist.com/api/v1/tasks', {'list_id': list_id, 'title': title})
 
     def init(self):
         lists_res = self.call('GET', 'https://a.wunderlist.com/api/v1/lists')
         self.lists = {x['title'].lower(): x['id'] for x in lists_res}
+        print self.lists
     
-c =  WunderlistClient(_WUNDERLIST_CLIENT_ID, _WUNDERLIST_ACCESS_TOKEN)
-c.init()
-c.create_task(c.lists['food'], 'Test #1')
+class Wunderlist(base.BaseFunction):
+    client = None
+
+    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
 
-"""
-class WunderbarTodo(base.BaseFunction):
     def init(self):
-        self.client = WunderlistClient(_WUNDERLIST_CLIENT_ID, _WUNDERLIST_ACCESS_TOKEN)
-        return self.client.init()
+        self.client.init()
+        if self.list_name and self.list_name not in self.client.lists:
+            logging.error('Could not find list %s', self.list_name)
+            return
+        self.initialized = True
 
-    def _groceries(self):
+    def call(self, **_):
         tts.tts('ready')
 
         lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
@@ -64,15 +72,7 @@ class WunderbarTodo(base.BaseFunction):
             for line in lines:
                 items.extend([t.strip() for t in line.split(' and ') if t.strip()])
 
-            logging.info(items)
+            for item in items:
+                self.client.create_task(self.list_name, item)
 
             tts.tts('ok')
-
-
-    def call(self, trigger=None, **_):
-        if trigger == 'food':
-            self._groceries()
-        else:
-            tts.tts('Bad trigger')
-
-"""

+ 12 - 11
main.py

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