浏览代码

add function the detect match order with a list of word. #TODO: fix encoding. It works in test.py but not in orderAnalyser

nico 8 年之前
父节点
当前提交
eada95221f
共有 3 个文件被更改,包括 97 次插入131 次删除
  1. 17 18
      brain.yml
  2. 37 3
      core/OrderAnalyser.py
  3. 43 110
      test.py

+ 17 - 18
brain.yml

@@ -1,15 +1,15 @@
 ---
-#  - name: "hello world"
-#    neurons:
-#      - say:
-#          message:
-#            - "Bonjour monsieur"
-#          args:
-#            - song_name
-#            - artist_name
-#    signals:
-#      - order: "hello"
-#      - order: "je voudrais la musique {{song_name}} de {{ artist_name }}"
+  - name: "hello world"
+    neurons:
+      - say:
+          message:
+            - "Bonjour monsieur"
+          args:
+            - hour
+            - minute
+
+    signals:
+      - order: "régle le réveil pour {{ hour }} heures et {{ minute }} minutes"
 
   - name: "say hello"
     neurons:
@@ -17,7 +17,6 @@
           message:
             - "Bonjour monsieur"
     signals:
-      - event: "57 22 * * *"
       - order: "dis bonjour"
 
   - name: "Meaning of life"
@@ -42,11 +41,10 @@
     neurons:
       - systemdate:
           say_template:
-            - "Il est {{ hours }} heures et {{ minutes }} minutes {{insulte}}"
-          tts: "voxygen"
+            - "il est {{ hours }} heure et {{ minutes }} minute"
           cache: False
     signals:
-      - order: "{{politesse}} quelle heure est-il {{insulte}}"
+      - order: "what time is it"
 
   - name: "Say local date from template"
     neurons:
@@ -95,7 +93,7 @@
     neurons:
       - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
       - say:
-          message: "Musique lancée, monsieur"
+          message: "Musique lance, monsieur"
     signals:
       - order: "mais nous de la musique"
       - order: "musique rock"
@@ -104,7 +102,7 @@
     neurons:
       - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
       - say:
-          message: "Musique stoppé, monsieur"
+          message: "Musique stopp, monsieur"
     signals:
       - order: "arrête la musique"
       - order: "stop la musique"
@@ -133,4 +131,5 @@
           password: "my_password"
           file_template: fr_gmail.j2
     signals:
-      - order: "est-ce que j'ai des emails"
+      - order: "est-ce que j'ai des emails"
+

+ 37 - 3
core/OrderAnalyser.py

@@ -1,3 +1,4 @@
+# coding: utf8
 import re
 
 from core.Utils import Utils
@@ -26,14 +27,14 @@ class OrderAnalyser:
             self.brain = BrainLoader.get_brain()
         else:
             self.brain = BrainLoader.get_brain(file_path=brain_file)
-            logger.debug("Receiver order: %s" % self.order)
+        logger.debug("OrderAnalyser, Received order: %s" % self.order)
 
     def start(self):
         synapses_found = False
         for synapse in self.brain.synapses:
             for signal in synapse.signals:
                 if type(signal) == Order:
-                    if self._spelt_order_match_brain_order(signal.sentence):
+                    if self._spelt_order_match_brain_order_via_table(signal.sentence, self.order):
                         synapses_found = True
                         logger.debug("Order found! Run neurons: %s" % synapse.neurons)
                         Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
@@ -46,7 +47,7 @@ class OrderAnalyser:
                         for neuron in synapse.neurons:
                             if isinstance(neuron.parameters, dict):
                                 if "args" in neuron.parameters:
-                                    print "the neuron wait for parameter"
+                                    logger.debug("The neuron wait for parameter")
                                     # check that the user added parameters to his order
                                     if params is None:
                                         # TODO: raise an error and break the program?
@@ -59,6 +60,7 @@ class OrderAnalyser:
                                                 logger.debug("Parameter %s added to the current parameter "
                                                              "of the neuron: %s" % (arg, neuron.name))
                                                 neuron.parameters[arg] = params[arg]
