Ubuntu 24.04 下使用 Docker Compose 本地部署 Whisper 语音识别
OpenAI Whisper 自动语音识别系统的技术特点与模型规格,详细演示了如何在 Ubuntu 24.04 环境下通过 Docker Compose 本地部署 Whisper。内容涵盖 FastAPI 和 Gradio 两种服务形式的实现代码、Dockerfile 配置及依赖管理,重点解决了音频预处理、模型加载及服务暴露等关键步骤,适用于会议记录、字幕生成等场景。

OpenAI Whisper 自动语音识别系统的技术特点与模型规格,详细演示了如何在 Ubuntu 24.04 环境下通过 Docker Compose 本地部署 Whisper。内容涵盖 FastAPI 和 Gradio 两种服务形式的实现代码、Dockerfile 配置及依赖管理,重点解决了音频预处理、模型加载及服务暴露等关键步骤,适用于会议记录、字幕生成等场景。

Whisper 是 OpenAI 于 2022 年 9 月开源的一款自动语音识别系统。它最突出的特点在于其鲁棒性,即使在面对口音、背景噪音或专业术语等复杂场景时,也能保持较高的识别准确性,在英语语音识别上已接近人类水平。
Whisper 的强大能力源于其独特的技术设计,主要包括以下几点:
Whisper 提供了多种规模的模型,以适应不同场景下对速度和精度的权衡需求。下面的表格整理了可用的模型及其大致参数,你可以根据实际需求(如对准确率的要求、可用的计算资源)进行选择。
| 模型名称 | 参数量 | 磁盘空间 | 适用场景 |
|---|---|---|---|
| tiny | 约 39 M | ~75 MB | 快速演示,对资源极度敏感 |
| base | 约 74 M | ~140 MB | 平衡速度与基本准确率 |
| small | 约 244 M | ~480 MB | 良好准确率与速度的折中 |
| medium | 约 769 M | ~1.5 GB | 追求较高准确率 |
| large | 约 1550 M | ~3 GB | 最高准确率,支持所有任务 |
凭借其高准确率和多语言支持,Whisper 可应用于多种场景:
Whisper 的使用非常灵活,主要有以下几种方式:
whisper audio.wav --model small --language Chinese。总而言之,Whisper 的核心优势可以概括为三点:
运行效果:使用 small 模型以及使用精确的转录参数;整体识别还可以,但依旧有很多同韵母的字和同音字会识别错误;使用 medium 模型会出现一个奇怪的问题,转录文字为繁体字;large 模型运行时间较长(3060 显卡)
优化:音频预处理、优化转录参数、阶段处理
转 FastAPI 服务
测试语句:
curl -X POST "http://localhost:7862/transcribe" -F "[email protected]"
更新配置:
# whisper_fastapi.py
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
import whisper
import tempfile
import os
import numpy as np
from scipy import signal
import librosa
import uvicorn
import soundfile as sf
# 初始化 FastAPI 应用
app = FastAPI(
title="Whisper 音频转录 API",
description="基于 OpenAI Whisper 的高级音频转录服务",
version="1.0.0"
)
# 初始化全局变量
model = None
def load_whisper_model():
global model
if model is None:
model = whisper.load_model("large")
return model
def preprocess_audio(audio_path):
""" 音频预处理:重采样、降噪、标准化 """
try:
# 加载音频
y, sr = librosa.load(audio_path, sr=16000)
# 重采样到 16kHz
# 应用高通滤波器去除低频噪声
b, a = signal.butter(4, 100, 'highpass', fs=sr)
y = signal.filtfilt(b, a, y)
# 音频标准化
y = y / np.max(np.abs(y))
# 保存处理后的临时文件
temp_path = tempfile.mktemp(suffix='.wav')
sf.write(temp_path, y, sr)
temp_path
Exception e:
()
audio_path
():
()
load_whisper_model()
()
():
valid_extensions = {, , , , , , }
file_extension = os.path.splitext(file.filename)[].lower()
file_extension valid_extensions:
HTTPException(
status_code=,
detail=
)
temp_path =
processed_audio =
:
tempfile.NamedTemporaryFile(delete=, suffix=file_extension) temp_file:
content = file.read()
temp_file.write(content)
temp_path = temp_file.name
processed_audio = preprocess_audio(temp_path)
model = load_whisper_model()
result = model.transcribe(
processed_audio,
language=,
task=,
beam_size=,
best_of=,
temperature=,
patience=,
suppress_tokens=[-]
)
JSONResponse(content={: , : result[], : result.get(, ), : file.filename})
Exception e:
HTTPException(status_code=, detail=)
:
temp_path os.path.exists(temp_path):
os.unlink(temp_path)
processed_audio processed_audio != temp_path os.path.exists(processed_audio):
os.unlink(processed_audio)
():
JSONResponse(content={: , : model })
():
{
: ,
: ,
: {
: ,
: ,
: ,
:
},
: ,
:
}
__name__ == :
uvicorn.run(app, host=, port=)
FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
# 设置工作目录
WORKDIR /app
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
# 安装系统依赖
RUN apt-get update && apt-get install -y \
ffmpeg \
python3 \
python3-pip \
python3-venv \
&& rm -rf /var/lib/apt/lists/* \
&& ln -sf /usr/bin/python3 /usr/bin/python
# 复制依赖文件
COPY requirements.txt .
# 安装 Python 依赖
RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
# 复制应用代码(修改为 FastAPI 文件)
COPY whisper_fastapi.py .
# 暴露 FastAPI 端口
EXPOSE 7862
# 设置环境变量:模型缓存路径
ENV WHISPER_MODEL_CACHE=/root/.cache/whisper
# 启动应用(修改为 FastAPI 启动命令)
CMD ["uvicorn", "whisper_fastapi:app", "--host", "0.0.0.0", "--port", "7862"]
# docker-compose.yml
services:
whisper-api:
build: .
container_name: whisper-fastapi
ports:
- "7862:7862"
volumes:
# 持久化缓存模型
- ./model_cache:/root/.cache/whisper
# 可选:挂载音频文件目录
- ./audio_files:/app/audio_files
environment:
- WHISPER_MODEL=medium
restart: unless-stopped
# 可选:设置资源限制
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 2
capabilities: [gpu]
Gradio 服务
# whisper_gradio.py
import gradio as gr
import whisper
import tempfile
import os
import numpy as np
from scipy import signal
import librosa
# 初始化全局变量
model = None
def load_whisper_model():
global model
if model is None:
model = whisper.load_model("medium")
return model
def preprocess_audio(audio_path):
""" 音频预处理:重采样、降噪、标准化 """
try:
# 加载音频
y, sr = librosa.load(audio_path, sr=16000)
# 重采样到 16kHz
# 应用高通滤波器去除低频噪声
b, a = signal.butter(4, 100, 'highpass', fs=sr)
y = signal.filtfilt(b, a, y)
# 音频标准化
y = y / np.max(np.abs(y))
# 保存处理后的临时文件
temp_path = tempfile.mktemp(suffix='.wav')
librosa.output.write_wav(temp_path, y, sr)
return temp_path
except Exception as e:
print(f"音频预处理失败:{str(e)}")
return audio_path # 如果预处理失败,返回原始文件
def ():
model = load_whisper_model()
audio_file :
:
processed_audio = preprocess_audio(audio_file)
result = model.transcribe(
processed_audio,
language=,
task=,
beam_size=,
best_of=,
temperature=,
patience=,
suppress_tokens=[-]
)
processed_audio != audio_file:
:
os.unlink(processed_audio)
:
result[]
Exception e:
gr.Blocks(title=) demo:
gr.Markdown()
gr.Markdown()
gr.Row():
gr.Column():
audio_input = gr.Audio(sources=[], =, label=, interactive=)
submit_btn = gr.Button(, variant=)
gr.Column():
text_output = gr.Textbox(label=, placeholder=, lines=, max_lines=)
submit_btn.click(fn=transcribe_audio, inputs=audio_input, outputs=text_output)
gr.Markdown()
__name__ == :
demo.launch(server_name=, server_port=, share=)
Docker 配置
FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
# 设置工作目录
WORKDIR /app
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
# 安装系统依赖
RUN apt-get update && apt-get install -y \
ffmpeg \
python3 \
python3-pip \
python3-venv \
&& rm -rf /var/lib/apt/lists/* \
&& ln -sf /usr/bin/python3 /usr/bin/python
# 复制依赖文件
COPY requirements.txt .
# 安装 Python 依赖
RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
# 复制应用代码
COPY whisper_gradio.py .
# 暴露 Gradio 默认端口
EXPOSE 7862
# 设置环境变量:禁用 Gradio 分析,缓存模型
ENV GRADIO_ANALYTICS_ENABLED=False
ENV WHISPER_MODEL_CACHE=/root/.cache/whisper
# 启动应用
CMD ["python", "whisper_gradio.py"]
# docker-compose.yml
services:
whisper-app:
build: .
ports:
- "29999:7862"
volumes:
# 可选:持久化缓存模型,避免每次重启下载
- ./cache:/root/.cache/whisper
environment:
- GRADIO_SERVER_NAME=0.0.0.0
- GRADIO_SERVER_PORT=7862
restart: unless-stopped
# requirements.txt
torch openai-whisper gradio ffmpeg-python pydub scipy librosa numpy soundfile fastapi uvicorn python-multipart

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online