WeNet语音识别调用通义千问

WeNet语音识别调用通义千问

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进行交互,并展示对话历史、系统状态等信息。

这样的集成将语音识别和聊天机器人交互结合在一起,为用户提供了一个使用简单且直观的界面,以便通过语音进行问题提问与回答。

实现代码

python 复制代码
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("""<p align="center"><img src="https://modelscope.cn/api/v1/models/qwen/Qwen-VL-Chat/repo?Revision=master&FilePath=assets/logo.jpg&View=true" style="height: 80px"/><p>""")
    gr.Markdown("""<center><font size=8>WeNet语音识别+Qwen-72B-Chat Bot👾</center>""")

    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

python 复制代码
wenet @ git+https://github.com/wenet-e2e/wenet
相关推荐
打工仔折腾 AI4 分钟前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
逐米时代25 分钟前
从试点验证到协同深化:制造业AI转型三年路线图设计方法
人工智能
GlobalInfo31 分钟前
全球及中国风电叶片检测机器人行业研究报告(2026版):市场现状、行业前景与占有率分析
运维·网络·人工智能·机器人
stormzhangV1 小时前
AI 越强,失业越严重
人工智能·aigc
夏文强2 小时前
Rerank 与混合检索:怎么让 RAG 从「能用」变成「好用」
人工智能·大模型·向量数据库·rag·检索增强生成
救救孩子把2 小时前
AI面试八股文-23_23-Agent可观测性与生产监控面试题
人工智能·面试·职场和发展·agent·langsmith·langfuase
IT_陈寒2 小时前
Java静态变量初始化坑得我头皮发麻
前端·人工智能·后端
知行产研2 小时前
白马山领跑、南山矿扩编 31 台,安徽露天矿无人驾驶进入规模化阶段
人工智能
FinelyYang2 小时前
考试系统简答题 AI 阅卷:覆盖度驱动、异步评分与人机协同落地实践
java·大数据·人工智能
伍树明2 小时前
mini-swe-agent 本地部署+效果评测记录
人工智能