baidu.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # encoding:utf-8
  2. from __future__ import division
  3. from ..__load__ import *
  4. import requests
  5. import datetime
  6. import uuid
  7. from dateutil import parser as dparser
  8. class Baidu(object):
  9. def get_token(self, api_key, secret_key):
  10. # 临时目录存放token
  11. cache = open(os.path.join(File.path() + 'runtime/', 'baiduToken.ini'), 'a+')
  12. try:
  13. pms = cache.readlines()
  14. if len(pms) > 0:
  15. time = pms[0]
  16. tk = pms[1]
  17. # 计算token是否过期 官方说明一个月,这里保守29天
  18. time = dparser.parse(time)
  19. endtime = datetime.datetime.now()
  20. if (endtime - time).days <= 29:
  21. return tk
  22. finally:
  23. cache.close()
  24. URL = 'http://openapi.baidu.com/oauth/2.0/token'
  25. params = {'grant_type': 'client_credentials',
  26. 'client_id': api_key,
  27. 'client_secret': secret_key}
  28. r = requests.get(URL, params=params)
  29. try:
  30. r.raise_for_status()
  31. token = r.json()['access_token']
  32. return token
  33. except requests.exceptions.HTTPError:
  34. return ''
  35. def getUnit(self, query, service_id, api_key, secret_key):
  36. """
  37. NLU 解析
  38. :param query: 用户的指令字符串
  39. :param service_id: UNIT 的 service_id
  40. :param api_key: UNIT apk_key
  41. :param secret_key: UNIT secret_key
  42. :returns: UNIT 解析结果。如果解析失败,返回 None
  43. """
  44. access_token = self.get_token(api_key, secret_key)
  45. url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + access_token
  46. request={
  47. "query":query,
  48. "user_id":"888888",
  49. }
  50. body={
  51. "log_id": str(uuid.uuid1()),
  52. "version":"2.0",
  53. "service_id": service_id,
  54. "session_id": str(uuid.uuid1()),
  55. "request":request
  56. }
  57. try:
  58. headers = {'Content-Type': 'application/json'}
  59. request = requests.post(url, json=body, headers=headers)
  60. return json.loads(request.text)
  61. except Exception:
  62. return None
  63. def getIntent(self, parsed):
  64. """
  65. 提取意图
  66. :param parsed: UNIT 解析结果
  67. :returns: 意图数组
  68. """
  69. if parsed is not None and 'result' in parsed and \
  70. 'response_list' in parsed['result']:
  71. return parsed['result']['response_list'][0]['schema']['intent']
  72. else:
  73. return ''
  74. def hasIntent(self, parsed, intent):
  75. """
  76. 判断是否包含某个意图
  77. :param parsed: UNIT 解析结果
  78. :param intent: 意图的名称
  79. :returns: True: 包含; False: 不包含
  80. """
  81. if parsed is not None and 'result' in parsed and \
  82. 'response_list' in parsed['result']:
  83. response_list = parsed['result']['response_list']
  84. for response in response_list:
  85. if response['schema']['intent'] == intent:
  86. return True
  87. return False
  88. else:
  89. return False
  90. def getSlots(self, parsed, intent=''):
  91. """
  92. 提取某个意图的所有词槽
  93. :param parsed: UNIT 解析结果
  94. :param intent: 意图的名称
  95. :returns: 词槽列表。你可以通过 name 属性筛选词槽,
  96. 再通过 normalized_word 属性取出相应的值
  97. """
  98. if parsed is not None and 'result' in parsed and \
  99. 'response_list' in parsed['result']:
  100. response_list = parsed['result']['response_list']
  101. if intent == '':
  102. return parsed['result']['response_list'][0]['schema']['slots']
  103. for response in response_list:
  104. if response['schema']['intent'] == intent:
  105. return response['schema']['slots']
  106. else:
  107. return []
  108. def getSlotWords(self, parsed, intent, name):
  109. """
  110. 找出命中某个词槽的内容
  111. :param parsed: UNIT 解析结果
  112. :param intent: 意图的名称
  113. :param name: 词槽名
  114. :returns: 命中该词槽的值的列表。
  115. """
  116. slots = getSlots(parsed, intent)
  117. words = []
  118. for slot in slots:
  119. if slot['name'] == name:
  120. words.append(slot['normalized_word'])
  121. return words
  122. def getSay(self, parsed, intent=''):
  123. """
  124. 提取 UNIT 的回复文本
  125. :param parsed: UNIT 解析结果
  126. :param intent: 意图的名称
  127. :returns: UNIT 的回复文本
  128. """
  129. if parsed is not None and 'result' in parsed and \
  130. 'response_list' in parsed['result']:
  131. response_list = parsed['result']['response_list']
  132. if intent == '':
  133. return response_list[0]['action_list'][0]['say']
  134. for response in response_list:
  135. if response['schema']['intent'] == intent:
  136. return response['action_list'][0]['say']
  137. return ''
  138. else:
  139. return ''