File size: 5,013 Bytes
547c405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare end-of-turn detectors scored by ``bench.py pipecat``, clip for clip.

Reads the per-clip scores of several result folders, keeps the clips they all scored, and prints
each system's accuracy per condition and the paired differences asked for, with 95% intervals
from a paired bootstrap over clips.

    python compare.py results/pipecat results/smartturn results/phone-1 \
        --pairs phone-1:original phone-1:smart_turn
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np


def load(folders: list[Path]) -> tuple[list[dict], list[str]]:
    """One row per clip scored in every folder, and the ``system/condition`` keys found."""
    merged: dict[str, dict] = {}
    for position, folder in enumerate(folders):
        seen = set()
        for path in sorted(folder.glob("*.jsonl")):
            for line in path.read_text(encoding="utf-8").splitlines():
                if line:
                    row = json.loads(line)
                    seen.add(row["id"])
                    if position == 0:
                        merged[row["id"]] = row
                    elif row["id"] in merged:
                        merged[row["id"]].update({k: v for k, v in row.items() if "/" in k})
        merged = {clip: row for clip, row in merged.items() if clip in seen}
    rows = list(merged.values())
    return rows, sorted(k for k in rows[0] if "/" in k)


def interval(values: np.ndarray) -> str:
    low, high = np.percentile(values, [2.5, 97.5])
    return f"({100 * low:+.2f} to {100 * high:+.2f})"


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("results", type=Path, nargs="+")
    parser.add_argument("--pairs", nargs="*", default=[], help="system:baseline, compared in every shared condition")
    parser.add_argument("--resamples", type=int, default=2000)
    parser.add_argument("--out", type=Path, default=None, help="also write the numbers as JSON")
    args = parser.parse_args()

    from sklearn import metrics

    rows, keys = load(args.results)
    labels = np.array([r["endpoint_bool"] for r in rows], dtype=bool)
    real = ~np.array([r["synthetic"] for r in rows], dtype=bool)
    scores = {k: np.array([r[k] for r in rows]) for k in keys}
    correct = {k: (scores[k] > 0.5) == labels for k in keys}
    draws = np.random.default_rng(0).integers(0, len(rows), (args.resamples, len(rows)))
    result = {"clips": len(rows), "real_clips": int(real.sum()), "systems": {}, "pairs": {}, "drops": {}}

    print(f"{len(rows)} clips scored by every system ({int(real.sum())} real recordings)\n")
    print(f"{'system/condition':28} accuracy     AUC   real recordings   synthetic")
    for key in keys:
        entry = {
            "accuracy": float(correct[key].mean()),
            "auc": float(metrics.roc_auc_score(labels, scores[key])),
            "accuracy_real": float(correct[key][real].mean()),
            "accuracy_synthetic": float(correct[key][~real].mean()),
        }
        result["systems"][key] = entry
        print(f"{key:28} {100 * entry['accuracy']:7.2f}%  {entry['auc']:.4f}  {100 * entry['accuracy_real']:14.2f}%  {100 * entry['accuracy_synthetic']:9.2f}%")

    systems = sorted({k.split("/")[0] for k in keys})
    print("\nLoss against the same system on clean audio, in points:")
    for system in systems:
        for key in keys:
            name, condition = key.split("/")
            if name == system and condition != "clean" and f"{system}/clean" in correct:
                gap = correct[key].astype(float) - correct[f"{system}/clean"]
                result["drops"][key] = {"points": float(100 * gap.mean()), "interval": [float(100 * v) for v in np.percentile(gap[draws].mean(axis=1), [2.5, 97.5])]}
                print(f"  {key:26} {100 * gap.mean():+.2f} {interval(gap[draws].mean(axis=1))}")

    for pair in args.pairs:
        system, baseline = pair.split(":")
        print(f"\n{system} minus {baseline}, accuracy in points:")
        for key in keys:
            name, condition = key.split("/")
            other = f"{baseline}/{condition}"
            if name != system or other not in correct:
                continue
            gap = correct[key].astype(float) - correct[other]
            entry = {"points": float(100 * gap.mean()), "interval": [float(100 * v) for v in np.percentile(gap[draws].mean(axis=1), [2.5, 97.5])]}
            entry["points_real"] = float(100 * gap[real].mean())
            entry["decisions_differ"] = float(((scores[key] > 0.5) != (scores[other] > 0.5)).mean())
            result["pairs"][f"{pair}/{condition}"] = entry
            print(f"  {condition:8} {entry['points']:+.2f} {interval(gap[draws].mean(axis=1))}   real recordings {entry['points_real']:+.2f}   decisions differ on {100 * entry['decisions_differ']:.1f}%")

    if args.out:
        args.out.write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()