File size: 10,415 Bytes
5f0f535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Packed speaker-diarization test sets and DER / JER scoring.

Packed file layout (``packed/diar_<snr>_<overlap>.pt``, see ``diarization_config``)::

    {sample_id: {
        "waveform": Tensor[T] (mono),
        "sample_rate": int,
        "segments": [(start_s, end_s, speaker), ...]   # or dicts / RTTM text
    }, ...}

Scoring is frame-based (10 ms) with no forgiveness collar and overlapping speech scored,
following the NIST md-eval decomposition:

    miss  = sum_t max(0, N_ref(t) - N_hyp(t))
    fa    = sum_t max(0, N_hyp(t) - N_ref(t))
    conf  = sum_t min(N_ref(t), N_hyp(t)) - N_correct(t)
    DER   = (miss + fa + conf) / sum_t N_ref(t)

where reference and hypothesis speakers are matched one-to-one to maximise overlap.
JER (DIHARD II) averages ``1 - |ref ∩ hyp| / |ref ∪ hyp|`` over reference speakers under
the mapping that maximises Jaccard similarity; unmatched reference speakers count as 1.
"""

from __future__ import annotations

import itertools
import math
import os
import re
from collections.abc import Callable, Iterable

import numpy as np

from diarization_config import CONDITIONS_BY_KEY, SCORING_FRAME_S
from storage import download_bucket_file

Segment = tuple[float, float, str]

_dataset_cache: dict[str, dict] = {}


def load_packed_condition(condition_key: str) -> dict:
    """Download and load a packed diarization split (cached after first load)."""
    import torch

    if condition_key in _dataset_cache:
        return _dataset_cache[condition_key]
    local_path = download_bucket_file(CONDITIONS_BY_KEY[condition_key].packed_path)
    data = torch.load(local_path, weights_only=False)
    os.unlink(local_path)
    _dataset_cache[condition_key] = data
    return data


# ---------------------------------------------------------------------------
# Segment parsing
# ---------------------------------------------------------------------------

_RTTM_LINE = re.compile(r"^\s*SPEAKER\s+\S+\s+\S+\s+([\d.]+)\s+([\d.]+)\s+\S+\s+\S+\s+(\S+)")


def _segments_from_text(text: str) -> list[Segment]:
    """RTTM lines, or ``start end speaker`` lines (NeMo Sortformer style)."""
    out: list[Segment] = []
    for line in text.splitlines():
        m = _RTTM_LINE.match(line)
        if m:
            start, dur, spk = float(m.group(1)), float(m.group(2)), m.group(3)
            out.append((start, start + dur, spk))
            continue
        parts = line.replace(",", " ").split()
        if len(parts) >= 3:
            try:
                out.append((float(parts[0]), float(parts[1]), str(parts[2])))
            except ValueError:
                continue
    return out


def normalize_segments(raw) -> list[Segment]:
    """Coerce diarizer output into ``[(start_s, end_s, speaker), ...]``.

    Accepts tuples / lists, dicts (``start``/``end``/``speaker`` or ``label``), RTTM or
    ``start end speaker`` text, objects with ``.start/.end/.speaker``, and pyannote
    ``Annotation`` (or pyannote 4 ``DiarizeOutput``) objects.
    """
    if raw is None:
        return []
    raw = getattr(raw, "speaker_diarization", raw)
    if hasattr(raw, "itertracks"):
        return [
            (float(turn.start), float(turn.end), str(label))
            for turn, _track, label in raw.itertracks(yield_label=True)
        ]
    if isinstance(raw, str):
        return _segments_from_text(raw)
    out: list[Segment] = []
    for item in raw:
        if isinstance(item, str):
            out.extend(_segments_from_text(item))
            continue
        if isinstance(item, dict):
            start = item.get("start", item.get("start_s"))
            end = item.get("end", item.get("end_s"))
            spk = item.get("speaker", item.get("label", item.get("spk")))
        elif hasattr(item, "start") and hasattr(item, "end"):
            start, end = item.start, item.end
            spk = getattr(item, "speaker", getattr(item, "label", None))
        else:
            seq = list(item)
            if len(seq) < 3:
                continue
            start, end, spk = seq[0], seq[1], seq[2]
        try:
            s, e = float(start), float(end)
        except (TypeError, ValueError):
            continue
        if e > s and spk is not None:
            out.append((s, e, str(spk)))
    return out


def reference_segments(sample: dict) -> list[Segment]:
    for key in ("segments", "rttm", "speakers"):
        if key in sample and sample[key] is not None:
            return normalize_segments(sample[key])
    raise KeyError("packed diarization sample needs a 'segments' (or 'rttm') field")


# ---------------------------------------------------------------------------
# Scoring
# ---------------------------------------------------------------------------


def _activity(segments: Iterable[Segment], n_frames: int, frame_s: float) -> tuple[list[str], np.ndarray]:
    labels = sorted({spk for _, _, spk in segments})
    index = {spk: i for i, spk in enumerate(labels)}
    act = np.zeros((len(labels), n_frames), dtype=bool)
    for start, end, spk in segments:
        a = max(0, int(round(start / frame_s)))
        b = min(n_frames, int(round(end / frame_s)))
        if b > a:
            act[index[spk], a:b] = True
    return labels, act


def _max_weight_matching(weights: np.ndarray) -> list[tuple[int, int]]:
    """One-to-one assignment maximising total weight (rows x cols, either may be larger)."""
    n_r, n_c = weights.shape
    if n_r == 0 or n_c == 0:
        return []
    try:
        from scipy.optimize import linear_sum_assignment

        rows, cols = linear_sum_assignment(-weights)
        return list(zip(rows.tolist(), cols.tolist()))
    except ImportError:
        pass
    transpose = n_r > n_c
    w = weights.T if transpose else weights
    small, large = w.shape
    if math.perm(large, small) <= 200_000:
        best, best_perm = -1.0, ()
        for perm in itertools.permutations(range(large), small):
            total = float(sum(w[i, j] for i, j in enumerate(perm)))
            if total > best:
                best, best_perm = total, perm
        pairs = list(enumerate(best_perm))
    else:
        pairs, used_r, used_c = [], set(), set()
        for flat in np.argsort(-w, axis=None):
            i, j = divmod(int(flat), large)
            if i not in used_r and j not in used_c:
                pairs.append((i, j))
                used_r.add(i)
                used_c.add(j)
    return [(j, i) for i, j in pairs] if transpose else pairs


def score_recording(
    ref: list[Segment],
    hyp: list[Segment],
    *,
    duration_s: float | None = None,
    frame_s: float = SCORING_FRAME_S,
) -> dict:
    """Per-recording error durations (seconds) + JER terms + speaker counts."""
    end = max([e for _, e, _ in ref] + [e for _, e, _ in hyp] + [duration_s or 0.0, 0.0])
    n_frames = max(1, int(math.ceil(end / frame_s)))
    ref_labels, R = _activity(ref, n_frames, frame_s)
    hyp_labels, H = _activity(hyp, n_frames, frame_s)

    n_ref = R.sum(axis=0).astype(np.int64)
    n_hyp = H.sum(axis=0).astype(np.int64)
    inter = R.astype(np.int64) @ H.T.astype(np.int64) if R.size and H.size else np.zeros(
        (len(ref_labels), len(hyp_labels)), dtype=np.int64
    )

    n_correct = np.zeros(n_frames, dtype=np.int64)
    for i, j in _max_weight_matching(inter.astype(float)):
        n_correct += (R[i] & H[j]).astype(np.int64)

    miss = np.maximum(0, n_ref - n_hyp).sum()
    fa = np.maximum(0, n_hyp - n_ref).sum()
    conf = (np.minimum(n_ref, n_hyp) - n_correct).sum()

    jer_sum = 0.0
    if ref_labels:
        ref_tot = R.sum(axis=1).astype(float)
        hyp_tot = H.sum(axis=1).astype(float) if hyp_labels else np.zeros(0)
        union = ref_tot[:, None] + hyp_tot[None, :] - inter if hyp_labels else np.zeros((len(ref_labels), 0))
        jacc = np.divide(inter, union, out=np.zeros_like(union, dtype=float), where=union > 0)
        matched = dict(_max_weight_matching(jacc))
        jer_sum = float(sum(1.0 - (jacc[i, matched[i]] if i in matched else 0.0) for i in range(len(ref_labels))))

    hyp_active = int((H.sum(axis=1) > 0).sum()) if hyp_labels else 0
    ref_active = int((R.sum(axis=1) > 0).sum()) if ref_labels else 0
    return {
        "total": float(n_ref.sum()) * frame_s,
        "miss": float(miss) * frame_s,
        "fa": float(fa) * frame_s,
        "conf": float(conf) * frame_s,
        "jer_sum": jer_sum,
        "n_ref_spk": len(ref_labels),
        "count_ok": int(hyp_active == ref_active),
    }


def aggregate_scores(per_file: list[dict]) -> dict[str, float]:
    """Corpus-level metrics (fractions): DER and components pooled over speech time."""
    total = sum(s["total"] for s in per_file)
    miss = sum(s["miss"] for s in per_file)
    fa = sum(s["fa"] for s in per_file)
    conf = sum(s["conf"] for s in per_file)
    n_spk = sum(s["n_ref_spk"] for s in per_file)
    out = {
        "der": (miss + fa + conf) / total if total > 0 else 0.0,
        "miss": miss / total if total > 0 else 0.0,
        "fa": fa / total if total > 0 else 0.0,
        "conf": conf / total if total > 0 else 0.0,
        "jer": sum(s["jer_sum"] for s in per_file) / n_spk if n_spk > 0 else 0.0,
        "spkacc": sum(s["count_ok"] for s in per_file) / len(per_file) if per_file else 0.0,
    }
    return {k: round(v, 4) for k, v in out.items()}


def evaluate_condition_timed(
    diarize: Callable[..., list[Segment]],
    condition_key: str,
    progress_cb=None,
) -> tuple[dict[str, float], int, float, float]:
    """Run ``diarize(audio_np, sr)`` on a packed split -> (metrics, n, audio_s, infer_s)."""
    import time

    data = load_packed_condition(condition_key)
    items = list(data.items())
    per_file: list[dict] = []
    audio_s = 0.0
    infer_s = 0.0
    for i, (_sid, sample) in enumerate(items):
        audio_np = sample["waveform"].numpy()
        sr = int(sample.get("sample_rate", 16000))
        dur = float(len(audio_np)) / float(sr)
        audio_s += dur
        t0 = time.perf_counter()
        hyp = normalize_segments(diarize(audio_np, sr))
        infer_s += time.perf_counter() - t0
        per_file.append(score_recording(reference_segments(sample), hyp, duration_s=dur))
        if progress_cb is not None:
            try:
                progress_cb(condition_key, i + 1, len(items))
            except Exception:
                pass
    return aggregate_scores(per_file), len(per_file), audio_s, infer_s