你是否厌倦了为在线语音识别 API 付费或者担心数据隐私问题本文将导引你如何使用 Hugging Face 的轻量级模型openai/whisper-large-v3-turbo在你的本机搭建一个完全免费的语音转文字 REST API 服务并解决实际部署中可能遇到的各种“坑”。为什么选择 Whisper large-v3-turbolarge-v3-turbo是large-v3的精简版将解码层从 32 层减少到 4 层参数大幅缩减至 0.8B。这意味着在精度略有下降的同时推理速度出现巨大提升非常适合 CPU 环境或本地实时转录且支持多语言含中文。第一步环境准备与模型获取模型地址https://huggingface.co/openai/whisper-large-v3-turbo在开始编码前你需要一个 Python 3.10 环境并为 Windows 用户指出了明确的下载指南。以下是两种下载完整模型的方式包含大文件方式 A使用 Git over SSH如果你已有 GitHub 秘钥# 安装 git-xet 以支持大文件协议 winget install git-xet # 克隆整个模型仓库包含 1.6GB 的权重文件 git clone githf.co:openai/whisper-large-v3-turbo方式 B使用 Hugging Face CLI 工具更通用# 安装 CLI 工具 powershell -ExecutionPolicy ByPass -c irm https://hf.co/cli/install.ps1 | iex # 完整下载模型到默认缓存 hf download openai/whisper-large-v3-turbo第二步极简 API 服务搭建 (FastAPI)安装必要的 Python 库pip install transformers torch torchaudio soundfile fastapi uvicorn我们编写的api.py脚本显式避开了对ffmpeg的依赖改用soundfile读取常见无损/PCM 音频。对于 MP3 等含压缩格式它对格式兼容尚有局限性但使服务器部署环境大幅简化。创建api.py这是核心启动脚本from fastapi import FastAPI, UploadFile import torch from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor import uvicorn import soundfile as sf import io import numpy as np app FastAPI() device cuda if torch.cuda.is_available() else cpu torch_dtype torch.float16 if torch.cuda.is_available() else torch.float32 model_path rE:\SoftWare\Develop\Models\whisper-large-v3-turbo model AutoModelForSpeechSeq2Seq.from_pretrained( model_path, torch_dtypetorch_dtype, low_cpu_mem_usageTrue, use_safetensorsTrue ).to(device) processor AutoProcessor.from_pretrained(model_path) def read_audio(audio_bytes): 用 soundfile 从字节流读取音频并重采样至 16kHz 单声道 audio_file io.BytesIO(audio_bytes) speech, sr sf.read(audio_file, dtypefloat32) if speech.ndim 1: speech speech.mean(axis1) # 转单声道 # 重采样到 16000简单线性插值适合非精确场景 if sr ! 16000: num_samples int(len(speech) * 16000 / sr) speech np.interp( np.linspace(0, len(speech) - 1, num_samples), np.arange(len(speech)), speech ) return speech.astype(np.float32) app.post(/v1/audio/transcriptions) async def transcribe(file: UploadFile): audio_bytes await file.read() try: speech read_audio(audio_bytes) except Exception as e: return {error: fAudio decoding failed: {str(e)}} inputs processor(speech, sampling_rate16000, return_tensorspt) inputs inputs.to(device, dtypetorch_dtype) with torch.no_grad(): generated_ids model.generate(**inputs) text processor.batch_decode(generated_ids, skip_special_tokensTrue)[0] return {text: text.strip()} if __name__ __main__: uvicorn.run(app, host0.0.0.0, port8000)在终端中运行python api.py若看到Uvicorn running on http://0.0.0.0:8000即代表服务成功上线。第三步请求与返回示例启动服务后你可以通过curl或任何 HTTP 客户端进行端到端测试请求上传音频文件curl.exe -X POST http://localhost:8000/v1/audio/transcriptions -F fileE:\SoftWare\Develop\11.mp3成功返回示例{ text: 可惜可惜差点就能赢了不要灰心我“打码效果”送你一张小“打码效果”的五元购车剪免券 }如果发送不支持的格式如 aac且没有ffmpeg环境API 会优雅地返回错误信息而非崩溃{ error: Audio decoding failed: Error opening _io.BytesIO object at 0x...: Format not recognised. }