大模型场景实战培训,提示词效果调优,大模型应用定制开发, 点击咨询
GPT-4的语音对话功能前段时间在网上火了一把,许多人被其强大的自然语言处理能力和流畅的语音交互所吸引。现在,让我们来看看如何使用类似的技术,即基于百度的ERNIE-Bot,来打造自己的语音对话功能。ERNIE-Bot是一种先进的语言理解模型,可以处理复杂的语言任务,包括语音到文本的转换和自然语言理解。
涉及技术:
- langchain Memory、Chain
- Ernie-bot
- 百度智能云语音识别: https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b
- 百度智能云语音合成: https://ai.baidu.com/ai-doc/SPEECH/plbxhh4be
依赖:
- ffmpeg
值得一提的是,在langchain构建ernie-bot多轮对话能力上,社区中已有成员对此进行了深入研究和实践: https://cloud.baidu.com/qianfandev/topic/
from langchain.chat_models import ErnieBotChat from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.memory import ConversationBufferMemory
定义一个大语言模型对象
llm = ErnieBotChat(ernie_client_id="xxxxx",
ernie_client_secret="xxxxxx", model_name='ERNIE-Bot', temperature=0.01 )
定义prompt template
template = """You are a chatbot having a conversation with a human. Please answer as briefly as possible.
{chat_history} Human: {human_input} Chatbot: """
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"], template=template
)
memory
memory = ConversationBufferMemory(llm=llm,memory_key="chat_history",return_messages=True)
chain
conversation = LLMChain(llm=llm, memory=memory,prompt=prompt)
推理
response = conversation.predict(human_input=input)
from aip import AipSpeech import tempfile import os, uuid from pydub import AudioSegment
APP_ID = ‘xxx’ API_KEY = ‘xxxxx’ SECRET_KEY = ‘xxxxxxxxx’
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def transcribe(audio):
with tempfile.TemporaryDirectory() as tempdir: print(f"Temporary directory created at {tempdir}") audio = AudioSegment.from_file(audio) new_frame_rate = 16000 new_audio = audio.set_frame_rate(new_frame_rate) random_code = uuid.uuid4() temp_audio_path = f"{tempdir}/output_audio_16000_{random_code}.wav" new_audio.export(temp_audio_path, format="wav") def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() ret = client.asr(get_file_content(temp_audio_path), 'wav', 16000, {'dev_pid': 1537}) # 注意:退出 with 块后,tempdir 及其内容会被自动删除 return ret.get('result')[0]
from pydub import AudioSegment
from pydub.playback import play
def play_voice(text):
result = client.synthesis(text, 'zh', 1, {'vol': 5}) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): with tempfile.NamedTemporaryFile(delete=True, suffix='.mp3', mode='wb') as temp_audio_file: temp_audio_file.write(result) temp_audio_file.seek(0) # 回到文件开头 # print(temp_audio_file.name) # 使用 pydub 播放音频 audio = AudioSegment.from_file(temp_audio_file.name, format="mp3") play(audio)
gradio的核心代码框架如下:
def clear_history(): # 返回一个空列表来清空聊天记录 return [], []
with gr.Blocks(css="#chatbot{height:800px} .overflow-y-auto{height:800px}") as demo:
chatbot = gr.Chatbot(elem_id="chatbot") state = gr.State([]) with gr.Row(): txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter") # 录音功能 with gr.Row(): # 得到音频文件地址 audio = gr.Audio(sources="microphone", type="filepath") with gr.Row(): clear_button = gr.Button("清空聊天记录") # 重要逻辑 txt.submit(predict, [txt, state], [chatbot, txt, state]) audio.change(process_audio, [audio, state], [chatbot, audio, state]) clear_button.click(clear_history, [], [chatbot, state])
启动gradio
demo.launch(share=False)
代码18/19行重点介绍下
txt.submit(predict, [txt, state], [chatbot, txt, state])txt.submit: 这是Gradio中Textbox组件的一个方法,用于绑定一个函数(在本例中是predict函数)到文本框的输入动作上。当用户在文本框中输入文本并提交(通常是按下回车键)时,绑定的predict函数会被触发。predict: 这是绑定到文本框提交动作的函数。这个函数会在用户提交文本后执行。[txt, state]: 这是传递给predict函数的参数列表。在这里,txt代表文本框的内容,state是一个State组件,用于在Gradio界面中维持状态。[chatbot, txt, state]: 这是predict函数执行后,其输出将被传递的组件列表。在此,函数的输出将被用来更新Chatbot组件(显示对话内容)、清空Textbox组件的文本,以及更新State组件的状态。
audio.change(process_audio, [audio, state], [chatbot, audio, state])audio.change: 这是Gradio中Audio组件的一个方法,用于将一个函数(在这个例子中是process_audio函数)绑定到音频输入的变化上。当用户通过音频组件提供新的音频输入时,绑定的process_audio函数会被触发。process_audio: 这是绑定到音频组件变化的函数。当音频输入改变时,这个函数会执行。[audio, state]: 这是传递给process_audio函数的参数列表。在这里,audio代表音频组件的输入,state仍然是用于维持状态的State组件。[chatbot, audio, state]: 这是process_audio函数执行后,其输出将被传递的组件列表。这意味着函数的输出将用于更新Chatbot组件、重置Audio组件的输入,以及更新State组件的状态。
总的来说,这两行代码将用户界面的交互(文本输入和音频输入)与相应的处理函数(predict和process_audio)关联起来,并定义了这些函数执行后如何更新界面组件。
两个函数的实现逻辑:
def play_voice(text):
result = client.synthesis(text, 'zh', 1, {'vol': 5}) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): with tempfile.NamedTemporaryFile(delete=True, suffix='.mp3', mode='wb') as temp_audio_file: temp_audio_file.write(result) temp_audio_file.seek(0) # 回到文件开头 # print(temp_audio_file.name) # 使用 pydub 播放音频 audio = AudioSegment.from_file(temp_audio_file.name, format="mp3") play(audio)
录音文件转文本的过程
def process_audio(audio, history=[]):
if audio: text = transcribe(audio) # print(text) if text is None: text="你好" responses, clear, updated_history = predict(text, history) # print(f"====={responses}") # print(f"++++{updated_history}") # 返回处理结果和 None 来清空音频输入 return responses, None, updated_history else: # print(f"------{history}") return [(u,b) for u,b in zip(history[::2], history[1::2])], None, history
调用ernie-bot对话功能
def predict(input, history=[]):
history.append(input) response = conversation.predict(human_input=input) history.append(response) # history[::2] 切片语法,每隔两个元素提取一个元素,即提取出所有的输入, # history[1::2]表示从历史记录中每隔2个元素提取一个元素,即提取出所有的输出 # zip函数把两个列表元素打包为元组的列表的方式 play_voice(response) responses = [(u,b) for u,b in zip(history[::2], history[1::2])] print("==取出输入:",history[::2]) print("==取出输出:",history[1::2]) print("组合元组:",responses) return responses, "", history
通过本文的介绍,我们探索了如何利用ERNIE-Bot来打造一个高效的语音对话功能。从设置开发环境、处理音频文件,到利用ERNIE-Bot进行语言理解和生成语音回应,每一步都是构建这一创新交互体验的关键部分。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/277766.html