前言
ChatGPT使用想必大家都不陌生,進(jìn)入官網(wǎng),注冊(cè)賬號(hào)即可開始正式的對(duì)話聊天,可是如何使用ChatGPT API,且在Linux環(huán)境下進(jìn)行語音交互呢?碰巧在今年暑期參加物聯(lián)網(wǎng)設(shè)計(jì)競賽有用到這項(xiàng)功能,今天就來教下大家詳細(xì)步驟。
一、ChatGPT API獲取
如何獲取一個(gè)ChatGPT賬號(hào)相比對(duì)大家來說不是一件難事,網(wǎng)上教程很多大家可以搜一下,獲取到一個(gè)賬號(hào)后,可以進(jìn)入https://platform.openai.com/account/api-keys頁面。
選擇創(chuàng)建一個(gè)api key 大家一定要保存好這個(gè)密鑰,后續(xù)使用都是利用這個(gè)密鑰。這里需要注意免費(fèi)API每個(gè)賬戶都是有限的,五美元,理論上自己日常使用時(shí)用不完了的。
二、API使用步驟
接下來就讓我們來試驗(yàn)一下API密鑰。首先在Linux環(huán)境下需要安裝openai的包這里我們以樹莓派為例。
pip3 install openai
成功安裝后我們就可以創(chuàng)建一個(gè)Python運(yùn)行一下,而眾所周知,ChatGPT是需要需要使用魔法的,API調(diào)用也不例外。
# -*- coding: utf-8 -*-
import openai
# 設(shè)置OpenAI API密鑰
openai.api_key = 'sk-xxxx'#這里需要替換為你的賬戶API KEY
# 定義初始對(duì)話歷史
conversation_history = [
{'role': 'system', 'content': 'You are a helpful assistant.'}
]
# 循環(huán)交互
while True:
# 處理用戶輸入
user_input = input("User: ")
# 將用戶輸入添加到對(duì)話歷史中
conversation_history.append({'role': 'user', 'content': user_input})
# 發(fā)送聊天請(qǐng)求
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=conversation_history,
max_tokens=100,
n=1,
stop=None,
temperature=0.7
)
# 獲取助手的回復(fù)
assistant_reply = response['choices'][0]['message']['content']
# 打印助手的回復(fù)
print("Assistant:", assistant_reply)
# 將助手的回復(fù)添加到對(duì)話歷史中
conversation_history.append({'role': 'assistant', 'content': assistant_reply})
# 檢查用戶是否選擇退出循環(huán)
if user_input.lower() == 'exit':
break
通過以上代碼實(shí)現(xiàn)簡單的API調(diào)用,運(yùn)行。
問出問題,就可以得到你想要的答案。其中的模型大家也可以根據(jù)需求選用。
三、語音識(shí)別
首先最重要的是外接一個(gè)麥克風(fēng)設(shè)備,對(duì)外界實(shí)時(shí)音頻進(jìn)行識(shí)別,這里樹莓派上使用的無驅(qū)的USB麥克風(fēng)設(shè)備。
想要實(shí)現(xiàn)真正意義上的語音交互,就只能從實(shí)時(shí)音頻流中讀取。
這里我們使用的是Google的語音識(shí)別API SpeechRecognition。
首先在終端中安裝相關(guān)包。
pip3 install SpeechRecognition
成功安裝,且麥克風(fēng)設(shè)備安裝完成,我們就可以進(jìn)入下一步。
我們使用一個(gè)Python程序來進(jìn)行實(shí)現(xiàn)。
import speech_recognition as sr
# 創(chuàng)建一個(gè)Recognizer對(duì)象
r = sr.Recognizer()
# 使用麥克風(fēng)錄音
with sr.Microphone() as source:
print("請(qǐng)說話:")
audio = r.listen(source)
# 將語音轉(zhuǎn)換為文本
try:
text = r.recognize_google(audio, language='zh-CN')
print("你說的是:" + text)
except sr.UnknownValueError:
print("無法識(shí)別你的語音")
except sr.RequestError as e:
print("無法連接到Google API,錯(cuò)誤原因:" + str(e))
這里是實(shí)現(xiàn)實(shí)時(shí)音頻的識(shí)別。需要注意的是,speech_recognition的使用也需要Linux環(huán)境下的魔法上網(wǎng)。
運(yùn)行代碼會(huì)出現(xiàn)許多報(bào)錯(cuò)信息,但這些都不影響我們的識(shí)別結(jié)果。
當(dāng)顯示請(qǐng)說話示例時(shí)就可以提出問題了。實(shí)測在安靜環(huán)境下識(shí)別速度和識(shí)別準(zhǔn)確率還是非常高的。
識(shí)別返回的結(jié)果保存在text中,只要將text賦值給上述GPT的輸入即可。
三、TTS(語音合成)
要想實(shí)現(xiàn)語音對(duì)話,還需要將GPT回復(fù)的問題經(jīng)過TTS轉(zhuǎn)化為音頻。
這里使用的阿里云的Sambert語音合成,實(shí)測合成速度很快,且語音自然。
首先需要下載Sambert的包
pip3 install dashscope
試驗(yàn)一下
# coding=utf-8
import dashscope
from dashscope.audio.tts import SpeechSynthesizer
dashscope.api_key='your-dashscope-api-key'
result = SpeechSynthesizer.call(model='sambert-zhichu-v1',
text='今天天氣怎么樣',
sample_rate=48000,
format='wav')
if result.get_audio_data() is not None:
with open('output.wav', 'wb') as f:
f.write(result.get_audio_data())
print(' get response: %s' % (result.get_response()))
執(zhí)行代碼后就能生成一個(gè)output.wav文件,文件內(nèi)容就是text中問出的問題。
四、音頻播放
得到了生成的音頻文件,我們還需要將他播放出來。
Linux環(huán)境下python播放音頻播放我嘗過各種方式,最后使用效果最好,延時(shí)最低的是使用pygame來播放。
還是以同樣的步驟,安裝pygame。
pip3 install pygame
五、功能整合
將所有功能進(jìn)行整合,即可實(shí)現(xiàn)最后想要實(shí)現(xiàn)的功能。
# -*- coding: utf-8 -*-
import openai
import pygame
from pygame import mixer
import dashscope
from dashscope.audio.tts import SpeechSynthesizer
import speech_recognition as sr
import time
# 創(chuàng)建一個(gè)Recognizer對(duì)象
r = sr.Recognizer()
mixer.init()
# 設(shè)置OpenAI API密鑰
openai.api_key = 'sk-xx'
dashscope.api_key='sk-xx'
# 定義初始對(duì)話歷史
conversation_history = [
{'role': 'system', 'content': 'You are a helpful assistant.'}
]
# 循環(huán)交互
while True:
# 處理用戶輸入
# 使用麥克風(fēng)錄音
with sr.Microphone() as source:
print("請(qǐng)開始說話...")
audio = r.listen(source)
try:
# 使用語音識(shí)別引擎將音頻轉(zhuǎn)換為文字
text = r.recognize_google(audio, language='zh-CN')
print("識(shí)別結(jié)果:", text)
except sr.UnknownValueError:
print("無法識(shí)別音頻")
except sr.RequestError as e:
print("請(qǐng)求出錯(cuò):", e)
user_input = text
# 將用戶輸入添加到對(duì)話歷史中
conversation_history.append({'role': 'user', 'content': user_input})
# 發(fā)送聊天請(qǐng)求
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=conversation_history,
max_tokens=100,
n=1,
stop=None,
temperature=0.7
)
# 獲取助手的回復(fù)
assistant_reply = response['choices'][0]['message']['content']
result = SpeechSynthesizer.call(model='sambert-zhimiao-emo-v1',
text=assistant_reply,
sample_rate=48000,
format='wav')
# 打印助手的回復(fù)
print("Assistant:", assistant_reply)
if result.get_audio_data() is not None:
with open('output.wav', 'wb') as f:
f.write(result.get_audio_data())
mixer.music.load('output.wav')
mixer.music.play()
# 將助手的回復(fù)添加到對(duì)話歷史中
conversation_history.append({'role': 'assistant', 'content': assistant_reply})
time.sleep(1)
while pygame.mixer.music.get_busy()!=True: # 在音頻播放完成之前不退出程序
pass
print(' get response: %s' % (result.get_response()))
運(yùn)行代碼,就可以的到想要得到的效果。因代理問題,最后效果會(huì)有短暫的延時(shí)。文章來源:http://www.zghlxwxcb.cn/news/detail-721161.html
總結(jié)
該案例實(shí)現(xiàn)起來不難,找準(zhǔn)如何使用才是關(guān)鍵所在,這里實(shí)現(xiàn)的用ChatGPT,也可換成文心一言等國內(nèi)大模型,其效果更好,響應(yīng)速度更快。本次的分享也就到這里,如果還有什么問題請(qǐng)各位批評(píng)指教,大家一起相互學(xué)習(xí)。文章來源地址http://www.zghlxwxcb.cn/news/detail-721161.html
到了這里,關(guān)于樹莓派Linux實(shí)現(xiàn)ChatGPT語音交互(語音識(shí)別,TTS)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!