简介:本文详细介绍如何本地部署OpenAI开源的免费AI语音转文字工具Whisper,涵盖环境配置、模型下载、运行测试及优化建议,适合开发者及企业用户快速实现本地化语音识别。
OpenAI于2022年9月开源的Whisper模型,是当前最先进的开源语音转文字(ASR)工具之一。其核心优势在于:
pip安装核心依赖:
pip install openai-whisper torch ffmpeg-python
ffmpeg用于音频格式转换,需单独安装:sudo apt install ffmpegbrew install ffmpegWhisper提供5种规模的模型,按性能排序如下:
| 模型名称 | 参数规模 | 适用场景 | 下载命令 |
|—————|—————|—————|—————|
| tiny | 39M | 实时应用 | whisper --model tiny |
| base | 74M | 通用场景 | whisper --model base |
| small | 244M | 高精度需求 | whisper --model small |
| medium | 769M | 专业场景 | whisper --model medium |
| large | 1550M | 最高精度 | whisper --model large |
建议:
tiny或base模型。medium或large。音频转文字:
whisper input.mp3 --model base --language zh --output_file output.txt
--language zh:指定中文识别。--output_file:输出文本文件路径。实时录音转文字:
whisper --model tiny --task transcribe --input_device 0
--input_device 0:使用默认麦克风。通过代码实现更灵活的控制:
import whisper# 加载模型model = whisper.load_model("base")# 音频转文字result = model.transcribe("input.mp3", language="zh")# 输出结果print(result["text"])
关键参数:
language:指定语言代码(如zh、en)。task:transcribe(转文字)或translate(翻译为英文)。安装CUDA:
nvidia-smi。启用GPU推理:
model = whisper.load_model("base", device="cuda")
large模型的推理速度可提升5-10倍。批量处理脚本:
import osimport whispermodel = whisper.load_model("base")audio_files = [f for f in os.listdir() if f.endswith(".mp3")]for file in audio_files:result = model.transcribe(file, language="zh")with open(f"{file}.txt", "w") as f:f.write(result["text"])
多线程并行:
from concurrent.futures import ThreadPoolExecutordef process_audio(file):result = model.transcribe(file, language="zh")with open(f"{file}.txt", "w") as f:f.write(result["text"])with ThreadPoolExecutor(max_workers=4) as executor:executor.map(process_audio, audio_files)
通过--word_threshold参数调整词汇识别阈值:
whisper input.mp3 --model base --word_threshold 0.1
CUDA out of memory或MemoryError。batch_size(通过--chunk_size参数)。tiny)。--language zh。ffmpeg降噪:
ffmpeg -i input.mp3 -af "highpass=f=200,lowpass=f=3000" output.mp3
tiny模型。--chunk_length 10)。使用Docker简化环境管理:
FROM python:3.9-slimRUN apt-get update && apt-get install -y ffmpegRUN pip install openai-whisper torchCOPY . /appWORKDIR /appCMD ["python", "transcribe.py"]
构建并运行:
docker build -t whisper .docker run -v /path/to/audio:/app/audio whisper
将Whisper封装为REST API:
from fastapi import FastAPIimport whisperapp = FastAPI()model = whisper.load_model("base")@app.post("/transcribe")async def transcribe(audio_file: bytes):# 保存音频并转文字with open("temp.mp3", "wb") as f:f.write(audio_file)result = model.transcribe("temp.mp3", language="zh")return {"text": result["text"]}
本地部署Whisper可实现:
通过本文的步骤,开发者可在数小时内完成Whisper的本地部署,并根据实际需求进行优化。无论是个人项目还是企业应用,Whisper都提供了一个高效、可靠的语音转文字解决方案。