Quellcode durchsuchen

fix mother neuron class

Nicolas Marcq vor 8 Jahren
Ursprung
Commit
c2cfb43a68

+ 3 - 3
brain_examples/fr/fr_systemdate.yml

@@ -3,7 +3,7 @@
     - systemdate:
         say_template:
           - "Il est {{ hours }} heures et {{ minutes }} minutes"
-        tts: "pico2wave"
+        tts: "voxygen"
   signals:
     - order: "test"
 
@@ -12,6 +12,6 @@
   neurons:
     - systemdate:
         file_template: fr_systemdate_template_example.j2
-        tts: "pico2wave"
+        tts: "voxygen"
   signals:
-    - order: "test 2"
+    - order: "tempate"

+ 1 - 2
brain_examples/fr/say_examples.yml

@@ -4,6 +4,5 @@
       - say:
           message:
             - "42"
-          tts: "voxygen"
     signals:
-      - order: "sens de la vie"
+      - order: "test"

+ 0 - 1
core/Cache.py

@@ -18,7 +18,6 @@ class Cache:
         self._module_name = module_name
         self._cache_path = cache_path
         self._cache_extension = cache_extension
-        self._cache_extension = DEFAULT_CACHE_EXTENSION
 
     def get_audio_file_cache_path(self, words, voice, language):
         # fix UnicodeEncodeError: 'ascii' codec can't encode character X in position Y

+ 2 - 2
core/ConfigurationManager/BrainLoader.py

@@ -3,7 +3,7 @@ from YAMLLoader import YAMLLoader
 from core.ConfigurationManager.ConfigurationChecker import ConfigurationChecker
 from core.Models.Brain import Brain
 from core.Models.Event import Event
-from core.Models.Neurone import Neurone
+from core.Models.Neuron import Neuron
 from core.Models.Order import Order
 from core.Models.Synapse import Synapse
 
@@ -72,7 +72,7 @@ class BrainLoader(YAMLLoader):
                     name = neuron_name
                     parameters = neuron_dict[name]
                     # print parameters
-                    new_neuron = Neurone(name=name, parameters=parameters)
+                    new_neuron = Neuron(name=name, parameters=parameters)
                     neurons.append(new_neuron)
 
         return neurons

+ 6 - 0
core/Models/Neuron.py

@@ -0,0 +1,6 @@
+
+
+class Neuron(object):
+    def __init__(self, name=None, parameters=None):
+        self.name = name
+        self.parameters = parameters

+ 0 - 140
core/Models/Neurone.py

