
Whisper Python サンプル:音声文字起こしの完全ガイド
Eric King
Author
Whisper Python サンプル:音声文字起こしの完全ガイド
OpenAI Whisper は、現在最も強力なオープンソース音声認識モデルのひとつです。本ガイドでは、Whisper と Python を使ってオーディオファイルを高精度でテキストに転写する方法を説明します。
本チュートリアルは次の方におすすめです。
- 音声テキスト化機能を開発するエンジニア
- オーディオデータを扱うデータサイエンティスト
- 実践的な Whisper Python サンプル を探している方
OpenAI Whisper とは?
Whisper は、68 万時間の多言語オーディオで学習した自動音声認識(ASR)システムです。次のことができます。
- 99 以上の言語で音声を転写する
- 言語を自動検出する
- 音声を英語に翻訳する
- ノイズの多い音声やアクセントに対応する
- 長時間のオーディオを処理する
前提条件
始める前に、次を用意してください。
- Python 3.8 以上
- パッケージマネージャー pip
- FFmpeg(オーディオ処理用)
- (任意)高速処理用の NVIDIA GPU
ステップ 1:Whisper をインストールする
pip で OpenAI Whisper パッケージをインストールします。
pip install openai-whisper
FFmpeg をインストールする
macOS(Homebrew 使用):
brew install ffmpeg
Ubuntu/Debian:
sudo apt update
sudo apt install ffmpeg
Windows:
ffmpeg.org から FFmpeg をダウンロードし、PATH に追加してください。
ステップ 2:基本的な Whisper Python の例
オーディオファイルを転写するシンプルな Python スクリプトです。
import whisper
# Load the Whisper model
model = whisper.load_model("base")
# Transcribe audio file
result = model.transcribe("audio.mp3")
# Print the transcription
print(result["text"])
出力:
Hello everyone, welcome to today's meeting. We will discuss the project timeline and upcoming milestones.
ステップ 3:エラーハンドリング付きの完全な Python 例
適切なエラーハンドリングを含む、より堅牢な例です。
import whisper
import os
def transcribe_audio(audio_path, model_size="base"):
"""
Transcribe an audio file using Whisper.
Args:
audio_path (str): Path to the audio file
model_size (str): Whisper model size (tiny, base, small, medium, large)
Returns:
dict: Transcription result with text and segments
"""
try:
# Check if audio file exists
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
# Load the Whisper model
print(f"Loading Whisper model: {model_size}")
model = whisper.load_model(model_size)
# Transcribe the audio
print(f"Transcribing: {audio_path}")
result = model.transcribe(audio_path)
return result
except Exception as e:
print(f"Error during transcription: {str(e)}")
return None
# Example usage
if __name__ == "__main__":
audio_file = "sample_audio.mp3"
result = transcribe_audio(audio_file, model_size="base")
if result:
print("\nTranscription:")
print(result["text"])
ステップ 4:言語検出を使った応用例
Whisper は言語を自動検出できますが、明示的に指定することもできます。
import whisper
model = whisper.load_model("base")
# Auto-detect language
result = model.transcribe("audio.mp3")
print(f"Detected language: {result['language']}")
print(f"Transcription: {result['text']}")
# Specify language explicitly
result_en = model.transcribe("audio.mp3", language="en")
result_zh = model.transcribe("audio.mp3", language="zh")
ステップ 5:タイムスタンプとセグメントを取得する
Whisper はタイムスタンプ付きの詳細なセグメント情報を返します。
import whisper
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
# Print full transcription
print("Full Text:")
print(result["text"])
# Print segments with timestamps
print("\nSegments with Timestamps:")
for segment in result["segments"]:
start = segment["start"]
end = segment["end"]
text = segment["text"]
print(f"[{start:.2f}s - {end:.2f}s] {text}")
出力:
Full Text:
Hello everyone, welcome to today's meeting. We will discuss the project timeline.
Segments with Timestamps:
[0.00s - 2.50s] Hello everyone, welcome to today's meeting.
[2.50s - 5.80s] We will discuss the project timeline.
ステップ 6:オーディオを英語に翻訳する
Whisper は英語以外の音声を直接英語に翻訳できます。
import whisper
model = whisper.load_model("base")
# Translate to English
result = model.transcribe("spanish_audio.mp3", task="translate")
print("Translated text:")
print(result["text"])
ステップ 7:複数のオーディオファイルを処理する
複数ファイルをバッチで転写する方法です。
import whisper
import os
from pathlib import Path
def batch_transcribe(audio_directory, model_size="base", output_dir="transcriptions"):
"""
Transcribe all audio files in a directory.
Args:
audio_directory (str): Directory containing audio files
model_size (str): Whisper model size
output_dir (str): Directory to save transcriptions
"""
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Load model once
model = whisper.load_model(model_size)
# Supported audio formats
audio_extensions = ['.mp3', '.wav', '.m4a', '.flac', '.ogg']
# Process each audio file
audio_files = [
f for f in os.listdir(audio_directory)
if any(f.lower().endswith(ext) for ext in audio_extensions)
]
for audio_file in audio_files:
audio_path = os.path.join(audio_directory, audio_file)
print(f"\nProcessing: {audio_file}")
try:
result = model.transcribe(audio_path)
# Save transcription to file
output_file = os.path.join(
output_dir,
Path(audio_file).stem + ".txt"
)
with open(output_file, "w", encoding="utf-8") as f:
f.write(result["text"])
print(f"✓ Saved: {output_file}")
except Exception as e:
print(f"✗ Error processing {audio_file}: {str(e)}")
# Example usage
batch_transcribe("audio_files/", model_size="base")
ステップ 8:SRT 字幕形式にエクスポートする
転写結果から SRT 字幕ファイルを作成します。
import whisper
def transcribe_to_srt(audio_path, output_path, model_size="base"):
"""
Transcribe audio and save as SRT subtitle file.
Args:
audio_path (str): Path to audio file
output_path (str): Path to save SRT file
model_size (str): Whisper model size
"""
model = whisper.load_model(model_size)
result = model.transcribe(audio_path)
# Generate SRT content
srt_content = ""
for i, segment in enumerate(result["segments"], start=1):
start_time = format_timestamp(segment["start"])
end_time = format_timestamp(segment["end"])
text = segment["text"].strip()
srt_content += f"{i}\n"
srt_content += f"{start_time} --> {end_time}\n"
srt_content += f"{text}\n\n"
# Save SRT file
with open(output_path, "w", encoding="utf-8") as f:
f.write(srt_content)
print(f"SRT file saved: {output_path}")
def format_timestamp(seconds):
"""Convert seconds to SRT timestamp format (HH:MM:SS,mmm)."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds % 1) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
# Example usage
transcribe_to_srt("video.mp4", "subtitles.srt", model_size="base")
Whisper モデルサイズの比較
用途に合わせて適切なモデルサイズを選びます。
| モデル | パラメータ | 速度 | 精度 | メモリ | 用途 |
|---|---|---|---|---|---|
| tiny | 39M | ⭐⭐⭐⭐⭐ | ⭐⭐ | ~1GB | 高速テスト、シンプルな音声 |
| base | 74M | ⭐⭐⭐⭐ | ⭐⭐⭐ | ~1GB | 汎用 |
| small | 244M | ⭐⭐⭐ | ⭐⭐⭐⭐ | ~2GB | バランス型 |
| medium | 769M | ⭐⭐ | ⭐⭐⭐⭐⭐ | ~5GB | 高精度が必要な場合 |
| large | 1550M | ⭐ | ⭐⭐⭐⭐⭐⭐ | ~10GB | 最高精度、ノイズ環境 |
Whisper Python のベストプラクティス
1. 適切なモデルサイズを選ぶ
# Fast and lightweight
model = whisper.load_model("tiny") # Good for testing
# Balanced
model = whisper.load_model("base") # Good for most cases
# High accuracy
model = whisper.load_model("medium") # For important transcriptions
2. 長いオーディオを扱う
非常に長いオーディオはチャンク分割を検討してください。
import whisper
from pydub import AudioSegment
def transcribe_long_audio(audio_path, chunk_length_ms=60000):
"""
Transcribe long audio by splitting into chunks.
Args:
audio_path: Path to audio file
chunk_length_ms: Length of each chunk in milliseconds
"""
model = whisper.load_model("base")
# Load audio
audio = AudioSegment.from_file(audio_path)
# Split into chunks
chunks = []
for i in range(0, len(audio), chunk_length_ms):
chunks.append(audio[i:i + chunk_length_ms])
# Transcribe each chunk
full_text = []
for i, chunk in enumerate(chunks):
chunk_path = f"chunk_{i}.wav"
chunk.export(chunk_path, format="wav")
result = model.transcribe(chunk_path)
full_text.append(result["text"])
# Clean up chunk file
os.remove(chunk_path)
return " ".join(full_text)
3. 高速化のために GPU を使う
NVIDIA GPU がある場合:
import whisper
# Whisper will automatically use GPU if available
model = whisper.load_model("base", device="cuda")
4. 精度向上のために言語を指定する
# If you know the language, specify it
result = model.transcribe("audio.mp3", language="en")
よくあるユースケース
ポッドキャストの転写
import whisper
model = whisper.load_model("medium")
result = model.transcribe("podcast_episode.mp3")
# Save transcript
with open("podcast_transcript.txt", "w") as f:
f.write(result["text"])
会議メモ
import whisper
from datetime import datetime
model = whisper.load_model("base")
result = model.transcribe("meeting_recording.mp3")
# Create formatted meeting notes
notes = f"""
Meeting Notes - {datetime.now().strftime('%Y-%m-%d')}
========================================
{result["text"]}
"""
with open("meeting_notes.txt", "w") as f:
f.write(notes)
動画字幕
import whisper
model = whisper.load_model("base")
result = model.transcribe("video.mp4")
# Generate VTT subtitle file
vtt_content = "WEBVTT\n\n"
for segment in result["segments"]:
start = format_vtt_timestamp(segment["start"])
end = format_vtt_timestamp(segment["end"])
text = segment["text"].strip()
vtt_content += f"{start} --> {end}\n{text}\n\n"
with open("subtitles.vtt", "w") as f:
f.write(vtt_content)
よくあるトラブルと対処
問題 1:FFmpeg が見つからない
エラー:
FileNotFoundError: ffmpeg対処:
# Install FFmpeg
# macOS
brew install ffmpeg
# Ubuntu/Debian
sudo apt install ffmpeg
# Windows
# Download from ffmpeg.org and add to PATH
問題 2:メモリ不足
エラー:
RuntimeError: CUDA out of memory対処:
# Use a smaller model
model = whisper.load_model("tiny") # Instead of "large"
# Or use CPU
model = whisper.load_model("base", device="cpu")
問題 3:処理が遅い
対処:
- より小さいモデル(tiny または base)を使う
- GPU アクセラレーションを有効にする
- オーディオをチャンクで処理する
- バッチジョブではマルチプロセスを使う
パフォーマンスのヒント
- 可能なら GPU を使う — CPU より 10〜50 倍高速
- タスクに合ったモデルサイズ — 単純な作業に「large」は不要
- オーディオの前処理 — 無音除去、音量正規化
- バッチ処理 — モデルは一度だけ読み込む
- スレッド — I/O 中心の処理向け
Whisper Python と他のソリューション
| 項目 | Whisper Python | Google Speech-to-Text | AssemblyAI |
|---|---|---|---|
| コスト | 無料(ローカル) | 従量課金 | 従量課金 |
| オフライン | ✅ | ❌ | ❌ |
| 精度 | 高い | 高い | 高い |
| セットアップ | 中程度 | 簡単 | 簡単 |
| 長尺音声 | ✅ | ✅ | ✅ |
| 多言語 | ✅ | ✅ | ✅ |
完全例:本番向けスクリプト
本番利用を想定した完全な例です。
#!/usr/bin/env python3
"""
Production-ready Whisper transcription script.
"""
import whisper
import argparse
import os
import json
from pathlib import Path
from datetime import datetime
def transcribe_file(
audio_path,
model_size="base",
language=None,
output_format="txt",
output_dir=None
):
"""
Transcribe an audio file with comprehensive output options.
Args:
audio_path: Path to audio file
model_size: Whisper model size
language: Language code (optional, auto-detected if None)
output_format: Output format (txt, json, srt, vtt)
output_dir: Output directory (default: same as audio file)
"""
# Validate input file
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
# Set output directory
if output_dir is None:
output_dir = os.path.dirname(audio_path)
os.makedirs(output_dir, exist_ok=True)
# Load model
print(f"Loading Whisper model: {model_size}")
model = whisper.load_model(model_size)
# Transcribe
print(f"Transcribing: {audio_path}")
transcribe_kwargs = {}
if language:
transcribe_kwargs["language"] = language
result = model.transcribe(audio_path, **transcribe_kwargs)
# Generate output filename
base_name = Path(audio_path).stem
output_path = os.path.join(output_dir, base_name)
# Save based on format
if output_format == "txt":
with open(f"{output_path}.txt", "w", encoding="utf-8") as f:
f.write(result["text"])
elif output_format == "json":
with open(f"{output_path}.json", "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
elif output_format == "srt":
srt_content = generate_srt(result["segments"])
with open(f"{output_path}.srt", "w", encoding="utf-8") as f:
f.write(srt_content)
elif output_format == "vtt":
vtt_content = generate_vtt(result["segments"])
with open(f"{output_path}.vtt", "w", encoding="utf-8") as f:
f.write(vtt_content)
print(f"✓ Transcription saved: {output_path}.{output_format}")
print(f" Language: {result['language']}")
print(f" Duration: {result['segments'][-1]['end']:.2f}s")
return result
def generate_srt(segments):
"""Generate SRT subtitle content."""
srt = ""
for i, segment in enumerate(segments, start=1):
start = format_timestamp(segment["start"])
end = format_timestamp(segment["end"])
text = segment["text"].strip()
srt += f"{i}\n{start} --> {end}\n{text}\n\n"
return srt
def generate_vtt(segments):
"""Generate VTT subtitle content."""
vtt = "WEBVTT\n\n"
for segment in segments:
start = format_vtt_timestamp(segment["start"])
end = format_vtt_timestamp(segment["end"])
text = segment["text"].strip()
vtt += f"{start} --> {end}\n{text}\n\n"
return vtt
def format_timestamp(seconds):
"""Format timestamp for SRT."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds % 1) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
def format_vtt_timestamp(seconds):
"""Format timestamp for VTT."""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds % 1) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millis:03d}"
def main():
parser = argparse.ArgumentParser(
description="Transcribe audio files using OpenAI Whisper"
)
parser.add_argument("audio", help="Path to audio file")
parser.add_argument(
"--model",
default="base",
choices=["tiny", "base", "small", "medium", "large"],
help="Whisper model size"
)
parser.add_argument(
"--language",
default=None,
help="Language code (e.g., 'en', 'zh', 'es')"
)
parser.add_argument(
"--output-format",
default="txt",
choices=["txt", "json", "srt", "vtt"],
help="Output format"
)
parser.add_argument(
"--output-dir",
default=None,
help="Output directory"
)
args = parser.parse_args()
transcribe_file(
args.audio,
model_size=args.model,
language=args.language,
output_format=args.output_format,
output_dir=args.output_dir
)
if __name__ == "__main__":
main()
使い方:
# Basic usage
python transcribe.py audio.mp3
# With options
python transcribe.py audio.mp3 --model medium --language en --output-format srt
# Save to specific directory
python transcribe.py audio.mp3 --output-dir ./transcriptions
まとめ
本ガイドでは、OpenAI Whisper を使った音声文字起こしの始め方を、Whisper Python の例とともに網羅しました。ポッドキャスト、会議、字幕制作など、Whisper はオーディオをテキストに変える強力で無料のソリューションです。
要点:
- Whisper は無料でオープンソース
- 99 以上の言語に対応
- オフラインで動作(API 呼び出し不要)
- 多くの用途で高精度
- Python プロジェクトへの組み込みが容易
リアルタイム転写や API アクセスが必要な本番環境では、SayToWords のようなクラウドサービス(Whisper ベースの API 提供)の利用も検討してください。
さあ始めましょう。 Whisper をインストールして、今日最初のオーディオファイルを転写してみてください。