Skip to content

Latest commit

 

History

History
1751 lines (1317 loc) · 66.5 KB

chapter-20.md

File metadata and controls

1751 lines (1317 loc) · 66.5 KB

搭建一个能听也能说的语音助手

在聊天框里问模型一个问题,已经很熟悉了。如果把键盘换成麦克风,直接开口问,等它把答案说出来,会是什么样?

这里会用到前面介绍过的几类模型,ASR 负责把语音转成文字,LLM 负责回答,TTS 再把文字转成声音。录音什么时候开始、用户有没有说话、历史对话怎样保存,也都要安排好。

从开口提问到听见回答,中间经过哪些步骤?

语音助手需要接收用户的语音问题,理解问题后生成回答,并通过语音将回答播放出来。这个过程主要由 ASR、LLM、TTS 三个核心模型共同完成。

ASR,先把你说的话转成文字

ASR 需要将麦克风采集到的音频信号转换为文本。

例如,用户对着麦克风说:“北京有哪些著名景点?”,麦克风采集到的是音频数据:

query.wav

LLM 不能按照普通文本的方式处理这些数据,需要先通过 ASR 进行语音识别,ASR 识别结果会作为文字输入交给后面的 LLM。

语音助手中的 ASR 不仅需要关注识别内容是否正确,还需要考虑口音、语速、环境噪声等因素。例如,同一句话在安静环境和嘈杂环境中的识别效果可能存在差异。

LLM,接过问题来回答

LLM 拿到 ASR 输出的用户问题文本,生成对应的回答文本。单轮对话中,问题进去回答出来,流程相对直接。

例如,ASR 识别得到:“北京有哪些著名景点?”,将这段文字发送给 LLM 后,模型生成回答:“北京比较著名的景点包括故宫、天坛、颐和园和八达岭长城等。”

多轮对话则不同。为了让 LLM 理解用户问题在上一轮或前几轮中的指代,需要将前几轮的用户问题和助手回答一并放入上下文。

TTS,把文字回答读出来

TTS 负责将 LLM 生成的回答转换成对应的语音,由语音助手把回答“说出来”,。

例如,针对 LLM 生成的回答:“北京比较著名的景点包括故宫、天坛、颐和园和八达岭长城等。”,利用 TTS 转为音频:

answer.wav

生成的语音可以直接通过扬声器播放,也可以保存为音频文件。

除了保证文字内容能够正确朗读,TTS 还会影响语音助手最终的听感。例如,声音是否清晰、停顿是否自然、语速是否合适,都会影响实际的交互体验。

在语音助手中,TTS 的输出方式分为非流式和流式两种。如果等 LLM 生成完整回答后再启动 TTS,用户会明显感知到等待时间。更合理的做法是流式 TTS——LLM 每生成几个字,TTS 就立即开始合成对应的音频片段并推送给播放模块,实现“边说边放”。

把录音、识别、回答和播放连起来

在实际的语音助手中,除了 ASR、LLM 和 TTS 三个核心模型,还需要音频采集、VAD 语音活动检测和音频播放等模块。各模块协同工作,将用户的语音问题转换为语音回答,并支持流式音频输出和多轮对话。完整的处理流程如下图所示。

正文配图

下面按照这条处理链路,从音频输入开始,逐步搭建一个可以在本地运行的语音助手。

动手搭一个能语音问答的助手

前面介绍了语音助手的基本处理流程。下面按照音频采集、VAD、ASR、LLM 和 TTS 的顺序,逐步实现各个功能模块,并在此基础上增加流式音频输出和多轮对话,最后将这些模块组合成一个完整的本地语音助手。

为了便于后续组合,本节会将需要加载模型的 ASR、LLM 和 TTS 封装成类,将音频采集、播放等功能封装成函数。每完成一个功能模块,都先单独进行测试,确认能够正常运行后,再继续后面的实现。

准备运行环境

安装基础依赖:

!pip3 install torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0
!pip3 install transformers accelerate modelscope
!pip3 install qwen-asr 
!pip3 install soundfile webrtcvad-wheels scipy
!pip3 install gradio
%pip install --no-deps --force-reinstall qwen-tts==0.1.1 faster-qwen3-tts==0.3.0
!pip3 install numpy==2.2.6 scipy
!pip3 install jiwer bert_score onnxruntime

结果展示:

正文配图

安装完以来后,需要点击上方的Restart重启 kernel。

正文配图

采集麦克风音频

语音助手首先需要获取用户的音频。

如果程序直接运行在本地电脑上,可以通过 sounddevice 等库访问麦克风设备。但本章使用的是 ModelScope Notebook,Python 程序实际运行在远程服务器上,服务器无法直接访问用户电脑上的麦克风。

因此,本节使用 Gradio 在浏览器中采集麦克风音频,再将音频数据传给后端程序。

音频采集有 2 种类型:

1)实时音频采集

开始采集后,会一直收集麦克风音频。代码如下:

import gradio as gr
import numpy as np

def receive_audio(stream, new_chunk):
    if new_chunk is None:
        return stream, "等待麦克风音频……"

    sample_rate, audio = new_chunk

    if audio.ndim > 1:
        audio = audio.mean(axis=1)

    audio = audio.astype(np.float32)

    if stream is None:
        stream = audio
    else:
        stream = np.concatenate([stream, audio])

    duration = len(stream) / sample_rate
    status = f"收到音频块,当前采集长度:{len(stream)},已采集:{duration:.2f}秒"

    print(status)
    return stream, status

with gr.Blocks() as demo:
    gr.Markdown("# 麦克风实时采集测试")
    gr.Markdown("点击麦克风开始录音,说话过程中可以观察音频采集状态。")

    audio_input = gr.Audio(sources=["microphone"], streaming=True, label="麦克风")
    status_output = gr.Textbox(label="采集状态", value="等待麦克风音频……")
    audio_state = gr.State(None)

    audio_input.stream(fn=receive_audio, inputs=[audio_state, audio_input], outputs=[audio_state, status_output])

demo.launch(share=True)

运行代码结果:

正文配图

打开日志打印的网页地址“http://127.0.0.1:7862”,点击“录制”,并允许浏览器使用麦克风。

正文配图

网页就会开始采集音频信息,直至手动停止。

正文配图

2)非实时音频采集

每次都需要用户手动触发,才会开始采集音频。代码如下:

import gradio as gr

# 一个简单的音频采集页面
with gr.Blocks() as demo:
    gr.Markdown("# 🎤 麦克风非实时音频采集")
    
    # 音频输入组件
    audio = gr.Audio(
    sources=["microphone"],
    type="numpy",
    streaming=False,
    label="🎤 点击「录制」说话,说完点击「停止」",
    visible=True,
    interactive=True,
    elem_classes="audio-component"
)
    
    # 显示音频信息
    audio_info = gr.Textbox(label="音频信息", lines=3)
    
    # 当录制完成时显示信息
    def show_audio_info(audio_data):
        if audio_data is None:
            return "未录制音频"
        sr, data = audio_data
        return f"采样率: {sr} Hz\n时长: {len(data)/sr:.2f} 秒\n数据形状: {data.shape}"
    
    audio.change(show_audio_info, inputs=audio, outputs=audio_info)

demo.launch()

运行代码结果:

正文配图

打开日志打印的网页地址“http://127.0.0.1:7868”,点击“录制”,并允许浏览器使用麦克风。

正文配图

然后说话即可,点击停止则结束录音。

停止后可以看到音频信息,这说明程序已经接采集到麦克风音频了。

正文配图

VAD 检测语音活动

