Przeglądaj źródła

PEP8 + PEP257 + optimize import

nico 8 lat temu
rodzic
commit
5c3d7b4945

+ 35 - 29
core/NeuronModule.py

@@ -17,54 +17,49 @@ logger = logging.getLogger("kalliope")
 
 class InvalidParameterException(Exception):
     """
-       Some Neuron parameters are invalid.
+   Some Neuron parameters are invalid.
     """
     pass
 
 
 class MissingParameterException(Exception):
     """
-       Some Neuron parameters are missing.
+    Some Neuron parameters are missing.
     """
     pass
 
 
 class NoTemplateException(Exception):
     """
-        You must specify a say_template or a file_template
+    You must specify a say_template or a file_template
     """
     pass
 
 
-
 class TemplateFileNotFoundException(Exception):
     """
-        Template file can not be found. Check the provided path.
+    Template file can not be found. Check the provided path.
     """
     pass
 
 
 class TTSModuleNotFound(Exception):
     """
-        TTS module can not be find. It must be configured in the settings file.
+    TTS module can not be find. It must be configured in the settings file.
     """
     pass
 
 
-
-
 class NeuronModule(object):
-
     """
-
-        This Abstract Class is representing main Class for Neuron.
-        Each Neuron must implement this Class.
+    This Abstract Class is representing main Class for Neuron.
+    Each Neuron must implement this Class.
     """
     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
+        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__
@@ -92,14 +87,14 @@ class NeuronModule(object):
 
     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
-
-            .. raises:: TTSModuleNotFound
+        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 or a list
+
+        .. raises:: TTSModuleNotFound
         """
         logger.debug("NeuronModule Say() called with message: %s" % message)
 
@@ -138,11 +133,11 @@ class NeuronModule(object):
 
     def _get_message_from_dict(self, message_dict):
         """
-            Generate a message that can be played by a TTS engine from a dict of variable and the jinja template
-            :param message_dict: the dict of message
-            :return: The message to say
+        Generate a message that can be played by a TTS engine from a dict of variable and the jinja template
+        :param message_dict: the dict of message
+        :return: The message to say
 
-            .. raises:: TemplateFileNotFoundException
+        .. raises:: TemplateFileNotFoundException
         """
         returned_message = None
 
@@ -181,11 +176,22 @@ class NeuronModule(object):
 
     @staticmethod
     def _get_content_of_file(real_file_template_path):
+        """
+        Return the content of a file in path <real_file_template_path>
+        :param real_file_template_path: path of the file to return the content
+        :return: file content str
+        """
         with open(real_file_template_path, 'r') as content_file:
             return content_file.read()
 
     @staticmethod
     def _update_cache_var(new_override_cache, args_list):
+        """
+        update the value for the key "cache" in the dict args_list
+        :param new_override_cache: cache bolean to set in place of the current one in args_list
+        :param args_list: arg list that contain "cache" to update
+        :return:
+        """
         logger.debug("args for TTS plugin before update: %s" % str(args_list))
         args_list["cache"] = new_override_cache
         logger.debug("args for TTS plugin after update: %s" % str(args_list))
@@ -194,8 +200,8 @@ class NeuronModule(object):
     @staticmethod
     def get_audio_from_stt(callback):
         """
-            Call the default STT to get an audio sample and return it into the callback method
-            :param callback: A callback function
+        Call the default STT to get an audio sample and return it into the callback method
+        :param callback: A callback function
         """
         # call the order listener
         oa = OrderListener(callback=callback)

+ 4 - 5
core/NeuroneLauncher.py

@@ -14,11 +14,10 @@ class NeuroneLauncher:
     @classmethod
     def start_neurone(cls, neuron):
         """
