Whisperの精度を上げる:文字起こし品質を高めるコツ

Whisperの精度を上げる:文字起こし品質を高めるコツ

Eric King

Eric King

Author


Whisperの精度を上げる:文字起こし品質を高めるコツ

OpenAI Whisperはすでにオープンソースの音声認識モデルの中でも高精度ですが、いくつかの戦略で文字起こし品質をさらに高められます。本ガイドでは、ユースケースに合わせてWhisperの精度を上げるための実践的なヒント、コード例、ベストプラクティスをまとめます。
こんな方向け:
  • Whisperの文字起こし精度を最適化する開発者
  • ポッドキャストや動画を文字起こしするクリエイター
  • 音声データを扱う研究者
  • Whisperの精度アップを探している方

Whisperの精度に影響するもの

最適化の前に、何が精度を左右するかを押さえましょう。
  • 音質(最も重要)
  • モデルサイズの選択
  • 言語検出の精度
  • 音声の前処理
  • 設定パラメータ
  • 音声の長さと分割

コツ1:適切なモデルサイズを選ぶ

Whisperには5つのサイズがあり、それぞれ速度と精度のバランスが異なります。
import whisper

# Model sizes from fastest to most accurate:
# tiny, base, small, medium, large

# For maximum accuracy, use medium or large
model = whisper.load_model("medium")  # Best balance
# or
model = whisper.load_model("large")  # Maximum accuracy
モデル選択の目安:
モデル精度速度使う場面
tiny⭐⭐⭐⭐⭐⭐⭐手早い検証、シンプルな音声
base⭐⭐⭐⭐⭐⭐⭐汎用、バランス型
small⭐⭐⭐⭐⭐⭐⭐精度と速度の両立
medium⭐⭐⭐⭐⭐⭐⭐高い精度が必要
large⭐⭐⭐⭐⭐⭐最高精度、ノイズの多い音声
コード例:
import whisper

def transcribe_with_optimal_model(audio_path, prioritize_accuracy=True):
    """
    Select model based on accuracy vs speed priority.
    
    Args:
        audio_path: Path to audio file
        prioritize_accuracy: True for accuracy, False for speed
    """
    if prioritize_accuracy:
        model_size = "medium"  # or "large" for best accuracy
    else:
        model_size = "base"  # or "small" for balanced
    
    model = whisper.load_model(model_size)
    result = model.transcribe(audio_path)
    
    return result

# For critical transcriptions
result = transcribe_with_optimal_model("important_meeting.mp3", prioritize_accuracy=True)
**要点:**精度が最重要ならmediumまたはlargeを使いましょう。重要なコンテンツでは、速度とのトレードオフは多くの場合に見合います。

コツ2:分かっているなら言語を指定する

Whisperは言語を自動検出できますが、明示的に指定すると精度が上がります。
import whisper

model = whisper.load_model("base")

# Auto-detect (less accurate)
result_auto = model.transcribe("audio.mp3")

# Specify language (more accurate)
result_en = model.transcribe("audio.mp3", language="en")
result_zh = model.transcribe("audio.mp3", language="zh")
result_es = model.transcribe("audio.mp3", language="es")
効く理由:
  • 言語判定ミスが減る
  • 多言語話者でも精度が上がりやすい
  • 検出ステップを省略して速くなる場合がある
  • アクセントや方言の扱いが安定しやすい
言語検出を使う例:
import whisper
import langdetect

def transcribe_with_language_detection(audio_path, model_size="base"):
    """
    Detect language first, then transcribe with explicit language.
    """
    model = whisper.load_model(model_size)
    
    # Quick language detection
    result_quick = model.transcribe(audio_path, language=None)
    detected_lang = result_quick["language"]
    
    # Re-transcribe with detected language for better accuracy
    result = model.transcribe(audio_path, language=detected_lang)
    
    return result

result = transcribe_with_language_detection("audio.mp3")