VAD 在语音助手中,主要用于判断用户什么时候开始说话,以及什么时候结束一轮语音输入。

WebRTC VAD 的检测等级可以设置为 0、1、2、3,数字越大,对非语音声音的过滤越严格。代码如下:

下面结合采集麦克风音频进行测试:

1)实时音频采集+VAD 语音活动检测

针对实时的音频采集,VAD 主要用来监测用户是否说话了,判断语音开始和结束的时间,并将用户说话的音频裁剪出来。这里采用逐 30ms 音频帧判断是否存在语音活动,VAD 检测代码如下:

import numpy as np
import webrtcvad
from scipy.signal import resample_poly

class StreamingVAD:

    def __init__(self, sample_rate=16000, frame_ms=30, mode=2, silence_seconds=1.0):
        self.sample_rate = sample_rate
        self.frame_ms = frame_ms
        self.frame_size = int(sample_rate * frame_ms / 1000)
        self.max_silence_frames = int(silence_seconds * 1000 / frame_ms)
        self.vad = webrtcvad.Vad(mode)
        self.reset()

    def reset(self):
        self.speech_started = False
        self.silence_frames = 0
        self.audio_frames = []
        self.buffer = np.array([], dtype=np.int16)

    def process(self, audio, sample_rate):
        if audio.ndim > 1:
            audio = audio.mean(axis=1)

        if np.issubdtype(audio.dtype, np.integer):
            audio = audio.astype(np.float32) / 32768.0
        else:
            audio = audio.astype(np.float32)

        if sample_rate != self.sample_rate:
            audio = resample_poly(audio, self.sample_rate, sample_rate)

        audio = np.clip(audio, -1.0, 1.0)
        audio = (audio * 32767).astype(np.int16)

        self.buffer = np.concatenate([self.buffer, audio])

        while len(self.buffer) >= self.frame_size:
            frame = self.buffer[:self.frame_size]
            self.buffer = self.buffer[self.frame_size:]

            is_speech = self.vad.is_speech(frame.tobytes(), self.sample_rate)

            if is_speech:
                if not self.speech_started:
                    print("检测到用户开始说话", flush=True)

                self.speech_started = True
                self.silence_frames = 0
                self.audio_frames.append(frame)

            elif self.speech_started:
                self.silence_frames += 1
                self.audio_frames.append(frame)

                if self.silence_frames >= self.max_silence_frames:
                    print("检测到连续静音,本轮语音结束", flush=True)
                    return True

        return False

    def get_audio(self):
        if not self.audio_frames:
            return None

        return np.concatenate(self.audio_frames)

测试页面代码:

import gradio as gr

vad_detector = StreamingVAD(mode=2, silence_seconds=1.0)
vad_logs = []
turn_index = 0

def detect_speech(chunk):
    global vad_logs, turn_index

    if chunk is None:
        return "\n".join(vad_logs) if vad_logs else "等待语音输入……"

    sample_rate, audio = chunk
    finished = vad_detector.process(audio, sample_rate)

    if finished:
        speech_audio = vad_detector.get_audio()
        if speech_audio is not None:
            turn_index += 1
            duration = len(speech_audio) / vad_detector.sample_rate
            log = f"第{turn_index}轮:检测到有效语音,时长{duration:.2f}秒"
            vad_logs.append(log)
            print(log, flush=True)
        vad_detector.reset()

    return "\n".join(vad_logs) if vad_logs else "等待语音输入……"

with gr.Blocks() as demo:
    gr.Markdown("# 实时音频采集 + VAD语音活动检测")
    gr.Markdown("点击“录制”启动麦克风,说话结束后保持约1秒静音。")

    audio_input = gr.Audio(sources=["microphone"], type="numpy", streaming=True, label="麦克风")
    log_output = gr.Textbox(label="VAD检测日志", value="等待语音输入……", lines=6)

    audio_input.stream(fn=detect_speech, inputs=audio_input, outputs=log_output, stream_every=0.5)

demo.launch(share=True)

运行结果:

正文配图

打开日志打印的网页地址:“http://127.0.0.1:7871”,点击“录制”并允许浏览器访问麦克风,然后说话即可。点击停止后页面会显示日志,样例如下。

正文配图

2)非实时音频采集+VAD 语音活动检测

针对非实时采集的音频,VAD 主要作为前置过滤器,去除静音和环境噪声,避免 ASR 做无效识别,节省资源。系统会将 Gradio 接收到的整个音频切片,分割为若干 20 毫秒的短帧,并对每一帧进行语音/非语音状态标记。最后根据该切片中的语音帧数量与阈值的关系,判断该段音频的是否交给 ASR 处理。VAD 检测代码如下:

import webrtcvad
import numpy as np
from collections import deque

class StreamingVAD:
    def __init__(self, mode=3, silence_seconds=1.0, min_speech_seconds=0.5, 
                 energy_threshold=0.03, start_frames=3, pre_buffer_chunks=5,
                 target_sr=16000):  # 添加目标采样率
        self.vad = webrtcvad.Vad(mode)
        self.silence_seconds = silence_seconds
        self.min_speech_seconds = min_speech_seconds
        self.energy_threshold = energy_threshold
        self.start_frames = start_frames
        self.pre_buffer_chunks = pre_buffer_chunks
        self.target_sr = target_sr  # VAD 支持的采样率
        self.reset()

    def reset(self):
        self.speech_started = False
        self.audio_chunks = []
        self.pre_buffer = deque(maxlen=self.pre_buffer_chunks)
        self.speech_count = 0
        self.speech_samples = 0
        self.silence_samples = 0
        self.sample_rate = None

    def _resample(self, audio, orig_sr, target_sr):
        """重采样到目标采样率"""
        if orig_sr == target_sr:
            return audio
        # 计算重采样比例
        ratio = target_sr / orig_sr
        # 重采样
        resampled = signal.resample(audio, int(len(audio) * ratio))
        return resampled.astype(np.float32)

    def _is_speech(self, audio, sample_rate):
        try:
            # 先重采样到目标采样率
            if sample_rate != self.target_sr:
                audio = self._resample(audio, sample_rate, self.target_sr)
                sample_rate = self.target_sr
            
            # 检查音频幅度
            rms = np.sqrt(np.mean(audio ** 2) + 1e-10)
            print(f"RMS: {rms:.6f}, 阈值: {self.energy_threshold}")
            
            if rms < self.energy_threshold:
                print(f"音频太安静")
                return False
            
            # 归一化到 [-1, 1]
            max_val = np.max(np.abs(audio))
            if max_val > 0:
                audio = audio / max_val
            
            frame_size = int(sample_rate * 0.02)  # 20ms
            speech_frames = 0
            total_frames = 0
            
            # 转换为 int16
            audio_int16 = (audio * 32767).astype(np.int16)
            
            for i in range(0, len(audio) - frame_size + 1, frame_size):
                frame = audio_int16[i:i + frame_size]
                is_speech = self.vad.is_speech(frame.tobytes(), sample_rate)
                speech_frames += int(is_speech)
                total_frames += 1
                
            if total_frames == 0:
                return False
            
            ratio = speech_frames / total_frames
            print(f"语音帧比例: {ratio:.2f} ({speech_frames}/{total_frames})")
            return ratio >= 0.5
            
        except Exception as e:
            print(f"VAD _is_speech 错误: {e}")
            traceback.print_exc()
            return False

    def process(self, audio, sample_rate):
        try:
            self.sample_rate = sample_rate
            audio = np.asarray(audio)
            if audio.ndim == 2:
                audio = audio.mean(axis=1)
            audio = audio.astype(np.float32)
            
            # 归一化(如果需要)
            if np.max(np.abs(audio)) > 1.0:
                audio = audio / 32768.0
            
            is_speech = self._is_speech(audio, sample_rate)
            print(f"is_speech: {is_speech}")
            
            if not self.speech_started:
                self.pre_buffer.append(audio)
                if is_speech:
                    self.speech_count += 1
                else:
                    self.speech_count = 0
                if self.speech_count >= self.start_frames:
                    self.speech_started = True
                    self.audio_chunks.extend(list(self.pre_buffer))
                    self.speech_samples = sum(len(chunk) for chunk in self.pre_buffer)
                    self.silence_samples = 0
                return False, is_speech
                
            self.audio_chunks.append(audio)
            if is_speech:
                self.speech_samples += len(audio)
                self.silence_samples = 0
            else:
                self.silence_samples += len(audio)
                
            speech_duration = self.speech_samples / sample_rate
            silence_duration = self.silence_samples / sample_rate
            
            if silence_duration >= self.silence_seconds:
                if speech_duration >= self.min_speech_seconds:
                    return True, is_speech
                self.reset()
            return False, is_speech
            
        except Exception as e:
            print(f"VAD process 错误: {e}")
            traceback.print_exc()
            return False, False

    def get_audio(self):
        if not self.audio_chunks:
            return np.array([], dtype=np.float32)
        return np.concatenate(self.audio_chunks)

