Sfoglia il codice sorgente

[Review] #242 code and tests review

monf 8 anni fa
parent
commit
5694722ccd

+ 0 - 1
Tests/__init__.py

@@ -2,7 +2,6 @@ from test_brain_loader import TestBrainLoader
 from test_configuration_checker import TestConfigurationChecker
 from test_configuration_checker import TestConfigurationChecker
 from test_dynamic_loading import TestDynamicLoading
 from test_dynamic_loading import TestDynamicLoading
 from test_file_manager import TestFileManager
 from test_file_manager import TestFileManager
-# from test_order_analyser import TestOrderAnalyser
 from test_rest_api import TestRestAPI
 from test_rest_api import TestRestAPI
 from test_settings_loader import TestSettingLoader
 from test_settings_loader import TestSettingLoader
 from test_singleton import TestSingleton
 from test_singleton import TestSingleton

+ 1 - 1
Tests/test_neuron_module.py

@@ -151,7 +151,7 @@ class TestNeuronModule(unittest.TestCase):
             neuron_mod = NeuronModule()
             neuron_mod = NeuronModule()
             neuron_mod.brain = br
             neuron_mod.brain = br
 
 
-            # Success, run synapse 1
+            # Success, run synapse 2
             launched_synapse = neuron_mod.run_synapse_by_name_with_order(order=order,
             launched_synapse = neuron_mod.run_synapse_by_name_with_order(order=order,
                                                                          synapse_name=synapse_name,
                                                                          synapse_name=synapse_name,
                                                                          order_template=answer)
                                                                          order_template=answer)

+ 16 - 16
Tests/test_order_analyser2.py → Tests/test_order_analyser.py

@@ -5,10 +5,10 @@ from kalliope.core.Models import Brain
 from kalliope.core.Models import Neuron
 from kalliope.core.Models import Neuron
 from kalliope.core.Models import Order
 from kalliope.core.Models import Order
 from kalliope.core.Models import Synapse
 from kalliope.core.Models import Synapse
-from kalliope.core.OrderAnalyser2 import OrderAnalyser2
+from kalliope.core.OrderAnalyser import OrderAnalyser
 
 
 
 
-class TestOrderAnalyser2(unittest.TestCase):
+class TestOrderAnalyser(unittest.TestCase):
 
 
     """Test case for the OrderAnalyser Class"""
     """Test case for the OrderAnalyser Class"""
 
 
@@ -38,19 +38,19 @@ class TestOrderAnalyser2(unittest.TestCase):
 
 
         # TEST1: should return synapse1
         # TEST1: should return synapse1
         spoken_order = "this is the sentence"
         spoken_order = "this is the sentence"
-        matched_synapses = OrderAnalyser2.get_matching_synapse(order=spoken_order, brain=br)
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
         self.assertEqual(len(matched_synapses), 1)
         self.assertEqual(len(matched_synapses), 1)
         self.assertTrue(any(synapse1 in matched_synapse for matched_synapse in matched_synapses))
         self.assertTrue(any(synapse1 in matched_synapse for matched_synapse in matched_synapses))
 
 
         # TEST2: should return synapse1 and 2
         # TEST2: should return synapse1 and 2
         spoken_order = "this is the second sentence"
         spoken_order = "this is the second sentence"
-        matched_synapses = OrderAnalyser2.get_matching_synapse(order=spoken_order, brain=br)
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
         self.assertEqual(len(matched_synapses), 2)
         self.assertEqual(len(matched_synapses), 2)
         self.assertTrue(synapse1, synapse2 in matched_synapses)
         self.assertTrue(synapse1, synapse2 in matched_synapses)
 
 
         # TEST3: should empty
         # TEST3: should empty
         spoken_order = "not a valid order"
         spoken_order = "not a valid order"
-        matched_synapses = OrderAnalyser2.get_matching_synapse(order=spoken_order, brain=br)
+        matched_synapses = OrderAnalyser.get_matching_synapse(order=spoken_order, brain=br)
         self.assertFalse(matched_synapses)
         self.assertFalse(matched_synapses)
 
 
     def test_spelt_order_match_brain_order_via_table(self):
     def test_spelt_order_match_brain_order_via_table(self):
@@ -58,41 +58,41 @@ class TestOrderAnalyser2(unittest.TestCase):
         sentence_to_test = "this is the order"
         sentence_to_test = "this is the order"
 
 
         # Success
         # Success
