基于大模型实现语音转文字应用
概述
本文介绍如何使用 Whisper 大模型结合 faster-whisper 和 Gradio 构建一个支持实时转录、多语言识别及 AI 润色的语音转文字应用。该项目展示了从模型加载到前端交互的完整流程,适用于本地部署或轻量级服务场景。
主要功能
- 实时音频转录:通过麦克风录音并进行实时的语音识别。
- 音频文件上传:支持上传音频或视频文件进行离线转录。
- 多语言支持:支持中文、英语、法语、西班牙语等多种语言切换。
- 字幕生成:可选输出 SRT 等字幕格式。
- AI 文本润色:集成 LLM 接口对识别结果进行纠错和语句优化。
环境配置与依赖安装
首先确保 Python 环境已就绪,并安装以下核心依赖:
faster-whisper:高效的 Whisper 推理库。gradio:快速构建 Web UI 的框架。zhconv:中文简繁转换工具(可选)。av:音视频处理库。requests:用于调用外部 AI 接口。
安装命令:
pip install faster-whisper gradio zhconv av requests
硬件检测与模型加载
为提升性能,程序会检测 CUDA 是否可用。若检测到 GPU,则加载量化后的 float16 模型;否则使用 CPU 模式下的 int8 量化模型。
import subprocess
from faster_whisper import WhisperModel
def check_cuda_available():
try:
result = subprocess.run(['nvidia-smi'], capture_output=True, text=True)
return result.returncode == 0
except FileNotFoundError:
return False
cuda_available = check_cuda_available()
model_path = "./models/faster-whisper-large-v2"
if cuda_available:
model = WhisperModel(model_size_or_path=model_path, device="cuda", compute_type="float16")
else:
model = WhisperModel(model_size_or_path=model_path, device="cpu", compute_type="int8")
实时录音与转录逻辑
实时转录涉及音频流的处理、语音活动检测(VAD)以及分块识别。
1. 音频采集与队列管理
录音数据被写入队列,后台线程负责消费队列数据。
2. VAD 语音分段
使用 Silero VAD 模型检测有效语音片段,过滤静音噪声。
3. 转录处理流程
关键代码如下:
import threading
import numpy as np
def start_recording():
global recording, total_frames, text_arr
recording = True
total_frames = np.array([], dtype=np.float32)
text_arr = []
threading.Thread(target=transcribe_process, daemon=True).start()
def transcribe_process():
global recording
while recording:
time.sleep(0.5)
if not data_queue.empty():
datas = [data_queue.get() for _ in range(data_queue.qsize())]
audio_data = resample_audio(np.concatenate(datas), 16000)
audio_data = audio_data.astype(np.float32) / 32768.0
total_frames = np.concatenate((total_frames, audio_data))
# 获取语音时间戳
speech_chunks = get_speech_timestamps(total_frames, vad_parameters)
if speech_chunks:
transcribe_frames = collect_chunks(total_frames, [speech_chunks[0]])
result = transcribe(transcribe_frames)
if text_arr:
text_arr.pop()
text_arr.append(result)
多语言与字幕支持
应用允许用户在界面选择输出语言,并可选择是否生成字幕格式。
language_arr = ["zh", "en", "fr", "es"]
language_label = ["中文", "英语", "法语", "西班牙语"]
output_type_checkbox = gr.Checkbox(label="字幕格式", value=False, interactive=True)
AI 文本润色功能
为了修正识别错误(如同音字、断句问题),可调用大模型 API 对文本进行二次处理。
def ai_summary(text):
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer <YOUR_TOKEN>'}
sys_prompt = "你是一个专业的文本校对助手,请修正错别字并优化句子流畅度。"
data = {
"messages": [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": text}
],
"model": "gpt-4o-mini"
}
response = requests.post(ai_service_url, headers=headers, json=data)
ai_text = ''.join([json.loads(line)["choices"][0]["delta"].get("content", '') for line in response.iter_lines() if line])
return ai_text
用户界面实现
使用 Gradio Blocks 构建交互界面,包含录音控件、文件上传、参数调节及结果显示区域。
with gr.Blocks() as iface:
gr.Markdown("# 语音转文字应用")
with gr.Row():
input_record = gr.Audio(label="实时转录", sources=["microphone"], streaming=True)
upload_file = gr.File(label="上传音频或视频")
with gr.Column():
beam_size_slider = gr.Slider(2, 10, step=1.0, value=5, label="Beam Size")
language_selector = gr.Dropdown(language_label, type="index", value=0, label="输出语言")
output_type_checkbox = gr.Checkbox(label="字幕格式", value=False)
with gr.Row():
output_text = gr.Textbox(label="转录结果", interactive=True)
summary_button = gr.Button("AI 润色", variant="primary")
summary_output = gr.Textbox(label="AI 润色结果", interactive=True)
summary_button.click(ai_summary, inputs=output_text, outputs=summary_output)
upload_file.upload(file_uploaded, inputs=upload_file, outputs=[play_audio, output_text])
input_record.change(input_audio_change, inputs=input_record)
input_record.start_recording(start_recording, outputs=output_text)
input_record.stop_recording(stop_recording, outputs=play_audio)
iface.launch()
优化与部署建议
1. 内存管理
在处理长音频时,注意及时清理 total_frames 数组,避免内存溢出。对于实时流,建议限制缓冲区大小。
2. 并发控制
Gradio 默认单进程运行,高并发场景下建议使用 Gunicorn 配合 Uvicorn 部署,并设置合理的 worker 数量。
3. 模型缓存
首次加载模型耗时较长,建议将模型文件预下载至本地,并在启动脚本中增加模型校验逻辑。
4. 错误处理
在调用外部 AI 接口时,应增加重试机制和超时设置,防止因网络波动导致应用卡死。
总结
本项目实现了完整的语音转文字系统,利用 Whisper 模型的强大能力并通过 Gradio 提供了易用的界面。结合了 AI 进行润色和多语言支持,极大提升了语音识别的效果和易用性。开发者可根据实际需求扩展更多功能,如方言识别或特定领域术语优化。

