""" Speaker diarization engine — maps speakers to transcription segments. Author: Maaldeens License: MIT """ import os import time import logging import math from typing import List, Dict, Optional import numpy as np try: import torch as _torch _TORCH_AVAILABLE = True except ImportError: _TORCH_AVAILABLE = False logger = logging.getLogger(__name__) # Optional pyannote import — diarization gracefully degrades if unavailable # Catches ImportError and OSError (e.g. missing CUDA libs on CPU-only containers) _PYANNOTE_IMPORT_ERROR: str = "" try: from pyannote.audio import Pipeline as DiarizationPipeline _PYANNOTE_AVAILABLE = True except Exception as e: _PYANNOTE_AVAILABLE = False _PYANNOTE_IMPORT_ERROR = f"{type(e).__name__}: {e}" logger.warning(f"pyannote.audio unavailable. {_PYANNOTE_IMPORT_ERROR}. Speaker diarization will be disabled.") class DiarizationEngine: """ Wraps pyannote.audio speaker diarization and aligns speaker labels with ASR transcript segments by time overlap. """ def __init__(self, hf_token: Optional[str] = None): self.pipeline = None self.hf_token = hf_token or os.getenv("HF_TOKEN") self._available = _PYANNOTE_AVAILABLE and self.hf_token is not None def _load_pipeline(self): if self.pipeline is not None: return if not _PYANNOTE_AVAILABLE: raise RuntimeError("pyannote.audio is not installed. Install it to enable diarization.") if not self.hf_token: raise RuntimeError( "HF_TOKEN environment variable is required for pyannote speaker diarization. " "Set it in your Hugging Face Space secrets or pass hf_token to DiarizationEngine." ) logger.info("Loading pyannote/speaker-diarization-3.1 pipeline…") try: # `token` is the current param name; `use_auth_token` was deprecated # in huggingface_hub ≥0.12. Try both for maximum compatibility. self.pipeline = DiarizationPipeline.from_pretrained( "pyannote/speaker-diarization-3.1", token=self.hf_token, ) except TypeError: self.pipeline = DiarizationPipeline.from_pretrained( "pyannote/speaker-diarization-3.1", use_auth_token=self.hf_token, ) # pyannote returns None (rather than raising) when the token cannot # access the gated model, which surfaced as "'NoneType' object has no # attribute 'to'". Fail with the actual cause instead. if self.pipeline is None: raise RuntimeError( "Could not load pyannote/speaker-diarization-3.1: HF_TOKEN lacks access " "to the gated model (accept its terms on huggingface.co with the token's account)." ) # Explicitly move to GPU — pyannote does not always auto-detect CUDA # when loaded inside a thread executor (the default device stays CPU). if _TORCH_AVAILABLE and _torch.cuda.is_available(): self.pipeline.to(_torch.device("cuda:0")) logger.info("Diarization pipeline moved to cuda:0.") else: logger.warning("CUDA not available — diarization will run on CPU (slow).") logger.info("Diarization pipeline loaded successfully.") def is_available(self) -> bool: return self._available def diarize( self, audio_path: str, num_speakers: Optional[int] = None, ) -> List[Dict]: """ Run diarization on an audio file. Returns a list of dicts: [{"start": float, "end": float, "speaker": "SPEAKER_00"}, ...] """ self._load_pipeline() kwargs = {} if num_speakers is not None: kwargs["num_speakers"] = num_speakers # No minimum otherwise: forcing two speakers split one-person # recordings in two. Voices pyannote merges are separated afterwards # by the per-sentence voice check (refine_with_voices). device = getattr(self.pipeline, "device", "unknown") logger.info(f"Running diarization on {audio_path} (num_speakers={num_speakers}, device={device})…") started = time.time() # Hand pyannote the waveform already in memory: given a path it # re-reads a crop from disk for every sliding window, which is a large # share of the runtime on hour-long recordings. try: import soundfile as _sf data, sr = _sf.read(audio_path, dtype="float32", always_2d=True) audio_input = {"waveform": _torch.from_numpy(data.T.copy()), "sample_rate": sr} except Exception as e: logger.warning(f"Could not preload audio for diarization ({e}); passing path.") audio_input = audio_path diarization = self.pipeline(audio_input, **kwargs) logger.info(f"Diarization took {time.time() - started:.1f}s on {device}.") turns = [] speaker_map: Dict[str, str] = {} next_idx = 0 for turn, _, speaker in diarization.itertracks(yield_label=True): if speaker not in speaker_map: speaker_map[speaker] = f"SPEAKER_{next_idx:02d}" next_idx += 1 turns.append({ "start": float(turn.start), "end": float(turn.end), "speaker": speaker_map[speaker], }) logger.info(f"Diarization complete: {len(turns)} turns, {next_idx} speakers.") return turns def refine_speakers(self, audio_path: str, segments: List[Dict], num_speakers: Optional[int] = None) -> List[Dict]: """Second opinion on who said each sentence, from a voice fingerprint of the whole sentence (see refine_with_voices). Uses the embedding model pyannote has already loaded. Never fails the job: any problem keeps pyannote's labels.""" try: self._load_pipeline() embed = getattr(self.pipeline, "_embedding", None) if embed is None: return segments import soundfile as _sf data, sr = _sf.read(audio_path, dtype="float32", always_2d=True) wave = _torch.from_numpy(data.mean(axis=1).copy()) target = getattr(embed, "sample_rate", 16000) if sr != target: import torchaudio wave = torchaudio.functional.resample(wave, sr, target) sr = target started = time.time() prints: List[Optional[np.ndarray]] = [] for seg in segments: a, b = float(seg.get("start", 0)), float(seg.get("end", 0)) if not seg.get("speaker") or b - a < VOICE_MIN_SEC: prints.append(None) continue if b - a > VOICE_MAX_SEC: mid = (a + b) / 2 a, b = mid - VOICE_MAX_SEC / 2, mid + VOICE_MAX_SEC / 2 clip = wave[int(a * sr):int(b * sr)] if clip.numel() < int(VOICE_MIN_SEC * sr): prints.append(None) continue vec = np.asarray(embed(clip.reshape(1, 1, -1))).reshape(-1) prints.append(vec if np.all(np.isfinite(vec)) else None) out = refine_with_voices(segments, prints, num_speakers) logger.info(f"Voice check took {time.time() - started:.1f}s for {len(segments)} sentences.") return out except Exception as e: logger.warning(f"Voice check skipped: {type(e).__name__}") return segments @staticmethod def align_speakers( transcript_segments: List[Dict], speaker_turns: List[Dict], ) -> List[Dict]: """ Assign a speaker to each transcript segment by accumulating temporal overlap across all speaker turns and picking the dominant speaker. This works for both fine-grained word-level segments and coarse chunk-level segments (e.g. 30 s) created by the audio chunker. """ # Union overlapping turns per speaker so duplicate/overlapping annotations # cannot count the same second twice and incorrectly win a segment. intervals: Dict[str, List] = {} for turn in speaker_turns: start, end = turn.get("start"), turn.get("end") if (not isinstance(start, (int, float)) or not isinstance(end, (int, float)) or not math.isfinite(start) or not math.isfinite(end) or end <= start or not turn.get("speaker")): continue intervals.setdefault(turn["speaker"], []).append((start, end)) turns = [] for speaker, spans in intervals.items(): merged = [] for start, end in sorted(spans): if merged and start <= merged[-1][1]: merged[-1] = (merged[-1][0], max(end, merged[-1][1])) else: merged.append((start, end)) turns.extend({"start": a, "end": b, "speaker": speaker} for a, b in merged) turns.sort(key=lambda t: (t["start"], t["end"], t["speaker"])) if not turns: return transcript_segments aligned = [] for seg in transcript_segments: start, end = seg.get("start", 0), seg.get("end", seg.get("start", 0)) out = dict(seg) out.pop("speaker", None) if not all(isinstance(v, (int, float)) and math.isfinite(v) for v in (start, end)) or end < start: aligned.append(out) continue overlap: Dict[str, float] = {} for turn in turns: seconds = max(0.0, min(end, turn["end"]) - max(start, turn["start"])) if seconds: speaker = turn["speaker"] overlap[speaker] = overlap.get(speaker, 0.0) + seconds if overlap: out["speaker"] = max(overlap, key=overlap.get) else: # Allow small timestamp drift, but never invent an identity # across a long silent gap. Unknown is preferable to false attribution. distance = lambda t: max(t["start"] - end, start - t["end"], 0.0) nearest = min(turns, key=distance) if distance(nearest) <= 0.5: out["speaker"] = nearest["speaker"] aligned.append(out) return aligned # ── Voice check per sentence ──────────────────────────────────────────────── # pyannote decides who speaks in 10 s windows. Two similar voices taking short # turns (a dialogue between two men, say) can end up as one speaker, and an # English narrator then takes the second slot. A voice fingerprint of each # whole sentence separates them much better, so after alignment the sentences # are also grouped by voice, and that grouping replaces pyannote's when it # separates the voices clearly better (silhouette score). VOICE_MIN_SEC = 1.0 # shorter sentences give unreliable fingerprints VOICE_MAX_SEC = 20.0 # long sentences: fingerprint the middle 20 s VOICE_THRESHOLD = 0.45 # cosine distance at which two voices stay apart VOICE_MIN_SHARE = 0.02 # a "voice" with less speech than this... VOICE_MIN_TOTAL_SEC = 3.0 # ...or this joins its nearest real voice VOICE_SWITCH_MARGIN = 0.10 # voice grouping must beat pyannote's by this much VOICE_ONE_SPEAKER_SILHOUETTE = 0.15 # below this pyannote's split doesn't follow the voices VOICE_SPLIT_MIN = 0.30 # voice groups must be at least this distinct to add speakers # (two-person dialogues scored 0.49-0.56; one-person tracks 0.10-0.15) def _silhouette(V: np.ndarray, labels: List) -> float: """Mean cosine silhouette of a labelling (rows of V are unit vectors).""" labels = np.asarray(labels, dtype=object) groups = list(dict.fromkeys(labels.tolist())) if len(groups) < 2: return -1.0 D = 1.0 - V @ V.T scores = [] for i in range(len(V)): own = labels == labels[i] n_own = own.sum() - 1 if n_own == 0: scores.append(0.0) continue a = D[i, own].sum() / n_own b = min(D[i, labels == g].mean() for g in groups if g != labels[i]) scores.append((b - a) / max(a, b) if max(a, b) > 0 else 0.0) return float(np.mean(scores)) def group_voices(V: np.ndarray, durations: np.ndarray, num_speakers: Optional[int] = None) -> np.ndarray: """Cluster sentence fingerprints into voices (average linkage, cosine).""" from scipy.cluster.hierarchy import linkage, fcluster if len(V) < 2: return np.zeros(len(V), dtype=int) Z = linkage(V, method="average", metric="cosine") if num_speakers: lab = fcluster(Z, t=num_speakers, criterion="maxclust") else: lab = fcluster(Z, t=VOICE_THRESHOLD, criterion="distance") total = durations.sum() big = [c for c in set(lab) if durations[lab == c].sum() >= max(VOICE_MIN_TOTAL_SEC, VOICE_MIN_SHARE * total)] if big: cent = {c: V[lab == c].mean(0) for c in big} for k, c in enumerate(lab): if c not in big: lab[k] = max(big, key=lambda b: float(V[k] @ cent[b]) / float(np.linalg.norm(cent[b]))) return lab def refine_with_voices(segments: List[Dict], fingerprints: List[Optional[np.ndarray]], num_speakers: Optional[int] = None) -> List[Dict]: """Relabel speakers by voice when that separates them clearly better. `fingerprints[i]` is sentence i's embedding, or None when too short.""" idx = [i for i, f in enumerate(fingerprints) if f is not None and segments[i].get("speaker") and np.isfinite(f).all()] if len(idx) < 4: return segments V = np.stack([fingerprints[i] for i in idx]).astype(np.float64) V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-9 dur = np.array([segments[i]["end"] - segments[i]["start"] for i in idx]) voice = group_voices(V, dur, num_speakers) current = [segments[i].get("speaker") or "none" for i in idx] s_current = _silhouette(V, current) s_voice = _silhouette(V, list(voice)) if len(set(voice)) > 1 else -1.0 if not num_speakers and s_current < VOICE_ONE_SPEAKER_SILHOUETTE and s_voice < VOICE_SPLIT_MIN: # Neither pyannote's split nor the voices show distinct people: # one speaker (a single-voice lesson was coming out as 2-3 speakers). if len(set(current)) > 1: logger.info(f"Voice check: one speaker (pyannote had {len(set(current))}).") out = [dict(s) for s in segments] for seg in out: if seg.get("speaker"): seg["speaker"] = "SPEAKER_00" return out return segments if len(set(voice)) < 2: return segments if not num_speakers and len(set(voice)) < len(set(current)): # The fix is for voices pyannote merged; never use it to merge people # pyannote kept apart (no reference shows that would be right). return segments if s_voice < max(s_current + VOICE_SWITCH_MARGIN, VOICE_SPLIT_MIN if not num_speakers else -1.0): logger.info(f"Voice check kept pyannote's speakers (silhouette {s_current:.2f} vs {s_voice:.2f}).") return segments # Name voices SPEAKER_00, 01... in order of first appearance. names: Dict[int, str] = {} for v in voice: names.setdefault(int(v), f"SPEAKER_{len(names):02d}") labelled = {i: names[int(v)] for i, v in zip(idx, voice)} out = [dict(s) for s in segments] for i, name in labelled.items(): out[i]["speaker"] = name # Sentences too short to fingerprint take the nearest labelled sentence. for i, seg in enumerate(out): if i in labelled or not seg.get("speaker"): continue nearest = min(labelled, key=lambda j: abs((segments[j]["start"] + segments[j]["end"]) / 2 - (seg["start"] + seg["end"]) / 2)) seg["speaker"] = labelled[nearest] logger.info(f"Voice check relabelled speakers: {len(set(current))} -> {len(names)} " f"(silhouette {s_current:.2f} -> {s_voice:.2f}).") return out