Przeglądaj źródła

[Doc] Docstrings of core package

monf 8 lat temu
rodzic
commit
63577433e8

+ 8 - 8
core/CrontabManager.py

@@ -26,9 +26,9 @@ class CrontabManager:
 
     def load_events_in_crontab(self):
         """
-        Remove all line in crontab with the CRONTAB_COMMENT
-        Then add back line from event in the brain.yml
-        :return:
+            Remove all line in crontab with the CRONTAB_COMMENT
+            Then add back line from event in the brain.yml
+
         """
         # clean the current crontab from all Kalliope event
         self._remove_all_job()
@@ -58,8 +58,8 @@ class CrontabManager:
 
     def _remove_all_job(self):
         """
-        Remove all line in crontab that are attached to Kalliope
-        :return:
+            Remove all line in crontab that are attached to Kalliope
+
         """
         iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
         for job in iter:
@@ -77,9 +77,9 @@ class CrontabManager:
 
     def _get_base_command(self):
         """
-        Return the path of the entry point of Kalliope
-        Example: /home/user/kalliope/kalliope.py
-        :return: The path of the entry point script kalliope.py
+            Return the path of the entry point of Kalliope
+            Example: /home/user/kalliope/kalliope.py
+            :return: The path of the entry point script kalliope.py
         """
         import inspect
         import os

+ 35 - 5
core/FileManager.py

@@ -8,16 +8,33 @@ logger = logging.getLogger("kalliope")
 
 
 class FileManager:
+
+    """
+
+     Usefull Class to manage Files
+    """
     def __init__(self):
         pass
 
     @staticmethod
     def create_directory(cache_path):
+        """
+            Create a directory at the provided `cache_path`
+            :param cache_path: the path of the directory to create
+            :type cache_path: String
+        """
         if not os.path.exists(cache_path):
             os.makedirs(cache_path)
 
     @staticmethod
     def write_in_file(file_path, content):
+        """
+            Write contents into a file
+            :param file_path: the path of the file to write on
+            :param content: the contents to write in the file
+
+            .. raises:: IOError
+        """
         try:
             with open(file_path, "wb") as file_open:
                 file_open.write(content)
@@ -32,10 +49,21 @@ class FileManager:
 
     @staticmethod
     def file_is_empty(file_path):
+        """
+            Check if the file is empty
+            :param file_path: the path of the file
+            :return: True if the file is empty, False otherwise
+        """
         return os.path.getsize(file_path) == 0
 
     @staticmethod
     def remove_file(file_path):
+        """
+
+            Remove the file locate at the provided `file_path`
+            :param file_path:
+            :return: True if the file has been removed succefully, False otherwise
+        """
         if os.path.exists(file_path):
             return os.remove(file_path)
 
@@ -43,8 +71,8 @@ class FileManager:
     @staticmethod
     def is_path_creatable(pathname):
         """
-        `True` if the current user has sufficient permissions to create the passed
-        pathname; `False` otherwise.
+            `True` if the current user has sufficient permissions to create the passed
+            pathname; `False` otherwise.
         """
         dirname = os.path.dirname(pathname) or os.getcwd()
         return os.access(dirname, os.W_OK)
@@ -52,10 +80,12 @@ class FileManager:
     @staticmethod
     def is_path_exists_or_creatable(pathname):
         """
-        `True` if the passed pathname is a valid pathname for the current OS _and_
-        either currently exists or is hypothetically creatable; `False` otherwise.
+            `True` if the passed pathname is a valid pathname for the current OS _and_
+            either currently exists or is hypothetically creatable; `False` otherwise.
+
+            This function is guaranteed to _never_ raise exceptions.
 
-        This function is guaranteed to _never_ raise exceptions.
+            .. raises:: OSError
         """
         try:
             return os.path.exists(pathname) or FileManager.is_path_creatable(pathname)

+ 17 - 12
core/MainController.py

@@ -18,6 +18,12 @@ logger = logging.getLogger("kalliope")
 
 
 class MainController:
+
+    """
+
+        This Class is the global controller of the application.
+
+    """
     def __init__(self, brain=None):
         self.brain = brain
         # get global configuration
@@ -39,9 +45,8 @@ class MainController:
 
     def callback(self):
         """
-        # we have detected the hotword, we can now pause the kalliope Trigger for a while
-        # The user can speak out loud his order during this time.
-        :return:
+            we have detected the hotword, we can now pause the Trigger for a while
+            The user can speak out loud his order during this time.
         """
         # pause the snowboy process
         self.trigger_instance.pause()
@@ -56,8 +61,8 @@ class MainController:
 
     def analyse_order(self, order):
         """
-        Receive an order, try to retreive it in the brain.yml to launch to attached plugins
-        :return:
+            Receive an order, try to retreive it in the brain.yml to launch to attached plugins
+            :param order: the sentence received
         """
         order_analyser = OrderAnalyser(order, main_controller=self, brain=self.brain)
         order_analyser.start()
@@ -71,8 +76,8 @@ class MainController:
 
     def _get_default_trigger(self):
         """
-        Return an instance of the default trigger
-        :return:
+            Return an instance of the default trigger
+            :return: Trigger
         """
         for trigger in self.settings.triggers:
             if trigger.name == self.settings.default_trigger_name:
