OrderAnalyser.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. def __init__(self, order, main_controller=None, brain=None):
  12. """
  13. Class used to load brain and run neuron attached to the received order
  14. :param order: spelt order
  15. :param main_controller
  16. :param brain: loaded brain
  17. """
  18. self.main_controller = main_controller
  19. self.order = order
  20. if isinstance(self.order, str):
  21. self.order = order.decode('utf-8')
  22. self.brain = brain
  23. logger.debug("OrderAnalyser, Received order: %s" % self.order)
  24. def start(self):
  25. synapses_found = False
  26. problem_in_neuron_found = False
  27. for synapse in self.brain.synapses:
  28. for signal in synapse.signals:
  29. if type(signal) == Order:
  30. if self._spelt_order_match_brain_order_via_table(signal.sentence, self.order):
  31. synapses_found = True
  32. logger.debug("Order found! Run neurons: %s" % synapse.neurons)
  33. Utils.print_success("Order matched in the brain. Running synapse \"%s\"" % synapse.name)
  34. # if the order contains bracket, we get parameters said by the user
  35. params = None
  36. if self._is_containing_bracket(signal.sentence):
  37. params = self._associate_order_params_to_values(signal.sentence)
  38. logger.debug("Parameters for order: %s" % params)
  39. for neuron in synapse.neurons:
  40. if isinstance(neuron.parameters, dict):
  41. # print neuron.parameters
  42. if "args" in neuron.parameters:
  43. logger.debug("The neuron wait for parameter")
  44. # check that the user added parameters to his order
  45. if params is None:
  46. # we don't raise an error and break the program but we don't run the neuron
  47. problem_in_neuron_found = True
  48. Utils.print_danger("Error: The neuron %s is waiting for argument. "
  49. "Argument found in bracket in the given order" % neuron.name)
  50. else:
  51. # we add wanted arguments the existing neuron parameter dict
  52. for arg in neuron.parameters["args"]:
  53. if arg in params:
  54. logger.debug("Parameter %s added to the current parameter "
  55. "of the neuron: %s" % (arg, neuron.name))
  56. neuron.parameters[arg] = params[arg]
  57. else:
  58. # we don't raise an error and break the program but
  59. # we don't run the neuron
  60. problem_in_neuron_found = True
  61. Utils.print_danger("Error: Argument \"%s\" not found in the"
  62. " order" % arg)
  63. # if no error detected, we run the neuron
  64. if not problem_in_neuron_found:
  65. NeuroneLauncher.start_neurone(neuron)
  66. else:
  67. Utils.print_danger("A problem has been found in the Synapse.")
  68. if not synapses_found:
  69. Utils.print_info("No synapse match the captured order: %s" % self.order)
  70. def _associate_order_params_to_values(self, order_to_check):
  71. """
  72. Associate the variables from the order to the incoming user order
  73. :param order_to_check: the order to check
  74. :return: the dict corresponding to the key / value of the params
  75. """
  76. pattern = '\s+(?=[^\{\{\}\}]*\}\})'
  77. # Remove white spaces (if any) between the variable and the double brace then split
  78. list_word_in_order = re.sub(pattern, '', order_to_check).split()
  79. # get the order, defined by the first words before {{
  80. # /!\ Could be empty if order starts with double brace
  81. the_order = order_to_check[:order_to_check.find('{{')]
  82. # remove sentence before order which are sentences not matching anyway
  83. truncate_user_sentence = self.order[self.order.find(the_order):]
  84. truncate_list_word_said = truncate_user_sentence.split()
  85. # make dict var:value
  86. dict_var = {}
  87. for idx, ow in enumerate(list_word_in_order):
  88. if self._is_containing_bracket(ow):
  89. # remove bracket and grab the next value / stop value
  90. var_name = ow.replace("{{", "").replace("}}", "")
  91. stop_value = self._get_next_value_list(list_word_in_order[idx:])
  92. if stop_value is None:
  93. dict_var[var_name] = " ".join(truncate_list_word_said)
  94. break
  95. for word_said in truncate_list_word_said:
  96. if word_said == stop_value:
  97. break
  98. if var_name in dict_var:
  99. dict_var[var_name] += " " + word_said
  100. truncate_list_word_said = truncate_list_word_said[1:]
  101. else:
  102. dict_var[var_name] = word_said
  103. truncate_list_word_said = truncate_list_word_said[1:]
  104. return dict_var
  105. @staticmethod
  106. def _is_containing_bracket(sentence):
  107. # print "sentence to test %s" % sentence
  108. pattern = r"{{|}}"
  109. # prog = re.compile(pattern)
  110. check_bool = re.search(pattern, sentence)
  111. if check_bool is not None:
  112. return True
  113. return False
  114. @staticmethod
  115. def _get_next_value_list(list_to_check):
  116. ite = list_to_check.__iter__()
  117. next(ite, None)
  118. return next(ite, None)
  119. def _spelt_order_match_brain_order_via_table(self, order_to_analyse, user_said):
  120. """
  121. return true if all string that are in the sentence are present in the order to test
  122. :param order_to_analyse: String order to test
  123. :param user_said: String to compare to the order
  124. :return: True if all string are present in the order
  125. """
  126. list_word_user_said = user_said.split()
  127. split_order_without_bracket = self._get_split_order_without_bracket(order_to_analyse)
  128. # if all words in the list of what the user said in in the list of word in the order
  129. return self._counter_subset(split_order_without_bracket, list_word_user_said)
  130. @staticmethod
  131. def _get_split_order_without_bracket(order):
  132. """
  133. Get an order with bracket inside like: "hello my name is {{ name }}.
  134. return a list of string without bracket like ["hello", "my", "name", "is"]
  135. :param order: sentence to split
  136. :return: list of string without bracket
  137. """
  138. pattern = r"((?:{{\s*)[\w\.]+(?:\s*}}))"
  139. # find everything like {{ word }}
  140. matches = re.findall(pattern, order)
  141. for match in matches:
  142. order = order.replace(match, "")
  143. # then split
  144. split_order = order.split()
  145. return split_order
  146. @staticmethod
  147. def _counter_subset(list1, list2):
  148. """
  149. check if the number of occurrences matches
  150. :param list1:
  151. :param list2:
  152. :return:
  153. """
  154. c1, c2 = Counter(list1), Counter(list2)
  155. for k, n in c1.items():
  156. if n > c2[k]:
  157. return False
  158. return True