はじめに
ういっすういっすういっすー!✌️ ぱー🖐 nikkieです。
過去にWhisperを触りましたが
このたびtransformersライブラリから簡単にWhisperを利用できることを知りました。
目次
- はじめに
- 目次
- 動作環境
- transformersで簡単にWhisperを利用
- コード例はopenai/whisper-baseから
- 落ち穂拾い
- 終わりに
- P.S. Whisper Distilled
動作環境
- macOS(M1 Mac)
- CPU環境
- Python 3.10.9
- ffmpeg version 6.0
brew install ffmpeg
しました
- transformers 4.35.0
- torch 2.1.0
pip install 'transformers[torch]'
認識させる音声ファイルを作成
say 親譲りの無鉄砲で子供の時から損ばかりしている -o sample.wav --data-format=LEF32@16000
transformersで簡単にWhisperを利用
以下3つをやるだけです
- transformersのpipelineを作成
- automatic-speech-recognitionタスクにWhisperを使う
- forced_decoder_idsを取得
- 日本語というのはここで伝える
- 音声ファイルのパスを渡して書き起こし
% python transformers-whisper.py {'text': '親譲りの無鉄砲で子供の時から損ばかりしている'}
Wow! なんて簡単なんでしょう🙌
コード例はopenai/whisper-baseから
pipelineを作って音声ファイルを渡したところ、英語が出力されました。
今回やりたいことは、英語にせずに日本語のままの書き起こしです。
Hugging Face Hubのコードの「French to French」を参考にしました(仕組みの理解はこれからです)。
forced_decoder_ids = processor.get_decoder_prompt_ids(language="french", task="transcribe") predicted_ids = model.generate(input_features, forced_decoder_ids=forced_decoder_ids)
- pipelineはモデルやトークナイザを持つ
- https://github.com/huggingface/transformers/blob/v4.35.0/src/transformers/pipelines/automatic_speech_recognition.py#L219-L220
- processorと
pipeline.tokenizer
は型が同じ - また
get_decoder_prompt_ids
メソッドの返り値も一致 - そこで
transcriber.tokenizer.get_decoder_prompt_ids
と書いています
- pipelineの
__call__
メソッドにgenerate_kwargs
引数を発見- https://huggingface.co/docs/transformers/v4.35.0/en/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline.__call__.generate_kwargs
forced_decoder_ids=forced_decoder_ids
を渡すことに成功! 日本語になりました
落ち穂拾い
(1) whisper-baseで動くのを確認してからmediumにモデルを引き上げています。
% python transformers-whisper.py {'text': '親ゆずりのむてっぽうで、子供の時から、そんばかりしている。'}
baseでもひらがなで書き起こせていますね
(2) pipelineに音声ファイルのパスが渡せるのはとても便利ですね。
この処理にffmpegが使われているようです。
__call__
のinputs引数のドキュメントより
The file will be read at the correct sampling rate to get the waveform using ffmpeg.
終わりに
Whisperの登場から1年が経過する中で、ライブラリtransformersでサポートされていました🤗
自然言語処理のTransformer系のモデルと同様のインターフェースで扱えます。これはすごいな〜
今後はマイクから音声を渡すのを試してみようと思います。
また、Hugging Face Hubのコードには「Long-Form Transcription」もあり、長い音声データを扱う際に役立ちそうな情報でした(chunk_length_s
引数など)
P.S. Whisper Distilled
今回手を動かしたきっかけはWhisperの蒸留モデルを知ったことです。
Welcome distil-whisper 🔥
— Vaibhav (VB) Srivastav (@reach_vb) 2023年11月2日
49% smaller, 6x faster, and within the 1% performance range of Whisper-large-v2!
All in the good ol' Transformers API.
1. Make sure to upgrade transformers to the latest release.
pip install --upgrade transformers
2. Import torch & transformers… pic.twitter.com/RCVPW9VAeG
ここで紹介したコードでモデルを変えたところ、日本語で書き起こせませんでした(なにか間違えたのかも)。
現時点ではサポートされていないのかなと思っていますが、少ないメモリでも高性能な書き起こしができる点には期待大です!