| 5 | |
| 6 | |
| 7 | class Brain(object): |
| 8 | |
| 9 | def __init__(self, mic, profile): |
| 10 | """ |
| 11 | Instantiates a new Brain object, which cross-references user |
| 12 | input with a list of modules. Note that the order of brain.modules |
| 13 | matters, as the Brain will cease execution on the first module |
| 14 | that accepts a given input. |
| 15 | |
| 16 | Arguments: |
| 17 | mic -- used to interact with the user (for both input and output) |
| 18 | profile -- contains information related to the user (e.g., phone |
| 19 | number) |
| 20 | """ |
| 21 | |
| 22 | self.mic = mic |
| 23 | self.profile = profile |
| 24 | self.modules = self.get_modules() |
| 25 | self._logger = logging.getLogger(__name__) |
| 26 | |
| 27 | @classmethod |
| 28 | def get_modules(cls): |
| 29 | """ |
| 30 | Dynamically loads all the modules in the modules folder and sorts |
| 31 | them by the PRIORITY key. If no PRIORITY is defined for a given |
| 32 | module, a priority of 0 is assumed. |
| 33 | """ |
| 34 | |
| 35 | logger = logging.getLogger(__name__) |
| 36 | locations = [jasperpath.PLUGIN_PATH] |
| 37 | logger.debug("Looking for modules in: %s", |
| 38 | ', '.join(["'%s'" % location for location in locations])) |
| 39 | modules = [] |
| 40 | for finder, name, ispkg in pkgutil.walk_packages(locations): |
| 41 | try: |
| 42 | loader = finder.find_module(name) |
| 43 | mod = loader.load_module(name) |
| 44 | except: |
| 45 | logger.warning("Skipped module '%s' due to an error.", name, |
| 46 | exc_info=True) |
| 47 | else: |
| 48 | if hasattr(mod, 'WORDS'): |
| 49 | logger.debug("Found module '%s' with words: %r", name, |
| 50 | mod.WORDS) |
| 51 | modules.append(mod) |
| 52 | else: |
| 53 | logger.warning("Skipped module '%s' because it misses " + |
| 54 | "the WORDS constant.", name) |
| 55 | modules.sort(key=lambda mod: mod.PRIORITY if hasattr(mod, 'PRIORITY') |
| 56 | else 0, reverse=True) |
| 57 | return modules |
| 58 | |
| 59 | def query(self, texts): |
| 60 | """ |
| 61 | Passes user input to the appropriate module, testing it against |
| 62 | each candidate module's isValid function. |
| 63 | |
| 64 | Arguments: |