-        self.assertTrue(OrderAnalyser2.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
 
         # Failure
         # Failure
         sentence_to_test = "unexpected sentence"
         sentence_to_test = "unexpected sentence"
-        self.assertFalse(OrderAnalyser2.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
+        self.assertFalse(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
 
         # Upper/lower cases
         # Upper/lower cases
         sentence_to_test = "THIS is THE order"
         sentence_to_test = "THIS is THE order"
-        self.assertTrue(OrderAnalyser2.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
+        self.assertTrue(OrderAnalyser.spelt_order_match_brain_order_via_table(order_to_test, sentence_to_test))
 
 
     def test_get_split_order_without_bracket(self):
     def test_get_split_order_without_bracket(self):
         # Success
         # Success
         order_to_test = "this is the order"
         order_to_test = "this is the order"
         expected_result = ["this", "is", "the", "order"]
         expected_result = ["this", "is", "the", "order"]
-        self.assertEqual(OrderAnalyser2._get_split_order_without_bracket(order_to_test), expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "No brackets Fails to return the expected list")
                          "No brackets Fails to return the expected list")
 
 
         order_to_test = "this is the {{ order }}"
         order_to_test = "this is the {{ order }}"
         expected_result = ["this", "is", "the"]
         expected_result = ["this", "is", "the"]
-        self.assertEqual(OrderAnalyser2._get_split_order_without_bracket(order_to_test), expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "With spaced brackets Fails to return the expected list")
                          "With spaced brackets Fails to return the expected list")
 
 
         order_to_test = "this is the {{order }}"    # left bracket without space
         order_to_test = "this is the {{order }}"    # left bracket without space
         expected_result = ["this", "is", "the"]
         expected_result = ["this", "is", "the"]
-        self.assertEqual(OrderAnalyser2._get_split_order_without_bracket(order_to_test), expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "Left brackets Fails to return the expected list")
                          "Left brackets Fails to return the expected list")
 
 
         order_to_test = "this is the {{ order}}"    # right bracket without space
         order_to_test = "this is the {{ order}}"    # right bracket without space
         expected_result = ["this", "is", "the"]
         expected_result = ["this", "is", "the"]
-        self.assertEqual(OrderAnalyser2._get_split_order_without_bracket(order_to_test), expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "Right brackets Fails to return the expected list")
                          "Right brackets Fails to return the expected list")
 
 
         order_to_test = "this is the {{order}}"  # bracket without space
         order_to_test = "this is the {{order}}"  # bracket without space
         expected_result = ["this", "is", "the"]
         expected_result = ["this", "is", "the"]
-        self.assertEqual(OrderAnalyser2._get_split_order_without_bracket(order_to_test), expected_result,
+        self.assertEqual(OrderAnalyser._get_split_order_without_bracket(order_to_test), expected_result,
                          "No space brackets Fails to return the expected list")
                          "No space brackets Fails to return the expected list")
 
 
     def test_counter_subset(self):
     def test_counter_subset(self):
@@ -100,9 +100,9 @@ class TestOrderAnalyser2(unittest.TestCase):
         list2 = ("word3", "word4")
         list2 = ("word3", "word4")
         list3 = ("word1", "word2", "word3", "word4")
         list3 = ("word1", "word2", "word3", "word4")
 
 
-        self.assertFalse(OrderAnalyser2._counter_subset(list1, list2))
-        self.assertTrue(OrderAnalyser2._counter_subset(list1, list3))
-        self.assertTrue(OrderAnalyser2._counter_subset(list2, list3))
+        self.assertFalse(OrderAnalyser._counter_subset(list1, list2))
+        self.assertTrue(OrderAnalyser._counter_subset(list1, list3))
+        self.assertTrue(OrderAnalyser._counter_subset(list2, list3))
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':

+ 4 - 4
Tests/test_rest_api.py

@@ -2,8 +2,6 @@ import json
 import os
 import os
 import unittest
 import unittest
 
 
-from werkzeug.datastructures import FileStorage
-
 from flask import Flask
 from flask import Flask
 from flask_testing import LiveServerTestCase
 from flask_testing import LiveServerTestCase
 
 
@@ -36,6 +34,7 @@ class TestRestAPI(LiveServerTestCase):
         sl.settings.active = True
         sl.settings.active = True
         sl.settings.port = 5000
         sl.settings.port = 5000
         sl.settings.allowed_cors_origin = "*"
         sl.settings.allowed_cors_origin = "*"
+        sl.settings.default_synapse = None
 
 
         # prepare a test brain
         # prepare a test brain
         brain_to_test = full_path_brain_to_test
         brain_to_test = full_path_brain_to_test
@@ -237,7 +236,6 @@ class TestRestAPI(LiveServerTestCase):
                 }
                 }
             ]
             ]
         }
         }
-        print result.get_data()
         self.assertEqual(json.dumps(expected_content), json.dumps(json.loads(result.get_data())))
         self.assertEqual(json.dumps(expected_content), json.dumps(json.loads(result.get_data())))
         self.assertEqual(result.status_code, 201)
         self.assertEqual(result.status_code, 201)
 
 
@@ -245,7 +243,9 @@ class TestRestAPI(LiveServerTestCase):
         url = self.get_server_url() + "/synapses/start/order"
         url = self.get_server_url() + "/synapses/start/order"
         data = {"order": "non existing order"}
         data = {"order": "non existing order"}
         headers = {"Content-Type": "application/json"}
         headers = {"Content-Type": "application/json"}
-        result = self.client.post(url, headers=headers, data=json.dumps(data))
+        result = self.client.post(url,
+                                  headers=headers,
+                                  data=json.dumps(data))
 
 
         expected_content = {'error': {'error': "The given order doesn't match any synapses"}}
         expected_content = {'error': {'error': "The given order doesn't match any synapses"}}
 
 

+ 4 - 3
Tests/test_synapse_launcher.py