测试代码:

import gradio as gr
import numpy as np
import traceback

vad = StreamingVAD(mode=3, silence_seconds=1.0)

def test_vad(audio_data):
    try:
        if audio_data is None:
            return "❌ 没有音频数据"
        
        sr, audio = audio_data
        vad.reset()
        
        # 分块处理(每块100ms)
        chunk_size = int(sr * 0.1)  # 100ms
        is_complete = False
        speech_found = False
        
        for i in range(0, len(audio), chunk_size):
            chunk = audio[i:i+chunk_size]
            if len(chunk) < chunk_size:
                break
            is_complete, is_speech = vad.process(chunk, sr)
            if is_speech:
                speech_found = True
            if is_complete:
                break
        
        # 获取裁剪后的音频
        speech_audio = vad.get_audio()
        speech_duration = len(speech_audio) / sr if len(speech_audio) > 0 else 0
        
        result = f"""✅ 检测完成
采样率: {sr} Hz
音频长度: {len(audio)} 样本
时长: {len(audio)/sr:.2f} 秒
检测到语音: {'是 ✅' if speech_found else '否 ❌'}
触发结束: {'是' if is_complete else '否'}
裁剪后时长: {speech_duration:.2f} 秒
        """
        
        return result
        
    except Exception as e:
        return f"❌ 错误: {str(e)}\n{traceback.format_exc()}"

with gr.Blocks() as demo:
    gr.Markdown("# 🎤 非实时音频采集+VAD语音活动检测")
    
    audio_input = gr.Audio(
        sources=["microphone"],
        type="numpy",
        label="录制音频(录长一点,包含停顿)"
    )
    
    result = gr.Textbox(label="检测结果", lines=8)
    
    audio_input.change(test_vad, audio_input, result)

demo.launch(debug=True)

运行结果:

正文配图

打开日志打印的网页地址:“http://127.0.0.1:7869”,点击“录制”并允许浏览器访问麦克风,然后说话即可。点击停止后页面会显示日志,样例如下。

正文配图

ASR 语音识别

获得音频以后,下一步是将语音转换成文字。以 Qwen/Qwen3-ASR-0.6B 模型为例,ASR 实现代码如下:

import torch
from modelscope import snapshot_download
from qwen_asr import Qwen3ASRModel

class ASRService:

    def __init__(self, model_id="Qwen/Qwen3-ASR-0.6B", device="cuda:0"):
        print("正在加载ASR模型……")

        model_dir = snapshot_download(model_id)
        self.model = (
            Qwen3ASRModel.from_pretrained(
                model_dir,
                dtype=torch.bfloat16,
                device_map=device,
                max_inference_batch_size=1,
                max_new_tokens=256,
            )
        )

        print("ASR模型加载完成")

    def transcribe(self, audio_file,language="Chinese"):
        result = self.model.transcribe(audio=audio_file, language=language)
        return result[0].text

测试命令:

asr = ASRService()
text = asr.transcribe("query.wav")

print("ASR识别结果:", text)

结果展示:

正文配图

LLM 理解问题并生成回答

本节使用 Qwen/Qwen3-4B 模型进行问题理解和答案生成,模型加载和推理代码如下:

from modelscope import AutoModelForCausalLM, AutoTokenizer

class LLMService:

    def __init__(self, model_id="Qwen/Qwen3-4B"):
        print("正在加载LLM……")

        self.tokenizer = AutoTokenizer.from_pretrained(model_id)

        self.model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="auto")

        print("LLM加载完成")

    def chat(self, user_text, history=None):
        messages = [
            {
                "role": "system",
                "content": "你是一个语音助手,请用简洁、自然的语言回答问题,尽量控制在150字以内。",
            }
        ]

        if history:
            messages.extend(history)

        messages.append({"role": "user", "content": user_text})

        text = self.tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True,
            enable_thinking=False,
        )

        inputs = self.tokenizer([text], return_tensors="pt").to(self.model.device)

        generated_ids = self.model.generate(
            **inputs,
            max_new_tokens=512,
            do_sample=True,
            temperature=0.7,
            top_p=0.8,
            top_k=20,
        )

        output_ids = generated_ids[:, inputs.input_ids.shape[1]:]
        answer = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]

        return answer.strip()

将enable_thinking设置为False,关闭思考模式,更适合普通语音问答,也可以减少用户等待时间。

测试问答效果:

llm = LLMService()
answer = llm.chat("北京有哪些著名景点?")

print("回答:", answer)

正文配图

TTS 生成回答语音

本节选择 Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice 模型将 LLM 答案转为语音,CustomVoice 模型支持指定预置音色生成语音,可以根据业务需要选择合适的音色。具体实现代码如下:

import torch
from modelscope import snapshot_download
from qwen_tts import Qwen3TTSModel

class TTSService:

    def __init__(
        self,
        model_id=("Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice"),
        device="cuda:0",
        speaker="Vivian",
    ):
        print("正在加载TTS模型……")

        model_dir = snapshot_download(model_id)

        self.model = (
            Qwen3TTSModel.from_pretrained(model_dir,device_map=device,dtype=torch.bfloat16)
        )

        self.speaker = speaker

        print("TTS模型加载完成")

    def synthesize(self, text, language="Chinese"):
        wavs, sample_rate = (
         self.model.generate_custom_voice(text=text,language=language,speaker=self.speaker)
        )

        return wavs[0], sample_rate

生成语音测试代码:

import soundfile as sf

tts = TTSService()

answer = "北京有许多著名景点,如故宫、长城、颐和园、天坛、景山、北海公园、南锣鼓巷等。这些地方历史悠久,风景优美,是北京的标志性景点。"

wav, sample_rate = tts.synthesize(answer)

sf.write("tts_answer.wav", wav, sample_rate)

print("语音已保存:tts_answer.wav")
print("采样率:", sample_rate)

结果展示:

正文配图

生成音频如下,可试听:

tts_answer.wav

流式处理

等整段语音合成完毕再播放,用户等待时间较长。流式生成在推理阶段同步输出音频,边生成边播放,首帧延迟明显降低,用户交互体验更流畅。TTSService 服务流式音频输出的实现代码如下:

import torch
import numpy as np
from modelscope import snapshot_download
from faster_qwen3_tts import FasterQwen3TTS

class TTSService:

    def __init__(
        self,
        model_id=("Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice"),
        device="cuda:0",
        speaker="Vivian",
        chunk_size=4,
    ):
        print("正在加载TTS模型……")

        model_dir = snapshot_download(model_id)
        self.model = FasterQwen3TTS.from_pretrained(
            model_dir,
            device=device,
            dtype=torch.bfloat16,
            attn_implementation="sdpa",
        )

        self.speaker = speaker
        self.chunk_size = chunk_size
        print("TTS模型加载完成")

    def synthesize(self, text, language="Chinese"):
        wavs, sample_rate = (
         self.model.generate_custom_voice(text=text,language=language,speaker=self.speaker)
        )
        return wavs[0], sample_rate

    def synthesize_stream(self, text, language="Chinese", cancelled=None):
        """流式输出,逐块返回新增波形。"""
        if not text.strip():
            return
        cancelled = cancelled or (lambda: False)
        if cancelled():
            return
        stream = self.model.generate_custom_voice_streaming(
            text=text,
            language=language,
            speaker=self.speaker,
            chunk_size=self.chunk_size,
            max_new_tokens=1024,
        )
        sample_rate = None
        try:
            for audio_chunk, sr, timing in stream:
                if cancelled():
                    break
                sr = int(sr)
                if sr <= 0 or (sample_rate is not None and sample_rate != sr):
                    raise ValueError("TTS 音频块的采样率发生变化")
                sample_rate = sr
                audio_chunk = np.asarray(audio_chunk, dtype=np.float32).reshape(-1)
                if audio_chunk.size:
                    yield np.clip(np.nan_to_num(audio_chunk), -1, 1), sr
        finally:
            stream.close()

测试代码:

import numpy as np
import soundfile as sf

tts = TTSService()
text = "今天天气真不错,适合出门散步。"

chunks = []
for audio_chunk, sr in tts.synthesize_stream(text):
    chunks.append(audio_chunk)
    print(f"收到音频块,当前共 {len(chunks)} 块")

if chunks:
    full_audio = np.concatenate(chunks)
    sf.write("output.wav", full_audio, sr)
    print(f"保存完成,共 {len(chunks)} 块,总时长 {len(full_audio)/sr:.2f}s")

结果展示:

正文配图

生成音频如下,可试听:

output.wav

实现多轮语音对话

多轮对话场景中,对于存在上下文关联的问题,如果只把当前问题发给 LLM,模型无法理解指代对象。例如:

用户:北京有哪些著名景点?
助手:北京有许多著名景点,如故宫、长城、颐和园、天坛、景山、北海公园、南锣鼓巷等。这些地方历史悠久,风景优美,是北京的标志性景点。

用户:第一个什么时候去比较好?

第二轮中的“第一个”依赖上一轮回答,但系统不保存历史记录,模型无从得知指代内容。因此需要保存历史问答记录,将完整对话上下文一并送入模型。

可以将历史对话封装成ConversationManager类:

class ConversationManager:

    def __init__(self):
        self.history = []

    def get_history(self):
        return self.history

    def add_turn(self, user_text, assistant_text):
        self.history.append({"role": "user", "content": user_text})
        self.history.append({"role": "assistant", "content": assistant_text})

    def clear(self):
        self.history.clear()

会话记录保存样例:

conversation = ConversationManager()
llm = LLMService()

question1 = "北京有哪些著名景点?"

answer1 = llm.chat(question1, conversation.get_history())
conversation.add_turn(question1, answer1)
print("第一轮会话结束")


question2 = ("第一个什么时候去比较好?")  
answer2 = llm.chat(question2, conversation.get_history())  
conversation.add_turn(question2, answer2)  
print("第二轮会话结束") 

print("会话历史:", conversation.get_history())

结果展示:

正文配图

多轮对话保存的是用户问题文本和助手回答文本。下一轮对话时,再把这些历史消息与新的用户问题一起发送给 LLM。这样,语音输入和输出仍然负责用户与系统之间的交互,而对话上下文则由 LLM 使用的文字历史进行管理。

一个完整的本地语音助手

前面已经分别介绍了音频采集、VAD、ASR、LLM、TTS、流式处理和多轮对话。现在可以直接复用前面定义的类和函数,将这些模块连接成一个完整的本地语音助手,其中对已有的ConversationManager类进行了改造,扩充了用于前端展示的额外信息存储。

由于 gadio 展示限制,这里采用非实时音频采集(点击录制→上传处理)和非流式音频输出(生成完整音频后返回)的方式搭建本地语音助手。

完整代码如下:

import gradio as gr
import numpy as np
import soundfile as sf
import tempfile, os, threading, time
from datetime import datetime
import base64
import librosa
import json

os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"

class ConversationManager:
    def __init__(self): self.reset()
    def reset(self):
        self.messages, self.conversation_history = [], []
        self.current_user_text = self.current_assistant_text = self.current_audio_html = None
    def add_user_message(self, text):
        self.messages.append(("user", text, None))
        self.conversation_history.append({"role": "user", "content": text})
        self.current_user_text = text
    def add_assistant_message(self, text, audio_html=None):
        self.messages.append(("assistant", text, audio_html))
        self.conversation_history.append({"role": "assistant", "content": text})
        self.current_assistant_text, self.current_audio_html = text, audio_html
    def get_history_html(self):
        if not self.messages:
            return '<p style="color: #999; text-align: center; padding: 40px;">暂无对话记录</p>'
        parts = []
        for role, text, audio_html in self.messages:
            if role == "user":
                parts.append(f'''
                <div style="display: flex; justify-content: flex-end; margin: 6px 0;">
                    <div style="max-width: 75%; background: #e3f2fd; padding: 8px 14px; border-radius: 16px 16px 4px 16px;">
                        <div style="font-size: 12px; color: #1565c0; font-weight: bold;">👤 我</div>
                        <div style="font-size: 14px; line-height: 1.5;">{text}</div>
                    </div>
                </div>
                ''')
            else:
                parts.append(f'''
                <div style="display: flex; justify-content: flex-start; margin: 6px 0;">
                    <div style="max-width: 75%; background: #f5f5f5; padding: 8px 14px; border-radius: 16px 16px 16px 4px;">
                        <div style="font-size: 12px; color: #2e7d32; font-weight: bold;">🤖 助手</div>
                        <div style="font-size: 14px; line-height: 1.5;">{text}</div>
                        {audio_html if audio_html else ''}
                    </div>
                </div>
                ''')
        return ''.join(parts)
    def get_history_for_llm(self): return self.conversation_history.copy()
    def get_current_round(self): return len([m for m in self.messages if m[0] == "user"])

chat, logs, pending_audio, is_processing, is_waiting_for_response = (
    ConversationManager(), [], None, False, False
)
process_lock, log_lock = threading.Lock(), threading.Lock()

def add_log(msg):
    line = f"[{datetime.now().strftime('%H:%M:%S')}] {msg}"
    with log_lock:
        logs.append(line)
        if len(logs) > 50: logs.pop(0)
    print(line)

def save_temp_audio(audio, sr):
    fd, path = tempfile.mkstemp(suffix=".wav", prefix="audio_")
    os.close(fd)
    audio = np.asarray(audio, dtype=np.float32)
    max_val = np.max(np.abs(audio))
    if max_val > 0: audio = audio / max_val
    sf.write(path, audio, sr)
    return path

