WeNet语音识别对通义千问(Qwen-72B-Chat Bot)调用,首先通过WeNet将用户的语音输入转录为文本,然后将此文本输入通用问答模型以获取答案。
WeNet语音识别部分: 使用WeNet库将录制的语音转换为文本。通过载入中文模型(chs_model)并使用其功能,对录制的语音进行转录处理。生成的文本作为用户输入被传递到下一步。
Qwen-72B-Chat Bot交互部分: 利用Dashscope库实现与Qwen-72B-Chat Bot的交互。根据用户的文本输入与Chat Bot进行交互,发送用户输入的文本并接收Chat Bot的回复。这里的逻辑在model_chat函数中完成,通过Generation.call()函数向Chat Bot发送消息并获取回复。
Gradio界面设计: Gradio库用于创建用户界面,包括麦克风录音输入、文本框显示以及清除历史和设置系统功能的按钮。在界面设计中,使用了Microphone、Textbox、Button和Chatbot等组件,允许用户进行语音输入并查看对话的交互结果。
整个代码的目的是提供一个基于Gradio的界面,使用户能够通过语音与Qwen-72B-Chat Bot进行交互,并展示对话历史、系统状态等信息。
这样的集成将语音识别和聊天机器人交互结合在一起,为用户提供了一个使用简单且直观的界面,以便通过语音进行问题提问与回答。
实现代码
import os
os.system('pip install dashscope')
os.system('pip install soundfile')
import gradio as gr
from http import HTTPStatus
import dashscope
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role
from typing import List, Optional, Tuple, Dict
from urllib.error import HTTPError
import wenet
import soundfile as sf
default_system = 'You are a helpful assistant.'
chs_model = wenet.load_model('chinese')
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
dashscope.api_key = YOUR_API_TOKEN
History = List[Tuple[str, str]]
Messages = List[Dict[str, str]]
def clear_session() -> History:
return []
def modify_system_session(system: str) -> str:
if system is None or len(system) == 0:
system = default_system
return system, system, []
def history_to_messages(history: History, system: str) -> Messages:
messages = [{'role': Role.SYSTEM, 'content': system}]
for h in history:
messages.append({'role': Role.USER, 'content': h[0]})
messages.append({'role': Role.ASSISTANT, 'content': h[1]})
return messages
def messages_to_history(messages: Messages) -> Tuple[str, History]:
assert messages[0]['role'] == Role.SYSTEM
system = messages[0]['content']
history = []
for q, r in zip(messages[1::2], messages[2::2]):
history.append([q['content'], r['content']])
return system, history
def model_chat(audio: Tuple[int, List[int]], history: Optional[History], system: str
) -> Tuple[str, str, History]:
path = "recorded_audio.wav"
sf.write(path, audio[1], audio[0])
query = chs_model.transcribe(path)['text']
if query is None:
query = ''
if history is None:
history = []
messages = history_to_messages(history, system)
messages.append({'role': Role.USER, 'content': query})
gen = Generation.call(
model = "qwen-72b-chat",
messages=messages,
result_format='message',
stream=True
)
for response in gen:
if response.status_code == HTTPStatus.OK:
role = response.output.choices[0].message.role
response = response.output.choices[0].message.content
system, history = messages_to_history(messages + [{'role': role, 'content': response}])
yield history, system
else:
raise HTTPError('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
with gr.Blocks() as demo:
gr.Markdown(""""""
)
gr.Markdown("""WeNet语音识别+Qwen-72B-Chat Bot """)
textbox = gr.Microphone(label="录音")
with gr.Row():
with gr.Column(scale=3):
system_input = gr.Textbox(value=default_system, lines=1, label='System')
with gr.Column(scale=1):
modify_system = gr.Button("️ 设置system并清除历史对话", scale=2)
system_state = gr.Textbox(value=default_system, visible=False)
chatbot = gr.Chatbot(label='Qwen-72B-Chat')
with gr.Row():
clear_history = gr.Button(" 清除历史对话")
sumbit = gr.Button(" 发送")
sumbit.click(model_chat,
inputs=[textbox, chatbot, system_state],
outputs=[chatbot, system_input],
concurrency_limit=10)
clear_history.click(fn=clear_session,
inputs=[],
outputs=[chatbot],
concurrency_limit=10)
modify_system.click(fn=modify_system_session,
inputs=[system_input],
outputs=[system_state, system_input, chatbot],
concurrency_limit=10)
demo.queue(api_open=False).launch(height=800, share=False)
依赖文件 requiements.txt
wenet @ git+https://github.com/wenet-e2e/wenet