コツ3:文字起こし前に音声を前処理する

前処理を行うと、Whisperの精度は大きく改善することがあります。
import whisper
import numpy as np
from scipy.io import wavfile
from scipy import signal

def preprocess_audio(audio_path, output_path):
    """
    Preprocess audio to improve transcription accuracy.
    """
    # Read audio file
    sample_rate, audio = wavfile.read(audio_path)
    
    # Normalize audio (scale to [-1, 1])
    if audio.dtype == np.int16:
        audio = audio.astype(np.float32) / 32768.0
    elif audio.dtype == np.int32:
        audio = audio.astype(np.float32) / 2147483648.0
    
    # Remove DC offset
    audio = audio - np.mean(audio)
    
    # Normalize volume
    max_val = np.max(np.abs(audio))
    if max_val > 0:
        audio = audio / max_val * 0.95  # Leave headroom
    
    # Resample to 16kHz (Whisper's optimal sample rate)
    if sample_rate != 16000:
        num_samples = int(len(audio) * 16000 / sample_rate)
        audio = signal.resample(audio, num_samples)
        sample_rate = 16000
    
    # Save preprocessed audio
    wavfile.write(output_path, sample_rate, (audio * 32767).astype(np.int16))
    
    return output_path

# Usage
preprocessed = preprocess_audio("raw_audio.wav", "preprocessed.wav")
model = whisper.load_model("base")
result = model.transcribe(preprocessed)
前処理のステップ:
  1. レベル正規化 — 音量を揃える
  2. DCオフセット除去 — 直流成分を取り除く
  3. 16kHzにリサンプル — Whisperに適したサンプルレート
  4. 無音区間の整理 — 発話部分に集中
  5. ノイズ低減 — 背景音を抑える

コツ4:temperatureで結果を調整する

temperatureパラメータはランダム性を制御します。低い値ほど精度に有利なことが多いです。
import whisper

model = whisper.load_model("base")

# Default temperature (0.0)
result_default = model.transcribe("audio.mp3")

# Lower temperature for more deterministic results
result_low_temp = model.transcribe(
    "audio.mp3",
    temperature=0.0,  # Most deterministic
    best_of=5,  # Try multiple decodings, pick best
    beam_size=5  # Beam search size
)
temperatureの目安:
  • temperature=0.0:最も決定的で、精度重視に有利
  • temperature=0.2:わずかなランダム性、バランス型
  • temperature=0.6:デフォルト、バランス型
  • 高い値:多様だが精度は落ちやすい
ベストプラクティス:
def transcribe_with_optimal_settings(audio_path, model_size="base"):
    """
    Use optimal settings for maximum accuracy.
    """
    model = whisper.load_model(model_size)
    
    result = model.transcribe(
        audio_path,
        temperature=0.0,  # Most deterministic
        best_of=5,  # Try 5 decodings, pick best
        beam_size=5,  # Beam search
        patience=1.0,  # Patience for beam search
        condition_on_previous_text=True,  # Use context
        initial_prompt="This is a conversation about technology."  # Context hint
    )
    
    return result

コツ5:initial promptで文脈を渡す

内容の文脈を与えると精度が上がります。
import whisper

model = whisper.load_model("base")

# Without context
result_basic = model.transcribe("meeting.mp3")

# With context (much better accuracy)
result_context = model.transcribe(
    "meeting.mp3",
    initial_prompt="This is a business meeting discussing project timelines and deliverables."
)

# For technical content
result_tech = model.transcribe(
    "lecture.mp3",
    initial_prompt="This is a computer science lecture about machine learning and neural networks."
)
initial promptが有効なとき:
  • **技術内容:**ドメイン用語を含める
  • **固有名詞:**重要な名前や地名を書く
  • **アクセント:**話者のアクセントや方言を説明
  • **シーン:**場面やトピックを短く説明
