-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrain.py
More file actions
executable file
·84 lines (68 loc) · 2.76 KB
/
brain.py
File metadata and controls
executable file
·84 lines (68 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import logging
from os import listdir
def logError():
logger = logging.getLogger('jasper')
fh = logging.FileHandler('jasper.log')
fh.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.error('Failed to execute module', exc_info=True)
class Brain(object):
def __init__(self, mic, profile):
"""
Instantiates a new Brain object, which cross-references user
input with a list of modules. Note that the order of brain.modules
matters, as the Brain will cease execution on the first module
that accepts a given input.
Arguments:
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 = 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 = filter(lambda m: hasattr(m, 'WORDS'), modules)
modules.sort(key=get_module_priority, reverse=True)
return modules
self.mic = mic
self.profile = profile
self.modules = get_modules()
def query(self, text):
"""
Passes user input to the appropriate module, testing it against
each candidate module's isValid function.
Arguments:
text -- user input, typically speech, to be parsed by a module
"""
for module in self.modules:
if module.isValid(text):
try:
module.handle(text, self.mic, self.profile)
break
except:
logError()
self.mic.say(
"I'm sorry. I had some trouble with that operation. Please try again later.")
break