This is a comprehensive request for implementing a speech-to-text pipeline with speaker diarization. Let me break down what's needed:
- Local Whisper for speech-to-text
- Speaker diarization using pyannote.audio
- Clustering on audio embeddings to identify different speakers
- Labeling segments with Speaker A, Speaker B, etc.
I'll create a complete implementation with:
- Audio loading and preprocessing
- Whisper transcription
- Pyannote speaker diarization
- Embedding-based clustering
- Integration and visualization
- Error handling
Let me write comprehensive code with explanations.
Speech-to-Text with Speaker Diarization using Whisper and pyannote
I'll create a complete implementation with local processing, clustering, and visualization.
1. Installation & Setup
# Install required packages
pip install openai-whisper pyannote.audio torch torchaudio
pip install librosa scipy scikit-learn matplotlib pandas
pip install huggingface-hub
# For pyannote to work, you need to accept the license on HuggingFace
# Visit: https://huggingface.co/pyannote/speaker-diarization-3.0
# and https://huggingface.co/pyannote/segmentation-3.0
# Set HuggingFace token (required for pyannote models)
# First login to HuggingFace CLI
from huggingface_hub import login
login() # This will prompt you to enter your token
2. Core Implementation
import torch
import torchaudio
import numpy as np
import whisper
from pyannote.audio import Pipeline
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from scipy.spatial.distance import pdist, squareform
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import pandas as pd
from typing import List, Dict, Tuple
import logging
from dataclasses import dataclass
from pathlib import Path
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class Segment:
"""Represents a transcribed segment with speaker info"""
start: float
end: float
text: str
speaker: str
confidence: float = None
embedding: np.ndarray = None
@dataclass
class TranscriptionResult:
"""Complete transcription with speaker labels"""
segments: List[Segment]
full_text: str
speakers: List[str]
duration: float
audio_path: str
class SpeakerDiarizationPipeline:
"""Complete speech-to-text with speaker diarization pipeline"""
def __init__(
self,
whisper_model: str = "base",
device: str = None,
language: str = "en"
):
"""
Initialize the pipeline
Args:
whisper_model: Size of Whisper model (tiny, base, small, medium, large)
device: torch device (cuda or cpu)
language: Language code
"""
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
self.device = device
self.language = language
logger.info(f"Loading Whisper model ({whisper_model})...")
self.whisper_model = whisper.load_model(whisper_model, device=device)
logger.info("Loading pyannote speaker diarization pipeline...")
self.diarization_pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization-3.0",
use_auth_token=True
).to(torch.device(device))
self.language = language
def load_audio(self, audio_path: str) -> Tuple[torch.Tensor, int]:
"""Load and resample audio to 16kHz"""
logger.info(f"Loading audio from {audio_path}...")
waveform, sample_rate = torchaudio.load(audio_path)
# Convert to mono if stereo
if waveform.shape[0] > 1:
waveform = waveform.mean(dim=0, keepdim=True)
# Resample to 16kHz if needed
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(
sample_rate, 16000
)
waveform = resampler(waveform)
sample_rate = 16000
return waveform, sample_rate
def transcribe_audio(
self,
audio_path: str,
language: str = None
) -> Dict:
"""Transcribe audio using Whisper"""
logger.info("Transcribing audio with Whisper...")
if language is None:
language = self.language
result = self.whisper_model.transcribe(
audio_path,
language=language,
verbose=False
)
return result
def perform_diarization(
self,
audio_path: str
) -> Dict:
"""Perform speaker diarization"""
logger.info("Performing speaker diarization...")
diarization = self.diarization_pipeline(audio_path)
return diarization
def extract_embeddings(
self,
audio_path: str,
diarization: Dict,
embedding_model: str = "pyannote/embedding"
) -> Dict[str, np.ndarray]:
"""
Extract speaker embeddings for clustering
Returns:
Dictionary mapping speaker labels to embeddings
"""
logger.info("Extracting speaker embeddings...")
from pyannote.audio import Embedding
embedding_pipeline = Embedding(
model_name=embedding_model
).to(torch.device(self.device))
waveform, sample_rate = torchaudio.load(audio_path)
if waveform.shape[0] > 1:
waveform = waveform.mean(dim=0, keepdim=True)
embeddings = {}
for turn, _, speaker in diarization.itertracks(yield_label=True):
start, end = turn.start, turn.end
# Extract segment
start_sample = int(start * sample_rate)
end_sample = int(end * sample_rate)
segment = waveform[:, start_sample:end_sample]
# Get embedding
with torch.no_grad():
embedding = embedding_pipeline(segment)
if speaker not in embeddings:
embeddings[speaker] = []
embeddings[speaker].append(embedding.cpu().numpy())
# Average embeddings per speaker
avg_embeddings = {
speaker: np.mean(embs, axis=0)
for speaker, embs in embeddings.items()
}
return avg_embeddings
def cluster_speakers(
self,
embeddings: Dict[str, np.ndarray],
n_clusters: int = None,
threshold: float = 0.6
) -> Dict[str, str]:
"""
Cluster speaker embeddings
Args:
embeddings: Dictionary of speaker embeddings
n_clusters: Number of clusters (if None, use threshold)
threshold: Distance threshold for hierarchical clustering
Returns:
Mapping from original speaker labels to cluster labels
"""
logger.info("Clustering speakers...")
speaker_labels = list(embeddings.keys())
embedding_list = np.array([embeddings[s] for s in speaker_labels])
# Standardize embeddings
scaler = StandardScaler()
embedding_list = scaler.fit_transform(embedding_list)
# Hierarchical clustering
distances = pdist(embedding_list, metric='cosine')
linkage_matrix = linkage(distances, method='ward')
if n_clusters:
cluster_labels = fcluster(linkage_matrix, n_clusters, criterion='maxclust')
else:
cluster_labels = fcluster(
linkage_matrix,
1 - threshold,
criterion='distance'
)
# Map to speaker names
speaker_mapping = {}
cluster_to_name = {}
for orig_label, cluster_id in zip(speaker_labels, cluster_labels):
if cluster_id not in cluster_to_name:
cluster_to_name[cluster_id] = f"Speaker {len(cluster_to_name) + 1}"
speaker_mapping[orig_label] = cluster_to_name[cluster_id]
return speaker_mapping
def align_transcription_with_diarization(
self,
transcription: Dict,
diarization: Dict,
speaker_mapping: Dict[str, str]
) -> List[Segment]:
"""Align Whisper transcription with diarization"""
logger.info("Aligning transcription with speaker diarization...")
segments = []
# Get diarization tracks
diarization_tracks = []
for turn, _, label in diarization.itertracks(yield_label=True):
diarization_tracks.append({
'start': turn.start,
'end': turn.end,
'speaker': speaker_mapping.get(label, label)
})
# Sort by start time
diarization_tracks.sort(key=lambda x: x['start'])
# Process each Whisper segment
for i, whisper_segment in enumerate(transcription['segments']):
seg_start = whisper_segment['start']
seg_end = whisper_segment['end']
text = whisper_segment['text'].strip()
confidence = whisper_segment.get('confidence', 0)
# Find overlapping diarization segment
assigned_speaker = "Unknown"
max_overlap = 0
for dia_track in diarization_tracks:
overlap_start = max(seg_start, dia_track['start'])
overlap_end = min(seg_end, dia_track['end'])
overlap = max(0, overlap_end - overlap_start)
if overlap > max_overlap:
max_overlap = overlap
assigned_speaker = dia_track['speaker']
if text: # Only add non-empty segments
segments.append(Segment(
start=seg_start,
end=seg_end,
text=text,
speaker=assigned_speaker,
confidence=confidence
))
return segments
def process(
self,
audio_path: str,
n_clusters: int = None,
threshold: float = 0.6
) -> TranscriptionResult:
"""
Complete processing pipeline
Args:
audio_path: Path to audio file
n_clusters: Force specific number of speakers
threshold: Clustering threshold (0-1)
Returns:
TranscriptionResult object
"""
audio_path = str(Path(audio_path).resolve())
# Get audio duration
waveform, sr = torchaudio.load(audio_path)
duration = waveform.shape[1] / sr
# Step 1: Transcribe
transcription = self.transcribe_audio(audio_path)
# Step 2: Diarize
diarization = self.perform_diarization(audio_path)
# Step 3: Extract embeddings and cluster
embeddings = self.extract_embeddings(audio_path, diarization)
speaker_mapping = self.cluster_speakers(
embeddings,
n_clusters=n_clusters,
threshold=threshold
)
# Step 4: Align transcription with diarization
segments = self.align_transcription_with_diarization(
transcription,
diarization,
speaker_mapping
)
# Generate full text
full_text = " ".join([seg.text for seg in segments])
# Get unique speakers
speakers = sorted(list(set([seg.speaker for seg in segments])))
return TranscriptionResult(
segments=segments,
full_text=full_text,
speakers=speakers,
duration=duration,
audio_path=audio_path
)
class DiarizationVisualizer:
"""Visualize diarization results"""
@staticmethod
def plot_segments(
result: TranscriptionResult,
save_path: str = None,
figsize: Tuple[int, int] = (14, 8)
) -> plt.Figure:
"""Plot transcription with speaker segments"""
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize, sharex=True)
# Define colors for speakers
colors = plt.cm.Set3(np.linspace(0, 1, len(result.speakers)))
speaker_colors = {
speaker: colors[i]
for i, speaker in enumerate(result.speakers)
}
# Plot 1: Speaker timeline
y_pos = 0
speaker_positions = {}
for segment in result.segments:
color = speaker_colors[segment.speaker]
if segment.speaker not in speaker_positions:
speaker_positions[segment.speaker] = y_pos
y_pos += 1
y = speaker_positions[segment.speaker]
ax1.add_patch(Rectangle(
(segment.start, y - 0.4),
segment.end - segment.start,
0.8,
facecolor=color,
edgecolor='black',
linewidth=1
))
# Add text if segment is long enough
if segment.end - segment.start > 1:
ax1.text(
(segment.start + segment.end) / 2,
y,
segment.speaker,
ha='center',
va='center',
fontsize=9,
weight='bold'
)
ax1.set_ylim(-0.5, y_pos - 0.5)
ax1.set_yticks(range(y_pos))
ax1.set_yticklabels(result.speakers)
ax1.set_ylabel('Speaker')
ax1.set_title('Speaker Diarization Timeline')
ax1.grid(axis='x', alpha=0.3)
# Plot 2: Transcript text with speaker labels
y_pos = 0
for segment in result.segments:
ax2.text(
0.02,
y_pos,
f"{segment.speaker} ({segment.start:.1f}s): {segment.text[:60]}...",
fontsize=10,
verticalalignment='top',
color=speaker_colors[segment.speaker],
weight='bold'
)
y_pos -= 0.05
ax2.set_xlim(0, 1)
ax2.set_ylim(y_pos, 0.05)
ax2.axis('off')
ax2.set_title('Transcription')
# Overall settings
ax1.set_xlabel('Time (seconds)')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Visualization saved to {save_path}")
return fig
@staticmethod
def export_to_srt(
result: TranscriptionResult,
output_path: str
) -> None:
"""Export transcription as SRT subtitle file"""
def seconds_to_srt_time(seconds):
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}"
with open(output_path, 'w') as f:
for i, segment in enumerate(result.segments, 1):
f.write(f"{i}\n")
f.write(
f"{seconds_to_srt_time(segment.start)} --> "
f"{seconds_to_srt_time(segment.end)}\n"
)
f.write(f"{segment.speaker}: {segment.text}\n\n")
logger.info(f"SRT file saved to {output_path}")
@staticmethod
def export_to_dataframe(result: TranscriptionResult) -> pd.DataFrame:
"""Convert result to pandas DataFrame"""
data = []
for segment in result.segments:
data.append({
'start_time': segment.start,
'end_time': segment.end,
'duration': segment.end - segment.start,
'speaker': segment.speaker,
'text': segment.text,
'confidence': segment.confidence
})
return pd.DataFrame(data)
3. Usage Example
def main():
"""Complete example usage"""
# Initialize pipeline
pipeline = SpeakerDiarizationPipeline(
whisper_model="base",
device="cuda",
language="en"
)
# Process audio file
audio_file = "meeting.wav"
result = pipeline.process(
audio_path=audio_file,
n_clusters=2, # Expect 2 speakers
threshold=0.6
)
# Print results
print("\n" + "="*60)
print("DIARIZATION RESULTS")
print("="*60)
print(f"\nAudio: {result.audio_path}")
print(f"Duration: {result.duration:.2f} seconds")
print(f"Speakers detected: {', '.join(result.speakers)}")
print(f"Number of segments: {len(result.segments)}")
print("\nTranscription:")
print("-" * 60)
for segment in result.segments:
print(
f"[{segment.start:.2f}s - {segment.end:.2f}s] "
f"{segment.speaker}: {segment.text}"
)
print("\nFull Transcript:")
print("-" * 60)
print(result.full_text)
# Visualize
visualizer = DiarizationVisualizer()
visualizer.plot_segments(result, save_path="diarization.png")
# Export to different formats
visualizer.export_to_srt(result, "transcript.srt")
df = visualizer.export_to_dataframe(result)
df.to_csv("transcript.csv", index=False)
print("\nExported to: transcript.srt, transcript.csv, diarization.png")
return result
if __name__ == "__main__":
result = main()
4. Advanced Features with Custom Clustering
class AdvancedClusteringPipeline(SpeakerDiarizationPipeline):
"""Extended pipeline with advanced clustering options"""
def cluster_speakers_kmeans(
self,
embeddings: Dict[str, np.ndarray],
n_speakers: int = 2
) -> Dict[str, str]:
"""K-means clustering for speaker discovery"""
from sklearn.cluster import KMeans
logger.info(f"Performing K-means clustering with k={n_speakers}...")
speaker_labels = list(embeddings.keys())
embedding_list = np.array([embeddings[s] for s in speaker_labels])
# Standardize
scaler = StandardScaler()
embedding_list = scaler.fit_transform(embedding_list)
# K-means
kmeans = KMeans(n_clusters=n_speakers, random_state=42)
cluster_labels = kmeans.fit_predict(embedding_list)
# Map to speaker names
speaker_mapping = {}
for orig_label, cluster_id in zip(speaker_labels, cluster_labels):
speaker_mapping[orig_label] = f"Speaker {cluster_id + 1}"
return speaker_mapping
def cluster_speakers_dbscan(
self,
embeddings: Dict[str, np.ndarray],
eps: float = 0.5,
min_samples: int = 1
) -> Dict[str, str]:
"""DBSCAN clustering for adaptive speaker discovery"""
from sklearn.cluster import DBSCAN
logger.info(f"Performing DBSCAN clustering...")
speaker_labels = list(embeddings.keys())
embedding_list = np.array([embeddings[s] for s in speaker_labels])
# Standardize
scaler = StandardScaler()
embedding_list = scaler.fit_transform(embedding_list)
# Calculate distances
distances = squareform(pdist(embedding_list, metric='cosine'))
# DBSCAN
dbscan = DBSCAN(eps=eps, min_samples=min_samples, metric='precomputed')
cluster_labels = dbscan.fit_predict(distances)
# Handle noise points
n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)
# Map to speaker names
speaker_mapping = {}
cluster_counter = 0
for orig_label, cluster_id in zip(speaker_labels, cluster_labels):
if cluster_id == -1:
# Noise point
speaker_mapping[orig_label] = f"Speaker {cluster_counter + 1}"
cluster_counter += 1
else:
speaker_mapping[orig_label] = f"Speaker {cluster_id + 1}"
return speaker_mapping
def plot_embeddings_2d(
self,
embeddings: Dict[str, np.ndarray],
speaker_mapping: Dict[str, str],
save_path: str = None
):
"""Visualize embeddings in 2D space using t-SNE"""
from sklearn.manifold import TSNE
logger.info("Creating 2D embedding visualization...")
speaker_labels = list(embeddings.keys())
embedding_list = np.array([embeddings[s] for s in speaker_labels])
# t-SNE projection
tsne = TSNE(n_components=2, random_state=42, perplexity=1)
embedding_2d = tsne.fit_transform(embedding_list)
# Plot
fig, ax = plt.subplots(figsize=(10, 8))
colors = plt.cm.Set1(np.linspace(0, 1, len(set(speaker_mapping.values()))))
color_map = {
speaker: colors[i]
for i, speaker in enumerate(sorted(set(speaker_mapping.values())))
}
for orig_label, (x, y) in zip(speaker_labels, embedding_2d):
cluster_label = speaker_mapping[orig_label]
ax.scatter(x, y, c=[color_map[cluster_label]], s=300, alpha=0.7)
ax.annotate(cluster_label, (x, y), ha='center', va='center')
ax.set_xlabel('t-SNE Component 1')
ax.set_ylabel('t-SNE Component 2')
ax.set_title('Speaker Embeddings Clustering')
ax.grid(alpha=0.3)
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
logger.info(f"Embedding visualization saved to {save_path}")
return fig
5. Complete Example with All Features
def advanced_example():
"""Advanced usage with multiple clustering methods"""
pipeline = AdvancedClusteringPipeline(
whisper_model="small",
device="cuda"
)
audio_file = "meeting.wav"
# Get transcription and diarization
transcription = pipeline.transcribe_audio(audio_file)
diarization = pipeline.perform_diarization(audio_file)
embeddings = pipeline.extract_embeddings(audio_file, diarization)
print("Testing different clustering methods:\n")
# Method 1: Hierarchical clustering (original)
print("1. Hierarchical Clustering:")
mapping1 = pipeline.cluster_speakers(embeddings, n_clusters=2)
print(f" Mapping: {mapping1}\n")
# Method 2: K-means
print("2. K-means Clustering:")
mapping2 = pipeline.cluster_speakers_kmeans(embeddings, n_speakers=2)
print(f" Mapping: {mapping2}\n")
# Method 3: DBSCAN
print("3. DBSCAN Clustering:")
mapping3 = pipeline.cluster_speakers_dbscan(embeddings, eps=0.3)
print(f" Mapping: {mapping3}\n")
# Use best mapping for final result
result = pipeline.process(audio_file, n_clusters=2)
# Visualizations
visualizer = DiarizationVisualizer()
visualizer.plot_segments(result, save_path="diarization.png")
pipeline.plot_embeddings_2d(embeddings, mapping1, save_path="embeddings_2d.png")
# Export results
df = visualizer.export_to_dataframe(result)
# Print statistics
print("\n" + "="*60)
print("STATISTICS")
print("="*60)
for speaker in result.speakers:
speaker_data = df[df['speaker'] == speaker]
total_time = speaker_data['duration'].sum()
num_segments = len(speaker_data)
print(f"\n{speaker}:")
print(f" Total speaking time: {total_time:.2f}s ({100*total_time/result.duration:.1f}%)")
print(f" Number of segments: {num_segments}")
print(f" Average segment length: {total_time/num_segments:.2f}s")
print(f" Average confidence: {speaker_data['confidence'].mean():.3f}")
return result, embeddings, mapping1
if __name__ == "__main__":
result, embeddings, mapping = advanced_example()
6. Real-time Processing Example
class RealtimeDiarizationProcessor:
"""Process audio in chunks for near real-time results"""
def __init__(self, pipeline: SpeakerDiarizationPipeline, chunk_duration: float = 10):
self.pipeline = pipeline
self.chunk_duration = chunk_duration
self.results = []
def process_stream(self, audio_file: str, callback=None):
"""Process audio file in chunks"""
import soundfile as sf
logger.info(f"Loading audio for streaming processing...")
audio, sr = sf.read(audio_file)
chunk_samples = int(self.chunk_duration * sr)
total_chunks = (len(audio) + chunk_samples - 1) // chunk_samples
for i in range(total_chunks):
start_idx = i * chunk_samples
end_idx = min((i + 1) * chunk_samples, len(audio))
chunk = audio[start_idx:end_idx]
logger.info(f"Processing chunk {i+1}/{total_chunks}")
if callback:
callback(chunk, i, total_chunks)
yield {
'chunk_idx': i,
'start_time': start_idx / sr,
'end_time': end_idx / sr,
'audio': chunk
}
# Example callback for real-time processing
def process_chunk_callback(chunk, chunk_idx, total_chunks):
logger.info(f"Chunk {chunk_idx + 1}/{total_chunks}: {len(chunk)} samples")
if __name__ == "__main__":
pipeline = SpeakerDiarizationPipeline()
processor = RealtimeDiarizationProcessor(pipeline, chunk_duration=10)
for chunk_info in processor.process_stream("meeting.wav", process_chunk_callback):
pass
Key Features:
✅ Local Whisper - No API calls, full control
✅ Pyannote Diarization - State-of-the-art speaker segmentation
✅ Embedding Clustering - Multiple clustering algorithms (hierarchical, K-means, DBSCAN)
✅ Alignment - Matches transcription with speaker segments
✅ Visualization - Timeline and 2D embedding plots
✅ Multiple Export Formats - SRT, CSV, DataFrame
✅ Statistics - Speaking time, confidence scores per speaker
✅ Real-time Processing - Stream processing support
This implementation handles the complete pipeline from audio to labeled transcription! 🎙️