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
相关推荐
搬砖的小码农_Sky1 小时前
AI Agent:macOS Sequoia 部署 OpenClaw 完整教程
人工智能·macos·ai·人机交互
无心水2 小时前
【Harness:设计规范】15、Harness 成熟度模型(H0-H3):你的 AI 智能体在第几层
人工智能·设计规范·openclaw·养龙虾·harness·hermes·honcho
Raink老师8 小时前
【AI面试临阵磨枪-79】实时数据 RAG:订单、商家、物流、天气、动态库存
人工智能·面试·职场和发展
脑极体8 小时前
点亮星河AI+鸿蒙,一座艺术场馆的日神觉醒
人工智能·华为·harmonyos
Cosolar8 小时前
Chroma向量库面试学习指南
数据库·人工智能·面试·职场和发展·数据库架构
BUG指挥官8 小时前
Claude Code的自动化编程
人工智能
意图共鸣8 小时前
意图共鸣科技《认知智能白皮书》——感知与执行分离:认知架构(CA)如何重塑大模型底层结构
人工智能·架构
等一个人的@8 小时前
让数据自己开口:数睿通智库新增智能问数模块
人工智能·自然语言处理
ZGi.ai8 小时前
人工审查节点:让自动化工作流多一步人工把关
运维·人工智能·自动化·人机协同·智能体工作流·人工审查
王莎莎-MinerU9 小时前
MinerU 深度技术解析:从架构原理到生产部署的全面指南
css·人工智能·自然语言处理·架构·ocr·个人开发