树莓派做一个聊天机器人
生活随笔
收集整理的這篇文章主要介紹了
树莓派做一个聊天机器人
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先來安裝所需要的第三方庫:
pip3 install baidu-aip為了播放音頻,還需要安裝播放器:
sudo apt-get install omxplayersudo apt-get -y install mpg321然后來看第一步,錄音,通過麥克風錄入音頻,文件保存在當前目錄下,一個函數解決:
def Sound_Recording(path) :# 1.錄音,通過麥克風錄入音領,文件保存在當前目錄下。print("Recording: ")os.system('sudo arecord -D "plughw:1,0" -f S16_LE -r 16000 -d 4' + path)# time.sleep(2)# print("play:" )# os.system( 'sudo omxplayer +path)其次來看第二步,通過調用百度語音識別的的API將音頻文件轉換為文本文件,這里需要在百度開發者平臺申請一個應用:
APP_ID = '16****18' API_KEY = 'MBb******************U02' SECRET_KEY = 'WEGcGnz******************0ih51bN' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)def speech_recognition(path) :# 2.通過調用百度語音識別的API將音頻文件轉換為文本文件。with open(path, 'rb') as fp :voices = fp.read()try :result = client.asr(voices, 'wav', 16000, {'dev_pid' : 1537.})# print(result )result_text = result["result"][0]print("you said: " + result_text)return result_textexcept KeyError :print("KeyError")然后是第三步,將文本文件通過圖靈機器人的API進行對話處理,保存回復文本文件,這里同樣需要在圖靈機器人平臺申請一個聊天機器人:
turing_api_key = 'fad1ed7e**************1b14206fd0' api_url = 'http://openapi.tuling123.com/openapi/api/v2' headers = {'Content-Type':'application/json;charset=UTF-8'}def Tu_Ling(text_words=""): #3.將文本文件通過圖靈機器人的API進行對話處理,保存恢復文本文件,req={"reqType":0,"perception": {"inputText": {"text": text_words},"selfInfo": {"location": {"city": "天津","province":"天津","street": "天津科技大學"}}},"userInfo": {"apiKey": turing_api_key,"userId": "Alex"}}req["perception"]["inputText"]["text"] = text_wordsresponse = requests.request("post",api_url, json=req, headers=headers)response_dict = json.loads(response.text)result = response_dict ["results"][0]["values"]["text"]print("AI Robot said: "+ result)return result最后一步,將回復文本文件轉換為語音。:
def speech_synthesis(text_words=""): #4.將回復文本文件轉換為語音。result = client.synthesis(text_words, 'zh', 1, {'per':4, 'vol':10, 'pit':9, 'spd':5})if not isinstance(result, dict):with open('auido.mp3','wb') as f:f.write(result)os. system('mpg321 auido.mp3')總結
以上是生活随笔為你收集整理的树莓派做一个聊天机器人的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树莓派初始设置
- 下一篇: django makemigrtions