例:
def transcribe_with_context(audio_path, context_description):
    """
    Transcribe with context for better accuracy.
    """
    model = whisper.load_model("medium")
    
    result = model.transcribe(
        audio_path,
        initial_prompt=context_description,
        language="en"
    )
    
    return result

# Example usage
result = transcribe_with_context(
    "interview.mp3",
    "This is an interview with Dr. Sarah Johnson about medical research. "
    "The conversation includes technical medical terminology."
)

コツ6:長い音声を適切に扱う

非常に長いファイルは精度を下げることがあります。次のように扱いましょう。
import whisper
from pydub import AudioSegment
import os

def transcribe_long_audio(audio_path, model_size="base", chunk_length_minutes=30):
    """
    Transcribe long audio by splitting into optimal chunks.
    """
    model = whisper.load_model(model_size)
    
    # Load audio
    audio = AudioSegment.from_file(audio_path)
    chunk_length_ms = chunk_length_minutes * 60 * 1000
    
    # 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 = []
    all_segments = []
    
    for i, chunk in enumerate(chunks):
        chunk_path = f"temp_chunk_{i}.wav"
        chunk.export(chunk_path, format="wav")
        
        print(f"Transcribing chunk {i+1}/{len(chunks)}")
        result = model.transcribe(chunk_path)
        
        # Adjust timestamps for chunk offset
        offset = i * chunk_length_ms / 1000.0
        for segment in result["segments"]:
            segment["start"] += offset
            segment["end"] += offset
            all_segments.append(segment)
        
        full_text.append(result["text"])
        
        # Clean up
        os.remove(chunk_path)
    
    # Combine results
    combined_result = {
        "text": " ".join(full_text),
        "segments": all_segments,
        "language": result["language"]
    }
    
    return combined_result

# Usage
result = transcribe_long_audio("long_podcast.mp3", model_size="medium", chunk_length_minutes=30)
長尺音声のコツ:
  • 20〜30分程度のチャンクに分割
  • チャンク間でモデルサイズを統一
  • チャンク間の文脈を意識する
  • タイムスタンプを正しく結合

コツ7:ノイズの多い音声向けに最適化

Whisperはノイズにも強いですが、さらに改善できます。
import whisper
import noisereduce as nr
import soundfile as sf
import numpy as np

def transcribe_noisy_audio(audio_path, model_size="medium"):
    """
    Reduce noise before transcription for better accuracy.
    """
    # Load audio
    audio, sample_rate = sf.read(audio_path)
    
    # Reduce noise
    reduced_noise = nr.reduce_noise(
        y=audio,
        sr=sample_rate,
        stationary=False,  # For non-stationary noise
        prop_decrease=0.8  # Reduce noise by 80%
    )
    
    # Save cleaned audio
    cleaned_path = "cleaned_audio.wav"
    sf.write(cleaned_path, reduced_noise, sample_rate)
    
    # Transcribe with larger model (better for noisy audio)
    model = whisper.load_model(model_size)
    result = model.transcribe(cleaned_path)
    
    # Clean up
    os.remove(cleaned_path)
    
    return result

# Usage
result = transcribe_noisy_audio("noisy_recording.mp3", model_size="medium")
ノイズが多いとき:
  • mediumまたはlargeを使う
  • ノイズ低減で前処理
  • best_ofを大きくする
  • ノイズの状況をプロンプトで伝える

コツ8:単語タイムスタンプで細かく制御

単語単位のタイムスタンプで、より細かい制御ができます。
import whisper

model = whisper.load_model("base")

# Get word timestamps
result = model.transcribe(
    "audio.mp3",
    word_timestamps=True  # Enable word-level timestamps
)

# Access word timestamps
for segment in result["segments"]:
    print(f"Segment: {segment['text']}")
    print(f"Start: {segment['start']:.2f}s, End: {segment['end']:.2f}s")
    
    if "words" in segment:
        for word in segment["words"]:
            print(f"  Word: {word['word']} ({word['start']:.2f}s - {word['end']:.2f}s)")