def get_audio_duration(audio, sr): return len(np.asarray(audio)) / sr

def create_html_audio_player(audio_path):
    if not audio_path or not os.path.exists(audio_path): return None
    try:
        with open(audio_path, 'rb') as f:
            audio_bytes = base64.b64encode(f.read()).decode('utf-8')
        return f'''
        <div style="margin-top: 6px; padding: 4px 6px; background: #f8f9fa; border-radius: 6px; border: 1px solid #e0e0e0;">
            <audio controls style="width: 100%; height: 32px;">
                <source src="data:audio/wav;base64,{audio_bytes}" type="audio/wav">
                您的浏览器不支持音频播放
            </audio>
        </div>
        '''
    except Exception as e:
        add_log(f"❌ 创建HTML播放器失败: {e}")
        return None

def process_with_yield(audio_data):
    global pending_audio, is_processing, is_waiting_for_response
    
    if is_processing or is_waiting_for_response:
        add_log("⏳ 正在处理中,请稍候...")
        yield gr.skip(), gr.skip()
        return
    
    if audio_data is None:
        yield gr.skip(), gr.skip()
        return
    
    try:
        sr, audio = audio_data
        if audio is None or len(audio) == 0:
            yield gr.skip(), gr.skip()
            return
        audio = np.asarray(audio)
        if audio.ndim == 2: audio = audio.mean(axis=1)
        duration = get_audio_duration(audio, sr)
        if duration < 0.8:
            add_log(f"⚠️ 音频太短 ({duration:.1f}秒),请说长一点")
            yield gr.skip(), gr.skip()
            return
        
        is_processing = is_waiting_for_response = True
        add_log(f"✅ 录制完成,{duration:.1f}秒")
        
        user_audio_file = save_temp_audio(audio, sr)
        add_log("🎤 开始处理...")
        add_log("🔊 ASR识别中...")
        
        try:
            user_text = asr.transcribe(user_audio_file).strip()
        except Exception as e:
            add_log(f"❌ ASR错误: {e}")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            yield gr.skip(), gr.skip()
            return
        
        if not user_text or len(user_text) < 2:
            add_log(f"⚠️ 未识别到有效文本: '{user_text}'")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            yield gr.skip(), gr.skip()
            return
        
        add_log(f"👤 我: {user_text}")
        
        # 第一步:显示用户文本
        chat.add_user_message(user_text)
        yield chat.get_history_html(), gr.update(value=None)
        
        history = chat.get_history_for_llm()
        add_log(f"📚 历史对话: {len(history)//2} 轮")
        add_log("🧠 LLM思考中...")
        
        try:
            answer = llm.chat(user_text, history=history).strip()
        except Exception as e:
            add_log(f"❌ LLM错误: {e}")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            chat.add_assistant_message(f"❌ LLM错误: {e}", None)
            yield chat.get_history_html(), gr.update(value=None)
            return
        
        if not answer:
            add_log("⚠️ LLM未生成回答")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            chat.add_assistant_message("⚠️ LLM未生成回答", None)
            yield chat.get_history_html(), gr.update(value=None)
            return
        
        add_log(f"🤖 助手: {answer}")
        add_log("🗣️ TTS生成中...")
        chunks, tts_sr = [], None
        
        try:
            for audio_chunk, sample_rate in tts.synthesize_stream(answer):
                if audio_chunk is not None and len(audio_chunk) > 0:
                    chunk = np.asarray(audio_chunk, dtype=np.float32)
                    chunks.append(chunk)
                    if tts_sr is None: tts_sr = sample_rate
        except Exception as e:
            add_log(f"❌ TTS错误: {e}")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            chat.add_assistant_message(f"❌ TTS错误: {e}", None)
            yield chat.get_history_html(), gr.update(value=None)
            return
        
        if not chunks:
            add_log("⚠️ TTS未生成音频")
            is_processing = is_waiting_for_response = False
            if os.path.exists(user_audio_file): os.remove(user_audio_file)
            chat.add_assistant_message("⚠️ TTS未生成音频", None)
            yield chat.get_history_html(), gr.update(value=None)
            return
        
        wav = np.concatenate(chunks)
        audio_path = save_temp_audio(wav, tts_sr)
        total_rounds = chat.get_current_round() + 1
        audio_html = create_html_audio_player(audio_path)
        
        # 第二步:显示助手答案 + 音频
        chat.add_assistant_message(answer, audio_html)
        
        add_log(f"✅ 第 {total_rounds} 轮对话完成,{len(wav)/tts_sr:.1f}秒")
        if os.path.exists(user_audio_file): os.remove(user_audio_file)
        is_processing = is_waiting_for_response = False
        
        yield chat.get_history_html(), gr.update(value=None)
        
    except Exception as e:
        add_log(f"❌ 处理错误: {e}")
        is_processing = is_waiting_for_response = False
        yield gr.skip(), gr.skip()

def clear_all():
    global generation_id, pending_audio, is_processing, is_waiting_for_response
    generation_id += 1
    chat.reset()
    pending_audio = None
    is_processing = is_waiting_for_response = False
    return '<p style="color: #999; text-align: center; padding: 40px;">暂无对话记录</p>', gr.update(value=None)

print("🚀 正在加载模型...")
# asr = ASRService()
# llm = LLMService()
# tts = TTSService()
print("✅ 所有模型加载完成!")

css = """
.progress-container { display: none !important; }
.gr-progress { display: none !important; }
.loading { display: none !important; }
#header-area { max-width:800px; margin:0 auto 16px auto; padding:12px 16px; background:#f5f5f5; border-radius:10px; }
#mic-area { display:flex; align-items:center; gap:12px; }
#mic-area .audio-component { flex:1; }
#mic-area .clear-button { flex-shrink:0; }
#chat-container { min-height:400px; max-height:500px; overflow-y:auto; padding:10px 14px; background:#fff; border-radius:8px; border:1px solid #e0e0e0; }
#chat-container::-webkit-scrollbar { width:5px; }
#chat-container::-webkit-scrollbar-track { background:#f1f1f1; border-radius:3px; }
#chat-container::-webkit-scrollbar-thumb { background:#c1c1c1; border-radius:3px; }
#chat-container::-webkit-scrollbar-thumb:hover { background:#a8a8a8; }
footer { display:none !important; }
"""

with gr.Blocks(css=css, theme=gr.themes.Soft(), title="语音助手") as demo:
    gr.Markdown("## 🎙️ 语音助手")
    with gr.Group(elem_id="header-area"):
        with gr.Row(elem_id="mic-area"):
            mic_audio = gr.Audio(
                sources=["microphone"],
                type="numpy",
                streaming=False,
                label="🎤 点击「录制」说话,说完点击「停止」",
                visible=True,
                interactive=True,
                elem_classes="audio-component"
            )
            clear_btn = gr.Button(
                "🗑️ 清空对话",
                variant="stop",
                size="sm",
                elem_classes="clear-button"
            )
    chat_history = gr.HTML(
        value='<p style="color: #999; text-align: center; padding: 40px;">暂无对话记录</p>',
        label="💬 对话记录",
        elem_id="chat-container"
    )
    
    mic_audio.change(
        fn=process_with_yield,
        inputs=mic_audio,
        outputs=[chat_history, mic_audio]
    )
    
    clear_btn.click(
        fn=clear_all,
        outputs=[chat_history, mic_audio],
        queue=False
    )

demo.queue(max_size=10)
demo.launch(share=True, show_error=True, debug=False)

运行结果展示:

正文配图

