简介:本文详细解析FunASR语音转文字技术的本地部署方法与API接口调用流程,涵盖环境配置、模型加载、服务启动及接口调用示例,助力开发者快速实现语音转文字功能。
FunASR是由中科院自动化所推出的开源语音识别工具包,基于深度学习技术实现高精度语音转文字功能。其核心优势在于支持多场景(如会议、访谈、视频字幕)的实时或离线转写,且提供灵活的部署方式(本地化或云端API)。本文将重点讲解本地部署的完整流程及API接口的调用方法。
paraformer-large)。
conda create -n funasr python=3.8conda activate funasr
pip install torch==1.12.1+cu113 -f https://download.pytorch.org/whl/torch_stable.htmlpip install funasr # 安装最新版FunASR
FunASR提供预训练模型库,可通过以下命令下载:
mkdir -p modelscd modelswget https://example.com/path/to/paraformer-large.zip # 替换为实际模型URLunzip paraformer-large.zip
或使用官方脚本自动下载:
from funasr import AutoModelmodel = AutoModel.from_pretrained("paraformer-large", cache_dir="./models")
FunASR提供funasr-cli工具,支持快速转写:
funasr-cli --model_path ./models/paraformer-large --audio_path test.wav --output_path result.txt
参数说明:
--model_path:模型目录路径。--audio_path:输入音频文件(支持WAV/FLAC格式)。--output_path:转写结果保存路径。
from funasr import AutoModelForSpeech2Textmodel = AutoModelForSpeech2Text.from_pretrained("./models/paraformer-large")audio_input = open("test.wav", "rb").read()output = model(audio_input)print(output["text"]) # 输出转写文本
若使用GPU,需确保CUDA环境正确配置,并在代码中指定设备:
import torchdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)
batch_size或使用torch.cuda.empty_cache()。paraformer-large-zh)。
from flask import Flask, request, jsonifyfrom funasr import AutoModelForSpeech2Textapp = Flask(__name__)model = AutoModelForSpeech2Text.from_pretrained("./models/paraformer-large")@app.route("/transcribe", methods=["POST"])def transcribe():if "audio" not in request.files:return jsonify({"error": "No audio file"}), 400audio_data = request.files["audio"].read()result = model(audio_data)return jsonify({"text": result["text"]})if __name__ == "__main__":app.run(host="0.0.0.0", port=5000)
启动服务后,可通过curl测试:
curl -X POST -F "audio=@test.wav" http://localhost:5000/transcribe
flask-limiter防止滥用。
import requestsurl = "http://localhost:5000/transcribe"files = {"audio": open("test.wav", "rb")}response = requests.post(url, files=files)print(response.json())
使用torch.quantization对模型进行8位量化,减少内存占用:
quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
FunASR支持多语言模型(如英语paraformer-large-en),切换时需重新加载模型。
FunASR的本地部署与API开发为开发者提供了高灵活性的语音转文字解决方案。通过合理配置硬件资源、优化模型性能及设计健壮的API接口,可满足从个人应用到企业级服务的多样化需求。未来,随着模型轻量化技术的进步,FunASR有望在边缘计算场景中发挥更大价值。