-            Start a neuron plugin
-            :param neuron: neuron object
-            :type neuron: Neuron
-            :return:
+        Start a neuron plugin
+        :param neuron: neuron object
+        :type neuron: Neuron
+        :return:
         """
         logger.debug("Run plugin \"%s\" with parameters %s" % (neuron.name, neuron.parameters))
         return Utils.get_dynamic_class_instantiation("neurons", neuron.name.capitalize(), neuron.parameters)
-

+ 26 - 24
core/OrderAnalyser.py

@@ -13,17 +13,15 @@ logger = logging.getLogger("kalliope")
 
 
 class OrderAnalyser:
-
     """
-
-        This Class is used to compate the incoming message to the Signal/Order sentences.
+    This Class is used to compare the incoming message to the Signal/Order sentences.
     """
     def __init__(self, order, main_controller=None, brain=None):
         """
-            Class used to load brain and run neuron attached to the received order
-            :param order: spelt order
-            :param main_controller
-            :param brain: loaded brain
+        Class used to load brain and run neuron attached to the received order
+        :param order: spelt order
+        :param main_controller
+        :param brain: loaded brain
         """
         self.main_controller = main_controller
         self.order = order
@@ -35,8 +33,7 @@ class OrderAnalyser:
     def start(self):
         # TODO : refactor this method !!
         """
-            This method matchs the incoming messages to the signals/order sentences provided in the Brain
-
+        This method matches the incoming messages to the signals/order sentences provided in the Brain
         """
         synapses_found = False
         problem_in_neuron_found = False
@@ -95,9 +92,9 @@ class OrderAnalyser:
 
     def _associate_order_params_to_values(self, order_to_check):
         """
-            Associate the variables from the order to the incoming user order
-            :param order_to_check: the order to check
-            :return: the dict corresponding to the key / value of the params
+        Associate the variables from the order to the incoming user order
+        :param order_to_check: the order to check
+        :return: the dict corresponding to the key / value of the params
         """
         pattern = '\s+(?=[^\{\{\}\}]*\}\})'
         # Remove white spaces (if any) between the variable and the double brace then split
@@ -134,6 +131,11 @@ class OrderAnalyser:
 
     @staticmethod
     def _is_containing_bracket(sentence):
+        """
+        Return True if the text in <sentence> contains brackets
+        :param sentence:
+        :return:
+        """
         # print "sentence to test %s" % sentence
         pattern = r"{{|}}"
         # prog = re.compile(pattern)
@@ -150,10 +152,10 @@ class OrderAnalyser:
 
     def _spelt_order_match_brain_order_via_table(self, order_to_analyse, user_said):
         """
-            return true if all string that are in the sentence are present in the order to test
-            :param order_to_analyse: String order to test
-            :param user_said: String to compare to the order
-            :return: True if all string are present in the order
+        return true if all string that are in the sentence are present in the order to test
+        :param order_to_analyse: String order to test
+        :param user_said: String to compare to the order
+        :return: True if all string are present in the order
         """
         list_word_user_said = user_said.split()
         split_order_without_bracket = self._get_split_order_without_bracket(order_to_analyse)
@@ -164,10 +166,10 @@ class OrderAnalyser:
     @staticmethod
     def _get_split_order_without_bracket(order):
         """
-            Get an order with bracket inside like: "hello my name is {{ name }}.
-            return a list of string without bracket like ["hello", "my", "name", "is"]
-            :param order: sentence to split
-            :return: list of string without bracket
+        Get an order with bracket inside like: "hello my name is {{ name }}.
+        return a list of string without bracket like ["hello", "my", "name", "is"]
+        :param order: sentence to split
+        :return: list of string without bracket
         """
         pattern = r"((?:{{\s*)[\w\.]+(?:\s*}}))"
         # find everything like {{ word }}
@@ -181,10 +183,10 @@ class OrderAnalyser:
     @staticmethod
     def _counter_subset(list1, list2):
         """
-            check if the number of occurrences matches
-            :param list1:
-            :param list2:
-            :return:
+        check if the number of occurrences matches
+        :param list1:
+        :param list2:
+        :return:
         """
         c1, c2 = Counter(list1), Counter(list2)
         for k, n in c1.items():

+ 14 - 17
core/OrderListener.py

@@ -13,25 +13,24 @@ logger = logging.getLogger("kalliope")
 
 class OrderListener(Thread):
     """
