本地离线部署 Whisper 模型实现语音转写
在本地搭建 Whisper 语音转写环境其实并不复杂,这套方案兼容 Windows、macOS 和 Linux 系统。下面分享具体的实施步骤,重点在于环境配置与脚本调用。
基础环境准备
首先确保安装了 Python 3.8 及以上版本。下载地址参考 python.org。安装过程中务必勾选 "Add Python to PATH",这一步至关重要,否则后续命令无法识别。
验证安装是否成功很简单,打开终端输入 python --version 或 python3 --version,能看到版本号即表示就绪。
安装 Whisper 核心库
对于国内用户,建议使用镜像源加速安装过程。执行以下命令:
pip install openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple
Whisper 对音频处理有额外依赖。Windows 用户需要单独下载并安装 FFmpeg,并将 ffmpeg.exe 所在目录添加到系统环境变量 PATH 中,否则无法处理部分音频格式。
模型选择与下载
Whisper 首次运行时会自动下载模型,但手动指定大型模型能获得更好的效果。推荐优先使用 large-v3 版本。安装时可指定模型:
pip install "openai-whisper[large-v3]"
模型文件默认保存在缓存目录中:
- Windows:
C:\Users\你的用户名\.cache\whisper\ - macOS/Linux:
~/.cache/whisper/
命令行直接转写
如果只是想快速测试,直接使用命令行最方便。支持 WAV、MP3、MP4 等多种格式。
whisper 你的音频文件路径.wav --model large-v3 --language Chinese
例如:
whisper D:\\Net_Program\\test\\whisper-test.wav --model large-v3 --language Chinese
关键参数说明
--model:指定模型大小,从tiny到large-v3,越大精度越高但越吃资源。--language Chinese:强制指定语言为中文,避免自动检测偏差。--output_dir:指定结果保存路径。--format:输出格式支持 txt、srt、vtt 等。
Python 脚本调用
如果需要集成到项目或批量处理,编写 Python 脚本更灵活。下面这个示例封装了 FFmpeg 检查、路径验证及繁简转换逻辑。
import whisper
import os
import pathlib
import subprocess
from zhconv import convert
def check_ffmpeg():
"""检查 FFmpeg 是否安装并配置正确"""
try:
subprocess.run(
["ffmpeg", "-version"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
return True
except FileNotFoundError:
print("错误:未找到 FFmpeg 工具,请先安装并配置环境变量")
return False
except Exception as e:
print(f"FFmpeg 检查失败:{str(e)}")
return False
def transcribe_audio(audio_path, model_name="large-v3", language="Chinese"):
# 检查 FFmpeg
if not check_ffmpeg():
return None
# 验证音频文件路径
audio_path = str(pathlib.Path(audio_path).resolve())
if not os.path.exists(audio_path):
print(f"错误:音频文件不存在 '{audio_path}'")
return None
if not os.path.isfile(audio_path):
print(f"错误:'{audio_path}' 不是有效的文件")
return None
# 加载模型并转写
try:
print(f"开始加载模型 {model_name}...")
model = whisper.load_model(model_name, device="cpu")
print(f"开始转写文件:{audio_path}")
# 关键设置:明确指定中文,并关闭自动语言检测
result = model.transcribe(
audio=audio_path,
language="Chinese", # 强制指定中文
verbose=True,
fp16=False,
initial_prompt="请用简体中文转写,不要使用繁体中文。" # 提示模型使用简体
)
# 强制将结果转换为简体中文(双重保险)
simplified_text = convert(result["text"], 'zh-cn')
# 保存结果
output_dir = "whisper_results"
os.makedirs(output_dir, exist_ok=True)
audio_name = os.path.splitext(os.path.basename(audio_path))[0]
output_path = os.path.join(output_dir, f"{audio_name}_transcript.txt")
with open(output_path, "w", encoding="utf-8") as f:
f.write(simplified_text)
print(f"\n✅ 转写完成(已转换为简体中文),结果保存至:{output_path}")
return simplified_text
except Exception as e:
print(f"转写过程出错:{str(e)}")
return None
if __name__ == "__main__":
# 安装繁转简依赖(首次运行需要)
try:
import zhconv
except ImportError:
print("正在安装繁转简依赖...")
subprocess.run(["pip", "install", "zhconv"], check=True)
import zhconv
# 替换为你的音频文件路径
audio_file = r"D:\\Net_Program\\test\\whisper-test.wav"
transcribe_audio(audio_file)
注意:脚本中使用了 zhconv 库来处理繁简转换,首次运行若未安装会自动尝试安装。实际使用时请修改 audio_file 路径为你本地的文件。
常见问题排查
- 内存不足:若遇到
OutOfMemoryError,建议换用medium或small模型。large-v3建议至少配备 16GB 内存。 - 音频格式错误:可使用 FFmpeg 预处理,例如转为 16kHz 单声道 WAV:
ffmpeg -i 输入文件.mp3 -ar 16000 -ac 1 输出文件.wav。 - 模型下载慢:可手动从 Hugging Face 下载模型文件放入
.cache/whisper/目录。
通过以上配置,即可在本地构建稳定的 Whisper 转写环境,无需依赖云端 API 或其他推理框架,直接调用模型进行高效语音转写。
