OrderAnalyser.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import re
  2. from core.Utils import Utils
  3. from core.ConfigurationManager.BrainLoader import BrainLoader
  4. from core.Models import Order
  5. from core.NeuroneLauncher import NeuroneLauncher
  6. from Cosine import *
  7. import logging
  8. logging.basicConfig()
  9. logger = logging.getLogger("jarvis")
  10. class OrderAnalyser:
  11. def __init__(self, order, main_controller=None, brain_file=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_file: To override the default brain.yml file
  17. """
  18. self.main_controller = main_controller
  19. self.order = order
  20. if brain_file is None:
  21. self.brain = BrainLoader.get_brain()
  22. else:
  23. self.brain = BrainLoader.get_brain(file_path=brain_file)
  24. logger.debug("Receiver order: %s" % self.order)
  25. def start(self):
  26. synapses_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(signal.sentence):
  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. params = {}
  35. if self._is_containing_bracket(signal.sentence):
  36. params = self._associate_order_params_to_values(signal.sentence)
  37. for neuron in synapse.neurons:
  38. neuron.parameters = dict(neuron.parameters.items() + params.items())
  39. NeuroneLauncher.start_neurone(neuron)
  40. if not synapses_found:
  41. Utils.print_info("No synapse match the captured order: %s" % self.order)
  42. def _spelt_order_match_brain_order(self, order_to_test):
  43. """
  44. test if the current order match the order spelt by the user
  45. :param order_to_test:
  46. :return:
  47. """
  48. # TODO : In "order_to_test" should we remove double brace and variable name before checking to optimise the cosine ?
  49. user_vector = text_to_vector(self.order)
  50. order_vector = text_to_vector(order_to_test)
  51. cosine = get_cosine(user_vector, order_vector)
  52. logger.debug("the cosine : %s, pour user_vector: %s , order_vector: %s" % (cosine, self.order, order_to_test))
  53. return cosine >= 0.5
  54. def _associate_order_params_to_values(self, order_to_check):
  55. """
  56. Associate the variables from the order to the incoming user order
  57. :param order: the order to check
  58. :return: the dict corresponding to the key / value of the params
  59. """
  60. # Remove white spaces (if any) between the variable and the double brace then split
  61. list_word_in_order = re.sub('\s+(?=[^\{\{\}\}]*\}\})', '', order_to_check).split()
  62. # get the order, defined by the first words before {{
  63. # /!\ Could be empty if order starts with double brace
  64. the_order = order_to_check[:order_to_check.find('{{')]
  65. # remove sentence before order which are sentences not matching anyway
  66. truncate_user_sentence = self.order[self.order.find(the_order):]
  67. truncate_list_word_said = truncate_user_sentence.split()
  68. # make dict var:value
  69. dictVar = {}
  70. for idx, ow in enumerate(list_word_in_order):
  71. if self._is_containing_bracket(ow):
  72. # remove bracket and grab the next value / stop value
  73. varname = ow.replace("{{", "").replace("}}", "")
  74. stopValue = self._get_next_value_list(list_word_in_order[idx:])
  75. if stopValue is None:
  76. dictVar[varname] = " ".join(truncate_list_word_said)
  77. break
  78. for word_said in truncate_list_word_said:
  79. if word_said == stopValue: break
  80. if varname in dictVar:
  81. dictVar[varname] += " " + word_said
  82. truncate_list_word_said = truncate_list_word_said[1:]
  83. else:
  84. dictVar[varname] = word_said
  85. truncate_list_word_said = truncate_list_word_said[1:]
  86. return dictVar
  87. @staticmethod
  88. def _is_containing_bracket(sentence):
  89. # print "sentence to test %s" % sentence
  90. pattern = r"{{|}}"
  91. # prog = re.compile(pattern)
  92. bool = re.search(pattern, sentence)
  93. if bool is not None:
  94. return True
  95. return False
  96. @staticmethod
  97. def _get_next_value_list(list):
  98. ite = list.__iter__()
  99. next(ite, None)
  100. return next(ite, None)