进入网址:http://127.0.0.1:7861。点击“录制”后开始录音,点击“停止”后就会开始解析问题、生成答案音频。

正文配图

语音助手评测

评测维度设计

语音助手的评测需要从四个相互独立的维度分别考察,每个维度对应一项或多项可计算的指标。四个维度分别为准确性、实时性、鲁棒性和交互自然度。

1)准确性

准确性衡量语音助手“说得对不对”和“答得对不对”两个层面。

ASR 字错率(WER) 是衡量语音转文字精度的硬指标。计算方法是将 ASR 输出的识别文本与人工标注的标准转写文本按最小编辑距离对齐,统计替换(S)、删除(D)、插入(I)三类错误的总数,除以标准文本总字数 N,即 WER = (S+D+I)/N。中文语音识别在实际业务中,WER 控制在 5%~15%就算可接受区间,再低当然更好,但要付出的优化成本会指数上升。

LLM 回答语义相似度评估生成回答与标准答案在语义层面的接近程度。采用 BERTScore 指标,通过预训练语言模型将生成回答和标准答案分别编码为上下文向量,计算两段文本中每个 token 向量的余弦相似度,再综合得到整体相似性分数。BERTScore 取值范围为 0 到 1,分数越接近 1 表示语义越一致。该指标相比传统的 BLEU 或 ROUGE,对同义表达具有更好的容忍度。对于无法自动判定的开放性问题,可辅以人工评分(5 分制)作为补充。

2)耗时

耗时衡量语音助手各阶段及整体的处理速度,直接反映系统的计算效率。

端到端总耗时是从 VAD 检测到用户语音结束(t_vad_end)到 TTS 完成全部音频输出(t_tts_end)之间的时间间隔,即 T = t_tts_end − t_vad_end。该指标反映了用户从结束发言到获得完整语音回答的完整等待时间。

各阶段独立耗时将端到端总耗时拆解为四个子阶段的分别耗时:

  • VAD 耗时:从音频输入到完成语音活动检测的时间
  • ASR 耗时:从语音段提取到完成文字识别的时间
  • LLM 耗时:从用户文本输入到完成回答生成的时间
  • TTS 耗时:从回答文本输入到完成全部音频合成的时间

分别记录各阶段的起止时间戳,便于定位系统瓶颈。四个子阶段耗时的加和即为端到端总耗时。

3)鲁棒性

鲁棒性考察语音助手在非理想条件下的性能衰减程度。

评测时需构建多组对照测试集,各组包含相同的问句集合,但施加不同的干扰条件,并将各条件下的评测结果与基线条件(安静环境、标准普通话、正常语速)进行对比,以性能衰减幅度作为鲁棒性的量化依据。

噪声环境:在原始语音上叠加三类背景噪声(白噪声、街道噪声、多说话人噪声),每种噪声按三个信噪比档位(0dB、10dB、20dB)分别施加,记录各档位下的 WER 和端到端延迟,观察噪声对识别精度和响应速度的影响。

口音差异:采集或合成带有不同方言口音(如四川话、东北话、粤式普通话)的测试语音,与标准普通话测试集的结果进行对比,WER 的差值直接反映 ASR 在各口音方向上的偏倚程度。

语速变化:通过语音信号处理工具将测试语音加速至 1.3 倍和减速至 0.7 倍,观察 WER 随语速变化而产生的波动。

4)交互自然度

交互自然度评估的是多轮对话场景下语音助手的行为是否连贯、顺畅。

VAD 误断率包含两类错误:误触发(用户未说话时 VAD 判定为有语音)和漏检(用户说话时 VAD 未能检测到)。误触发会导致助手在静默状态下意外开始录音和处理,漏检则会导致用户语音被截断,两者均影响交互体验。评测时在真实对话场景中连续运行 30 分钟,统计 VAD 判定状态与人工标注的真实语音活动之间的不一致帧数占总帧数的比例。

多轮对话上下文保持能力:测试语音助手能否在连续 3~5 轮对话中正确指代上文提到的实体和意图。例如用户依次说“今天北京天气怎么样”“那上海呢”“两个地方哪个更冷”,考察第二轮的“那”和第三轮的“两个地方”能否被正确解析。该指标无法自动计算,需人工对照对话记录逐轮判定上下文引用是否正确,以正确轮次占总轮次的比例表示。

TTS 自然度 MOS 分采用平均意见分(Mean Opinion Score)方法评估合成语音的自然程度。邀请不少于 10 名听音人对 TTS 生成的语音样本进行 5 分制主观打分(5 分=与真人无异,1 分=完全机械声),取所有打分的算术平均值。测试样本需涵盖陈述句、疑问句、感叹句和长短句四种类型,每类不少于 5 条,以避免单一文本类型对评分的偏差。

四个维度的全部指标汇总如下表所示:

维度

指标

计算方式

数值类型

是否支持自动化评测

准确性

ASR WER

(S+D+I)/N

百分比,越低越好

是

准确性

LLM 语义相似度

BERTScore

0~1,越高越好

是

耗时

端到端总耗时

t_tts_end − t_vad_end

毫秒,越低越好

是

耗时

VAD 耗时

t_vad_end − t_vad_start

毫秒,越低越好

是

耗时

ASR 耗时

t_asr_end − t_asr_start

毫秒,越低越好

是

耗时

LLM 耗时

t_llm_end − t_llm_start

毫秒,越低越好

是

耗时

TTS 耗时

t_tts_end − t_tts_start

毫秒,越低越好

是

鲁棒性

各条件下 WER 变化

施扰结果 − 基线结果

差值(pp),越小越鲁棒

是

交互自然度

VAD 误断率

不一致帧数 / 总帧数

百分比,越低越好

是

交互自然度

上下文保持准确率

正确指代轮次 / 总轮次

百分比,越高越好

否

交互自然度

TTS 自然度 MOS

多人打分的算术均值

1~5,越高越好

否

自动化评测脚本

自动化评测脚本的核心任务是:读取标准测试集,对每条测试音频依次执行 VAD、ASR、LLM、TTS 四个阶段,记录每阶段的耗时和中间结果,最后与标准答案比对,生成量化评测报告。

1)测试集结构设计

测试集以 JSON 格式组织,存放于 /mnt/workspace/ 目录下。每条测试样本包含以下字段:

{
  "samples": [
    {
      "id": "sample_001",
      "audio_path": "/mnt/workspace/query.wav",
      "reference_text": "北京有哪些著名景点",
      "reference_answer": "北京有许多著名景点,如故宫、长城、颐和园、天坛、景山、北海公园、南锣鼓巷等。这些地方历史悠久,风景优美,是北京的标志性景点。",
      "category": "weather",
      "noise_type": "clean",
      "speaker_accent": "standard"
    }
  ]
}

其中 reference_text 为 ASR 阶段的标准转写文本,用于计算 WER;reference_answer 为 LLM 阶段的标准回答,用于计算语义相似度。

测试音频文件的采样率统一为 16000 Hz,单声道,时长控制在 2~8 秒之间。若需要测试鲁棒性,可在 noise_type 和 speaker_accent 字段中标注干扰条件。

2)自动化评测

构建评测执行器 AudioEvaluator 接收音频文件路径,依次调用 VAD、ASR、LLM、TTS 四个模块,记录各阶段的起始和结束时间戳,保存中间输出,并计算 WER 和 BERTScore 指标。 遍历测试集所有样本,调用执行器逐条处理,汇总统计结果。评测代码如下:

import os
import json
import time
import tempfile
import traceback
from pathlib import Path
from typing import Dict
from collections import defaultdict