+    This Class allows to Listen to an Incoming voice order.
 
-        This Class allows to Listen to an Incoming voice order.
-
-        .. notes:: Thread are used to calibrate the sound of the microphone input with the noise while
-            starting to listen the incoming order. Basically it avoids delays.
+    .. notes:: Thread are used to calibrate the sound of the microphone input with the noise while
+        starting to listen the incoming order. Basically it avoids delays.
     """
 
     def __init__(self, callback=None, stt=None):
         """
-            This class is called after we catch the hotword that have woke up Kalliope.
-            We now wait for an order spoken out loud by the user, translate the order into a text and run the action
-             attached to this order from settings
-            :param callback: callback function to call
-            :type callback: Callback function
-            :param stt: Speech to text plugin name to load. If not provided,
-            :type stt: STT intance
-            we will load the default one set in settings
+        This class is called after we catch the hotword that have woke up Kalliope.
+        We now wait for an order spoken out loud by the user, translate the order into a text and run the action
+         attached to this order from settings
+        :param callback: callback function to call
+        :type callback: Callback function
+        :param stt: Speech to text plugin name to load. If not provided,
+        :type stt: STT instance
+        we will load the default one set in settings
 
-            .. seealso::  STT
+        .. seealso::  STT
         """
         # this is a trick to ignore ALSA output error
         # see http://stackoverflow.com/questions/7088672/pyaudio-working-but-spits-out-error-messages-each-time
@@ -44,7 +43,7 @@ class OrderListener(Thread):
 
     def run(self):
         """
-           Start thread
+        Start thread
         """
         self.load_stt_plugin()
 
@@ -62,7 +61,7 @@ class OrderListener(Thread):
     @staticmethod
     def _ignore_stderr():
         """
-            Try to forward PortAudio messages from stderr to /dev/null.
+        Try to forward PortAudio messages from stderr to /dev/null.
         """
         ffi = _FFI()
         ffi.cdef("""
@@ -81,5 +80,3 @@ class OrderListener(Thread):
                 stdio.__stderrp = devnull
             except KeyError:
                 stdio.fclose(devnull)
-
-

+ 4 - 12
core/Players/Mplayer.py

@@ -5,16 +5,12 @@ import subprocess
 logging.basicConfig()
 logger = logging.getLogger("kalliope")
 
-
 MPLAYER_EXEC_PATH = "/usr/bin/mplayer"
 
 
 class Mplayer(object):
-
     """
-
-        This Class is representing the MPlayer Object used to play the all sound of the system.
-
+    This Class is representing the MPlayer Object used to play the all sound of the system.
     """
 
     def __init__(self):
@@ -23,11 +19,10 @@ class Mplayer(object):
     @classmethod
     def play(cls, filepath):
         """
-
         Play the sound located in the provided filepath
 
         :param filepath: The file path of the sound to play
-        :type synapses_list: String
+        :type filepath: str
 
         :Example:
 
@@ -38,7 +33,6 @@ class Mplayer(object):
         .. warnings:: Class Method and Public
         """
 
-
         mplayer_exec_path = [MPLAYER_EXEC_PATH]
         mplayer_options = ['-slave', '-quiet']
         mplayer_command = list()
@@ -48,8 +42,6 @@ class Mplayer(object):
         mplayer_command.append(filepath)
         logger.debug("Mplayer cmd: %s" % str(mplayer_command))
 
-        FNULL = open(os.devnull, 'w')
-
-        subprocess.call(mplayer_command, stdout=FNULL, stderr=FNULL)
-
+        fnull = open(os.devnull, 'w')
 
+        subprocess.call(mplayer_command, stdout=fnull, stderr=fnull)

+ 23 - 24
core/ShellGui.py

