File size: 15,568 Bytes
305b729
 
 
 
 
 
 
32c229b
305b729
6ad496b
305b729
a8bd243
 
1deeec7
 
 
 
 
 
305b729
 
 
4ef007b
ff7b4ba
305b729
 
 
4ef007b
305b729
ff7b4ba
 
305b729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1deeec7
 
 
 
 
 
 
 
 
 
 
 
 
32c229b
 
 
 
 
 
 
 
 
1deeec7
 
 
 
 
 
 
 
 
305b729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e98e60e
 
 
305b729
32c229b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305b729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8bd243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305b729
 
 
 
 
 
3dcdf79
 
 
 
305b729
 
 
 
 
 
 
 
 
 
3dcdf79
 
305b729
 
 
 
3dcdf79
 
 
305b729
3dcdf79
 
 
305b729
 
3dcdf79
305b729
f6a9200
 
 
 
 
 
 
 
 
 
305b729
 
a8bd243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e98e60e
 
 
a8bd243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e98e60e
 
 
 
 
 
 
 
 
 
 
 
 
a8bd243
 
 
 
 
 
e98e60e
a8bd243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
Speaker diarization engine β€” maps speakers to transcription segments.
Author: Maaldeens
License: MIT
"""

import os
import time
import logging
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 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.
        """
        if not speaker_turns:
            return transcript_segments

        aligned = []
        for seg in transcript_segments:
            seg_start = seg.get("start", 0)
            seg_end = seg.get("end", seg_start)
            seg_duration = seg_end - seg_start

            # Accumulate overlap per speaker across all turns
            speaker_overlap: Dict[str, float] = {}
            for turn in speaker_turns:
                ov_start = max(seg_start, turn["start"])
                ov_end = min(seg_end, turn["end"])
                overlap = max(0.0, ov_end - ov_start)
                if overlap > 0:
                    spk = turn["speaker"]
                    speaker_overlap[spk] = speaker_overlap.get(spk, 0.0) + overlap

            best_speaker = None
            best_overlap = 0.0
            for spk, overlap in speaker_overlap.items():
                if overlap > best_overlap:
                    best_overlap = overlap
                    best_speaker = spk

            # A line nobody is heard on (a turn ended just before it, or it
            # falls in a gap pyannote skipped) goes to the closest turn: a
            # line without a speaker reads as a fault in the transcript.
            if not best_speaker:
                mid = (seg_start + seg_end) / 2
                nearest = min(speaker_turns, key=lambda t: max(t["start"] - mid, mid - t["end"], 0.0))
                best_speaker = nearest["speaker"]
            aligned_seg = dict(seg)
            aligned_seg["speaker"] = best_speaker
            aligned.append(aligned_seg)

        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]
    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:
                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:
            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