技能:video-transcribe-and-caption
目的
將影片中的語音轉換為文字,完全不需要雲端服務:使用 yt-dlp 下載影片,使用 faster-whisper 在本機轉錄,產生 SRT 字幕檔,並可選擇使用 ffmpeg 將字幕燒錄進影片,讓任何播放器都能顯示字幕。
步驟
1. 檢查工具
which yt-dlp ffmpeg uv; nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null
uvx yt-dlp 和 uv run --with faster-whisper 可以避免安裝任何東西。只有 ffmpeg 的 subtitles 濾鏡需要一個真正支援 libass 的 ffmpeg 版本(透過 ffmpeg -filters | grep subtitles 檢查);imageio-ffmpeg 隨附的二進位檔可能缺少此功能。
2. 下載
uvx yt-dlp -f "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/b" --merge-output-format mp4 -o "video.%(ext)s" --no-playlist "<url>"
uvx yt-dlp --skip-download -j "<url>" | jq '{title, uploader, upload_date, description}'
3. 轉錄為 SRT
# srt.py — run with: uv run --with faster-whisper python srt.py
from faster_whisper import WhisperModel
def ts(t):
h, r = divmod(t, 3600); m, s = divmod(r, 60)
return f"{int(h):02d}:{int(m):02d}:{int(s):02d},{int(s % 1 * 1000):03d}"
model = WhisperModel("large-v3", device="cpu", compute_type="int8") # device="cuda" if a GPU exists
segments, info = model.transcribe("video.mp4", vad_filter=True, beam_size=5)
with open("video.srt", "w") as f:
for i, s in enumerate(segments, 1):
f.write(f"{i}\n{ts(s.start)} --> {ts(s.end)}\n{s.text.strip()}\n\n")
模型選擇:
small速度很快,但多人語音、笑話和專業術語容易出錯。適合快速查看,但不適用於正式字幕。large-v3是最終交付的版本。首次下載約為 3 GB,存於~/.cache/huggingface/hub/;在慢速網路下,光下載就可能需要 30 分鐘以上。請告知使用者並在開始前取得同意;medium的大小只有一半。- 長時間的轉錄應在背景執行,並誠實回報進度:檢查 HF 快取中的
.incomplete區塊是否仍在增長(下載中),或是程序處於高 CPU 使用率(正在轉錄)。
4. 修正誤聽的行
Whisper 仍會誤聽姓名和領域特定詞。不要重新執行整個檔案,只重新轉錄錯誤區段並加入詞彙提示:
ffmpeg -loglevel error -y -ss 53 -to 64 -i video.mp4 -vn -ac 1 -ar 16000 clip.wav
segments, _ = model.transcribe("clip.wav", beam_size=5,
initial_prompt="Short list of expected words: product names, jargon, emoji names.")
然後手動編輯那些 SRT 條目(保留時間戳)。如果畫面文字有助於釐清音訊,可抽取一個畫面 (ffmpeg -ss 58 -i video.mp4 -frames:v 1 f.jpg)。向使用者報告哪些行仍屬低可信度,而不是將猜測當作事實呈現。
5. 燒錄字幕
ffmpeg -hide_banner -loglevel error -y -i video.mp4 \
-vf "subtitles=video.srt:force_style='FontSize=20,Outline=1,MarginV=30'" \
-c:v libx264 -preset fast -crf 20 -c:a copy video_cc.mp4
將 SRT 檔案保留在輸出檔案旁邊,這樣如果只有一行需要修正,便可在一分鐘內重新渲染。如果需要軟字幕(可開關),則使用 ffmpeg -i video.mp4 -i video.srt -c copy -c:s mov_text video_cc.mp4 來封裝。
交付產物
原始影片、加上字幕的影片、.srt 字幕檔以及純文字逐字稿。提及快取的模型大小,方便使用者刪除。
常見錯誤
- 將
small模型的輸出當作正式字幕交付。 - 未經詢問就開始下載數 GB 的模型。
- 為了修正三行錯誤而重新執行完整轉錄。
- 使用不支援 libass 的 ffmpeg,導致「No such filter: subtitles」錯誤。