Repository navigation
Description
Context
In meetings with 3 or more participants, the current online speaker diarization algorithm fails to accurately separate speakers. Speaker labels get merged or swapped, which compromises transcription accuracy and downstream features like action item extraction.
A real-world example of this issue in action shows generic tags like Speaker 1, Speaker 2, and Speaker 3 displayed in the transcription feed. Under Speaker 1, the text simply reads "You.", illustrating how the system struggles to resolve who the primary user is versus other meeting participants.
Important Note: While the screenshot illustrates this in the mobile app UI, the solution must be entirely backend-driven and platform-agnostic. Do not build any dependencies on client-side screen layout or UI state.
Visual Comparison: Online vs. Offline Clustering
graph TD
subgraph "1. Online Centroid-Based (Current: Centroid Drift)"
S1["Segment 1: Spk A"] --> C1(Centroid A)
S2["Segment 2: Spk B"] --> C2(Centroid B)
S3["Segment 3: Noisy A"] --> C1_drift(Shifted Centroid A)
S4["Segment 4: Spk C"] --> C1_drift
end
subgraph "2. Offline Agglomerative Hierarchical (Proposed: Stable Linkage)"
E1[All Segments] --> M[Cosine Distance Matrix]
M --> L[SciPy Linkage Tree]
L --> Cl(Clusters: A, B, C)
Cl --> Final(Attributed Speaker Groups)
end
Root Cause Analysis
The current diarization pipeline in backend/parakeet/transcribe.py (specifically _diarize_segments) uses an online centroid-based clustering algorithm. For 3+ speakers, this approach breaks down due to three factors:
- Order Dependency: Processing segments sequentially makes the initial centroids highly sensitive to the voice dynamics of the first few speakers.
- Centroid Drift: Matched segment embeddings are averaged into centroids:
$$\text{centroid}{\text{new}} = \frac{\text{centroid}{\text{old}} \cdot n + \text{embedding}}{n + 1}$$
As noisy or short segments get merged, the centroids drift. This causes the cluster boundary to shift, eventually merging segments from different speakers. - Unbounded Clustering Heuristic: PyAnnote community pipelines run with no speaker count constraints (e.g.,
num_speakers,min_speakers,max_speakers), forcing the clustering algorithm to guess the partition size.
Solution Design & Technical Specs
We replace the online centroid matching in _diarize_segments with an offline average-linkage Agglomerative Hierarchical Clustering (AHC) algorithm using SciPy.
1. Exposed API Routing (backend/parakeet/main.py)
Expose query parameters for optional speaker count guidelines:
@app.post("/v2/transcribe")
async def transcribe_v2(
file: UploadFile = File(...),
diarize: bool = Form(True),
min_speakers: Optional[int] = Query(None),
max_speakers: Optional[int] = Query(None),
num_speakers: Optional[int] = Query(None),
):
...2. Agglomerative Hierarchical Clustering (backend/parakeet/transcribe.py)
Using SciPy, we construct a pairwise distance matrix of all valid segment embeddings (excluding segments shorter than MIN_SEGMENT_DURATION = 0.6 seconds):
from scipy.cluster.hierarchy import linkage, fcluster
import numpy as np
# Vectorized distance computation and average linkage
X = np.vstack(embeddings)
Z = linkage(X, method='average', metric='cosine')3. Constraint Clamping & Tree Cutting
Partition the distance tree at the predefined cosine threshold SPEAKER_MATCH_THRESHOLD = 0.45 and clamp the outputs to user constraints:
if num_speakers is not None:
n_clust = min(num_speakers, len(embeddings))
labels = fcluster(Z, t=n_clust, criterion='maxclust')
else:
labels = fcluster(Z, t=SPEAKER_MATCH_THRESHOLD, criterion='distance')
num_clusters = len(np.unique(labels))
if min_speakers is not None and num_clusters < min_speakers:
n_clust = min(min_speakers, len(embeddings))
labels = fcluster(Z, t=n_clust, criterion='maxclust')
elif max_speakers is not None and num_clusters > max_speakers:
n_clust = max_speakers
labels = fcluster(Z, t=n_clust, criterion='maxclust')4. Post-Clustering Mapping for Short Clips
Segments that are too short to produce reliable embeddings are mapped to the temporally closest valid segment cluster:
def get_center(s):
return (s["start"] + s["end"]) / 2.0
assigned_labels = {}
for j in range(len(base["segments"])):
if j in valid_labels:
assigned_labels[j] = valid_labels[j]
else:
center_j = get_center(base["segments"][j])
closest_idx = min(valid_indices, key=lambda v: abs(get_center(base["segments"][v]) - center_j))
assigned_labels[j] = valid_labels[closest_idx]Karpathy Guidelines for Implementation
- Surgical Edits: Touch only the clustering logic inside
_diarize_segmentsinbackend/parakeet/transcribe.pyand the parameter schema mapping inbackend/parakeet/main.py. Do not refactor adjacent transcription or VAD code. - Simplicity First: Do not add speculative features or abstract the linkage helper. Keep the scipy operations clean and direct.
- Goal-Driven Verification: Ensure all local test suites run and pass. Run verification commands explicitly:
python -m pytest backend/tests/unit/test_parakeet_diarization.pypython -m pytest backend/tests/unit/test_parakeet_endpoints.py
Verification Plan
- Run the VoxConverse DER benchmark suite:
pytest tests/container/test_parakeet_der_benchmark.py - Verify that aggregate DER drops below 15% for multi-speaker audio clips.
- Verify that memory footprints do not leak or grow exponentially with segment counts.
Activity
[-]Robust 3+ Speaker Diarization via Offline Agglomerative Hierarchical Clustering (AHC)[/-][+]Backend: Offline agglomerative clustering for robust 3+ speaker diarization (#5470)[/+]fix(parakeet): cluster batch diarization offline, not by arrival order
fix(parakeet): cluster batch diarization offline, not by arrival order (