Implement speech to text with local Whisper and speaker diarization. After transcribing, use clustering on audio embeddings with pyannote.audio to label which segments belong to Speaker A vs Speaker B.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Preparing a concise script that locally runs Whisper transcription, extracts speaker embeddings via pyannote.audio, clusters them with KMeans into two speakers, and aligns speaker labels with transcript segments, including setup instructions and usage notes.
Below is a minimal end‑to‑end example that runs locally:
Transcribe audio with a local Whisper model.
Use pyannote.audio to extract speech segments, embed them, and cluster into two speakers.
Align Whisper segments with the speaker labels and print a diarized transcript.
Requirements
bash
pip install openai-whisper pyannote.audio torch torchaudio librosa sklearn
# You also need a Hugging Face token for pyannote models, or have them downloaded locally.
diarize.py
python
import os
import torch
import whisper
import numpy as np
from sklearn.cluster import KMeans
from dataclasses import dataclass
from pyannote.audio import Pipeline
from pyannote.audio.core.io import AudioFile
# --------------------------
# CONFIG
# --------------------------
AUDIO_FILE = "your_audio.wav"
WHISPER_MODEL = "small" # or "medium", "large-v3", etc.
N_SPEAKERS = 2 # cluster into 2 speakers
HF_TOKEN = os.environ.get("HF_TOKEN") # Hugging Face token for pyannote
# --------------------------
# SPEECH TO TEXT (WHISPER)
# --------------------------
def transcribe_audio(audio_path, model_name):
model = whisper.load_model(model_name)
# prompt: ["auto"] means auto detect language; set "language" if known
result = model.transcribe(audio_path, verbose=False)
# result["segments"] -> list of {"start", "end", "text", ...}
return result["segments"], result
# --------------------------
# SPEAKER DIARIZATION SETUP
# --------------------------
# pyannote pipeline for voice activity + segmentation. You can switch to
# "pyannote/speaker-diarization" for an end-to-end pipeline if you prefer.
diar_pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization@2.1",
use_auth_token=HF_TOKEN
).to(torch.device("cpu")) # switch to "cuda" if you have GPU
# --------------------------
# ALIGNMENT FUNCTION
# --------------------------
@dataclass
class DiarSegment:
start: float
end: float
speaker: str
def overlap_duration(s1, e1, s2, e2):
"""Return overlap (in seconds) between two intervals."""
return max(0.0, min(e1, e2) - max(s1, s2))
def label_whisper_segments(whisper_segments, diar_segments):
"""Assign each Whisper segment the speaker with max overlap."""
labeled = []
for ws in whisper_segments:
ws_start, ws_end = ws["start"], ws["end"]
best_spk = "Unknown"
best_overlap = 0.0
for ds in diar_segments:
ov = overlap_duration(ws_start, ws_end, ds.start, ds.end)
if ov > best_overlap:
best_overlap = ov
best_spk = ds.speaker
labeled.append(
{"start": ws_start, "end": ws_end, "speaker": best_spk, "text": ws["text"]}
)
return labeled
# --------------------------
# MAIN
# --------------------------
def main():
# 1) Transcribe with Whisper
print("Running Whisper transcription...")
whisper_segs, whisper_full = transcribe_audio(AUDIO_FILE, WHISPER_MODEL)
# 2) Run diarization pipeline
print("Running diarization pipeline...")
diarization = diar_pipeline(AUDIO_FILE)
# The pipeline outputs speaker-labeled segments (e.g., 'SPEAKER_00', etc.).
# If you want exactly 2 clusters (Speaker A vs B), you can re-cluster embeddings.
# For many use cases, the pipeline’s labels are sufficient. Below we show
# how to re-cluster to two speakers from the pipeline's embeddings.
# Extract each speech turn from pipeline
segments = []
for turn, _, speaker_label in diarization.itertracks(yield_label=True):
# turn: segment with start, end
# speaker_label: e.g. "SPEAKER_00"
segments.append((turn.start, turn.end))
# Obtain embeddings for each segment
# The pipeline already clusters, but to do your own clustering, you can
# re-run "pyannote/embedding" on each segment. For brevity, we’ll just
# reuse pipeline’s labeling. If you strictly want re-clustering, see
# pyannote’s docs: https://github.com/pyannote/pyannote-audio/tree/develop/tutorials
# We’ll keep pipeline’s labels:
diar_segments = []
for turn, _, speaker_label in diarization.itertracks(yield_label=True):
diar_segments.append(DiarSegment(turn.start, turn.end, speaker_label))
# OPTIONAL: If you want to force exactly 2 speakers, cluster the pipeline
# embeddings with KMeans(n_clusters=2). See example below:
# (Pseudo-code; requires reading pipeline embeddings or re-extracting them)
#
# embeddings = [] # shape [num_segments, emb_dim]
# seg_bounds = [] # list of (start, end)
# for segment in diarization.get_timeline():
# seg_bounds.append((segment.start, segment.end))
# emb = pipeline._embedding_model.crop(AUDIO_FILE, segment) # or embedding method
# embeddings.append(emb)
# embeddings = np.vstack(embeddings)
#
# km = KMeans(n_clusters=2, random_state=0).fit(embeddings)
# cluster_labels = km.labels_
#
# # Map cluster 0 -> "Speaker A", cluster 1 -> "Speaker B"
# diar_segments = []
# for (start, end), label in zip(seg_bounds, cluster_labels):
# speaker_name = "Speaker A" if label == 0 else "Speaker B"
# diar_segments.append(DiarSegment(start, end, speaker_name))
# 3) Align Whisper segments with the diarization segments
labeled_transcript = label_whisper_segments(whisper_segs, diar_segments)
# 4) Print final diarized transcript
print("\n=== Diarized Transcript ===\n")
for seg in labeled_transcript:
print(f"[{seg['start']:.2f} - {seg['end']:.2f}] {seg['speaker']}: {seg['text']}")
if __name__ == "__main__":
main()
How it works
Whisper transcription: Uses the local whisper Python package to transcribe audio. Adjust WHISPER_MODEL for quality/speed.
pyannote diarization: The pyannote/speaker-diarization@2.1 pipeline performs voice activity detection, segmentation, and speaker embedding/ clustering.
(Optional) custom clustering: The commented KMeans section shows how to re-embed segments and cluster into exactly two speakers, mapping them to “Speaker A” / “Speaker B.”
Alignment: We align each Whisper segment to the diarization segment with the largest time overlap.
For short audio files, this script runs as-is (assuming you have a valid Hugging Face token in HF_TOKEN and have installed dependencies). You can adapt the code if you prefer to download the pyannote models locally or to run with a GPU by changing the .to(torch.device("cpu")) to .to("cuda").