OrderAnalyser.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # coding: utf8
  2. import re
  3. from collections import Counter
  4. from core.Utils import Utils
  5. from core.Models import Order
  6. from core.NeuroneLauncher import NeuroneLauncher
  7. import logging
  8. logging.basicConfig()
  9. logger = logging.getLogger("kalliope")
  10. class OrderAnalyser:
  11. """
  12. This Class is used to compare the incoming message to the Signal/Order sentences.
  13. """
  14. def __init__(self, order, main_controller=None, brain=None):
  15. """
  16. Class used to load brain and run neuron attached to the received order
  17. :param order: spelt order
  18. :param main_controller
  19. :param brain: loaded brain
  20. """
  21. self.main_controller = main_controller
  22. self.order = order
  23. if isinstance(self.order, str):
  24. self.order = order.decode('utf-8')
  25. self.brain = brain
  26. logger.debug("OrderAnalyser, Received order: %s" % self.order)
  27. def start(self):
  28. # TODO : refactor this method !!
  29. """
  30. This method matches the incoming messages to the signals/order sentences provided in the Brain
  31. """
  32. # create a dict of synapses that have benn launched
  33. launched_synapses = self._get_matching_synapse_list(self.brain.synapses, self.order)
  34. if not launched_synapses:
  35. Utils.print_info("No synapse match the captured order: %s" % self.order)
  36. else:
  37. for synapse in launched_synapses:
  38. params = self._get_synapse_params(synapse, self.order)
  39. for neuron in synapse.neurons:
  40. self._start_neuron(neuron, params)
  41. # return the list of launched synapse
  42. return launched_synapses
  43. @classmethod
  44. def _get_matching_synapse_list(cls, all_synapses_list, order_to_match):
  45. """
  46. Class method to return all the matching synapses with the order from the complete of synapses.
  47. :param all_synapses_list: the complete list of all synapses
  48. :param order_to_match: the order to match
  49. :return: the list of matching synapses
  50. """
  51. matching_synapses_list = list()
  52. for synapse in all_synapses_list:
  53. for signal in synapse.signals:
  54. if type(signal) == Order:
  55. if cls._spelt_order_match_brain_order_via_table(signal.sentence, order_to_match):
  56. matching_synapses_list.append(synapse)
  57. logger.debug("Order found! Run neurons: %s" % synapse.neurons)
  58. Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
  59. return matching_synapses_list
  60. @classmethod
  61. def _get_synapse_params(cls, synapse, order_to_check):
  62. """
  63. Class method to get all params comming from a synapse. Returns a dict of key/value.
  64. :param synapse: the synapse to check
  65. :param order_to_check: the order to match
  66. :return: the dict key/value
  67. """
  68. params = dict()
  69. for signal in synapse.signals:
  70. if cls._is_containing_bracket(signal.sentence):
  71. params = cls._associate_order_params_to_values(order_to_check, signal.sentence)
  72. logger.debug("Parameters for order: %s" % params)
  73. return params
  74. @classmethod
  75. def _start_neuron(cls, neuron, params):
  76. """
  77. Associate params and Starts a neuron.
  78. :param neuron: the neuron to start
  79. :param params: the params to check and associate to the neuron args.
  80. """
  81. problem_in_neuron_found = False
  82. if isinstance(neuron.parameters, dict):
  83. # print neuron.parameters
  84. if "args" in neuron.parameters:
  85. logger.debug("The neuron waits for parameter")
  86. # check that the user added parameters to his order
  87. if params is None:
  88. # we don't raise an error and break the program but we don't run the neuron
  89. problem_in_neuron_found = True
  90. Utils.print_danger("Error: The neuron %s is waiting for argument. "
  91. "Argument found in bracket in the given order" % neuron.name)
  92. else:
  93. # we add wanted arguments the existing neuron parameter dict
  94. for arg in neuron.parameters["args"]:
  95. if arg in params:
  96. logger.debug("Parameter %s added to the current parameter "
  97. "of the neuron: %s" % (arg, neuron.name))
  98. neuron.parameters[arg] = params[arg]
  99. else:
  100. # we don't raise an error and break the program but
  101. # we don't run the neuron
  102. problem_in_neuron_found = True
  103. Utils.print_danger("Error: Argument \"%s\" not found in the"
  104. " order" % arg)
  105. # if no error detected, we run the neuron
  106. if not problem_in_neuron_found:
  107. NeuroneLauncher.start_neurone(neuron)
  108. else:
  109. Utils.print_danger("A problem has been found in the Synapse.")
  110. @classmethod
  111. def _associate_order_params_to_values(cls, order, order_to_check):
  112. """
  113. Associate the variables from the order to the incoming user order
  114. :param order_to_check: the order to check incoming from the brain
  115. :type order_to_check: str
  116. :param order: the order from user
  117. :type order: str
  118. :return: the dict corresponding to the key / value of the params
  119. """
  120. pattern = '\s+(?=[^\{\{\}\}]*\}\})'
  121. # Remove white spaces (if any) between the variable and the double brace then split
  122. list_word_in_order = re.sub(pattern, '', order_to_check).split()
  123. # get the order, defined by the first words before {{
  124. # /!\ Could be empty if order starts with double brace
  125. the_order = order_to_check[:order_to_check.find('{{')]
  126. # remove sentence before order which are sentences not matching anyway
  127. truncate_user_sentence = order[order.find(the_order):]
  128. truncate_list_word_said = truncate_user_sentence.split()
  129. # make dict var:value
  130. dict_var = dict()
  131. for idx, ow in enumerate(list_word_in_order):
  132. if cls._is_containing_bracket(ow):
  133. # remove bracket and grab the next value / stop value
  134. var_name = ow.replace("{{", "").replace("}}", "")
  135. stop_value = cls._get_next_value_list(list_word_in_order[idx:])
  136. if stop_value is None:
  137. dict_var[var_name] = " ".join(truncate_list_word_said)
  138. break
  139. for word_said in truncate_list_word_said:
  140. if word_said == stop_value:
  141. break
  142. if var_name in dict_var:
  143. dict_var[var_name] += " " + word_said
  144. truncate_list_word_said = truncate_list_word_said[1:]
  145. else:
  146. dict_var[var_name] = word_said
  147. truncate_list_word_said = truncate_list_word_said[1:]
  148. return dict_var
  149. @staticmethod
  150. def _is_containing_bracket(sentence):
  151. """
  152. Return True if the text in <sentence> contains brackets
  153. :param sentence:
  154. :return:
  155. """
  156. # print "sentence to test %s" % sentence
  157. pattern = r"{{|}}"
  158. # prog = re.compile(pattern)
  159. check_bool = re.search(pattern, sentence)
  160. if check_bool is not None:
  161. return True
  162. return False
  163. @staticmethod
  164. def _get_next_value_list(list_to_check):
  165. ite = list_to_check.__iter__()
  166. next(ite, None)
  167. return next(ite, None)
  168. @classmethod
  169. def _spelt_order_match_brain_order_via_table(cls, order_to_analyse, user_said):
  170. """
  171. return true if all string that are in the sentence are present in the order to test
  172. :param order_to_analyse: String order to test
  173. :param user_said: String to compare to the order
  174. :return: True if all string are present in the order
  175. """
  176. list_word_user_said = user_said.split()
  177. split_order_without_bracket = cls._get_split_order_without_bracket(order_to_analyse)
  178. # if all words in the list of what the user said in in the list of word in the order
  179. return cls._counter_subset(split_order_without_bracket, list_word_user_said)
  180. @staticmethod
  181. def _get_split_order_without_bracket(order):
  182. """
  183. Get an order with bracket inside like: "hello my name is {{ name }}.
  184. return a list of string without bracket like ["hello", "my", "name", "is"]
  185. :param order: sentence to split
  186. :return: list of string without bracket
  187. """
  188. pattern = r"((?:{{\s*)[\w\.]+(?:\s*}}))"
  189. # find everything like {{ word }}
  190. matches = re.findall(pattern, order)
  191. for match in matches:
  192. order = order.replace(match, "")
  193. # then split
  194. split_order = order.split()
  195. return split_order
  196. @staticmethod
  197. def _counter_subset(list1, list2):
  198. """
  199. check if the number of occurrences matches
  200. :param list1:
  201. :param list2:
  202. :return:
  203. """
  204. c1, c2 = Counter(list1), Counter(list2)
  205. for k, n in c1.items():
  206. if n > c2[k]:
  207. return False
  208. return True