@@ -38,8 +38,9 @@ class TestSynapseLauncher(unittest.TestCase):
         self.brain_test = Brain(synapses=all_synapse_list)
         self.brain_test = Brain(synapses=all_synapse_list)
         self.settings_test = Settings(default_synapse="Synapse3")
         self.settings_test = Settings(default_synapse="Synapse3")
 
 
-    def test_match_synapse1(self):
+    def test_run_matching_synapse_or_default(self):
 
 
+        # test_match_synapse1
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
             order_to_match = "this is the sentence"
             order_to_match = "this is the sentence"
             expected_result = [self.synapse1]
             expected_result = [self.synapse1]
@@ -49,7 +50,7 @@ class TestSynapseLauncher(unittest.TestCase):
                                                                              brain=self.brain_test,
                                                                              brain=self.brain_test,
                                                                              settings=self.settings_test))
                                                                              settings=self.settings_test))
 
 
-    def test_match_synapse1_and_2(self):
+        # test_match_synapse1_and_2
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron_list"):
             order_to_match = "this is the second sentence"
             order_to_match = "this is the second sentence"
             expected_result = [self.synapse1, self.synapse2]
             expected_result = [self.synapse1, self.synapse2]
@@ -59,7 +60,7 @@ class TestSynapseLauncher(unittest.TestCase):
                                                                              brain=self.brain_test,
                                                                              brain=self.brain_test,
                                                                              settings=self.settings_test))
                                                                              settings=self.settings_test))
 
 
-    def test_match_default_synapse(self):
+        # test_match_default_synapse
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron"):
         with mock.patch("kalliope.core.NeuronLauncher.start_neuron"):
             order_to_match = "this is an invalid order"
             order_to_match = "this is an invalid order"
             expected_result = [self.synapse3]
             expected_result = [self.synapse3]

+ 5 - 5
Tests/test_utils.py

@@ -53,7 +53,7 @@ class TestUtils(unittest.TestCase):
         # Test the absolute path
         # Test the absolute path
         dir_path = "/tmp/kalliope/tests/"
         dir_path = "/tmp/kalliope/tests/"
         file_name = "test_real_file_path"
         file_name = "test_real_file_path"
-        absolute_path_to_test = os.path.join(dir_path,file_name)
+        absolute_path_to_test = os.path.join(dir_path, file_name)
         expected_result = absolute_path_to_test
         expected_result = absolute_path_to_test
         if not os.path.exists(dir_path):
         if not os.path.exists(dir_path):
             os.makedirs(dir_path)
             os.makedirs(dir_path)
@@ -108,7 +108,7 @@ class TestUtils(unittest.TestCase):
         dir_path = "../kalliope/"
         dir_path = "../kalliope/"
         file_name = "test_real_file_path"
         file_name = "test_real_file_path"
         path_to_test = os.path.join(dir_path, file_name)
         path_to_test = os.path.join(dir_path, file_name)
-        expected_result = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep +"kalliope" + os.sep + file_name)
+        expected_result = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep + "kalliope" + os.sep + file_name)
         if not os.path.exists(dir_path):
         if not os.path.exists(dir_path):
             os.makedirs(dir_path)
             os.makedirs(dir_path)
 
 
@@ -119,8 +119,8 @@ class TestUtils(unittest.TestCase):
                           expected_result,
                           expected_result,
                           "Fail to match the /an/unknown/path/kalliope path")
                           "Fail to match the /an/unknown/path/kalliope path")
         # Clean up
         # Clean up
-        if os.path.exists(file_name):
-            os.remove(file_name)
+        if os.path.exists(expected_result):
+            os.remove(expected_result)
 
 
     def test_get_dynamic_class_instantiation(self):
     def test_get_dynamic_class_instantiation(self):
         """
         """
@@ -222,4 +222,4 @@ class TestUtils(unittest.TestCase):
         expected_result = "This is the {{bracket}} {{second}}"
         expected_result = "This is the {{bracket}} {{second}}"
         self.assertEqual(Utils.remove_spaces_in_brackets(sentence=sentence),
         self.assertEqual(Utils.remove_spaces_in_brackets(sentence=sentence),
                          expected_result,
                          expected_result,
-                         "Fail to remove spaces in two brackets")
+                         "Fail to remove spaces in two brackets")

+ 11 - 3
kalliope/__init__.py

@@ -5,6 +5,7 @@ import logging
 
 
 from kalliope.core import ShellGui
 from kalliope.core import ShellGui
 from kalliope.core import Utils
 from kalliope.core import Utils
+from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.ConfigurationManager.BrainLoader import BrainLoader
 from kalliope.core.ConfigurationManager.BrainLoader import BrainLoader
 from kalliope.core.EventManager import EventManager
 from kalliope.core.EventManager import EventManager
 from kalliope.core.MainController import MainController
 from kalliope.core.MainController import MainController
@@ -110,15 +111,22 @@ def main():
     brain_loader = BrainLoader(file_path=brain_file)
     brain_loader = BrainLoader(file_path=brain_file)
     brain = brain_loader.brain
     brain = brain_loader.brain
 
 
