Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download benchmark/diarization.py from treble-technologies/ffasr: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/benchmark/diarization.py
- Command line
-
hf download hf://spaces/treble-technologies/ffasr/benchmark/diarization.py
-
curl -L -o diarization.py https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/benchmark/diarization.py
10.4 kB
| """ | |
| 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 | |