Python使用Whisper + Transformers自動生成中英文雙語字幕的完整流程
引言
本文將教你如何使用 OpenAI 的 Whisper 語音識別模型,結(jié)合 HuggingFace Transformers 翻譯模型,實現(xiàn)從視頻中提取音頻、識別語音、生成中英雙語字幕的完整流程。
支持自動語言檢測、進(jìn)度條顯示、以及自動生成 .srt 字幕文件。
一、環(huán)境準(zhǔn)備
在開始之前,請先安裝所需依賴包:
pip install openai-whisper transformers pydub librosa tqdm torch ffmpeg-python modelscope
需要提前安裝 FFmpeg(Windows 用戶請到 ffmpeg.org 下載并配置環(huán)境變量)
二、項目功能概述
本項目實現(xiàn)的流程如下:
- 提取視頻音頻(使用 FFmpeg)
- 驗證音頻文件是否可用(使用
pydub) - 使用 Whisper 模型進(jìn)行語音識別
- 自動檢測音頻語言
- 使用 Transformers 翻譯模型進(jìn)行中英文互譯
- 生成雙語字幕文件
.srt
三、國內(nèi)下載模型方法
from modelscope import snapshot_download
# 下載模型到當(dāng)前目錄
model_dir = snapshot_download('Helsinki-NLP/opus-mt-en-zh', cache_dir='./')
print(f"? 模型已下載到當(dāng)前目錄: {model_dir}")
model_dir = snapshot_download('Helsinki-NLP/opus-mt-zh-en', cache_dir='./')
print(f"? 模型已下載到當(dāng)前目錄: {model_dir}")

四、完整代碼(含中文注釋)
import whisper
import warnings
from datetime import timedelta
from tqdm import tqdm
import librosa
import time
from transformers import pipeline
import torch
from pydub import AudioSegment
import os
import ffmpeg
# 忽略警告信息
warnings.filterwarnings("ignore", category=UserWarning)
# 輸入視頻路徑(可修改)
input_video = r"./Gesture Drawing Practice _ 20 and 40 sec. poses.mp4"
# 輸出音頻路徑
output_audio = "Gesture Drawing Practice _ 20 and 40 sec. poses.wav"
# =========================
# Step 1: 提取視頻中的音頻
# =========================
ffmpeg.input(input_video).output(output_audio, ac=1, ar=16000).run()
# =========================
# Step 2: 時間戳格式化函數(shù)
# =========================
def format_timestamp(seconds):
"""將秒數(shù)轉(zhuǎn)換為 SRT 時間格式(HH:MM:SS,mmm)"""
td = timedelta(seconds=seconds)
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
milliseconds = int(td.microseconds / 1000)
return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"
# =========================
# Step 3: 驗證音頻文件是否有效
# =========================
def validate_audio(audio_file):
"""檢查音頻文件是否有效,并返回其基本信息"""
try:
audio = AudioSegment.from_file(audio_file)
duration = len(audio) / 1000.0 # 秒
sample_rate = audio.frame_rate
channels = audio.channels
print(f"? 音頻驗證成功:時長={duration:.2f}s, 采樣率={sample_rate}Hz, 聲道={channels}")
return True, duration
except Exception as e:
print(f"? 音頻驗證失敗: {e}")
return False, 0
# =========================
# Step 4: 初始化翻譯模型
# =========================
print("?? 正在加載翻譯模型,請稍候...")
translator_en_to_zh = pipeline("translation", model="./Helsinki-NLP/opus-mt-en-zh") # 英譯中
translator_zh_to_en = pipeline("translation", model="./Helsinki-NLP/opus-mt-zh-en") # 中譯英
print("? 翻譯模型加載完成。")
# =========================
# Step 5: 驗證音頻文件
# =========================
audio_file = output_audio
is_valid, duration = validate_audio(audio_file)
if not is_valid:
raise ValueError(f"無效的音頻文件: {audio_file}")
# 備用方案:使用 librosa 檢查時長
try:
duration = librosa.get_duration(path=audio_file)
except Exception as e:
print(f"Librosa 檢查失敗: {e}")
# =========================
# Step 6: 初始化 Whisper 模型
# =========================
print("??? 正在加載 Whisper 模型...")
try:
model = whisper.load_model("base") # 可選 tiny, base, small, medium, large
except Exception as e:
print(f"加載模型失敗: {e},回退到 'medium' 模型。")
model = whisper.load_model("medium")
# 進(jìn)度條初始化
progress_bar = tqdm(total=100, desc="語音識別中", unit="%")
# =========================
# Step 7: 執(zhí)行語音識別(帶進(jìn)度)
# =========================
def transcribe_with_progress(model, audio_file, language=None):
start_time = time.time()
# 自動檢測語言
if language is None:
try:
audio = whisper.load_audio(audio_file)
mel = whisper.log_mel_spectrogram(audio, n_mels=80).to(model.device)
_, probs = model.detect_language(mel)
detected_language = max(probs, key=probs.get)
print(f"?? 自動檢測語言: {detected_language}")
except Exception as e:
print(f"語言檢測失敗: {e},默認(rèn)使用英語(en)。")
detected_language = "en"
else:
detected_language = language
print(f"?? 使用指定語言: {detected_language}")
# 執(zhí)行轉(zhuǎn)錄
try:
result = model.transcribe(audio_file, language=detected_language)
except Exception as e:
print(f"轉(zhuǎn)錄失敗: {e}")
raise
# 更新進(jìn)度條
progress_bar.update(100 - progress_bar.n)
progress_bar.close()
elapsed_time = time.time() - start_time
print(f"? 轉(zhuǎn)錄完成,用時 {elapsed_time:.2f} 秒。")
return result, detected_language
# 執(zhí)行轉(zhuǎn)錄(可指定語言)
result, detected_language = transcribe_with_progress(model, audio_file, language="en")
# =========================
# Step 8: 生成中英雙語字幕文件
# =========================
srt_path = f"{output_audio}.srt"
with open(srt_path, "w", encoding="utf-8") as f:
for i, segment in enumerate(result["segments"]):
start_time = format_timestamp(segment["start"])
end_time = format_timestamp(segment["end"])
text = segment["text"].strip()
# 判斷語言并翻譯
if detected_language == "zh":
# 中文音頻:原文中文 + 翻譯英文
zh_text = text
en_text = translator_zh_to_en(text)[0]["translation_text"]
else:
# 英語音頻:原文英文 + 翻譯中文
zh_text = translator_en_to_zh(text)[0]["translation_text"]
en_text = text
# 寫入 SRT 文件(中文在上,英文在下)
f.write(f"{i+1}\n")
f.write(f"{start_time} --> {end_time}\n")
f.write(f"{zh_text}\n{en_text}\n\n")
print(f"?? 字幕文件生成成功:{srt_path}")
執(zhí)行效果后