用途:
  • **字幕:**単語単位の同期
  • **誤り修正:**問題のある単語の特定
  • **検索:**トランスクリプト内の検索
  • **話し方分析:**発話パターンの分析

コツ9:複数デコードを組み合わせる

best_ofで複数のデコードを試し、最良のものを選べます。
import whisper

model = whisper.load_model("base")

# Single decoding (default)
result_single = model.transcribe("audio.mp3")

# Multiple decodings, pick best (more accurate)
result_best = model.transcribe(
    "audio.mp3",
    best_of=5,  # Try 5 decodings
    temperature=(0.0, 0.2, 0.4, 0.6, 0.8)  # Different temperatures
)
トレードオフ:
  • **精度:**複数デコードほど上がりやすい
  • **速度:**遅くなる(best_of=5で約5倍)
  • **向いているとき:**精度優先で速度は二の次

コツ10:トランスクリプトを後処理する

後処理でWhisperの典型エラーを直せます。
import re
import whisper

def post_process_transcript(text):
    """
    Fix common transcription errors.
    """
    # Fix common contractions
    text = re.sub(r"\b(\w+) '(\w+)\b", r"\1'\2", text)  # Fix spacing in contractions
    
    # Fix common homophones (add your own)
    replacements = {
        "there": "their",  # Context-dependent
        "its": "it's",  # Context-dependent
        # Add more based on your domain
    }
    
    # Capitalize sentences
    sentences = re.split(r'([.!?]\s+)', text)
    capitalized = []
    for i, sentence in enumerate(sentences):
        if sentence.strip():
            capitalized.append(sentence[0].upper() + sentence[1:] if len(sentence) > 1 else sentence.upper())
        else:
            capitalized.append(sentence)
    
    return "".join(capitalized)

# Usage
model = whisper.load_model("base")
result = model.transcribe("audio.mp3")
processed_text = post_process_transcript(result["text"])

完全例:本番向けの精度最適化

複数の精度テクニックを組み合わせた完全な例です。
import whisper
import os
from pathlib import Path

def transcribe_with_maximum_accuracy(
    audio_path,
    model_size="medium",
    language=None,
    context_prompt=None,
    output_format="txt"
):
    """
    Transcribe audio with maximum accuracy using best practices.
    
    Args:
        audio_path: Path to audio file
        model_size: Whisper model size (medium or large recommended)
        language: Language code (None for auto-detect)
        context_prompt: Initial prompt for context
        output_format: Output format (txt, json, srt)
    """
    # Load model (medium or large for best accuracy)
    print(f"Loading Whisper model: {model_size}")
    model = whisper.load_model(model_size)
    
    # Prepare transcription parameters
    transcribe_kwargs = {
        "temperature": 0.0,  # Most deterministic
        "best_of": 5,  # Try multiple decodings
        "beam_size": 5,  # Beam search
        "patience": 1.0,
        "condition_on_previous_text": True,
        "word_timestamps": True,  # Get word-level timestamps
    }
    
    # Add language if specified
    if language:
        transcribe_kwargs["language"] = language
    
    # Add context prompt if provided
    if context_prompt:
        transcribe_kwargs["initial_prompt"] = context_prompt
    
    # Transcribe
    print(f"Transcribing: {audio_path}")
    result = model.transcribe(audio_path, **transcribe_kwargs)
    
    # Post-process
    result["text"] = post_process_transcript(result["text"])
    
    # Save result
    base_name = Path(audio_path).stem
    output_path = f"{base_name}_transcript.{output_format}"
    
    if output_format == "txt":
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(result["text"])
    elif output_format == "json":
        import json
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
    
    print(f"✓ Transcription saved: {output_path}")
    print(f"  Language: {result['language']}")
    print(f"  Duration: {result['segments'][-1]['end']:.2f}s")
    
    return result

# Example usage
result = transcribe_with_maximum_accuracy(
    audio_path="important_meeting.mp3",
    model_size="medium",
    language="en",
    context_prompt="This is a business meeting discussing quarterly results and project updates.",
    output_format="txt"
)

精度の比較:最適化の前後

最適化で期待できる目安です。
最適化精度の改善速度への影響
モデルサイズ(base→medium)+15〜20%−50%
言語指定+5〜10%+10%(速くなる場合)
initial prompt+5〜15%ほぼなし
Temperature=0.0+2〜5%ほぼなし
best_of=5+3〜8%−80%(約5倍遅い)
音声前処理+10〜20%小さい
組み合わせると、デフォルト比で精度が30〜50%改善することもあります。

ベストプラクティス早見表

最高精度を狙うとき:

  1. mediumまたはlarge
  2. ✅ 言語を明示
  3. initial_promptで文脈
  4. ✅ 決定的結果にはtemperature=0.0
  5. ✅ 詳細出力にword_timestamps
  6. ✅ ノイズ音声は前処理
  7. ✅ 長いファイルは分割
  8. ✅ 重要コンテンツはbest_of=5

速度と精度のバランス:

  1. smallまたはbase
  2. ✅ 言語は自動検出のまま
  3. ✅ デフォルトのtemperature
  4. best_ofは使わない
  5. ✅ 前処理は最小限

よくある失敗

❌ 重要な内容にtinyを使う

**対処:**少なくともbase、できればsmallまたはmedium

❌ 言語を指定しない

**対処:**分かるときは必ず指定

❌ 文脈を入れない

**対処:**専門分野ではinitial_promptを使う

❌ ノイズが多いのにデフォルトのまま

**対処:**大きいモデルと前処理

❌ 非常に長いファイルを一括処理

**対処:**20〜30分単位に分割

精度トラブルの対処

問題:専門用語で精度が低い

対処:
result = model.transcribe(
    "technical_audio.mp3",
    initial_prompt="This audio contains technical terminology related to machine learning, neural networks, and deep learning."
)

問題:アクセントで精度が落ちる

対処:
# Use larger model
model = whisper.load_model("medium")

# Provide accent context
result = model.transcribe(
    "accented_audio.mp3",
    initial_prompt="This speaker has a British accent.",
    language="en"
)

問題:固有名詞で誤認識

対処:
# Include names in initial prompt
result = model.transcribe(
    "interview.mp3",
    initial_prompt="This interview features Dr. Sarah Johnson and Professor Michael Chen discussing research."
)

まとめ

Whisperの精度は、次の選択で決まります。
  • **モデル:**重要なコンテンツはmediumまたはlarge
  • **設定:**temperatureとデコード設定を最適化
  • **文脈:**ドメイン情報をinitial_promptで渡す
  • **前処理:**文字起こし前に音声を整える
  • **後処理:**よくある誤りを自動修正
押さえるポイント:
  1. モデルサイズが精度への影響が最も大きい
  2. 言語指定は効果が大きい
  3. 文脈プロンプトは専門内容で特に有効
  4. best_ofは精度アップと引き換えに遅くなる
  5. 最も大事なのは音質
これらのコツを押さえれば、商用サービスに匹敵する、あるいはそれ以上の文字起こし品質を、データとワークフローを自分で握ったまま実現できます。

Whisperの精度を上げたいですか? まずは大きいモデルにし、言語を指定してみてください。すぐに違いが分かります。

今すぐ無料で試す

当社のAI音声・オーディオ/ビデオサービスを今すぐお試しください。高精度な音声文字起こし、多言語翻訳、話者分離に対応するだけでなく、自動動画字幕生成、音声・映像コンテンツのインテリジェント編集、音声と映像を組み合わせた同期解析も実現します。会議記録、ショート動画制作、ポッドキャスト制作など、あらゆるシーンをこれ一つでカバーできます。今すぐ無料トライアルを始めましょう!