+    # load settings
+    # get global configuration once
+    settings_loader = SettingLoader()
+    settings = settings_loader.settings
+
     if args.action == "start":
     if args.action == "start":
 
 
         # user set a synapse to start
         # user set a synapse to start
         if args.run_synapse is not None:
         if args.run_synapse is not None:
-            SynapseLauncher.start_synapse(args.run_synapse, brain=brain)
+            SynapseLauncher.start_synapse(args.run_synapse,
+                                          brain=brain)
 
 
         if args.run_order is not None:
         if args.run_order is not None:
-            order_analyser = OrderAnalyser(args.run_order, brain=brain)
-            order_analyser.start()
+            SynapseLauncher.run_matching_synapse_or_default(args.run_order,
+                                                            brain=brain,
+                                                            settings=settings)
 
 
         if (args.run_synapse is None) and (args.run_order is None):
         if (args.run_synapse is None) and (args.run_order is None):
             # first, load events in event manager
             # first, load events in event manager

+ 1 - 1
kalliope/core/MainController.py

@@ -6,7 +6,7 @@ from flask import Flask
 
 
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
-from kalliope.core.OrderAnalyser2 import OrderAnalyser2
+from kalliope.core.OrderAnalyser import OrderAnalyser
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from transitions import Machine
 from transitions import Machine
 
 

+ 2 - 2
kalliope/core/NeuronLauncher.py

@@ -36,10 +36,10 @@ class NeuronLauncher:
     def start_neuron_list(cls, neuron_list, parameters_dict=None):
     def start_neuron_list(cls, neuron_list, parameters_dict=None):
         """
         """
         Execute each neuron from the received neuron_list.
         Execute each neuron from the received neuron_list.
-        Replace parameter if existe in the received dict of parameters_dict
+        Replace parameter if exist in the received dict of parameters_dict
         :param neuron_list: list of Neuron object to run
         :param neuron_list: list of Neuron object to run
         :param parameters_dict: dict of parameter to load in each neuron if expecting a parameter
         :param parameters_dict: dict of parameter to load in each neuron if expecting a parameter
-        :return:
+        :return: List of the instantiated neurons (no errors detected)
         """
         """
 
 
         instantiated_neuron = list()
         instantiated_neuron = list()

+ 6 - 6
kalliope/core/NeuronModule.py

@@ -10,7 +10,7 @@ from kalliope.core.ConfigurationManager import SettingLoader, BrainLoader
 from kalliope.core.Models import Order
 from kalliope.core.Models import Order
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
-from kalliope.core.OrderAnalyser2 import OrderAnalyser2
+from kalliope.core.OrderAnalyser import OrderAnalyser
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope.core.Utils.Utils import Utils
 from kalliope.core.Utils.Utils import Utils
 
 
@@ -189,10 +189,10 @@ class NeuronModule(object):
     def run_synapse_by_name(self, name):
     def run_synapse_by_name(self, name):
         SynapseLauncher.start_synapse(name=name, brain=self.brain)
         SynapseLauncher.start_synapse(name=name, brain=self.brain)
 
 
-    def is_order_matching(self, order_said, order_match):
-
-        return OrderAnalyser2().spelt_order_match_brain_order_via_table(order_to_analyse=order_match,
-                                                                        user_said=order_said)
+    @staticmethod
+    def is_order_matching(order_said, order_match):
+        return OrderAnalyser().spelt_order_match_brain_order_via_table(order_to_analyse=order_match,
+                                                                       user_said=order_said)
 
 
     def run_synapse_by_name_with_order(self, order, synapse_name, order_template):
     def run_synapse_by_name_with_order(self, order, synapse_name, order_template):
         """
         """
@@ -216,8 +216,8 @@ class NeuronModule(object):
                 if isinstance(signal, Order):
                 if isinstance(signal, Order):
                     parameters = NeuronParameterLoader.get_parameters(synapse_order=order_template,
                     parameters = NeuronParameterLoader.get_parameters(synapse_order=order_template,
                                                                       user_order=order)
                                                                       user_order=order)
-                    logger.debug("[NeuronModule]-> parameter load from user answer: %s" % parameters)
                     if parameters is not None:
                     if parameters is not None:
+                        logger.debug("[NeuronModule]-> parameter load from user answer: %s" % parameters)
                         break
                         break
 
 
             # start the neuron list
             # start the neuron list

+ 34 - 252
kalliope/core/OrderAnalyser.py

@@ -1,12 +1,10 @@
 # coding: utf8
 # coding: utf8
-import re
 import collections
 import collections
 from collections import Counter
 from collections import Counter
 
 
 from kalliope.core.Utils.Utils import Utils
 from kalliope.core.Utils.Utils import Utils
 from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.Models import Order
 from kalliope.core.Models import Order
-from kalliope.core.NeuronLauncher import NeuronLauncher
 
 
 import logging
 import logging
 
 
@@ -14,228 +12,48 @@ logging.basicConfig()
 logger = logging.getLogger("kalliope")
 logger = logging.getLogger("kalliope")
 
 
 
 
-class OrderAnalyser:
+class OrderAnalyser2:
     """
     """
-    This Class is used to compare the incoming message to the Signal/Order sentences.
+    This Class is used to get a list of synapses that match a given Spoken order
     """
     """
 
 