@@ -1,140 +0,0 @@
-from jinja2 import Template
-import random
-import os.path
-import logging
-
-from core.ConfigurationManager.SettingLoader import SettingLoader
-
-
-class NoTemplateException(Exception):
-    pass
-
-
-class MultipleTemplateException(Exception):
-    pass
-
-
-class TemplateFileNotFoundException(Exception):
-    pass
-
-
-class TTSModuleNotFound(Exception):
-    pass
-
-
-class TTSNotInstantiable(Exception):
-    pass
-
-
-class Neurone(object):
-    def __init__(self, name=None, parameters=None, **kargs):
-        # get the name of the plugin who load Neurone mother class
-        # print self.__class__.__name__
-        self.name = name
-        self.parameters = parameters
-
-        logging.debug("Neurone class called with name %s and parameters: %s" % (name, parameters))
-
-        # get the tts if is specified otherwise use default
-        tts = None
-        if self.parameters is not None:
-            tts = self.parameters.get('tts', None)
-            print "tts %s" % tts
-
-        if tts is not None:
-            self.tts = tts
-        else:
-            self.tts = SettingLoader().get_default_text_to_speech()
-        # get tts args
-        self.tts_args = SettingLoader().get_tts_args(self.tts)
-        # load the module
-        self.tts_instance = self._get_tts_instance()
-
-    def say(self, message, **kwargs):
-        # get the tts if is specified otherwise use default
-        tts = kwargs.get('tts', None)
-        if tts is not None:
-            # the user want to use another TSS than the default one for this neuron
-            self.tts = tts
-            self.tts_instance = self._get_tts_instance()
-            self.tts_args = SettingLoader().get_tts_args(self.tts)
-
-        # get if the cache settings is present
-        override_cache = kwargs.get('cache', None)
-        if override_cache is not None:
-            # the user set the "cache var"
-            self.tts_args = self._update_cache_var(override_cache)
-
-        # check if it's a single message or multiple one
-        if isinstance(message, list):
-            # then we pick randomly one message
-            message = random.choice(message)
-
-        # Check if there is a template associate to the output message
-        say_template = kwargs.get('say_template', None)
-        # check if there is a template file associate to the output message
-        file_template = kwargs.get('file_template', None)
-
-        # we check if the user provide a say_template or a file_template, Not both
-        if say_template is not None and file_template is not None:
-            raise MultipleTemplateException("You must provide a say_template or a file_template, not both")
-
-        # check on of the two option is set
-        if isinstance(message, dict):
-            if (say_template is not None and file_template is None) or \
-                    (say_template is None and file_template is not None):
-                if say_template is not None:    # the user choose a say_template option
-                    if isinstance(say_template, list):
-                        # then we pick randomly one template
-                        say_template = random.choice(say_template)
-                    t = Template(say_template)
-                    message = t.render(**message)
-                if file_template is not None:   # the user choose a file_template option
-                    real_file_template_path = "templates/%s" % file_template
-                    if os.path.isfile(real_file_template_path):
-                        # load the content of the file as template
-                        t = Template(self._get_content_of_file(real_file_template_path))
-                        message = t.render(**message)
-                    else:
-                        raise TemplateFileNotFoundException("Template file %s not found in templates folder"
-                                                            % real_file_template_path)
-
-            else:
-                raise NoTemplateException("You must specify a say_template or a file_template", message.keys())
-
-        # here we use the tts to make jarvis talk
-        # the module is imported on fly, depending on the selected tts from settings
-        print "To TTS instance type is: %s" % self.tts_instance.__class__.__name__
-        self.tts_instance.say(words=message, **(self.tts_args if self.tts_args is not None else {}))
-
-    def _get_tts_instance(self):
-        # capitalise for loading module name
-        self.tts = self.tts.capitalize()
-        logging.info("Import TTS module named %s " % self.tts)
-        mod = __import__('tts', fromlist=[str(self.tts)])
-        try:
-            klass = getattr(mod, self.tts)
-        except ImportError, e:
-            raise TTSModuleNotFound("The TTS not found: %s" % e)
-
-        if klass is not None:
-            # run the plugin
-            return klass()
-        else:
-            raise TTSNotInstantiable("TTS module %s not instantiable" % self.tts)
-
-    @staticmethod
-    def _check_file_exist(real_file_template):
-        return os.path.isfile(real_file_template)
-
-    @staticmethod
-    def _get_content_of_file(real_file_template_path):
-        with open(real_file_template_path, 'r') as content_file:
-            return content_file.read()
-
-    def _update_cache_var(self, override_cache):
-        print "args for TTS plugin before update: %s" % str(self.tts_args)
-        self.tts_args["cache"] = override_cache
-
-        print "args for TTS plugin after update: %s" % str(self.tts_args)
-        return self.tts_args

+ 1 - 1
core/Models/__init__.py

@@ -2,4 +2,4 @@ from Event import Event
 from Brain import Brain
 from Order import Order
 from Synapse import Synapse
-from Neurone import Neurone
+from Neuron import Neuron

+ 159 - 0
core/NeuronModule.py

@@ -0,0 +1,159 @@
+import logging
+import os
+import random
+
+from jinja2 import Template
+
+from core.ConfigurationManager import SettingLoader
+
+
+class NoTemplateException(Exception):
+    pass
+
+
+class MultipleTemplateException(Exception):
+    pass
+
+
+class TemplateFileNotFoundException(Exception):
+    pass
+
+
+class TTSModuleNotFound(Exception):
+    pass
+
+
+class TTSNotInstantiable(Exception):
+    pass
+
+
+class NeuronModule(object):
+    def __init__(self, **kwargs):
+        """
+        Class used by neuron for talking
+        :param kwargs: Same parameter as the Child. Can contain info about the tts to use instead of the
+        default one
+        """
+        # get the child who called the class
+        child_name = self.__class__.__name__
+        logging.debug("NeuronModule called from class %s with parameters: %s" % (child_name, kwargs))
+
+        # check if the user has overrider the TTS
+        tts = kwargs.get('tts', None)
+        if tts is None:
+            # No tts provided,  we load the default one
+            self.tts = SettingLoader().get_default_text_to_speech()
+        else:
+            self.tts = tts
+
+        # get if the cache settings is present
+        self.override_cache = kwargs.get('cache', None)
+
+        # get templates if provided
+        # Check if there is a template associate to the output message
+        self.say_template = kwargs.get('say_template', None)
+        # check if there is a template file associate to the output message
+        self.file_template = kwargs.get('file_template', None)
+
+    def say(self, message):
+        """
+        USe TTS to speak out loud the Message.
+        A message can be a string, a list or a dict
+        If it's a string, simply use the TTS with the message
+        If it's a list, we select randomly a string in the list and give it to the TTS
+        If it's a dict, we use the template given in parameter to create a string that we give to the TTS
+        :param message: Can be a String or a dict
+        :return:
+        """
+        logging.debug("NeuronModule Say() called with message: %s" % message)
+
+        tts_message = None
+
+        if isinstance(message, str):
+            print "message is string"
+            tts_message = message
+
+        if isinstance(message, list):
+            print "message is list"
+            tts_message = self._get_message_from_list(message)
+
+        if isinstance(message, dict):
+            print "message is dict"
+            tts_message = self._get_message_from_dict(message)
+
+        if message is not None:
+            # get an instance of the target TTS
+            tts_instance = self._get_tts_instance(self.tts)
+            tts_args = SettingLoader().get_tts_args(self.tts)
+            # change the cache settings with the one precised for the current neuron
+            if self.override_cache:
+                tts_args = self._update_cache_var(self.override_cache, tts_args)
+            tts_instance.say(words=tts_message, **(tts_args if tts_args is not None else {}))
+
+    @staticmethod
+    def _get_message_from_list(message_list):
+        """
+        Return an element from the list randomly
+        :param message_list:
+        :return:
+        """
+        return random.choice(message_list)
+
+    def _get_message_from_dict(self, message_dict):
+        returned_message = None
+
+        if (self.say_template is not None and self.file_template is None) or \
+                (self.say_template is None and self.file_template is not None):
+
+            # the user choose a say_template option
+            if self.say_template is not None:
+                if isinstance(self.say_template, list):
+                    # then we pick randomly one template
+                    self.say_template = random.choice(self.say_template)
+                t = Template(self.say_template)
+                returned_message = t.render(**message_dict)
+
+            # the user choose a file_template option
+            if self.file_template is not None:  # the user choose a file_template option
+                real_file_template_path = "templates/%s" % self.file_template
+                if os.path.isfile(real_file_template_path):
+                    # load the content of the file as template
+                    t = Template(self._get_content_of_file(real_file_template_path))
+                    returned_message = t.render(**message_dict)
+                else:
+                    raise TemplateFileNotFoundException("Template file %s not found in templates folder"
+                                                        % real_file_template_path)
+            return returned_message
+
+        else:
+            raise NoTemplateException("You must specify a say_template or a file_template")
+
+    @staticmethod
+    def _get_content_of_file(real_file_template_path):
+        with open(real_file_template_path, 'r') as content_file:
+            return content_file.read()
+
+    @staticmethod
+    def _get_tts_instance(tts_name):
+        # capitalise for loading module name
+        tts = tts_name.capitalize()
+        logging.info("Import TTS module named %s " % tts)
+        mod = __import__('tts', fromlist=[str(tts)])
+        try:
+            klass = getattr(mod, tts)
+        except ImportError, e:
+            raise TTSModuleNotFound("The TTS not found: %s" % e)
+
+        if klass is not None:
+            # run the plugin
+            return klass()
+        else:
+            raise TTSNotInstantiable("TTS module %s not instantiable" % tts)
+
+    @staticmethod
+    def _update_cache_var(new_override_cache, args_list):
+        print "args for TTS plugin before update: %s" % str(args_list)
+        args_list["cache"] = new_override_cache
+
+        print "args for TTS plugin after update: %s" % str(args_list)
+        return args_list

