【Python】用Python实现一个智能聊天机器人 前言: 准备: 代码: 总结:
简单描述一下自己的实现思路:
1.运行程序 ---> 2.语音输入 ---> 3.语音转文字 ---> 4.聊天回复 ---> 5.文字转语音 ---> 6.播放语音
这里的语音功能全部使用的是百度语音的API,聊天回复这里使用的是图灵机器人,Python版本使用的是Python3.6。由于我笔记本的录音效果较差,我就用了在家吃土的蓝牙音响,作为语音的输入输出设备,有点智能音响的感觉了。
准备:
百度智能云登录注册链接:https://cloud.baidu.com/,这里进入百度语音的管理界面,创建一个新应用后,将该应用的AppID、API Key以及Secret Key记录下来,后面的Python脚本中需要用到。
图灵机器人登录注册链接:http://www.tuling123.com/sso-web/login
这里选择创建机器人,根据引导,配置完成后,进入管理界面,记录下该机器人的Key。
代码:
以下代码中,需要自己填写自己申请的百度语音的key以及图灵机器人的Key
1 import time 2 import os 3 import pygame 4 import urllib.request 5 import json 6 from aip import AipSpeech 7 import speech_recognition as sr 8 import urllib3 9 10 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # 忽略百度api连接时的报错信息。 11 12 # Baidu Speech API 13 APP_ID = '这里填自己的ID' 14 API_KEY = '这里填自己的APIKey' 15 SECRET_KEY = '这里填自己的KEY' 16 17 client = AipSpeech(APP_ID,API_KEY,SECRET_KEY) 18 19 #Turing API 20 TURING_KEY = "这里填自己的图灵机器人API" 21 API_URL = "http://openapi.tuling123.com/openapi/api/v2" 22 23 # 录音 24 def rec(rate=16000): 25 r = sr.Recognizer() 26 with sr.Microphone(sample_rate=rate) as source: 27 print("please say something") 28 audio = r.listen(source) 29 30 with open("recording.wav", "wb") as f: 31 f.write(audio.get_wav_data()) 32 33 # 百度语音转文字 34 def listen(): 35 with open('recording.wav', 'rb') as f: 36 audio_data = f.read() 37 38 result = client.asr(audio_data, 'wav', 16000, { 39 'dev_pid': 1536, 40 }) 41 42 text_input = result["result"][0] 43 44 print("我说: " + text_input) 45 Robot_think(text_input) 46 47 48 # 图灵处理 49 def Robot_think(text_input): 50 req = { 51 "perception": 52 { 53 "inputText": 54 { 55 "text": text_input 56 }, 57 58 "selfInfo": 59 { 60 "location": 61 { 62 "city": "东营", 63 "province": "东营", 64 "street": "黄河路" 65 } 66 } 67 }, 68 "userInfo": 69 { 70 "apiKey": TURING_KEY, 71 "userId": "这里随便填" 72 } 73 } 74 # print(req) 75 # 将字典格式的req编码为utf8 76 req = json.dumps(req).encode('utf8') 77 # print(req) 78 79 http_post = urllib.request.Request(API_URL, data=req, headers={'content-type': 'application/json'}) 80 response = urllib.request.urlopen(http_post) 81 response_str = response.read().decode('utf8') 82 # print(response_str) 83 response_dic = json.loads(response_str) 84 # print(response_dic) 85 86 intent_code = response_dic['intent']['code'] 87 results_text = response_dic['results'][0]['values']['text'] 88 print("AI说: " + results_text) 89 du_say(results_text) 90 play_mp3('robot.mp3') 91 # 文字转语音 92 def du_say(results_text): 93 # per 3是汉子 4是妹子,spd 是语速,vol 是音量 94 result = client.synthesis(results_text, 'zh', 1, { 95 'vol': 5, 'per': 4, 'spd': 4 96 }) 97 # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 98 if not isinstance(result, dict): 99 with open('robot.mp3', 'wb') as f: 100 f.write(result) 101 102 # 播放Mp3文件 103 def play_mp3(file): 104 pygame.mixer.init() 105 pygame.mixer.music.load(file) 106 pygame.mixer.music.play() 107 while pygame.mixer.music.get_busy(): 108 time.sleep(1) 109 pygame.mixer.music.stop() 110 pygame.mixer.quit() 111 112 if __name__ == '__main__': 113 while True: 114 rec() 115 listen()
总结:
这里只是简单的实现了自己提出的功能,还有可以完善的地方,比如语音唤醒,还有语音输入是空白的时候,自动处理,而不是程序异常结束。