-    def __init__(self, order, brain=None):
-        """
-        Class used to load brain and run neuron attached to the received order
-        :param order: spelt order
-        :param brain: loaded brain
-        """
-        sl = SettingLoader()
-        self.settings = sl.settings
-        self.order = order
-        if isinstance(self.order, str):
-            self.order = order.decode('utf-8')
-        self.brain = brain
-        logger.debug("OrderAnalyser, Received order: %s" % self.order)
-
-    def start(self, synapses_to_run=None, external_order=None):
-        """
-        This method matches the incoming messages to the signals/order sentences provided in the Brain.
-
-        Note: we use named tuples:
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
-        """
-
-        synapse_order_tuple = collections.namedtuple('tuple_synapse_matchingOrder', ['synapse', 'order'])
-        synapses_order_tuple_list = list()
-
-        if synapses_to_run is not None and external_order is not None:
-            for synapse in synapses_to_run:
-                synapses_order_tuple_list.append(synapse_order_tuple(synapse=synapse,
-                                                                     order=external_order))
-
-        # if list of synapse is not provided, let's find one
-        else:  # synapses_to_run is None or external_order is None:
-            # create a dict of synapses that have been launched
-            logger.debug("[orderAnalyser.start]-> No Synapse provided, let's find one")
-            synapses_order_tuple_list = self._find_synapse_to_run(brain=self.brain,
-                                                                  settings=self.settings,
-                                                                  order=self.order)
+    brain = None
+    settings = None
 
 
-        # retrieve params
-        synapses_launched = list()
-        for tuple in synapses_order_tuple_list:
-            logger.debug("[orderAnalyser.start]-> Grab the params")
-            params = self._get_params_from_order(tuple.order, self.order)
-
-            # Start a neuron list with params
-            self._start_list_neurons(list_neurons=tuple.synapse.neurons,
-                                     params=params,
-                                     settings=self.settings)
-            synapses_launched.append(tuple.synapse)
-
-        # return the list of launched synapse
-        return synapses_launched
+    @classmethod
+    def __init__(cls):
+        cls.settings = SettingLoader().settings
 
 
     @classmethod
     @classmethod
-    def _find_synapse_to_run(cls, brain, settings, order):
+    def get_matching_synapse(cls, order, brain=None):
         """
         """
-        Find the list of the synapse matching the order.
-
-        Note: we use named tuples:
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
-
-        :param brain: the brain
-        :param settings: the settings
-        :param order: the provided order to match
-        :return: the list of synapses launched (named tuples)
+        Return the list of matching synapses from the given order
+        :param order: The user order
+        :param brain: The loaded brain
+        :return: The List of synapses matching the given order
         """
         """
+        cls.brain = brain
+        logger.debug("[OrderAnalyser] Received order: %s" % order)
+        if isinstance(order, str):
+            order = order.decode('utf-8')
 
 
-        synapse_to_run = cls._get_matching_synapse_list(brain.synapses, order)
-        if not synapse_to_run:
-            Utils.print_info("No synapse match the captured order: %s" % order)
-
-            if settings.default_synapse is not None:
-                default_synapse = cls._get_default_synapse_from_sysnapses_list(brain.synapses,
-                                                                               settings.default_synapse)
-
-                if default_synapse is not None:
-                    logger.debug("Default synapse found %s" % default_synapse)
-                    Utils.print_info("Default synapse found: %s, running it" % default_synapse.name)
-                    tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder',
-                                                                         ['synapse', 'order'])
-                    synapse_to_run.append(tuple_synapse_order(synapse=default_synapse,
-                                                                      order=""))
-
-        return synapse_to_run
+        # We use a namedtuple to associate the synapse and the signal of the synapse
+        synapse_order_tuple = collections.namedtuple('tuple_synapse_matchingOrder',
+                                                     ['synapse', 'order'])
 
 
-    @classmethod
-    def _get_matching_synapse_list(cls, all_synapses_list, order_to_match):
-        """
-        Class method to return all the matching synapses with the order from the complete of synapses.
-
-        Note: we use named tuples:
-        tuple_synapse_matchingOrder = collections.namedtuple('tuple_synapse_matchingOrder',['synapse', 'order'])
+        list_match_synapse = list()
 
 
-        :param all_synapses_list: the complete list of all synapses
-        :param order_to_match: the order to match
-        :type order_to_match: str
-        :return: the list of matching synapses (named tuples)
-        """
-        tuple_synapse_order = collections.namedtuple('tuple_synapse_matchingOrder', ['synapse', 'order'])
-        matching_synapses_list = list()
-        for synapse in all_synapses_list:
+        # test each synapse from the brain
+        for synapse in cls.brain.synapses:
+            # we are only concerned by synapse with a order type of signal
             for signal in synapse.signals:
             for signal in synapse.signals:
                 if type(signal) == Order:
                 if type(signal) == Order:
-                    if cls.spelt_order_match_brain_order_via_table(signal.sentence, order_to_match):
-                        matching_synapses_list.append(tuple_synapse_order(synapse=synapse,
-                                                                                  order=signal.sentence))
-                        logger.debug("Order found! Run neurons: %s" % synapse.neurons)
+                    if cls.spelt_order_match_brain_order_via_table(signal.sentence, order):
+                        # the order match the synapse, we add it to the returned list
+                        logger.debug("Order found! Run synapse name: %s" % synapse.name)
                         Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
                         Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