srt文件

五、完成效果

以上就是Python使用Whisper + Transformers自動生成中英文雙語字幕的完整流程的詳細(xì)內(nèi)容,更多關(guān)于Python Whisper中英文雙語字幕的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python中的Numpy入門教程
- Python機器學(xué)習(xí)工具scikit-learn的使用筆記
- Python自然語言處理使用spaCy庫進(jìn)行文本預(yù)處理
- Python機器學(xué)習(xí)庫sklearn(scikit-learn)的基礎(chǔ)知識和高級用法
- Python使用Transformers實現(xiàn)機器翻譯功能
- Python?langchain?ReAct?使用范例詳解
- Python spaCy 庫(NLP處理庫)的基礎(chǔ)知識詳解
- Python中NumPy庫的核心知識總結(jié)大全
- 一文帶你搞懂Python?FastAPI中所有核心參數(shù)的設(shè)置
- 全面解析Python中的Scikit-learn強大工具
- Python與數(shù)據(jù)科學(xué)工具鏈之NumPy、Pandas、Matplotlib快速上手教程
- 2026年最值得投入學(xué)習(xí)的PythonAI框架top10排行榜
相關(guān)文章
通過selenium抓取某東的TT購買記錄并分析趨勢過程解析
這篇文章主要介紹了通過selenium抓取某東的TT購買記錄并分析趨勢過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
Python 使用指定的網(wǎng)卡發(fā)送HTTP請求的實例
今天小編就為大家分享一篇Python 使用指定的網(wǎng)卡發(fā)送HTTP請求的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
pandas將list數(shù)據(jù)拆分成行或列的實現(xiàn)
這篇文章主要介紹了pandas將list數(shù)據(jù)拆分成行或列的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Python爬蟲實現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能案例
這篇文章主要介紹了Python爬蟲實現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能,結(jié)合實例形式分析了Python基于beautifulSoup4模塊爬取名言網(wǎng)并存入MySQL數(shù)據(jù)庫相關(guān)操作技巧,需要的朋友可以參考下2019-09-09

