From e5c3058a64ae6e27d2bd323a18f02c26df1cdfdf Mon Sep 17 00:00:00 2001 From: schneefux Date: Sat, 24 May 2014 18:34:54 -0700 Subject: dynamic module loading with priorities --- .gitignore | 1 + client/brain.py | 41 +++++++++++++++++++++++++++++++++++++---- client/modules/HN.py | 2 ++ client/modules/News.py | 2 ++ client/modules/Unclear.py | 3 +++ 5 files changed, 45 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index b40c969..08cf7c5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +env/ client/env client/venv *.pyc diff --git a/client/brain.py b/client/brain.py index b5e0c1d..2e7607a 100644 --- a/client/brain.py +++ b/client/brain.py @@ -1,5 +1,5 @@ import logging -from modules import * +from os import listdir def logError(): @@ -25,11 +25,44 @@ class Brain(object): mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ + + def get_modules(): + """ + Dynamically loads all the modules in the modules folder and sorts + them by the PRIORITY key. If no PRIORITY is defined for a given + module, a priority of 0 is assumed. + """ + + folder = 'modules' + + def get_module_names(): + module_names = [m.replace('.py', '') + for m in listdir(folder) if m.endswith('.py')] + module_names.remove('__init__') + module_names.remove('app_utils') + module_names = map(lambda s: folder + '.' + s, module_names) + return module_names + + def import_module(name): + mod = __import__(name) + components = name.split('.') + for comp in components[1:]: + mod = getattr(mod, comp) + return mod + + def get_module_priority(m): + try: + return m.PRIORITY + except: + return 0 + + modules = map(import_module, get_module_names()) + modules.sort(key=get_module_priority, reverse=True) + return modules + self.mic = mic self.profile = profile - self.modules = [ - Gmail, Notifications, Birthday, Weather, HN, News, Time, Joke, Life] - self.modules.append(Unclear) + self.modules = get_modules() def query(self, text): """ diff --git a/client/modules/HN.py b/client/modules/HN.py index 692abea..493fa1d 100644 --- a/client/modules/HN.py +++ b/client/modules/HN.py @@ -7,6 +7,8 @@ from semantic.numbers import NumberService WORDS = ["HACKER", "NEWS", "YES", "NO", "FIRST", "SECOND", "THIRD"] +PRIORITY = 4 + URL = 'http://news.ycombinator.com' diff --git a/client/modules/News.py b/client/modules/News.py index 0cedd3a..59495a3 100644 --- a/client/modules/News.py +++ b/client/modules/News.py @@ -5,6 +5,8 @@ from semantic.numbers import NumberService WORDS = ["NEWS", "YES", "NO", "FIRST", "SECOND", "THIRD"] +PRIORITY = 3 + URL = 'http://news.ycombinator.com' diff --git a/client/modules/Unclear.py b/client/modules/Unclear.py index 39f56d0..23ab2ed 100644 --- a/client/modules/Unclear.py +++ b/client/modules/Unclear.py @@ -1,7 +1,10 @@ +from sys import maxint import random WORDS = [] +PRIORITY = -(maxint + 1) + def handle(text, mic, profile): """ -- cgit v1.3.1