import numpy as np
import soundfile as sf
import librosa
from jiwer import wer
import torch
from transformers import AutoTokenizer, AutoModel

# 使用 modelscope 加载 BERT 模型(会自动下载)
from modelscope import AutoTokenizer, AutoModel

def compute_bert_score(pred_text: str, ref_text: str, model, tokenizer) -> float:
    """
    使用本地 BERT 模型计算语义相似度(简化版 BERTScore)
    """
    if not pred_text or not ref_text:
        return 0.0
    
    # 编码
    pred_tokens = tokenizer(pred_text, return_tensors="pt", truncation=True, max_length=512)
    ref_tokens = tokenizer(ref_text, return_tensors="pt", truncation=True, max_length=512)
    
    with torch.no_grad():
        pred_outputs = model(**pred_tokens)
        ref_outputs = model(**ref_tokens)
    
    # 获取最后一层的隐藏状态
    pred_embeds = pred_outputs.last_hidden_state.squeeze(0)
    ref_embeds = ref_outputs.last_hidden_state.squeeze(0)
    
    # 计算 token 级别余弦相似度(取平均)
    pred_norm = torch.nn.functional.normalize(pred_embeds, p=2, dim=1)
    ref_norm = torch.nn.functional.normalize(ref_embeds, p=2, dim=1)
    
    # 计算余弦相似度矩阵
    sim_matrix = torch.matmul(pred_norm, ref_norm.T)
    
    # 取每个预测 token 的最佳匹配,然后取平均
    max_sim, _ = sim_matrix.max(dim=1)
    score = max_sim.mean().item()
    
    return score

class AudioEvaluator:
    def __init__(self, vad, asr, llm, tts, bert_model, bert_tokenizer):
        self.vad = vad
        self.asr = asr
        self.llm = llm
        self.tts = tts
        self.bert_model = bert_model
        self.bert_tokenizer = bert_tokenizer
    
    def evaluate_single(self, audio_path: str) -> Dict:
        result = {
            "audio_path": audio_path,
            "stages": {},
            "asr_text": "",
            "llm_answer": "",
            "status": "success",
            "error_detail": ""
        }
        
        try:
            # 检查音频文件是否存在
            if not os.path.exists(audio_path):
                result["status"] = "音频文件不存在"
                result["error_detail"] = f"文件路径: {audio_path}"
                return result
            
            # 加载音频
            try:
                audio, sr = sf.read(audio_path)
            except Exception as e:
                result["status"] = "音频加载失败"
                result["error_detail"] = f"{e}\n{traceback.format_exc()}"
                return result
            
            if sr != 16000:
                try:
                    audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
                    sr = 16000
                except Exception as e:
                    result["status"] = "音频重采样失败"
                    result["error_detail"] = f"{e}\n{traceback.format_exc()}"
                    return result
            
            # ---------- VAD 阶段 ----------
            t0 = time.perf_counter()
            try:
                # 重置 VAD 状态
                self.vad.reset()
                
                # 分块处理(每块100ms)
                chunk_size = int(sr * 0.1)
                is_complete = False
                speech_found = False
                
                for i in range(0, len(audio), chunk_size):
                    chunk = audio[i:i+chunk_size]
                    if len(chunk) < chunk_size:
                        break
                    is_complete, is_speech = self.vad.process(chunk, sr)
                    if is_speech:
                        speech_found = True
                    if is_complete:
                        break
                
                # 获取裁剪后的语音音频
                speech_audio = self.vad.get_audio()
                
                # 如果检测到语音,使用裁剪后的音频
                if speech_found and len(speech_audio) > 0:
                    audio = speech_audio
                    
            except Exception as e:
                result["status"] = f"VAD错误: {e}"
                result["error_detail"] = traceback.format_exc()
                return result
            t1 = time.perf_counter()
            result["stages"]["vad"] = (t1 - t0) * 1000
            
            # ---------- ASR 阶段 ----------
            t0 = time.perf_counter()
            try:
                with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
                    sf.write(tmp.name, audio, sr)
                    tmp_path = tmp.name
                asr_text = self.asr.transcribe(tmp_path).strip()
                os.unlink(tmp_path)
            except Exception as e:
                result["status"] = f"ASR错误: {e}"
                result["error_detail"] = traceback.format_exc()
                return result
            t1 = time.perf_counter()
            result["stages"]["asr"] = (t1 - t0) * 1000
            result["asr_text"] = asr_text
            
            if not asr_text or len(asr_text) < 1:
                result["status"] = "ASR结果为空"
                result["error_detail"] = f"asr_text: '{asr_text}'"
                return result
            
            # ---------- LLM 阶段 ----------
            t0 = time.perf_counter()
            try:
                llm_answer = self.llm.chat(asr_text, history=[]).strip()
            except Exception as e:
                result["status"] = f"LLM错误: {e}"
                result["error_detail"] = traceback.format_exc()
                return result
            t1 = time.perf_counter()
            result["stages"]["llm"] = (t1 - t0) * 1000
            result["llm_answer"] = llm_answer
            
            if not llm_answer:
                result["status"] = "LLM回答为空"
                result["error_detail"] = f"llm_answer: '{llm_answer}'"
                return result
            
            # ---------- TTS 阶段 ----------
            t0 = time.perf_counter()
            try:
                chunks = []
                tts_sr = None
                for chunk, sr_chunk in self.tts.synthesize_stream(llm_answer):
                    if chunk is not None and len(chunk) > 0:
                        chunks.append(np.asarray(chunk, dtype=np.float32))
                        if tts_sr is None:
                            tts_sr = sr_chunk
                if not chunks:
                    result["status"] = "TTS未生成音频"
                    result["error_detail"] = "TTS返回空chunks"
                    return result
            except Exception as e:
                result["status"] = f"TTS错误: {e}"
                result["error_detail"] = traceback.format_exc()
                return result
            t1 = time.perf_counter()
            result["stages"]["tts"] = (t1 - t0) * 1000
            
            result["total_time"] = sum(result["stages"].values())
            
        except Exception as e:
            result["status"] = f"未知错误: {e}"
            result["error_detail"] = traceback.format_exc()
        
        return result