+                                                print params[arg]
                                             else:
                                                 # TODO: raise an error and break the program?
                                                 Utils.print_danger("Error: Argument \"%s\" not found in the"
@@ -139,3 +141,35 @@ class OrderAnalyser:
         ite = list.__iter__()
         next(ite, None)
         return next(ite, None)
+
+    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
+        """
+        list_word_user_said = user_said.split()
+        split_order_without_bracket = self._get_split_order_without_bracket(order_to_analyse)
+        print split_order_without_bracket
+
+        number_of_word_in_order = len(split_order_without_bracket)
+        # if all words in the list of what the user said in in the list of word in the order
+        return len(set(split_order_without_bracket).intersection(list_word_user_said)) == number_of_word_in_order
+
+    @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
+        """
+        pattern = r"((?:{{\s*)[\w\.]+(?:\s*}}))"
+        # find everything like {{ word }}
+        matches = re.findall(pattern, order)
+        for match in matches:
+            order = order.replace(match, "")
+        # then split
+        split_order = order.split()
+        return split_order

+ 43 - 110
test.py

@@ -1,119 +1,52 @@
-# -*- coding: utf-8 -*-
-
-import re, math
-from collections import Counter
-
-
-
-# user_said = "maman je voudrais ecouter ACDC"
-# order = "je voudrais ecouter {{ artist_name }}"
-
-user_said = "s'il te plait regle le reveil pour dix huit heures et dix neuf  minutes trente trois  secondes cent quatre vingt dix "
-
-user_said_list = [" regle le reveil pour neuf  heures et quinze minutes trente trois secondes ",
-                 "s'il te plait regle le reveil pour dix huit huf  minutes trente trois  secondes cent quatre vingt dix ",
-                 "regle pour dix huit heures et   trente trois  secondes cent quatre vingt dix ",
-                 "s'il te plait regle le reveil poutes trente trois  secondes cent quatre vingt dix ",
-                 "RIEN A VOIR"
-                  ]
-
-order = "{{ politesse }} regle le reveil pour {{ hour}} heures et {{minute }} minutes {{ seconde  }} secondes {{mili}}"
-
-order_list = ["regle le reveil pour  heures et  minutes  secondes ",
-              "{{ politesse }} regle le reveil pour {{ hour}} heures et {{minute }} minutes {{ seconde  }} secondes {{mili}}",
-              " reveil pour {{ hour}}  et {{minute }} minutes  secondes {{mili}}",
-              "{{ politesse }} regle le reveil pour "
-              ]
-
-
-# take a look to each order
-
-WORD = re.compile(r'\w+')
-
-def get_cosine(vec1, vec2):
-     intersection = set(vec1.keys()) & set(vec2.keys())
-     numerator = sum([vec1[x] * vec2[x] for x in intersection])
-
-     sum1 = sum([vec1[x]**2 for x in vec1.keys()])
-     sum2 = sum([vec2[x]**2 for x in vec2.keys()])
-     denominator = math.sqrt(sum1) * math.sqrt(sum2)
-
-     if not denominator:
-        return 0.0
-     else:
-        return float(numerator) / denominator
-
-def text_to_vector(text):
-     words = WORD.findall(text)
-     return Counter(words)
-
-
-def _is_containing_bracket(sentence):
-    # print "sentence to test %s" % sentence
-    pattern = r"{{|}}"
-    # prog = re.compile(pattern)
-    bool = re.search(pattern, sentence)
-    if bool is not None:
-        return True
-    return False
-
-
-def _get_next_value_list(list):
-    ite = list.__iter__()
-    next(ite, None)
-    return next(ite, None)
-
-# check if the order contain bracket
-if _is_containing_bracket(order):
-    # remove white space between {{ and }}
-    # get a table of word said
-    list_word_in_order = re.sub('\s+(?=[^\{\{\}\}]*\}\})', '',order).split()
-    print "order matched: %s" % list_word_in_order
-
-    # get the order, defined by the first words before {{
-    the_order = order[:order.find('{{')]
-    print "the order catched %s" % the_order
-
-
-    # remove sentence before order
-    nb = user_said[user_said.find(the_order):]
-    truncate_list_word_said = nb.split()
-    print "truncate_list_word_said : %s" % truncate_list_word_said
-
-
-    # make dict var:value
-    dictVar = {}
-    for idx, ow in enumerate(list_word_in_order):
-        if _is_containing_bracket(ow):
-            # remove bracket et key dict
-            varname = ow.replace("{{","").replace("}}", "")
-            stopValue = _get_next_value_list(list_word_in_order[idx:])
-            if stopValue is None:
-                dictVar[varname] = " ".join(truncate_list_word_said)
-                break
-            for word_said in truncate_list_word_said:
-                if word_said == stopValue: break
-                if varname in dictVar:
-                    dictVar[varname] += " " + word_said
-                    truncate_list_word_said = truncate_list_word_said[1:]
-                else:
-                    dictVar[varname] = word_said
-        truncate_list_word_said = truncate_list_word_said[1:]
-    print "The dict Var : %s" % dictVar
+# coding: utf8
+import logging
+import re
+from core import OrderAnalyser
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+logger.setLevel(logging.DEBUG)
+
+# This does not work because of different encoding when using accent
+# from core import OrderAnalyser
+# order = "jarvis régle le réveil pour sept heures et vingt minutes"
+#
+# oa = OrderAnalyser(order)
+#
+# oa.start()
 
 
+user_said = "jarvis régle le réveil pour sept heures et vingts minutes please"
 
-# for us in user_said_list:
-#     for od in order_list:
-#         vector1 = text_to_vector(us)
-#         vector2 = text_to_vector(od)
-#
-#         cosine = get_cosine(vector1, vector2)
-#
-#         print "Cosine -> ", cosine, " for usersaid: ",us, " ,order:", od
+order = "régle le réveil pour {{ hour }} heures et {{ minute }} minutes"
 
 
+def _spelt_order_match_brain_order_via_table(order_to_analyse, user_said):
+    list_word_user_said = user_said.split()
+    split_order_without_bracket = _get_list_word_without_bracket(order_to_analyse)
 
+    number_of_word_in_order = len(split_order_without_bracket)
+    # if all words in the list of what the user said in in the list of word in the order
+    return len(set(split_order_without_bracket).intersection(list_word_user_said)) == number_of_word_in_order
 
 
+def _get_list_word_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
+    """
+    pattern = r"((?:{{\s*)[\w\.]+(?:\s*}}))"
+    # find everything like {{ word }}
+    matches = re.findall(pattern, order)
+    for match in matches:
+        order = order.replace(match, "")
+    # then split
+    split_order = order.split()
+    return split_order
 
+# main test
+if _spelt_order_match_brain_order_via_table(order, user_said):
+    print "order matched"
+else:
+    print "order does not match"