-        return matching_synapses_list
-
-    @classmethod
-    def _get_params_from_order(cls, string_order, order_to_check):
-        """
-        Class method to get all params coming from a string order. Returns a dict of key/value.
-
-        :param string_order: the  string_order to check
-        :param order_to_check: the order to match
-        :type order_to_check: str
-        :return: the dict key/value
-        """
-        params = dict()
-        if Utils.is_containing_bracket(string_order):
-            params = cls._associate_order_params_to_values(order_to_check, string_order)
-            logger.debug("Parameters for order: %s" % params)
-        return params
-
-    @classmethod
-    def _start_list_neurons(cls, list_neurons, params, settings):
-        # start neurons
-        for neuron in list_neurons:
-            cls._start_neuron(neuron, params)
-
-    @staticmethod
-    def _start_neuron(neuron, params):
-        """
-        Associate params and Starts a neuron.
-
-        :param neuron: the neuron to start
-        :param params: the params to check and associate to the neuron args.
-        """
-
-        problem_in_neuron_found = False
-        if isinstance(neuron.parameters, dict):
-            # print neuron.parameters
-            if "args" in neuron.parameters:
-                logger.debug("The neuron waits for parameter")
-                # check that the user added parameters to his order
-                if params is None:
-                    # we don't raise an error and break the program but we don't run the neuron
-                    problem_in_neuron_found = True
-                    Utils.print_danger("Error: The neuron %s is waiting for argument. "
-                                       "Argument found in bracket in the given order" % neuron.name)
-                else:
-                    # we add wanted arguments the existing neuron parameter dict
-                    for arg in neuron.parameters["args"]:
-                        if arg in params:
-                            logger.debug("Parameter %s added to the current parameter "
-                                         "of the neuron: %s" % (arg, neuron.name))
-                            neuron.parameters[arg] = params[arg]
-                        else:
-                            # we don't raise an error and break the program but
-                            # we don't run the neuron
-                            problem_in_neuron_found = True
-                            Utils.print_danger("Error: Argument \"%s\" not found in the"
-                                               " order" % arg)
-
-        # if no error detected, we run the neuron
-        if not problem_in_neuron_found:
-            NeuronLauncher.start_neuron(neuron)
-        else:
-            Utils.print_danger("A problem has been found in the Synapse.")
-
-    @staticmethod
-    def _associate_order_params_to_values(order, order_to_check):
-        """
-        Associate the variables from the order to the incoming user order
-        :param order_to_check: the order to check incoming from the brain
-        :type order_to_check: str
-        :param order: the order from user
-        :type order: str
-        :return: the dict corresponding to the key / value of the params
-        """
-        logger.debug("[OrderAnalyser._associate_order_params_to_values] user order: %s, "
-                     "order to check: %s" % (order, order_to_check))
-
-        list_word_in_order = Utils.remove_spaces_in_brackets(order_to_check).split()
-
-        # get the order, defined by the first words before {{
-        # /!\ Could be empty if order starts with double brace
-        the_order = order_to_check[:order_to_check.find('{{')]
-
-        # remove sentence before order which are sentences not matching anyway
-        # Manage Upper/Lower case
-        truncate_user_sentence = order[order.lower().find(the_order.lower()):]
-        truncate_list_word_said = truncate_user_sentence.split()
-
-        # make dict var:value
-        dict_var = dict()
-        for idx, ow in enumerate(list_word_in_order):
-            if Utils.is_containing_bracket(ow):
-                # remove bracket and grab the next value / stop value
-                var_name = ow.replace("{{", "").replace("}}", "")
-                stop_value = Utils.get_next_value_list(list_word_in_order[idx:])
-                if stop_value is None:
-                    dict_var[var_name] = " ".join(truncate_list_word_said)
-                    break
-                for word_said in truncate_list_word_said:
-                    if word_said == stop_value:
-                        break
-                    if var_name in dict_var:
-                        dict_var[var_name] += " " + word_said
-                        truncate_list_word_said = truncate_list_word_said[1:]
-                    else:
-                        dict_var[var_name] = word_said
-            truncate_list_word_said = truncate_list_word_said[1:]
-        return dict_var
-
+                        list_match_synapse.append(synapse_order_tuple(synapse=synapse, order=signal.sentence))
+        return list_match_synapse
 
 
     @classmethod
     @classmethod
     def spelt_order_match_brain_order_via_table(cls, order_to_analyse, user_said):
     def spelt_order_match_brain_order_via_table(cls, order_to_analyse, user_said):
@@ -246,36 +64,20 @@ class OrderAnalyser:
         :param user_said: String to compare to the order
         :param user_said: String to compare to the order
         :return: True if all string are present in the order
         :return: True if all string are present in the order
         """
         """