def run_batch_evaluation(test_set_path: str, evaluator: AudioEvaluator) -> Dict:
    with open(test_set_path, 'r', encoding='utf-8') as f:
        test_set = json.load(f)
    
    samples = test_set["samples"]
    total = len(samples)
    
    all_results = []
    stage_times = defaultdict(list)
    wer_list = []
    bert_scores = []
    e2e_latencies = []
    errors = []
    
    for idx, sample in enumerate(samples):
        print(f"评测进度: {idx+1}/{total} - {sample['id']}")
        
        result = evaluator.evaluate_single(sample["audio_path"])
        result["id"] = sample["id"]
        result["reference_text"] = sample["reference_text"]
        result["reference_answer"] = sample["reference_answer"]
        result["category"] = sample.get("category", "unknown")
        result["noise_type"] = sample.get("noise_type", "clean")
        result["speaker_accent"] = sample.get("speaker_accent", "standard")
        result["speed_factor"] = sample.get("speed_factor", 1.0)
        
        # 打印错误详情
        if result["status"] != "success":
            print(f"❌ 样本 {sample['id']} 失败: {result['status']}")
            print(f"   详情: {result.get('error_detail', '无详细信息')}")
            errors.append(result)
            all_results.append(result)
            continue
        
        print(f"✅ 样本 {sample['id']} 成功")
        
        # 计算 WER
        wer_value = wer(sample["reference_text"], result["asr_text"])
        result["wer"] = wer_value
        wer_list.append(wer_value)
        
        # 计算 BERTScore(使用本地 modelscope 加载的模型)
        try:
            score = compute_bert_score(
                result["llm_answer"], 
                sample["reference_answer"],
                evaluator.bert_model,
                evaluator.bert_tokenizer
            )
            result["bert_score"] = score
            bert_scores.append(score)
        except Exception as e:
            print(f"⚠️ BERTScore计算失败: {e}")
            result["bert_score"] = None
        
        e2e_latencies.append(result["total_time"])
        
        for stage, duration in result["stages"].items():
            stage_times[stage].append(duration)
        
        all_results.append(result)
    
    wer_by_noise = {}
    wer_by_accent = {}
    wer_by_speed = {}
    baseline_wer = None
    
    for r in all_results:
        if r["status"] != "success":
            continue
        noise = r.get("noise_type", "clean")
        wer_by_noise.setdefault(noise, []).append(r["wer"])
        accent = r.get("speaker_accent", "standard")
        wer_by_accent.setdefault(accent, []).append(r["wer"])
        speed = str(r.get("speed_factor", 1.0))
        wer_by_speed.setdefault(speed, []).append(r["wer"])
        
        if noise == "clean" and accent == "standard" and r.get("speed_factor", 1.0) == 1.0:
            baseline_wer = r["wer"]
    
    robustness_results = {}
    for noise, wers in wer_by_noise.items():
        if noise == "clean":
            continue
        mean_wer = np.mean(wers)
        robustness_results[f"noise_{noise}"] = {
            "mean_wer": mean_wer,
            "delta_from_baseline": mean_wer - baseline_wer if baseline_wer is not None else None,
            "count": len(wers)
        }
    for accent, wers in wer_by_accent.items():
        if accent == "standard":
            continue
        mean_wer = np.mean(wers)
        robustness_results[f"accent_{accent}"] = {
            "mean_wer": mean_wer,
            "delta_from_baseline": mean_wer - baseline_wer if baseline_wer is not None else None,
            "count": len(wers)
        }
    for speed, wers in wer_by_speed.items():
        if speed == "1.0":
            continue
        mean_wer = np.mean(wers)
        robustness_results[f"speed_{speed}x"] = {
            "mean_wer": mean_wer,
            "delta_from_baseline": mean_wer - baseline_wer if baseline_wer is not None else None,
            "count": len(wers)
        }
    
    summary = {
        "total_samples": total,
        "success_count": len([r for r in all_results if r["status"] == "success"]),
        "error_count": len(errors),
        "errors": errors,
        "wer": {
            "mean": np.mean(wer_list) if wer_list else None,
            "std": np.std(wer_list) if wer_list else None,
            "min": np.min(wer_list) if wer_list else None,
            "max": np.max(wer_list) if wer_list else None
        },
        "bert_score": {
            "mean": np.mean([s for s in bert_scores if s is not None]) if bert_scores else None,
            "std": np.std([s for s in bert_scores if s is not None]) if bert_scores else None,
            "min": np.min([s for s in bert_scores if s is not None]) if bert_scores else None,
            "max": np.max([s for s in bert_scores if s is not None]) if bert_scores else None
        },
        "e2e_latency_ms": {
            "mean": np.mean(e2e_latencies) if e2e_latencies else None,
            "p50": np.percentile(e2e_latencies, 50) if e2e_latencies else None,
            "p90": np.percentile(e2e_latencies, 90) if e2e_latencies else None,
            "p99": np.percentile(e2e_latencies, 99) if e2e_latencies else None
        },
        "stage_times_ms": {
            stage: {
                "mean": np.mean(times),
                "std": np.std(times),
                "p50": np.percentile(times, 50),
                "p90": np.percentile(times, 90),
                "p99": np.percentile(times, 99)
            }
            for stage, times in stage_times.items()
        },
        "robustness": robustness_results,
        "details": all_results
    }
    
    return summary

# ============================================================
# 在 Jupyter Notebook 中直接运行
# ============================================================

print("🚀 加载模型...")

# 1. 加载 VAD
# vad = StreamingVAD(mode=3, silence_seconds=1.0)

# # 2. 加载 ASR
# asr = ASRService()

# # 3. 加载 LLM
# llm = LLMService()

# # 4. 加载 TTS
tts = TTSService()

# 5. 加载 BERT 模型(使用 modelscope)
print("📚 加载 BERT 模型...")
bert_model_name = "google-bert/bert-base-chinese"
bert_tokenizer = AutoTokenizer.from_pretrained(bert_model_name)
bert_model = AutoModel.from_pretrained(bert_model_name)
bert_model.eval()
print("✅ BERT 模型加载完成")

print("✅ 所有模型加载完成")

# 创建评测执行器
evaluator = AudioEvaluator(vad, asr, llm, tts, bert_model, bert_tokenizer)

# 设置测试集路径
TEST_SET_PATH = "/mnt/workspace/test.json"

# 加载测试集
print(f"📂 加载测试集: {TEST_SET_PATH}")
with open(TEST_SET_PATH, 'r', encoding='utf-8') as f:
    test_set = json.load(f)

# 执行评测
print(f"开始评测 {len(test_set['samples'])} 条样本...")
summary = run_batch_evaluation(TEST_SET_PATH, evaluator)

# 打印结果摘要
print("\n" + "=" * 60)
print("自动化评测结果摘要")
print("=" * 60)
print(f"样本总数: {summary['total_samples']}")
print(f"成功数: {summary['success_count']} | 失败数: {summary['error_count']}")

if summary["wer"]["mean"] is not None:
    print(f"\n📊 ASR WER: {summary['wer']['mean']*100:.2f}% ± {summary['wer']['std']*100:.2f}%")

if summary["bert_score"]["mean"] is not None:
    print(f"📊 LLM BERTScore: {summary['bert_score']['mean']:.3f} ± {summary['bert_score']['std']:.3f}")

if summary["e2e_latency_ms"]["mean"] is not None:
    print(f"⏱️  端到端耗时: {summary['e2e_latency_ms']['mean']:.1f} ms (P50: {summary['e2e_latency_ms']['p50']:.1f} ms, P90: {summary['e2e_latency_ms']['p90']:.1f} ms)")

print("\n⏱️  各阶段耗时 (均值 ± 标准差):")
for stage, stats in summary["stage_times_ms"].items():
    print(f"  {stage.upper()}: {stats['mean']:.1f} ± {stats['std']:.1f} ms")

if summary["robustness"]:
    print("\n🛡️  鲁棒性 (各条件下WER劣化):")
    for cond, stats in summary["robustness"].items():
        if stats["delta_from_baseline"] is not None:
            print(f"  {cond}: +{stats['delta_from_baseline']*100:.2f}% (WER={stats['mean_wer']*100:.2f}%)")

if summary["errors"]:
    print("\n❌ 失败样本详情:")
    for err in summary["errors"]:
        print(f"  - {err['id']}: {err['status']}")
        if err.get("error_detail"):
            detail = err["error_detail"][:500]
            print(f"    详情: {detail}...")

print("=" * 60)

# 保存报告到文件
with open("evaluation_result.json", "w", encoding="utf-8") as f:
    json.dump(summary, f, ensure_ascii=False, indent=2)
print("📊 报告已保存至 evaluation_result.json")

结果展示:

正文配图

本章代码及相关文件见:https://www.modelscope.cn/gallery/liucong/59e8531d-ec1b-4a83-bf3e-fe463e3fdfa2