免费体验:基于ONNX量化的SenseVoice语音识别服务
本文介绍了如何在星图GPU平台自动化部署sensevoice-small-语音识别-onnx模型(带量化后),实现高效的多语言语音识别。该镜像支持中文、英文、粤语等多种语言的实时转写,适用于会议记录、视频字幕生成等场景,显著提升语音处理效率。
免费体验:基于ONNX量化的SenseVoice语音识别服务
你是不是经常需要处理语音转文字的任务?无论是会议记录、采访整理,还是视频字幕生成,手动转录既费时又容易出错。市面上的语音识别服务要么收费昂贵,要么对中文支持不够好,特别是粤语、日语等语言,更是难找到合适的解决方案。
今天我要介绍一个完全免费的语音识别方案——基于ONNX量化的SenseVoice多语言语音识别服务。这个服务最厉害的地方在于,它不仅能准确识别中文、英文,还专门优化了对粤语、日语和韩语的支持,甚至能自动检测说话人的情感和背景音频事件。
更棒的是,由于采用了ONNX量化技术,模型大小从原来的1.2GB压缩到仅230MB,推理速度却提升了3倍,10秒的音频只需要70毫秒就能处理完成。这意味着你可以在普通的CPU环境下运行,不需要昂贵的GPU设备。
这篇文章将手把手教你如何快速部署和使用这个语音识别服务。从环境搭建到API调用,从基础功能到高级技巧,我都会用最简单的语言和实际的代码示例来讲解。无论你是Python新手还是有经验的开发者,都能在10分钟内搭建起自己的语音识别服务。
1. 快速部署:三步启动语音识别服务
1.1 环境准备与依赖安装
首先,我们需要准备一个Python环境。推荐使用Python 3.8或更高版本,这个版本与所有的依赖库兼容性最好。
打开你的终端或命令行工具,执行以下命令安装必要的依赖库:
pip install funasr-onnx gradio fastapi uvicorn soundfile jieba
这些库各自有不同的作用:
funasr-onnx:提供了ONNX版本的语音识别模型gradio:用于构建Web界面,方便测试和演示fastapi和uvicorn:用于创建REST API服务soundfile:用于处理音频文件读写jieba:中文分词工具,提升文本处理效果
安装过程通常只需要2-3分钟。如果遇到网络问题,可以考虑使用国内的镜像源:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple funasr-onnx gradio fastapi uvicorn soundfile jieba
1.2 启动语音识别服务
依赖安装完成后,我们就可以启动语音识别服务了。创建一个新的Python文件,比如叫做start_service.py,然后添加以下内容:
from funasr_onnx import SenseVoiceSmall
import uvicorn
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import tempfile
import os
app = FastAPI(title="SenseVoice语音识别服务")
# 初始化模型
model = SenseVoiceSmall(
model_dir="/root/ai-models/danieldong/sensevoice-small-onnx-quant",
batch_size=10,
quantize=True
)
@app.post("/api/transcribe")
async def transcribe_audio(
file: UploadFile = File(...),
language: str = "auto",
use_itn: bool = True
):
"""语音转写API接口"""
# 保存上传的音频文件
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
content = await file.read()
tmp_file.write(content)
tmp_path = tmp_file.name
try:
# 执行语音识别
result = model([tmp_path], language=language, use_itn=use_itn)
return JSONResponse({
"text": result[0]["text"],
"language": result[0].get("lang", "unknown"),
"emotion": result[0].get("emotion", "neutral"),
"success": True
})
finally:
# 清理临时文件
os.unlink(tmp_path)
@app.get("/health")
async def health_check():
"""健康检查接口"""
return {"status": "healthy", "model_loaded": True}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
保存文件后,在终端中运行:
python start_service.py
服务启动后,你会看到类似这样的输出:
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:7860
这表示服务已经成功启动,现在可以通过http://localhost:7860访问了。
1.3 验证服务是否正常工作
服务启动后,我们可以通过几种方式验证它是否正常工作。
首先打开浏览器,访问 http://localhost:7860/docs,你会看到一个自动生成的API文档页面。这里可以看到所有的API接口和参数说明。
也可以通过命令行测试健康检查接口:
curl http://localhost:7860/health
如果返回{"status": "healthy", "model_loaded": True},说明服务运行正常。
最简单的方法是使用Web界面。访问 http://localhost:7860,你会看到一个上传音频文件的界面。点击上传按钮,选择一个WAV或MP3文件,稍等片刻就能看到识别结果。
2. 核心功能使用指南
2.1 多语言语音识别
SenseVoice最强大的功能之一就是多语言识别。它支持超过50种语言,并能自动检测输入音频的语言类型。
让我们通过几个例子来看看不同语言的识别效果。首先准备一个中文音频文件:
from funasr_onnx import SenseVoiceSmall
model = SenseVoiceSmall("/root/ai-models/danieldong/sensevoice-small-onnx-quant")
# 中文识别
result = model(["chinese_audio.wav"], language="zh")
print(f"中文识别: {result[0]['text']}")
print(f"检测语言: {result[0]['lang']}")
# 粤语识别
result = model(["cantonese_audio.wav"], language="yue")
print(f"粤语识别: {result[0]['text']}")
# 英语识别
result = model(["english_audio.wav"], language="en")
print(f"英语识别: {result[0]['text']}")
# 自动语言检测
result = model(["unknown_audio.wav"], language="auto")
print(f"自动检测: {result[0]['text']} (语言: {result[0]['lang']})")
在实际使用中,如果你知道音频的语言类型,建议明确指定language参数,这样能提高识别准确率。如果不确定,使用auto让模型自动检测。
2.2 富文本转写与情感分析
除了基本的语音转文字,SenseVoice还能分析说话人的情感和检测音频中的事件。
情感分析功能可以识别出说话人是开心、生气、悲伤还是中性情绪。这在客服质检、内容分析等场景特别有用:
result = model(["customer_service.wav"], language="auto", output_emotion=True)
print(f"转写文本: {result[0]['text']}")
print(f"情感分析: {result[0]['emotion']}")
print(f"时间戳: {result[0]['timestamp']}")
# 输出可能是:
# 转写文本: 你们的产品质量太差了,我要退货!
# 情感分析: angry
# 时间戳: 0.5s-3.2s
音频事件检测可以识别出背景中的特定声音,比如敲门声、狗叫声、警报声等:
result = model(["audio_with_events.wav"], language="auto", output_events=True)
if "events" in result[0]:
for event in result[0]["events"]:
print(f"检测到事件: {event['type']} at {event['timestamp']}")
2.3 API接口调用示例
在实际项目中,我们通常通过API接口来调用语音识别服务。以下是几种常见的调用方式。
使用curl命令调用:
curl -X POST "http://localhost:7860/api/transcribe" \
-F "file=@audio.wav" \
-F "language=auto" \
-F "use_itn=true"
使用Python的requests库调用:
import requests
url = "http://localhost:7860/api/transcribe"
files = {"file": open("audio.wav", "rb")}
data = {"language": "auto", "use_itn": "true"}
response = requests.post(url, files=files, data=data)
result = response.json()
print(f"识别结果: {result['text']}")
print(f"语言: {result['language']}")
print(f"情感: {result['emotion']}")
使用JavaScript调用:
async function transcribeAudio(file) {
const formData = new FormData();
formData.append('file', file);
formData.append('language', 'auto');
formData.append('use_itn', 'true');
const response = await fetch('http://localhost:7860/api/transcribe', {
method: 'POST',
body: formData
});
return await response.json();
}
// 使用示例
const audioFile = document.getElementById('audio-file').files[0];
transcribeAudio(audioFile).then(result => {
console.log('识别结果:', result.text);
});
3. 高级功能与优化技巧
3.1 批量处理与性能优化
当需要处理大量音频文件时,我们可以使用批量处理功能来提高效率。
import os
from funasr_onnx import SenseVoiceSmall
from concurrent.futures import ThreadPoolExecutor
model = SenseVoiceSmall("/root/ai-models/danieldong/sensevoice-small-onnx-quant")
def process_audio(file_path):
"""处理单个音频文件"""
try:
result = model([file_path], language="auto")
return {
"file": file_path,
"text": result[0]["text"],
"language": result[0].get("lang", "unknown"),
"success": True
}
except Exception as e:
return {
"file": file_path,
"error": str(e),
"success": False
}
# 批量处理音频文件
audio_files = ["audio1.wav", "audio2.wav", "audio3.wav", "audio4.wav"]
# 使用多线程并行处理
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_audio, audio_files))
for result in results:
if result["success"]:
print(f"{result['file']}: {result['text'][:50]}...")
else:
print(f"{result['file']} 处理失败: {result['error']}")
对于性能优化,可以考虑以下几个方面:
- 调整batch_size:根据你的硬件配置调整批量大小
- 启用量化:使用量化模型减少内存占用和提高速度
- 音频预处理:统一音频格式和采样率
# 优化后的配置
model = SenseVoiceSmall(
"/root/ai-models/danieldong/sensevoice-small-onnx-quant",
batch_size=8, # 根据显存调整
quantize=True, # 启用量化
device="cuda" # 使用GPU加速(如果可用)
)
3.2 自定义词典与热词优化
在某些专业领域,可能会有一些特定的术语或词汇,我们可以通过自定义词典来提高这些词汇的识别准确率。
from funasr_onnx import SenseVoiceSmall
model = SenseVoiceSmall("/root/ai-models/danieldong/sensevoice-small-onnx-quant")
# 添加专业术语热词
hotwords = [
"深度学习", "机器学习", "神经网络",
"Transformer", "BERT", "GPT",
"人工智能", "自然语言处理"
]
result = model(
["tech_presentation.wav"],
language="zh",
hotwords=hotwords,
hotword_weight=5.0 # 热词权重
)
print(f"优化后识别: {result[0]['text']}")
对于不同的行业,可以准备不同的热词表:
# 医疗行业热词
medical_terms = [
"心电图", "CT扫描", "核磁共振", "血压",
"血糖", "胆固醇", "抗生素", "疫苗"
]
# 金融行业热词
finance_terms = [
"股票", "债券", "基金", "期货",
"汇率", "利率", "通货膨胀", "GDP"
]
# 法律行业热词
legal_terms = [
"原告", "被告", "诉讼", "仲裁",
"合同", "条款", "知识产权", "专利权"
]
3.3 实时语音识别
除了处理录音文件,SenseVoice还支持实时语音识别。这对于构建实时字幕系统、语音助手等应用非常有用。
import pyaudio
import numpy as np
from funasr_onnx import SenseVoiceSmall
from collections import deque
import threading
class RealTimeASR:
def __init__(self):
self.model = SenseVoiceSmall("/root/ai-models/danieldong/sensevoice-small-onnx-quant")
self.audio_buffer = deque(maxlen=16000 * 10) # 10秒缓冲区
self.is_recording = False
def start_recording(self):
"""开始实时录音和识别"""
self.is_recording = True
p = pyaudio.PyAudio()
stream = p.open(
format=pyaudio.paInt16,
channels=1,
rate=16000,
input=True,
frames_per_buffer=1024
)
print("开始录音...")
while self.is_recording:
data = stream.read(1024)
audio_data = np.frombuffer(data, dtype=np.int16)
self.audio_buffer.extend(audio_data)
# 每2秒识别一次
if len(self.audio_buffer) >= 32000: # 2秒数据
self.process_audio()
stream.stop_stream()
stream.close()
p.terminate()
def process_audio(self):
"""处理音频缓冲区"""
audio_chunk = np.array(self.audio_buffer)
# 这里需要将音频数据保存为临时文件或直接处理
# 实际实现会更复杂,需要处理音频格式转换等
def stop_recording(self):
"""停止录音"""
self.is_recording = False
# 使用示例
asr = RealTimeASR()
recording_thread = threading.Thread(target=asr.start_recording)
recording_thread.start()
# 当需要停止时
# asr.stop_recording()
4. 常见问题与解决方案
4.1 安装与部署问题
在安装和部署过程中,可能会遇到一些常见问题。以下是这些问题及其解决方案。
问题一:依赖库安装失败
如果安装funasr-onnx或其他依赖库时失败,可以尝试以下方法:
# 先升级pip
pip install --upgrade pip
# 使用国内镜像源
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple funasr-onnx
# 或者使用conda安装
conda install -c conda-forge onnxruntime
问题二:模型下载缓慢
模型文件大约230MB,如果下载缓慢,可以手动下载:
# 创建模型目录
mkdir -p /root/ai-models/danieldong/sensevoice-small-onnx-quant
# 手动下载模型文件(需要实际的下载URL)
wget -O /root/ai-models/danieldong/sensevoice-small-onnx-quant/model_quant.onnx https://example.com/path/to/model
问题三:端口被占用
如果7860端口已被其他程序占用,可以更改服务端口:
python app.py --host 0.0.0.0 --port 8080
4.2 识别准确率优化
提高识别准确率可以从多个方面入手:
音频质量优化:
# 音频预处理函数
def preprocess_audio(input_path, output_path):
"""优化音频质量"""
import librosa
import soundfile as sf
# 读取音频
y, sr = librosa.load(input_path, sr=16000)
# 降噪(简单版本)
y_denoised = librosa.effects.preemphasis(y)
# 音量归一化
y_normalized = librosa.util.normalize(y_denoised)
# 保存处理后的音频
sf.write(output_path, y_normalized, sr)
return output_path
# 使用预处理
clean_audio = preprocess_audio("noisy_audio.wav", "clean_audio.wav")
result = model([clean_audio], language="zh")
参数调优:
# 尝试不同的参数组合
configs = [
{"language": "zh", "vad_mode": 1, "beam_size": 5},
{"language": "auto", "vad_mode": 2, "beam_size": 10},
{"language": "zh", "vad_mode": 0, "beam_size": 8}
]
for config in configs:
result = model(["audio.wav"], **config)
print(f"配置 {config}: {result[0]['text'][:30]}...")
4.3 性能监控与资源管理
对于长期运行的服务,监控性能和资源使用情况很重要。
import psutil
import time
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/system_status")
async def system_status():
"""获取系统状态"""
cpu_percent = psutil.cpu_percent()
memory_info = psutil.virtual_memory()
disk_usage = psutil.disk_usage("/")
return JSONResponse({
"cpu_usage": f"{cpu_percent}%",
"memory_usage": f"{memory_info.percent}%",
"disk_usage": f"{disk_usage.percent}%",
"timestamp": time.time()
})
# 添加性能监控中间件
@app.middleware("http")
async def monitor_performance(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
print(f"请求 {request.url} 处理时间: {process_time:.3f}秒")
return response
还可以设置自动重启机制,确保服务长期稳定运行:
# 使用shell脚本监控服务
while true; do
if ! pgrep -f "python app.py" > /dev/null; then
echo "服务未运行,重新启动..."
python app.py --host 0.0.0.0 --port 7860 &
fi
sleep 30
done
5. 总结
通过本文的介绍,你应该已经掌握了基于ONNX量化的SenseVoice语音识别服务的完整使用流程。这个服务最吸引人的地方在于它的多功能性和高效率——支持50多种语言识别、具备情感分析和音频事件检测能力,同时由于量化技术的应用,使得模型大小大幅减少而推理速度显著提升。
我们从最基础的环境搭建开始,一步步讲解了如何启动服务、调用API接口、使用高级功能以及优化识别效果。无论是简单的语音转文字任务,还是复杂的多语言实时识别场景,SenseVoice都能提供出色的表现。
特别是在中文和粤语识别方面,这个模型表现出色,准确率明显高于许多国际通用的语音识别服务。而且完全免费开源,可以自由部署和使用。
在实际应用中,你可以根据自己的需求调整参数配置,添加专业领域的热词词典,结合音频预处理技术来进一步提升识别准确率。对于大规模应用,还可以通过批量处理和性能优化来提高效率。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。
更多推荐
所有评论(0)