@@ -81,11 +86,11 @@ class MainController:
     @staticmethod
     def _get_random_sound(random_wake_up_sounds):
         """
-        Return a path of a sound to play
-        If the path is absolute, test if file exist
-        If the path is relative, we check if the file exist in the sound folder
-        :param random_wake_up_sounds:
-        :return:
+            Return a path of a sound to play
+            If the path is absolute, test if file exist
+            If the path is relative, we check if the file exist in the sound folder
+            :param random_wake_up_sounds: List of wake_up sounds
+            :return: path of a sound to play
         """
         # take first randomly a path
         random_path = random.choice(random_wake_up_sounds)

+ 24 - 16
core/NeuronModule.py

@@ -44,11 +44,17 @@ class TTSNotInstantiable(Exception):
 
 
 class NeuronModule(object):
+
+    """
+
+        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__
@@ -76,13 +82,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
-        :return:
+            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
         """
         logger.debug("NeuronModule Say() called with message: %s" % message)
 
@@ -121,9 +128,11 @@ class NeuronModule(object):
 
     def _get_message_from_dict(self, message_dict):
         """
-        Generate a message taht can be played by a TTS engine from a dict of variable and the jinja template
-        :param message_dict:
-        :return:
+            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
         """
         returned_message = None
 
@@ -175,9 +184,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:
-        :return:
+            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 - 4
core/NeuroneLauncher.py

@@ -18,10 +18,10 @@ class NeuroneLauncher:
     @classmethod
     def start_neurone(cls, neuron):
         """
-        Start a neuron plugin
-        :param neuron: neuron object
-        :type neuron: Neurone
-        :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)

+ 29 - 19
core/OrderAnalyser.py

@@ -13,12 +13,17 @@ logger = logging.getLogger("kalliope")
 
 
 class OrderAnalyser:
+
+    """
+
+        This Class is used to compate 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
@@ -28,6 +33,11 @@ class OrderAnalyser:
         logger.debug("OrderAnalyser, Received order: %s" % self.order)
 
     def start(self):
+        # TODO : refactor this method !!
+        """
+            This method matchs the incoming messages to the signals/order sentences provided in the Brain
+
+        """
         synapses_found = False
         problem_in_neuron_found = False
         # create a dict of synapses that have benn launched
@@ -85,9 +95,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
@@ -140,10 +150,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)
@@ -154,10 +164,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 }}
@@ -171,10 +181,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():

+ 23 - 7
core/OrderListener.py

@@ -12,15 +12,26 @@ logger = logging.getLogger("kalliope")
 
 
 class OrderListener(Thread):
+    """
+
+        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.
+    """
 
     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
-        :param stt: Speech to text plugin name to load. If not provided,
-        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 intance
+            we will load the default one set in settings
+
+            .. 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
@@ -32,6 +43,9 @@ class OrderListener(Thread):
         self.settings = SettingLoader.get_settings()
 
     def run(self):
+        """
+           Start thread
+        """
         self.load_stt_plugin()
 
     def load_stt_plugin(self):
@@ -47,7 +61,9 @@ 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("""
         /* from stdio.h */

+ 29 - 29
core/ShellGui.py

@@ -19,10 +19,10 @@ 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
-    :return:
+        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,8 +34,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:
+            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
         """
         # override brain
         self.brain = brain
@@ -52,9 +55,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
-        :return:
+            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",
@@ -72,9 +74,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
-        :return:
+            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
@@ -97,11 +98,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
-        :return:
+            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
@@ -136,10 +137,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
-        :return:
+            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')
@@ -149,9 +149,10 @@ class ShellGui:
     @staticmethod
     def _get_choices_tuple_from_list(list_to_convert):
         """
-        Return a list of tup that can be used in Dialog menu
-        :param list_to_convert: List of object to convert into tuple
-        :return:
+            Return a list of tup that can be used in Dialog menu
+            :param list_to_convert: List of object to convert into tuple
+            :return: List of choices
+            :rtype: List
         """
         # create a list of tuple that can be used by the dialog menu
         choices = list()
@@ -163,9 +164,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)
 
@@ -174,8 +175,7 @@ class ShellGui:
 
     def show_synapses_test_menu(self):
         """
-        Show a list of available synapse in the brain to run it directly
-        :return:
+            Show a list of available synapse in the brain to run it directly
         """
 
         # create a tuple for the list menu

+ 6 - 6
core/SynapseLauncher.py

@@ -14,9 +14,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
@@ -37,9 +37,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/TriggerLauncher.py

@@ -13,12 +13,12 @@ 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

+ 6 - 8
kalliope.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
-    :return:
+        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,7 +33,7 @@ ACTION_LIST = ["start", "gui"]
 
 def main():
     """
-    Entry point of Kalliope program
+        Entry point of Kalliope program
     """
     # create arguments
     parser = argparse.ArgumentParser(description='Kalliope')
@@ -93,9 +92,8 @@ def main():
 
 def configure_logging(debug=None):
     """
-    Prepare log folder in current home directory
-    :param debug: If true, set the lof level to debug
-    :return:
+        Prepare log folder in current home directory
+        :param debug: If true, set the lof level to debug
     """
     logger = logging.getLogger("kalliope")
     logger.propagate = False