+ 4 - 5
neurons/ansible_tasks/ansible_tasks.py

@@ -4,13 +4,12 @@ from ansible.vars import VariableManager
 from ansible.inventory import Inventory
 from ansible.executor.playbook_executor import PlaybookExecutor
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
-class Ansible_tasks(Neurone):
-    def __init__(self, task_file):
-        Neurone.__init__(self)
-
+class Ansible_tasks(NeuronModule):
+    def __init__(self, task_file, **kwargs):
+        super(Ansible_tasks, self).__init__(**kwargs)
         Options = namedtuple('Options',
                              ['connection', 'forks', 'become', 'become_method', 'become_user', 'check', 'listhosts',
                               'listtasks', 'listtags', 'syntax', 'module_path'])

+ 4 - 4
neurons/command/command.py

@@ -1,11 +1,11 @@
 import subprocess
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
-class Command(Neurone):
-    def __init__(self, command):
-        Neurone.__init__(self)
+class Command(NeuronModule):
+    def __init__(self, command, **kwargs):
+        super(Command, self).__init__(**kwargs)
         p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
         (output, err) = p.communicate()
 

+ 4 - 5
neurons/kill_switch/kill_switch.py

@@ -1,11 +1,10 @@
 import sys
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
-class Kill_switch(Neurone):
-
-    def __init__(self, *args , **kwargs):
-        Neurone.__init__(self)
+class Kill_switch(NeuronModule):
 
+    def __init__(self, **kwargs):
+        super(Kill_switch, self).__init__(**kwargs)
         sys.exit()

+ 4 - 4
neurons/say/say.py

@@ -1,17 +1,17 @@
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
 class NoMessageException(Exception):
     pass
 
 
-class Say(Neurone):
+class Say(NeuronModule):
     def __init__(self, **kwargs):
-        Neurone.__init__(self, **kwargs)
+        super(Say, self).__init__(**kwargs)
         # get message to spell out loud
         message = kwargs.get('message', None)
         # user must specify a message
         if message is None:
             raise NoMessageException("You must specify a message string or a list of messages as parameter")
         else:
-            self.say(**kwargs)
+            self.say(message)

+ 5 - 7
neurons/script/script.py

@@ -1,7 +1,7 @@
 import subprocess
 import os
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
 class ScriptNotFound(Exception):
@@ -12,11 +12,10 @@ class ScriptNotExecutable(Exception):
     pass
 
 
-class Script(Neurone):
-    def __init__(self, *args , **kwargs):
-        Neurone.__init__(self)
-
+class Script(NeuronModule):
+    def __init__(self, **kwargs):
         # get message to spell out loud
+        super(Script, self).__init__(**kwargs)
         script_path = kwargs.get('path', "")
 
         # test that the file exist and is executable
@@ -24,7 +23,6 @@ class Script(Neurone):
             p = subprocess.Popen(script_path, stdout=subprocess.PIPE, shell=True)
             (output, err) = p.communicate()
 
-
     def is_exe(self, fpath):
         returned_value = True
         if not os.path.isfile(fpath):
@@ -32,4 +30,4 @@ class Script(Neurone):
         if not os.access(fpath, os.X_OK):
             raise ScriptNotExecutable()
 
-        return returned_value
+        return returned_value

+ 4 - 5
neurons/sleep/sleep.py

@@ -1,18 +1,17 @@
 import time
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
 class NoSecondsException(Exception):
     pass
 
 
-class Sleep(Neurone):
-
-    def __init__(self, *args , **kwargs):
-        Neurone.__init__(self)
+class Sleep(NeuronModule):
 
+    def __init__(self, **kwargs):
         # get message to spell out loud
+        super(Sleep, self).__init__(**kwargs)
         seconds = kwargs.get('seconds', None)
         # user must specify a message
         if seconds is None:

+ 5 - 4
neurons/systemdate/systemdate.py

@@ -1,14 +1,15 @@
 #!/usr/bin/python
 import time
 
-from core.Models.Neurone import Neurone
+from core.NeuronModule import NeuronModule
 
 
-class Systemdate(Neurone):
+class Systemdate(NeuronModule):
     def __init__(self, **kwargs):
-        Neurone.__init__(self, **kwargs)
+        super(Systemdate, self).__init__(**kwargs)
 
         # get hours and minutes
+
         hour = time.strftime("%H")
         minute = time.strftime("%M")
 
@@ -16,4 +17,4 @@ class Systemdate(Neurone):
             "hours": hour,
             "minutes": minute
         }
-        self.say(message, **kwargs)
+        self.say(message)

+ 8 - 1
test.py

@@ -1,6 +1,13 @@
 # coding=utf-8
 from core.OrderAnalyser import OrderAnalyser
 
-oa = OrderAnalyser("test 2", brain_file="brain_examples/fr/fr_systemdate.yml")
+import logging
+logger = logging.getLogger()
+logger.setLevel(logging.DEBUG)
+
+
+# oa = OrderAnalyser("test", brain_file="brain_examples/fr/say_examples.yml")
+
+oa = OrderAnalyser("test", brain_file="brain_examples/fr/fr_systemdate.yml")
 
 oa.start()

+ 4 - 2
tts/pico2wave/pico2wave.py

@@ -5,7 +5,7 @@ import logging, sys
 
 class Pico2wave(TTS):
     PICO2WAVE_LANGUAGES = dict(fr="fr-FR", us="en-US", uk="en-GB", de="de-DE", es="es-ES", it="it-IT")
-    PICO2WAVE_LANGUAGES_DEFAULT = PICO2WAVE_LANGUAGES['fr']
+    PICO2WAVE_LANGUAGES_DEFAULT = 'fr'
 
     def __init__(self, audio_player_type=None):
         """
@@ -22,10 +22,12 @@ class Pico2wave(TTS):
         self.play_audio(file_path, cache=cache)
 
     def get_voice(self, language):
+        print "asked lang: %s" % language
+
         if language in self.PICO2WAVE_LANGUAGES:
             return self.PICO2WAVE_LANGUAGES[language]
 
-        logging.warn("Cannot find language matching language: %s voice: %s replace by default voice: %s", language, self.PICO2WAVE_LANGUAGES_DEFAULT)
+        logging.warn("Cannot find language matching language:  %s replace by default voice: %s", language, self.PICO2WAVE_LANGUAGES_DEFAULT)
         return self.PICO2WAVE_LANGUAGES_DEFAULT
 
     @staticmethod

+ 1 - 1
tts/voxygen/voxygen.py

@@ -28,7 +28,7 @@ class Voxygen(TTS):
     VOXYGEN_TIMEOUT_SEC = 30
 
     def __init__(self):
-        TTS.__init__(self, AudioPlayer.PLAYER_MP3)
+        TTS.__init__(self, AudioPlayer.PLAYER_MP3, cache_extension="tts")
 
     def say(self, words=None, voice=None, language=VOXYGEN_LANGUAGES_DEFAULT, cache=True):
         voice = self.get_voice(voice, language)