Skip to content
HUIAHUB

TutorialAudio & speech

Speaker diarization Whisper guide: who said what with WhisperX and pyannote

Set up speaker diarization Whisper workflows with pyannote and WhisperX, check speaker labels against familiar audio, and export named SRT or VTT files.

Edited by Published 8 min read9 sources
An audio waveform splits into three speaker tracks, each passing through verification icons before becoming a transcript document.

Illustration generated with ChatGPT

A speaker diarization Whisper workflow combines Whisper's transcript with pyannote's speaker turns. Whisper transcribes speech but does not identify who said each sentence. You can join both outputs by timestamp or use WhisperX to transcribe, align words, and assign speaker labels in one local pipeline.

Speaker diarization Whisper workflow: what each model does

OpenAI Whisper (opens in a new tab) converts audio into text with timestamps. Its standard transcription output does not identify speakers. A meeting with several participants can produce readable text without indicating who spoke.

Speaker diarization handles that missing information. It divides a recording into time ranges and groups speech from the same voice under an identifier such as SPEAKER_00.

Combining transcription and diarization produces speaker-attributed text:

Illustrative transcript:

[00:02.0] SPEAKER_00: Did you review the changes?
[00:04.5] SPEAKER_01: Yes, I checked them yesterday.
[00:07.2] SPEAKER_00: Any problems?

The labels identify voice clusters, not people's names. You must listen to the recording to establish which participant matches each label.

The processing steps are:

  1. Transcription: Whisper produces words and timestamps.
  2. Diarization: pyannote estimates when each speaker talks.
  3. Alignment and assignment: The timestamps connect words with speaker turns.
  4. Review: A listener checks the labels and assigns names.

For a separate introduction to transcription, see HuiaHub's guide to running Whisper locally.

How do you set up pyannote speaker diarization?

pyannote.audio (opens in a new tab) is a Python toolkit for speaker diarization. Its Community-1 pipeline runs locally and returns speaker-labeled time ranges.

The model requires accepting its Hugging Face access conditions before downloading the files.

Step 1: Accept the model terms

Sign in to Hugging Face and open the speaker-diarization-community-1 model page (opens in a new tab).

Complete these steps:

  1. Review and accept the model's user conditions.
  2. Open your Hugging Face account's Access Tokens settings.
  3. Create a token with read access.
  4. Keep the token private and available to your local script.

Community-1 is released under CC-BY-4.0. Its access form also requests permission to share Hugging Face account information with the publisher and describes possible email contact.

Review the license and access conditions before using the model in a distributed application.

Older instructions can cause confusion. The speaker-diarization-3.1 model (opens in a new tab) has an MIT license and documents separate acceptance of the pyannote/segmentation-3.0 conditions.

That older setup also documents use_auth_token. Current Community-1 examples use token. Follow the instructions for the model you are loading rather than mixing the two setups.

Step 2: Install pyannote.audio

Install FFmpeg first. The current pyannote documentation identifies it as a dependency for audio decoding through TorchCodec.

Then install the Python package:

pip install pyannote.audio

The pipeline uses the CPU by default. CUDA acceleration is optional when a compatible GPU is available.

Step 3: Run diarization on an audio file

Set an environment variable named HF_TOKEN containing your Hugging Face read token.

For a Bash shell, you can enter the token without displaying it:

read -rsp "Hugging Face read token: " HF_TOKEN
echo
export HF_TOKEN

Save the following as diarize.py:

import os
from pyannote.audio import Pipeline

pipeline = Pipeline.from_pretrained(
    "pyannote/speaker-diarization-community-1",
    token=os.environ["HF_TOKEN"],
)

output = pipeline("meeting.wav")

for turn, speaker in output.speaker_diarization:
    print(
        f"{turn.start:.2f}-{turn.end:.2f} "
        f"{speaker}"
    )

Run it:

python diarize.py

Replace meeting.wav with the path to your recording.

Community-1 accepts audio at different sample rates and resamples it to 16 kHz. Multichannel recordings are downmixed to mono.

The returned time ranges identify speakers without transcription text. Once the model is downloaded, Community-1 also supports loading its files from a local directory for offline processing.

Step 4: Inspect the speaker turns

Community-1 returns output.speaker_diarization and output.exclusive_speaker_diarization.

The first contains the regular diarization result. The exclusive version assigns one speaker at a time, making it easier to match speaker turns with transcription timestamps.

Use the exclusive output for a simple transcript join. Keep the regular output available when checking simultaneous speech, since exclusive diarization cannot represent two active speakers at the same instant.

How do you transcribe and diarize with WhisperX?

WhisperX combines transcription, word-level alignment, and pyannote speaker assignment. Its transcription backend uses faster-whisper, while phoneme-based alignment supplies word timestamps.

The WhisperX repository (opens in a new tab) documents both a command-line interface and a Python API.

Step 1: Install WhisperX

pip install whisperx

For NVIDIA GPU acceleration, the current setup instructions specify CUDA Toolkit 12.8. WhisperX also documents CPU execution.

The command-line default transcription model is small. You can select another supported Whisper model using --model.

Step 2: Transcribe with diarization enabled

After accepting the Community-1 conditions and setting HF_TOKEN, run:

whisperx meeting.wav \
  --diarize \
  --hf_token "$HF_TOKEN" \
  --min_speakers 2 \
  --max_speakers 2 \
  --output_format all \
  --output_dir output

This example assumes the recording has exactly two speakers. Remove both speaker-count arguments when the number is unknown.

WhisperX performs the following work:

  • Finds speech regions before transcription.
  • Transcribes the recording with its faster-whisper backend.
  • Aligns recognized words using a language-specific alignment model.
  • Runs pyannote to detect speakers.
  • Assigns speaker IDs to transcript segments and individual words.

The --output_format all option writes the available output formats, including JSON, TXT, SRT, and VTT.

For CPU execution, WhisperX documents these arguments:

--device cpu --compute_type int8

Add them to the transcription command when running without CUDA.

Step 3: Inspect the word-level result

WhisperX also exposes the processing stages through Python:

import os
import whisperx
from whisperx.diarize import DiarizationPipeline

device = "cuda"
audio = whisperx.load_audio("meeting.wav")

model = whisperx.load_model(
    "large-v2",
    device,
    compute_type="float16",
)

result = model.transcribe(audio, batch_size=16)

align_model, metadata = whisperx.load_align_model(
    language_code=result["language"],
    device=device,
)

result = whisperx.align(
    result["segments"],
    align_model,
    metadata,
    audio,
    device,
    return_char_alignments=False,
)

diarizer = DiarizationPipeline(
    token=os.environ["HF_TOKEN"],
    device=device,
)

turns = diarizer(audio)

result = whisperx.assign_word_speakers(
    turns,
    result,
)

for segment in result["segments"]:
    print(
        segment.get("speaker", "UNKNOWN"),
        segment["text"],
    )

This example follows the repository's documented GPU workflow. Its batch size and model choice are examples, not required settings.

The aligned results contain word timestamps when alignment succeeds. Speaker assignment adds labels to matching words and segments.

WhisperX needs a suitable alignment model for the recording's language. Its documentation warns that some words, including certain numbers and currency expressions, may lack word timestamps when their characters cannot be aligned.

How do you join Whisper segments with pyannote turns manually?

A manual timestamp join is useful when you already have Whisper transcription results and want to retain your existing transcription process.

Whisper segments contain start, end, and text fields. pyannote supplies start times, end times, and speaker labels.

For each transcript segment, calculate its overlap with every diarization turn:

overlap = max(
    0,
    min(transcript_end, speaker_end)
    - max(transcript_start, speaker_start)
)

Add the overlap durations for each speaker. Assign the speaker with the largest total overlap.

Here is a reusable Python function:

def assign_speakers(segments, turns):
    for segment in segments:
        durations = {}

        for start, end, speaker in turns:
            overlap = max(
                0.0,
                min(segment["end"], end)
                - max(segment["start"], start),
            )

            if overlap > 0:
                durations[speaker] = (
                    durations.get(speaker, 0.0)
                    + overlap
                )

        segment["speaker"] = (
            max(durations, key=durations.get)
            if durations
            else None
        )

    return segments

segments is the list of Whisper transcript segments. turns is a list of (start, end, speaker) tuples.

For Community-1, construct the tuples from its exclusive output:

turns = [
    (turn.start, turn.end, speaker)
    for turn, speaker
    in output.exclusive_speaker_diarization
]

This approach has a limitation. If one transcript segment contains speech from two people, the function assigns the entire segment to whichever speaker has more overlap.

Word-level assignment gives you more precise boundaries. WhisperX already implements overlap-based speaker assignment for both segments and aligned words.

Leave a segment unassigned when there is no matching speaker turn. Guessing from a nearby turn can incorrectly attribute speech, especially around pauses.

How do speaker counts, overlapping speech, and short turns affect results?

Known speaker counts

pyannote can estimate the number of speakers automatically. If you know the exact count, supply it:

output = pipeline(
    "meeting.wav",
    num_speakers=2,
)

For an uncertain count, provide a range:

output = pipeline(
    "meeting.wav",
    min_speakers=2,
    max_speakers=4,
)

WhisperX exposes --min_speakers and --max_speakers through its command-line interface.

A known count constrains the clustering process. It does not establish which speaker is which or guarantee correct attribution.

Overlapping speech

Two participants can speak simultaneously during an interruption.

The regular pyannote diarization output can represent overlapping speaker activity. Community-1's exclusive output simplifies that information into one active speaker at a time.

WhisperX documents overlapping speech as a limitation of its transcription and diarization pipeline.

Check interruptions against the audio. A single subtitle cue or transcript segment may conceal speech from another participant.

Very short turns

Brief responses such as "yes," "right," or "mm-hmm" deserve extra review.

A short interruption may be attached to the surrounding speaker or receive an incorrect label. Speaker changes inside longer Whisper segments also need attention.

When checking these cases, listen to a longer portion of audio around the suspected error. Compare the voices before changing the label.

How do you check speaker labels against a recording you know?

Use a recording where you can independently recognize the participants. Knowing their voices gives you a reference for checking the model's speaker assignments.

Begin with a clear turn from each participant. Write down which real person matches each anonymous speaker ID.

Then replay the places where mistakes are more likely to matter.

Copyable speaker review checklist

Recording sectionWhat to verify
First clear turn from each personMatch each speaker ID to a real name
First change between speakersCheck the boundary timestamp
Very short responsesCheck the assigned voice
Interruptions and simultaneous speechCheck whether both participants are represented
A speaker returning after a pauseCheck whether the original ID is reused
Final turnsCheck whether labels remain consistent

Keep a correction record using timestamps, the predicted speaker, the verified speaker, and the reason for the change.

For example, if the same person appears under two IDs, inspect several turns before combining them. If two people share one predicted ID, review the affected intervals separately.

Do not treat a correctly transcribed sentence as proof that its speaker label is correct. Transcription errors and speaker-assignment errors are different problems.

A useful final check is to replay the recording while following the labeled transcript. Pay particular attention to the first and last words around speaker changes.

How do you export named SRT or VTT subtitles?

WhisperX can write both SRT and VTT files. Its subtitle writer implementation (opens in a new tab) adds speaker ID prefixes when speaker information is available.

The output can look like this:

1
00:00:02,000 --> 00:00:04,500
[SPEAKER_00]: Did you review the changes?

2
00:00:04,500 --> 00:00:07,000
[SPEAKER_01]: Yes, I checked them.

Illustrative subtitle data.

The timestamps follow SRT formatting. VTT uses a WEBVTT header and periods instead of commas for milliseconds.

Replace speaker IDs with verified names

Once you have checked the labels, replace anonymous IDs with participant names.

For files generated by the earlier WhisperX command, the following Python script creates renamed SRT and VTT copies:

from pathlib import Path

# Illustrative mapping. Verify against audio first.
names = {
    "SPEAKER_00": "Alice",
    "SPEAKER_01": "Bob",
}

for extension in ("srt", "vtt"):
    source = Path(f"output/meeting.{extension}")

    text = source.read_text(encoding="utf-8")

    for speaker_id, name in names.items():
        text = text.replace(
            f"[{speaker_id}]:",
            f"{name}:",
        )

    destination = Path(
        f"output/meeting_named.{extension}"
    )

    destination.write_text(
        text,
        encoding="utf-8",
    )

This script changes the speaker prefixes while preserving the existing subtitle timestamps and text.

It does not correct speaker-assignment errors. A subtitle cue containing speech from more than one person may still need to be split or edited.

Use WhisperX's word-level JSON to inspect speaker changes inside a segment before publishing captions. When an automatic label cannot be verified, keep an unknown-speaker designation rather than assigning a person's name.

Sources

  1. 1.GitHub - pyannote/pyannote-audio: Neural building blocks for speaker diarization: speech activity detection, speaker change detection, overlapped speech detection, speaker embedding · GitHubRepositoryPrimarygithub.com
  2. 2.pyannote/speaker-diarization-community-1 · Hugging FaceOfficial docsPrimaryhuggingface.co
  3. 3.pyannote/speaker-diarization-3.1 · Hugging FaceOfficial docsPrimaryhuggingface.co
  4. 4.GitHub - m-bain/whisperX: WhisperX: Automatic Speech Recognition with Word-level Timestamps (& Diarization) · GitHubRepositoryPrimarygithub.com
  5. 5.GitHub - openai/whisper: Robust Speech Recognition via Large-Scale Weak Supervision · GitHubRepositoryPrimarygithub.com
  6. 6.raw.githubusercontent.com/openai/whisper/main/whisper/transcribe.pyWeb
  7. 7.raw.githubusercontent.com/m-bain/whisperX/main/whisperx/__main__.pyWeb
  8. 8.raw.githubusercontent.com/m-bain/whisperX/main/whisperx/diarize.pyWeb
  9. 9.raw.githubusercontent.com/m-bain/whisperX/main/whisperx/utils.pyWeb

Spotted an error? See our corrections policy.

Enjoyed this? Get the weekly brief.

New guides, Project & Tool of the Week and the AI developments that matter. One email, no spam.

Read next

More on these topics