@@ -19,10 +19,9 @@ logger = logging.getLogger("kalliope")
 
 def signal_handler(signal, frame):
     """
-        Used to catch a keyboard signal like Ctrl+C in order to kill the kalliope program
-        :param signal: signal handler
-        :param frame: execution frame
-
+    Used to catch a keyboard signal like Ctrl+C in order to kill the kalliope program
+    :param signal: signal handler
+    :param frame: execution frame
     """
     print "\n"
     Utils.print_info("Ctrl+C pressed. Killing Kalliope")
@@ -34,11 +33,11 @@ signal.signal(signal.SIGINT, signal_handler)
 class ShellGui:
     def __init__(self, brain=None):
         """
-            Load a GUI in a shell console for testing TTS, STT and brain configuration
-            :param brain: The Brain object provided by the brain.yml
-            :type brain: Brain
+        Load a GUI in a shell console for testing TTS, STT and brain configuration
+        :param brain: The Brain object provided by the brain.yml
+        :type brain: Brain
 
-            .. seealso:: Brain
+        .. seealso:: Brain
         """
         # override brain
         self.brain = brain
@@ -55,8 +54,8 @@ class ShellGui:
 
     def show_main_menu(self):
         """
-            Main menu of the shell UI.
-            Provide a list of action the user can select to test his settings
+        Main menu of the shell UI.
+        Provide a list of action the user can select to test his settings
         """
 
         code, tag = self.d.menu("Test your Kalliope settings from this menu",
@@ -74,8 +73,8 @@ class ShellGui:
 
     def show_stt_test_menu(self):
         """
-            Show the list of available STT.
-            Clicking on a STT will load the engine to catch the user audio and return a text
+        Show the list of available STT.
+        Clicking on a STT will load the engine to catch the user audio and return a text
         """
         # we get STT from settings
         stt_list = self.settings.stts
@@ -98,11 +97,11 @@ class ShellGui:
 
     def show_tts_test_menu(self, sentence_to_test=None):
         """
-            A menu for testing text to speech
-            - select a TTS engine to test
-            - type a sentence
-            - press ok and listen the generated audio from the typed text
-            :param sentence_to_test: the screen written sentence to test
+        A menu for testing text to speech
+        - select a TTS engine to test
+        - type a sentence
+        - press ok and listen the generated audio from the typed text
+        :param sentence_to_test: the screen written sentence to test
         """
         continue_bool = True
         # if we don't have yet a sentence to test, we ask the user to type one
@@ -137,9 +136,9 @@ class ShellGui:
     @staticmethod
     def _run_tts_test(tts_name, sentence_to_test):
         """
-            Call the TTS
-            :param tts_name: Name of the TTS module to launch
-            :param sentence_to_test: String text to send to the TTS engine
+        Call the TTS
+        :param tts_name: Name of the TTS module to launch
+        :param sentence_to_test: String text to send to the TTS engine
         """
         sentence_to_test = sentence_to_test.encode('utf-8')
         tts_name = tts_name.encode('utf-8')
@@ -164,9 +163,9 @@ class ShellGui:
 
     def callback_stt(self, audio):
         """
-            Callback function called after the STT has finish his job
-            Print the text of what the STT engine think we said on the screen
-            :param audio: Text from the translated audio
+        Callback function called after the STT has finish his job
+        Print the text of what the STT engine think we said on the screen
+        :param audio: Text from the translated audio
         """
         code = self.d.msgbox("The STT engine think you said:\n %s" % audio, width=50)
 
@@ -175,7 +174,7 @@ class ShellGui:
 
     def show_synapses_test_menu(self):
         """
-            Show a list of available synapse in the brain to run it directly
+        Show a list of available synapse in the brain to run it directly
         """
 
         # create a tuple for the list menu

+ 8 - 9
core/SynapseLauncher.py

@@ -1,12 +1,11 @@
-from core.ConfigurationManager.BrainLoader import BrainLoader
 from core.NeuroneLauncher import NeuroneLauncher
 
 
 class SynapseNameNotFound(Exception):
     """
-        The Synapse has not been found
+    The Synapse has not been found
 
-        .. seealso: Synapse
+    .. seealso: Synapse
     """
     pass
 
@@ -19,9 +18,9 @@ class SynapseLauncher(object):
     @classmethod
     def start_synapse(cls, name, brain=None):
         """
-            Start a synapse by it's name
-            :param name: Name (Unique ID) of the synapse to launch
-            :param brain: Brain instance
+        Start a synapse by it's name
+        :param name: Name (Unique ID) of the synapse to launch
+        :param brain: Brain instance
         """
         synapse_name_launch = name
         # get the brain
@@ -42,9 +41,9 @@ class SynapseLauncher(object):
     @classmethod
     def _run_synapse(cls, synapse):
         """
-            Start all neurons in the synapse
-            :param synapse: Synapse for which we run neurons
-            :return:
+        Start all neurons in the synapse
+        :param synapse: Synapse for which we run neurons
+        :return:
         """
         for neuron in synapse.neurons:
             NeuroneLauncher.start_neurone(neuron)

+ 6 - 6
core/TTS/TTSLauncher.py

@@ -13,13 +13,13 @@ class TTSLauncher(object):
     @classmethod
     def get_tts(cls, tts):
         """
-            Return an instance of a TTS module from the name of this module
-            :param tts: TTS model
-            :type tts: Tts
-            :return: TTS module instance
+        Return an instance of a TTS module from the name of this module
+        :param tts: TTS model
+        :type tts: Tts
+        :return: TTS module instance
 
-            .. seealso::  TTS
-            .. warnings:: Class Method and Public
+        .. seealso::  TTS
+        .. warnings:: Class Method and Public
         """
         logger.debug("get TTS module \"%s\" with parameters %s" % (tts.name, tts.parameters))
         return Utils.get_dynamic_class_instantiation("tts", tts.name.capitalize(), tts.parameters)

+ 24 - 24
core/TTS/TTSModule.py

@@ -13,32 +13,32 @@ logger = logging.getLogger("kalliope")
 
 class MissingTTSParameter(Exception):
     """
-        Some TTS Parameters are missing in the settings.yml file.
+    Some TTS Parameters are missing in the settings.yml file.
 
-        .. seealose:: Settings
+    .. seealose:: Settings
     """
     pass
 
 
 class TtsGenerateAudioFunctionNotFound(Exception):
     """
-        You must provide a callBack to the TTS
+    You must provide a callBack to the TTS
     """
     pass
 
 
 class FailToLoadSoundFile(Exception):
     """
-        Fail while truing to load the sound file.
+    Fail while truing to load the sound file.
     """
     pass
 
 
 class TTSModule(object):
     """
-        Mother class of TTS module. Handle:
-        - Cache: call cache object to create file, delete file, check if file exist
-        - Player: call the default player to play the generated file
+    Mother class of TTS module. Handle:
+    - Cache: call cache object to create file, delete file, check if file exist
+    - Player: call the default player to play the generated file
     """
 
     def __init__(self, **kwargs):
@@ -65,19 +65,19 @@ class TTSModule(object):
 
     def play_audio(self):
         """
-            Play the audio file
+        Play the audio file
         """
         Mplayer.play(self.file_path)
 
     def generate_and_play(self, words, generate_audio_function_from_child=None):
         """
-            Generate an audio file from <words> if not already in cache and call the Player to play it
-            :param words: Sentence text from which we want to generate an audio file
-            :type words: String
-            :param generate_audio_function_from_child: The child function to generate a file if necessary
-            :type generate_audio_function_from_child; Callback function
+        Generate an audio file from <words> if not already in cache and call the Player to play it
+        :param words: Sentence text from which we want to generate an audio file
+        :type words: String
+        :param generate_audio_function_from_child: The child function to generate a file if necessary
+        :type generate_audio_function_from_child; Callback function
 
-            .. raises:: TtsGenerateAudioFunctionNotFound
+        .. raises:: TtsGenerateAudioFunctionNotFound
         """
         if generate_audio_function_from_child is None:
             raise TtsGenerateAudioFunctionNotFound
@@ -103,15 +103,15 @@ class TTSModule(object):
 
     def _get_path_to_store_audio(self):
         """
-            Get a sentence (a text) an return the full path of the file
+        Get a sentence (a text) an return the full path of the file
 
-            Path syntax:
-            </path/in/settings>/<tts.name>/tts.parameter["language"]/tts.parameter["voice"]/<md5_of_sentence.tts
+        Path syntax:
+        </path/in/settings>/<tts.name>/tts.parameter["language"]/tts.parameter["voice"]/<md5_of_sentence.tts
 
-            E.g:
-            /tmp/kalliope/voxygene/fr/abcd12345.tts
+        E.g:
+        /tmp/kalliope/voxygene/fr/abcd12345.tts
 
-            :return: path String
+        :return: path String
         """
         md5 = self.generate_md5_from_words(self.words)+".tts"
         self.base_cache_path = os.path.join(self.settings.cache_path, self.tts_caller_name, self.language, self.voice)
@@ -123,9 +123,9 @@ class TTSModule(object):
     @staticmethod
     def generate_md5_from_words(words):
         """
-            Generate a md5 hash from received text
-            :param words: Text to convert into md5 hash
-            :return: String md5 hash from the received words
+        Generate a md5 hash from received text
+        :param words: Text to convert into md5 hash
+        :return: String md5 hash from the received words
         """
         if isinstance(words, unicode):
             words = words.encode('utf-8')
@@ -133,7 +133,7 @@ class TTSModule(object):
 
     def is_file_already_in_cache(self):
         """
-            Return true if the file to generate has already been generated before
+        Return true if the file to generate has already been generated before
         """
         # generate sub folder
         FileManager.create_directory(self.base_cache_path)

+ 7 - 8
core/TriggerLauncher.py

@@ -13,16 +13,15 @@ class TriggerLauncher(object):
     @classmethod
     def get_trigger(cls, trigger, callback):
         """
-            Start a trigger module
-            :param trigger: trigger object to instantiate
-            :type trigger: Trigger
-            :param callback: Callback function to call when the trigger
-            catch the magic word
-            :return:
+        Start a trigger module
+        :param trigger: trigger object to instantiate
+        :type trigger: Trigger
+        :param callback: Callback function to call when the trigger
+        catch the magic word
+        :return:
         """
         # add the callback method to parameters
         trigger.parameters["callback"] = callback
         logger.debug("TriggerLauncher: Start trigger %s with parameters: %s" % (trigger.name, trigger.parameters))
         return Utils.get_dynamic_class_instantiation("trigger", trigger.name.capitalize(),
-                                                                 trigger.parameters)
-
+                                                     trigger.parameters)

+ 9 - 3
core/Utils.py

@@ -6,9 +6,9 @@ logger = logging.getLogger("kalliope")
 
 class ModuleNotFoundError(Exception):
     """
-       The module can not been found
+    The module can not been found
 
-       .. notes: Check the case: must be in lower case.
+    .. notes: Check the case: must be in lower case.
     """
     pass
 
@@ -60,7 +60,13 @@ class Utils(object):
 
     @classmethod
     def get_dynamic_class_instantiation(cls, package_name, module_name, parameters=None):
-
+        """
+        Load a python class dynamically
+        :param package_name: name of the package where we will find the module to load (neurons, tts, stt, trigger)
+        :param module_name: name of the module from the package_name to load
+        :param parameters:  dict parameters to send as argument to the module
+        :return:
+        """
         logger.debug("Run plugin %s with parameter %s" % (module_name, parameters))
         mod = __import__(package_name, fromlist=[module_name])
         try: