Windows 10 に Whisper での Youtube 文字起こし環境を作る

英語の動画辛い

調子いい時ならまだしも、疲れてる時に英語のチュートリアルとかで調べ物するのが本当にしんどいです。

最近は自動翻訳もいい感じにやってくれますが、もっとスムーズに内容を理解できるようになりたいところです。

その一環として、さくっと英語の文字起こしテキストを取得できる環境を作ります。

Youtube の文字起こしではだめなの?

もちろん十分な場合もあります。

Whisper

github.com

環境

Windows 10 Pro 21H2

Python

Download Python | Python.org

インストーラーを利用しました。

$ py --version
Python 3.10.9

ローカル環境

venv で仮想環境を作ります。

$ py -m venv env
$ env\Scripts\activate.bat
(env) $

ffmpeg

公式にもありますが scoop を使います。

$ scoop install ffmpeg

CUDA

今回は 12.0 をインストールしました。

$ nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2022 NVIDIA Corporation
Built on Mon_Oct_24_19:40:05_Pacific_Daylight_Time_2022
Cuda compilation tools, release 12.0, V12.0.76
Build cuda_12.0.r12.0/compiler.31968024_0

PyTorch

Start Locally | PyTorch

(env) $ pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117

現時点では上記のサイトで CUDA の 12.0 が選べませんでしたので 11.7 版を利用しています。

Whisper

(env) $ pip install git+https://github.com/openai/whisper.git

動作確認

ローカルに whisper のリポジトリを clone します。

$ git clone https://github.com/openai/whisper.git

ここでは whisper コマンドを利用します。

(env) $ whisper whisper\tests\jfk.flac --model tiny --language English
[00:00.000 --> 00:11.000]  And so my fellow Americans, ask not what your country can do for you, ask what you can do for your country.

上記の結果が出れば成功です。

Youtube のダウンロード環境

今回は yt_dlp を利用します。Python の環境は Whisper と同じ場所を利用しています。

(env) $ pip install yt-dlp

pythonでYouTubeをダウンロードするyt-dlpのコピペコード14本まとめ | DIYプログラミング

上記のサイトを参考に以下のようなスクリプトにしておきます。

import yt_dlp

URLS = ["https://www.youtube.com/watch?v=xxx"]

ydl_opts = {
    "format": "m4a/bestaudio/best", # 品質は高め
    "outtmpl": "video.m4a",  # 保存ファイル名 (パス含む)
    "postprocessors": [
        {
            "key": "FFmpegExtractAudio",
            "preferredcodec": "m4a",
        }
    ],
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    error_code = ydl.download(URLS)

Whisper でファイルから読み込む

audio_name = "video.m4a"

model = whisper.load_model("large", device="cuda")
result = model.transcribe(audio_name)

with open('transcribe.txt', 'w') as f:
    f.write(result["text"])

load_modeldevice 指定は不要かもしれませんが一応。時間よりも品質重視なので large を指定しています。

後は翻訳するだけ

後は transcribe.txt の内容を DeepL なり ChatGPT なりで翻訳してしまえばいいかなと思います。

参考にさせていただいたサイト