-        logger.debug("[spelt_order_match_brain_order_via_table] before formatting, "
-                     "order to analyse: %s, "
-                     "user sentence: %s"
-                     % (order_to_analyse, user_said))
-        order_to_analyse, user_said = cls._format_sentences_to_analyse(order_to_analyse=order_to_analyse,
-                                                                       user_said=user_said)
-        list_word_user_said = user_said.split()
-        split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
-
-        # if all words in the list of what the user said in in the list of word in the order
-        return cls._counter_subset(split_order_without_bracket, list_word_user_said)
-
-    @staticmethod
-    def _format_sentences_to_analyse(order_to_analyse, user_said):
-        """
-        return formatted tuple of the order_to_analyse, user_said
-        :param order_to_analyse: String order to test
-        :param user_said: String to compare to the order
-        :return: tuple of the order_to_analyse, user_said
-        """
         # Lowercase all incoming
         # Lowercase all incoming
         order_to_analyse = order_to_analyse.lower()
         order_to_analyse = order_to_analyse.lower()
         user_said = user_said.lower()
         user_said = user_said.lower()
 
 
-        logger.debug("[_format_sentences_to_analyse] formatted, "
+        logger.debug("[spelt_order_match_brain_order_via_table] "
                      "order to analyse: %s, "
                      "order to analyse: %s, "
                      "user sentence: %s"
                      "user sentence: %s"
                      % (order_to_analyse, user_said))
                      % (order_to_analyse, user_said))
 
 
-        return order_to_analyse, user_said
+        list_word_user_said = user_said.split()
+        split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
+
+        # if all words in the list of what the user said in in the list of word in the order
+        return cls._counter_subset(split_order_without_bracket, list_word_user_said)
 
 
     @staticmethod
     @staticmethod
     def _get_split_order_without_bracket(order):
     def _get_split_order_without_bracket(order):
@@ -306,23 +108,3 @@ class OrderAnalyser:
             if n > c2[k]:
             if n > c2[k]:
                 return False
                 return False
         return True
         return True
-
-    @staticmethod
-    def _get_default_synapse_from_sysnapses_list(all_synapses_list, default_synapse_name):
-        """
-        Static method to get the default synapse if it exists.
-
-        :param all_synapses_list: the complete list of all synapses
-        :param default_synapse_name: the synapse to find
-        :return: the Synapse
-        """
-        default_synapse = None
-        for synapse in all_synapses_list:
-            if synapse.name == default_synapse_name:
-                logger.debug("Default synapse found: %s" % synapse.name)
-                default_synapse = synapse
-                break
-        if default_synapse is None:
-            logger.debug("Default synapse not found")
-            Utils.print_warning("Default synapse not found")
-        return default_synapse

+ 0 - 104
kalliope/core/OrderAnalyser2.py

