价值百亿的人工智能部分代码
import random
import json
import requests
import os
from aip import AipSpeech
from playsound import playsound
client_id = "trDlLCP25KyD2f5myKqvFN7B"
client_secret = "FlSwaoOs37GvWGTVgAOqxVvfn7uKh011"
def unit_chat(chat_input, user_id='1'):
'''
功能: 聊天对话
参数说明:
chat_input: 用户输入的内容
user_id: 该用户ID
:return 返回百度unit机器人的回复语句
'''
chat_reply = 'sorry小主,您说的太深奥了,我还理解不了...'
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" % (
client_id, client_secret)
res = requests.get(url)
access_token = eval(res.text)['access_token']
unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token
post_data = {
"log_id": str(random.random()),
"bot_id": ["1116655", "1116652", "1116618", "1116621"],
"request": {
"query": chat_input,
"user_id": user_id
},
"session_id": "",
"service_id": "S58125",
"version": "2.0"
}
res = requests.post(url=unit_chatbot_url, json=post_data)
unit_chat_obj = json.loads(res.content)
if unit_chat_obj['error_code'] != 0:
return chat_reply
unit_chat_obj_result = unit_chat_obj['result']
unit_chat_response_list = unit_chat_obj_result['response_list']
unit_chat_response_obj = random.choice([unit_chat_response for unit_chat_response in unit_chat_response_list if
unit_chat_response['schema']['intent_confidence'] > 0.0])
unit_chat_response_action_list = unit_chat_response_obj['action_list']
unit_chat_response_action_obj = random.choice(unit_chat_response_action_list)
unit_chat_response_say = unit_chat_response_action_obj['say']
return unit_chat_response_say
def playSound(str):
""" 你的 APPID AK SK 最好是用你的替换,不要用我的 """
APP_ID = '24838923'
API_KEY = 'qaCknGykc3zhrgfMhm0ruGtG'
SECRET_KEY = 'zOADaE3SviPlbbQGLSrYmg2aRpvTVkN9'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis(str, 'zh', 1, {
'vol': 3,
'spd': 5,
'pit': 9,
'per': 4,
})
if not isinstance(result, dict):
with open('audio.mp3', 'wb') as f:
f.write(result)
playsound('audio.mp3')
os.remove('audio.mp3')
if __name__ == '__main__':
say = '今天的不开心就止于此吧,明天依旧光芒万丈哦,主人,我是小爱,我来为您服务~'
print(say)
playSound(say)
while True:
chat_input = input('用户输入:')
chat_reply = unit_chat(chat_input)
print('机器人回复内容 >>>', chat_reply)
playSound(chat_reply)
if chat_input == 'q':
break