字幕をダウンロードしたいよね
youtube-dl
$ brew info youtube-dl
==> youtube-dl: stable 2021.12.17 (bottled), HEAD
Download YouTube videos from the command-line
https://youtube-dl.org/
インストール(homebrew)
$ brew install youtube-dl
公式サイト

GitHub - ytdl-org/youtube-dl: Command-line program to download videos from YouTube.com and other video sites
Command-line program to download videos from YouTube.com and other video sites - GitHub - ytdl-org/youtube-dl: Command-line program to download videos from YouTube.com and other video sites
Youtubeから字幕データをダウンロード
字幕データが用意されている場合
$ youtube-dl --write-sub --sub-lang en --skip-download https://youtu.be/Qm7k1CPFkIc
–skip-download を使うと、動画のダウンロードを行わずに済む
字幕データが用意されていない場合
$ youtube-dl --write-auto-sub --sub-lang en --skip-download https://youtu.be/Qm7k1CPFkIc
–write-auto-subは自動で字幕化したデータ。日本語の自動翻訳の精度はあまり良くないので、元の動画が英語なら、英語のままダウンロードして、テキスト化してからDeepLなりで翻訳するのが良さそう
- カレントディレクトリに xxx(動画タイトル).vtt というファイルが保存される
VTTは人間が読める書式じゃない
読めるテキストに変換するスクリプト
vtt2txt.sh
#!/bin/bash
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: vtt2txt.sh input.vtt output.txt"
exit 1
fi
if [ ! -f "$1" ]; then
echo "Error: input file not found"
exit 1
fi
vttCaption=$(cat "$1")
if [ -z "$vttCaption" ]; then
echo "Error: input file is empty"
exit 1
fi
# 不要な文字列を正規表現で置換する
vttCaption=$(echo "$vttCaption" | sed -E 's/.+ --> .+//g')
vttCaption=$(echo "$vttCaption" | sed -E 's/<\/?[^>]+>//g')
vttCaption=$(echo "$vttCaption" | sed -E 's/^\s*$//g')
vttCaption=$(echo "$vttCaption" | sed -E 's/ / /g')
# 各行を取り出し、空白文字で結合する
lines=$(echo "$vttCaption" | sed -n '5,$p' | tr -d '\r')
lines=$(echo "$lines" | awk '{ $1=$1; print }')
lines=$(echo "$lines" | awk ' !x[$0]++')
echo "$lines" > "$2"
テキスト変換スクリプトの使い方
$ ./vtt2txt.sh input.vtt output.vtt