@@ -1,104 +0,0 @@
-# coding: utf8
-import collections
-from collections import Counter
-
-from kalliope.core.Utils.Utils import Utils
-from kalliope.core.ConfigurationManager import SettingLoader
-from kalliope.core.Models import Order
-
-import logging
-
-logging.basicConfig()
-logger = logging.getLogger("kalliope")
-
-
-class OrderAnalyser2:
-    """
-    This Class is used to get a list of synapses that match a given Spoken order
-    """
-
-    brain = None
-    settings = None
-
-    @classmethod
-    def __init__(cls):
-        cls.settings = SettingLoader().settings
-
-    @classmethod
-    def get_matching_synapse(cls, order, brain=None):
-        cls.brain = brain
-        logger.debug("[OrderAnalyser] Received order: %s" % order)
-        if isinstance(order, str):
-            order = order.decode('utf-8')
-
-        # We use a namedtuple to associate the synapse and the signal of the synapse
-        synapse_order_tuple = collections.namedtuple('tuple_synapse_matchingOrder',
-                                                     ['synapse', 'order'])
-
-        list_match_synapse = list()
-
-        # test each synapse from the brain
-        for synapse in cls.brain.synapses:
-            # we are only concerned by synapse with a order type of signal
-            for signal in synapse.signals:
-                if type(signal) == Order:
-                    if cls.spelt_order_match_brain_order_via_table(signal.sentence, order):
-                        # the order match the synapse, we add it to the returned list
-                        logger.debug("Order found! Run synapse name: %s" % synapse.name)
-                        Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
-                        list_match_synapse.append(synapse_order_tuple(synapse=synapse, order=signal.sentence))
-        return list_match_synapse
-
-    @classmethod
-    def spelt_order_match_brain_order_via_table(cls, order_to_analyse, user_said):
-        """
-        return true if all formatted(_format_sentences_to_analyse(order_to_analyse, user_said)) strings
-                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
-        """
-        # Lowercase all incoming
-        order_to_analyse = order_to_analyse.lower()
-        user_said = user_said.lower()
-
-        logger.debug("[spelt_order_match_brain_order_via_table] "
-                     "order to analyse: %s, "
-                     "user sentence: %s"
-                     % (order_to_analyse, user_said))
-
-        list_word_user_said = user_said.split()
-        split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
-
-        # if all words in the list of what the user said in in the list of word in the order
-        return cls._counter_subset(split_order_without_bracket, list_word_user_said)
-
-    @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
-        """
-
-        matches = Utils.find_all_matching_brackets(order)
-        for match in matches:
-            order = order.replace(match, "")
-        # then split
-        split_order = order.split()
-        return split_order
-
-    @staticmethod
-    def _counter_subset(list1, list2):
-        """
-        check if the number of occurrences matches
-        :param list1:
-        :param list2:
-        :return:
-        """
-        c1, c2 = Counter(list1), Counter(list2)
-        for k, n in c1.items():
-            if n > c2[k]:
-                return False
-        return True

+ 5 - 7
kalliope/core/RestAPI/FlaskAPI.py

@@ -4,9 +4,6 @@ import threading
 
 
 import time
 import time
 
 
-from kalliope.core.NeuronLauncher import NeuronLauncher
-from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
-from kalliope.core.OrderAnalyser2 import OrderAnalyser2
 from kalliope.core.Utils.FileManager import FileManager
 from kalliope.core.Utils.FileManager import FileManager
 
 
 from kalliope.core.ConfigurationManager import SettingLoader
 from kalliope.core.ConfigurationManager import SettingLoader
@@ -16,9 +13,8 @@ from werkzeug.utils import secure_filename
 from flask import jsonify
 from flask import jsonify
 from flask import request
 from flask import request
 from flask_restful import abort
 from flask_restful import abort
-from flask_cors import CORS, cross_origin
+from flask_cors import CORS
 
 
-from kalliope.core import OrderAnalyser
 from kalliope.core.RestAPI.utils import requires_auth
 from kalliope.core.RestAPI.utils import requires_auth
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope.core.SynapseLauncher import SynapseLauncher
 from kalliope._version import version_str
 from kalliope._version import version_str
@@ -172,8 +168,10 @@ class FlaskAPI(threading.Thread):
         if order is not None:
         if order is not None:
             # get the order
             # get the order
             order_to_run = order["order"]
             order_to_run = order["order"]
-            oa = OrderAnalyser(order=order_to_run, brain=self.brain)
-            launched_synapses = oa.start()
+
+            launched_synapses = SynapseLauncher.run_matching_synapse_or_default(order_to_run,
+                                                                                self.brain,
+                                                                                self.settings)
 
 
             if launched_synapses:
             if launched_synapses:
                 # if the list is not empty, we have launched one or more synapses
                 # if the list is not empty, we have launched one or more synapses

+ 11 - 9
kalliope/core/SynapseLauncher.py

@@ -2,7 +2,7 @@ import logging
 
 
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronLauncher import NeuronLauncher
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
 from kalliope.core.NeuronParameterLoader import NeuronParameterLoader
-from kalliope.core.OrderAnalyser2 import OrderAnalyser2
+from kalliope.core.OrderAnalyser import OrderAnalyser
 
 
 
 
 logging.basicConfig()
 logging.basicConfig()
@@ -61,16 +61,16 @@ class SynapseLauncher(object):
         :return: Return a list of launched synapse
         :return: Return a list of launched synapse
         """
         """
         no_synapse_match = False
         no_synapse_match = False
+        # create a list of launched synapse to return
+        launched_synapses = list()
         if order_to_process is not None:  # maybe we have received a null audio from STT engine
         if order_to_process is not None:  # maybe we have received a null audio from STT engine
-            launched_synapses_tuple = OrderAnalyser2.get_matching_synapse(order=order_to_process, brain=brain)
+            launched_synapses_tuple = OrderAnalyser.get_matching_synapse(order=order_to_process, brain=brain)
 
 
-            # oa2 contains the list Named tuple of synapse to run with the associated order that has matched
+            # oa contains the list Named tuple of synapse to run with the associated order that has matched
             # for each synapse, get neurons, et for each neuron, get parameters
             # for each synapse, get neurons, et for each neuron, get parameters
             if not launched_synapses_tuple:
             if not launched_synapses_tuple:
                 no_synapse_match = True
                 no_synapse_match = True
             else:
             else:
-                # create a list of launched synapse to return
-                launched_synapses = list()
                 # the order match one or more synapses
                 # the order match one or more synapses
                 for tuple_el in launched_synapses_tuple:
                 for tuple_el in launched_synapses_tuple:
                     launched_synapses.append(tuple_el.synapse)
                     launched_synapses.append(tuple_el.synapse)
@@ -80,13 +80,15 @@ class SynapseLauncher(object):
                     # start the neuron list
                     # start the neuron list
                     NeuronLauncher.start_neuron_list(neuron_list=tuple_el.synapse.neurons,
                     NeuronLauncher.start_neuron_list(neuron_list=tuple_el.synapse.neurons,
                                                      parameters_dict=parameters)
                                                      parameters_dict=parameters)
-                # return the launched synapse list
-                return launched_synapses
         else:
         else:
             no_synapse_match = True
             no_synapse_match = True
 
 
         if no_synapse_match:  # then run the default synapse
         if no_synapse_match:  # then run the default synapse
             if settings.default_synapse is not None:
             if settings.default_synapse is not None:
-                launched_synapses = SynapseLauncher.start_synapse(name=settings.default_synapse, brain=brain)
+                logger.debug("No matching Synapse-> running default synapse ")
+                synapses = SynapseLauncher.start_synapse(name=settings.default_synapse,
+                                                         brain=brain)
+                launched_synapses.append(synapses)
 
 
-                return [launched_synapses]
+        # return the launched synapse list
+        return launched_synapses