NeuronModule.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # coding: utf8
  2. import logging
  3. import os
  4. import random
  5. import sys
  6. from jinja2 import Template
  7. from core import OrderListener
  8. from core.SynapseLauncher import SynapseLauncher
  9. from core.Utils import Utils
  10. from core.ConfigurationManager import SettingLoader, BrainLoader
  11. logging.basicConfig()
  12. logger = logging.getLogger("kalliope")
  13. class InvalidParameterException(Exception):
  14. """
  15. Some Neuron parameters are invalid.
  16. """
  17. pass
  18. class MissingParameterException(Exception):
  19. """
  20. Some Neuron parameters are missing.
  21. """
  22. pass
  23. class NoTemplateException(Exception):
  24. """
  25. You must specify a say_template or a file_template
  26. """
  27. pass
  28. class TemplateFileNotFoundException(Exception):
  29. """
  30. Template file can not be found. Check the provided path.
  31. """
  32. pass
  33. class TTSModuleNotFound(Exception):
  34. """
  35. TTS module can not be find. It must be configured in the settings file.
  36. """
  37. pass
  38. class NeuronModule(object):
  39. """
  40. This Abstract Class is representing main Class for Neuron.
  41. Each Neuron must implement this Class.
  42. """
  43. def __init__(self, **kwargs):
  44. """
  45. Class used by neuron for talking
  46. :param kwargs: Same parameter as the Child. Can contain info about the tts to use instead of the
  47. default one
  48. """
  49. # get the child who called the class
  50. child_name = self.__class__.__name__
  51. logger.debug("NeuronModule called from class %s with parameters: %s" % (child_name, str(kwargs)))
  52. sl = SettingLoader.Instance()
  53. self.settings = sl.settings
  54. brain_loader = BrainLoader.Instance()
  55. self.brain = brain_loader.brain
  56. # check if the user has overrider the TTS
  57. tts = kwargs.get('tts', None)
  58. if tts is None:
  59. # No tts provided, we load the default one
  60. self.tts = self.settings.default_tts_name
  61. else:
  62. self.tts = tts
  63. # get if the cache settings is present
  64. self.override_cache = kwargs.get('cache', None)
  65. # get templates if provided
  66. # Check if there is a template associate to the output message
  67. self.say_template = kwargs.get('say_template', None)
  68. # check if there is a template file associate to the output message
  69. self.file_template = kwargs.get('file_template', None)
  70. def say(self, message):
  71. """
  72. USe TTS to speak out loud the Message.
  73. A message can be a string, a list or a dict
  74. If it's a string, simply use the TTS with the message
  75. If it's a list, we select randomly a string in the list and give it to the TTS
  76. If it's a dict, we use the template given in parameter to create a string that we give to the TTS
  77. :param message: Can be a String or a dict or a list
  78. .. raises:: TTSModuleNotFound
  79. """
  80. logger.debug("NeuronModule Say() called with message: %s" % message)
  81. tts_message = None
  82. if isinstance(message, str) or isinstance(message, unicode):
  83. logger.debug("message is string")
  84. tts_message = message
  85. if isinstance(message, list):
  86. logger.debug("message is list")
  87. tts_message = random.choice(message)
  88. if isinstance(message, dict):
  89. logger.debug("message is dict")
  90. tts_message = self._get_message_from_dict(message)
  91. if tts_message is not None:
  92. logger.debug("tts_message to say: %s" % tts_message)
  93. # create a tts object from the tts the user want to user
  94. tts_object = next((x for x in self.settings.ttss if x.name == self.tts), None)
  95. if tts_object is None:
  96. raise TTSModuleNotFound("The tts module name %s does not exist in settings file" % self.tts)
  97. # change the cache settings with the one precised for the current neuron
  98. if self.override_cache is not None:
  99. tts_object.parameters = self._update_cache_var(self.override_cache, tts_object.parameters)
  100. logger.debug("NeuroneModule: TTS args: %s" % tts_object)
  101. # get the instance of the TTS module
  102. tts_module_instance = Utils.get_dynamic_class_instantiation("tts", tts_object.name.capitalize(),
  103. tts_object.parameters)
  104. # generate the audio file and play it
  105. tts_module_instance.say(tts_message)
  106. def _get_message_from_dict(self, message_dict):
  107. """
  108. Generate a message that can be played by a TTS engine from a dict of variable and the jinja template
  109. :param message_dict: the dict of message
  110. :return: The message to say
  111. .. raises:: TemplateFileNotFoundException
  112. """
  113. returned_message = None
  114. if (self.say_template is not None and self.file_template is None) or \
  115. (self.say_template is None and self.file_template is not None):
  116. # the user choose a say_template option
  117. if self.say_template is not None:
  118. if isinstance(self.say_template, list):
  119. # then we pick randomly one template
  120. self.say_template = random.choice(self.say_template)
  121. t = Template(self.say_template)
  122. returned_message = t.render(**message_dict)
  123. # trick to remobe unicode problem when loading jinja template with non ascii char
  124. reload(sys)
  125. sys.setdefaultencoding('utf-8')
  126. # the user choose a file_template option
  127. if self.file_template is not None: # the user choose a file_template option
  128. if not os.path.isabs(self.file_template): # os.path.isabs returns True if the path is absolute
  129. # here we are
  130. dir_we_are = os.path.dirname(os.path.realpath(__file__))
  131. # root directory
  132. root_dir = os.path.normpath(dir_we_are + os.sep + os.pardir)
  133. # real path of the template
  134. real_file_template_path = os.path.join(root_dir, self.file_template)
  135. else:
  136. real_file_template_path = self.file_template
  137. if os.path.isfile(real_file_template_path):
  138. # load the content of the file as template
  139. t = Template(self._get_content_of_file(real_file_template_path))
  140. returned_message = t.render(**message_dict)
  141. else:
  142. raise TemplateFileNotFoundException("Template file %s not found in templates folder"
  143. % real_file_template_path)
  144. return returned_message
  145. # we don't force the usage of a template. The user can choose to do nothing with returned value
  146. # else:
  147. # raise NoTemplateException("You must specify a say_template or a file_template")
  148. def run_synapse_ny_name(self, name):
  149. SynapseLauncher.start_synapse(name=name, brain=self.brain)
  150. @staticmethod
  151. def _get_content_of_file(real_file_template_path):
  152. """
  153. Return the content of a file in path <real_file_template_path>
  154. :param real_file_template_path: path of the file to return the content
  155. :return: file content str
  156. """
  157. with open(real_file_template_path, 'r') as content_file:
  158. return content_file.read()
  159. @staticmethod
  160. def _update_cache_var(new_override_cache, args_list):
  161. """
  162. update the value for the key "cache" in the dict args_list
  163. :param new_override_cache: cache bolean to set in place of the current one in args_list
  164. :param args_list: arg list that contain "cache" to update
  165. :return:
  166. """
  167. logger.debug("args for TTS plugin before update: %s" % str(args_list))
  168. args_list["cache"] = new_override_cache
  169. logger.debug("args for TTS plugin after update: %s" % str(args_list))
  170. return args_list
  171. @staticmethod
  172. def get_audio_from_stt(callback):
  173. """
  174. Call the default STT to get an audio sample and return it into the callback method
  175. :param callback: A callback function
  176. """
  177. # call the order listener
  178. oa = OrderListener(callback=callback)
  179. oa.start()