# -*- coding: utf-8 -*-
from __future__ import division
from .__load__ import *
# 大脑,技能,记忆
class Brain(object):
def init(self, robot):
# vecan机器人
self.robot = robot
# 记忆
self.memory = []
# 询问模式
self.hasPardon = False
# 插件
self.plugins = []
#self.plugins = plugin_loader.get_plugins(self.robot)
self.handling = False
return self
def isImmersive(self, plugin, text, parsed):
return self.robot.getImmersiveMode() == plugin.SLUG and \
plugin.isValidImmersive(text, parsed)
def printPlugins(self):
plugin_list = []
for plugin in self.plugins:
plugin_list.append(plugin.SLUG)
self.robot.logger.info(self.log('已激活插件:{}'.format(plugin_list)))
def query(self, text):
"""
query 模块
Arguments:
text -- 用户输入
"""
args = {
"service_id": "S13442",
"api_key": 'w5v7gUV3iPGsGntcM84PtOOM',
"secret_key": 'KffXwW6E1alcGplcabcNs63Li6GvvnfL'
}
parsed = self.robot.doParse(text, **args)
print parsed
return parsed
for plugin in self.plugins:
if not plugin.isValid(text, parsed) and not self.isImmersive(plugin, text, parsed):
continue
self.robot.logger.info(self.log("'{}' 命中技能 {}".format(text, plugin.SLUG)))
self.robot.matchPlugin = plugin.SLUG
if plugin.IS_IMMERSIVE:
self.robot.setImmersiveMode(plugin.SLUG)
continueHandle = False
try:
self.handling = True
continueHandle = plugin.handle(text, parsed)
self.handling = False
except Exception:
self.robot.logger.critical('Failed to execute plugin',
exc_info=True)
reply = u"抱歉,插件{}出故障了,晚点再试试吧".format(plugin.SLUG)
self.robot.say(reply, plugin=plugin.SLUG)
else:
self.robot.logger.debug(self.log("Handling of phrase '%s' by " +
"plugin '%s' completed", text,
plugin.SLUG))
finally:
if not continueHandle:
return True
self.robot.logger.debug(self.log("No plugin was able to handle phrase {} ".format(text)))
return False
def restore(self):
""" 恢复某个技能的处理 """
if not self.robot.immersiveMode:
return
for plugin in self.plugins:
if plugin.SLUG == self.robot.immersiveMode and plugin.restore:
plugin.restore()
def pause(self):
""" 暂停某个技能的处理 """
if not self.robot.immersiveMode:
return
for plugin in self.plugins:
if plugin.SLUG == self.robot.immersiveMode and plugin.pause:
plugin.pause()
def understand(self, fp):
if self.robot and self.robot.tool['asr']:
return self.robot.tool['asr'].asr(fp)
return None
def say(self, msg, cache=False):
if self.robot and self.robot.tool['tts']:
self.robot.tool['tts'].tts(msg)
def think(self, query, uid='', onSay=None):
# 统计
#statistic.report(1)
self.robot.stop()
self.addMemory(0, query, uid)
if onSay:
self.onSay = onSay
if query.strip() == '':
self.pardon()
return
lastImmersiveMode = self.robot.immersiveMode
if not self.query(query):
# 没命中技能,使用机器人回复
msg = self.robot.tool['ai'].ai(query)
self.robot.say(msg, True, completed=self.robot.checkRestore)
else:
if lastImmersiveMode is not None and lastImmersiveMode != self.robot.matchPlugin:
time.sleep(1)
if self.checkSpeeker():
self.robot.logger.debug(self.log('等说完再checkRestore'))
self.speaker.appendOnCompleted(lambda: self.checkRestore())
else:
self.robot.logger.debug(self.log('checkRestore'))
self.robot.checkRestore()
def doubt(self, msg):
if Demeter.config['snowboy']['active_mode'] and (msg.endswith('?') or msg.endswith(u'?') or u'告诉我' in msg or u'请回答' in msg):
query = self.robot.ear.listen()
self.think(query)
def pardon(self):
if not self.hasPardon:
self.robot.say('抱歉,刚刚没听清,能再说一遍吗?', completed=lambda: self.response(self.robot.ear.listen()))
self.hasPardon = True
else:
self.robot.say('没听清呢')
self.hasPardon = False
def getMemory(self):
return self.memory
def addMemory(self, t, text, uid=''):
if t in (0, 1) and text != '':
if text.endswith(',') or text.endswith(','):
text = text[:-1]
if uid == '' or uid == None or uid == 'null':
uid = Demeter.uuid(__name__)
# 将图片处理成HTML
pattern = r'https?://.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF)'
url_pattern = r'^https?://.+'
imgs = re.findall(pattern, text)
for img in imgs:
text = text.replace(img, '
'.format(img))
urls = re.findall(url_pattern, text)
for url in urls:
text = text.replace(url, '{}'.format(url, url))
self.memory.append({'type': t, 'text': text, 'time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), 'uid': uid})
def log(self, text):
return 'Brain:' + text