brain.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. from .__load__ import *
  4. # 大脑,技能,记忆
  5. class Brain(object):
  6. def init(self, robot):
  7. # vecan机器人
  8. self.robot = robot
  9. # 记忆
  10. self.memory = []
  11. # 询问模式
  12. self.hasPardon = False
  13. # 插件
  14. self.plugins = []
  15. #self.plugins = plugin_loader.get_plugins(self.robot)
  16. self.handling = False
  17. return self
  18. def isImmersive(self, plugin, text, parsed):
  19. return self.robot.getImmersiveMode() == plugin.SLUG and \
  20. plugin.isValidImmersive(text, parsed)
  21. def printPlugins(self):
  22. plugin_list = []
  23. for plugin in self.plugins:
  24. plugin_list.append(plugin.SLUG)
  25. self.robot.logger.info(self.log('已激活插件:{}'.format(plugin_list)))
  26. def query(self, text):
  27. """
  28. query 模块
  29. Arguments:
  30. text -- 用户输入
  31. """
  32. args = {
  33. "service_id": "S13442",
  34. "api_key": 'w5v7gUV3iPGsGntcM84PtOOM',
  35. "secret_key": 'KffXwW6E1alcGplcabcNs63Li6GvvnfL'
  36. }
  37. parsed = self.robot.doParse(text, **args)
  38. return parsed
  39. for plugin in self.plugins:
  40. if not plugin.isValid(text, parsed) and not self.isImmersive(plugin, text, parsed):
  41. continue
  42. self.robot.logger.info(self.log("'{}' 命中技能 {}".format(text, plugin.SLUG)))
  43. self.robot.matchPlugin = plugin.SLUG
  44. if plugin.IS_IMMERSIVE:
  45. self.robot.setImmersiveMode(plugin.SLUG)
  46. continueHandle = False
  47. try:
  48. self.handling = True
  49. continueHandle = plugin.handle(text, parsed)
  50. self.handling = False
  51. except Exception:
  52. self.robot.logger.critical('Failed to execute plugin',
  53. exc_info=True)
  54. reply = u"抱歉,插件{}出故障了,晚点再试试吧".format(plugin.SLUG)
  55. self.robot.say(reply, plugin=plugin.SLUG)
  56. else:
  57. self.robot.logger.debug(self.log("Handling of phrase '%s' by " +
  58. "plugin '%s' completed", text,
  59. plugin.SLUG))
  60. finally:
  61. if not continueHandle:
  62. return True
  63. self.robot.logger.debug(self.log("No plugin was able to handle phrase {} ".format(text)))
  64. return False
  65. def restore(self):
  66. """ 恢复某个技能的处理 """
  67. if not self.robot.immersiveMode:
  68. return
  69. for plugin in self.plugins:
  70. if plugin.SLUG == self.robot.immersiveMode and plugin.restore:
  71. plugin.restore()
  72. def pause(self):
  73. """ 暂停某个技能的处理 """
  74. if not self.robot.immersiveMode:
  75. return
  76. for plugin in self.plugins:
  77. if plugin.SLUG == self.robot.immersiveMode and plugin.pause:
  78. plugin.pause()
  79. def understand(self, fp):
  80. if self.robot and self.robot.tool['asr']:
  81. return self.robot.tool['asr'].asr(fp)
  82. return None
  83. def say(self, msg, cache=False):
  84. if self.robot and self.robot.tool['tts']:
  85. self.robot.tool['tts'].tts(msg)
  86. def think(self, query, uid='', onSay=None):
  87. # 统计
  88. #statistic.report(1)
  89. self.robot.stop()
  90. self.addMemory(0, query, uid)
  91. if onSay:
  92. self.onSay = onSay
  93. if query.strip() == '':
  94. self.pardon()
  95. return
  96. lastImmersiveMode = self.robot.immersiveMode
  97. if not self.query(query):
  98. # 没命中技能,使用机器人回复
  99. msg = self.robot.tool['ai'].ai(query)
  100. self.robot.say(msg, True, completed=self.robot.checkRestore)
  101. else:
  102. if lastImmersiveMode is not None and lastImmersiveMode != self.robot.matchPlugin:
  103. time.sleep(1)
  104. if self.checkSpeeker():
  105. self.robot.logger.debug(self.log('等说完再checkRestore'))
  106. self.speaker.appendOnCompleted(lambda: self.checkRestore())
  107. else:
  108. self.robot.logger.debug(self.log('checkRestore'))
  109. self.robot.checkRestore()
  110. def doubt(self, msg):
  111. if Demeter.config['snowboy']['active_mode'] and (msg.endswith('?') or msg.endswith(u'?') or u'告诉我' in msg or u'请回答' in msg):
  112. query = self.robot.ear.listen()
  113. self.think(query)
  114. def pardon(self):
  115. if not self.hasPardon:
  116. self.robot.say('抱歉,刚刚没听清,能再说一遍吗?', completed=lambda: self.response(self.robot.ear.listen()))
  117. self.hasPardon = True
  118. else:
  119. self.robot.say('没听清呢')
  120. self.hasPardon = False
  121. def getMemory(self):
  122. return self.memory
  123. def addMemory(self, t, text, uid=''):
  124. if t in (0, 1) and text != '':
  125. if text.endswith(',') or text.endswith(','):
  126. text = text[:-1]
  127. if uid == '' or uid == None or uid == 'null':
  128. uid = Demeter.uuid(__name__)
  129. # 将图片处理成HTML
  130. pattern = r'https?://.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF)'
  131. url_pattern = r'^https?://.+'
  132. imgs = re.findall(pattern, text)
  133. for img in imgs:
  134. text = text.replace(img, '<img src={} class="img"/>'.format(img))
  135. urls = re.findall(url_pattern, text)
  136. for url in urls:
  137. text = text.replace(url, '<a href={} target="_blank">{}</a>'.format(url, url))
  138. self.memory.append({'type': t, 'text': text, 'time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), 'uid': uid})
  139. def log(self, text):
  140. return 'Brain:' + text