File size: 11,378 Bytes
a1fe2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate a checkpoint.

Clip level (one window per clip): accuracy, EER, FRR at a fixed FAR, and the
same rates broken down by region, gender, source and label.

Streaming (``--stream``): slides the detector over every full recording, the way
the device runs it, and reports FRR against false accepts per hour for a range
of thresholds. This is the number to use when choosing the shipping threshold.

    vitakws-eval --checkpoint runs/hey_vita/best.pt --split test --stream
"""

from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np

from vitakws import metrics as M
from vitakws.data import audio
from vitakws.data.augment import coloured_noise
from vitakws.data.manifest import KEYWORD_KIND, Item, LabelMap, read_manifest
from vitakws.engine import eval_dataset, load_checkpoint, pick_device
from vitakws.logging_utils import RunLogger
from vitakws.streaming import (
    InferFn,
    StreamConfig,
    onnx_infer_fn,
    score_stream,
    torch_infer_fn,
    window_end_times,
)
from vitakws.train import evaluate_split

STREAM_LEAD = 1.0  # seconds of padding before a positive clip
STREAM_TAIL = 1.0  # seconds after the keyword in which a detection still counts
STREAM_FLOOR_DBFS = -60.0
THRESHOLDS = np.round(np.concatenate([np.arange(0.05, 0.95, 0.05), np.arange(0.95, 1.0, 0.01)]), 2)


def stream_scores(
    items: list[Item], infer: InferFn, label_map: LabelMap, cfg: StreamConfig
) -> tuple[np.ndarray, list[np.ndarray], float]:
    """Peak score near each keyword, the score track of each negative, and negative hours."""
    sr = cfg.sample_rate
    rng = np.random.default_rng(0)
    floor = 10.0 ** (STREAM_FLOOR_DBFS / 20.0)
    peaks, tracks, neg_seconds = [], [], 0.0
    for item in items:
        wave = audio.load(item.audio, sr)
        if item.kind == KEYWORD_KIND:
            kw_end = len(wave) / sr if item.kw_end is None else item.kw_end
            # Cut what follows the scoring region so later speech cannot rescue a miss.
            wave = wave[: int((kw_end + STREAM_TAIL) * sr)]
            wave = np.concatenate([np.zeros(int(STREAM_LEAD * sr), np.float32), wave])
            pad = int((kw_end + STREAM_LEAD + STREAM_TAIL) * sr) - len(wave)
            if pad > 0:
                wave = np.concatenate([wave, np.zeros(pad, np.float32)])
        wave = wave + floor * coloured_noise(len(wave), rng, tilt=1.0) if len(wave) else wave
        probs = score_stream(wave, infer, cfg)
        scores = M.keyword_scores(probs, label_map.keyword_ids)
        if item.kind == KEYWORD_KIND:
            times = window_end_times(len(scores), cfg)
            inside = (times >= kw_end + STREAM_LEAD) & (times <= kw_end + STREAM_LEAD + STREAM_TAIL)
            peaks.append(float(scores[inside].max()) if inside.any() else 0.0)
        else:
            tracks.append(scores)
            neg_seconds += len(wave) / sr
    return np.asarray(peaks), tracks, neg_seconds / 3600.0


def stream_table(
    peaks: np.ndarray, tracks: list[np.ndarray], hours: float, cfg: StreamConfig
) -> list[dict]:
    rows = []
    for thr in THRESHOLDS:
        false_accepts = sum(M.count_events(t, thr, cfg.refractory_hops) for t in tracks)
        rows.append(
            {
                "threshold": float(thr),
                "frr": float((peaks < thr).mean()) if len(peaks) else float("nan"),
                "false_accepts": int(false_accepts),
                "fa_per_hour": false_accepts / hours if hours > 0 else float("nan"),
            }
        )
    return rows


def pick_operating_point(rows: list[dict], target_fa_per_hour: float) -> dict | None:
    """Lowest threshold (so lowest FRR) whose false-accept rate meets the target."""
    ok = [r for r in rows if r["fa_per_hour"] <= target_fa_per_hour]
    return min(ok, key=lambda r: r["threshold"]) if ok else None


def plot_det(scores: np.ndarray, is_pos: np.ndarray, path: Path) -> bool:
    try:
        import matplotlib

        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
    except ImportError:
        return False
    if not is_pos.any() or is_pos.all():
        return False
    _, frr, far = M.det_curve(scores[is_pos], scores[~is_pos])
    fig, ax = plt.subplots(figsize=(5, 4))
    floor = 0.5 / max(len(scores), 1)
    ax.loglog(np.maximum(far, floor), np.maximum(frr, floor))
    ax.set_xlabel("False accept rate (negative clips)")
    ax.set_ylabel("False reject rate")
    ax.set_title("DET curve, clip level")
    ax.grid(True, which="both", alpha=0.3)
    fig.tight_layout()
    fig.savefig(path, dpi=120)
    plt.close(fig)
    return True


def fmt(value: float, digits: int = 4) -> str:
    return "n/a" if isinstance(value, float) and math.isnan(value) else f"{value:.{digits}f}"


def write_report(path: Path, report: dict) -> None:
    lines = [
        f"# Evaluation: {report['checkpoint']}",
        "",
        f"Split `{report['split']}`, {report['num_items']} clips.",
        "",
        "## Clip level",
        "",
    ]
    clip = report["clip"]
    lines += ["| Metric | Value |", "|---|---|"]
    lines += [f"| {k} | {fmt(v) if isinstance(v, float) else v} |" for k, v in clip.items()]
    for field, groups in report["groups"].items():
        lines += [
            "",
            f"### By {field} (threshold {fmt(clip['threshold_at_far'])})",
            "",
            "| Group | Positives | FRR | Negatives | FAR |",
            "|---|---|---|---|---|",
        ]
        lines += [
            f"| {g} | {r['num_pos']} | {fmt(r['frr'])} | {r['num_neg']} | {fmt(r['far'])} |"
            for g, r in groups.items()
        ]
    stream = report.get("stream")
    if stream:
        lines += [
            "",
            "## Streaming",
            "",
            f"{stream['num_positives']} keyword clips, {stream['negative_hours']:.3f} hours "
            "of negative audio.",
            "",
        ]
        point = stream["operating_point"]
        if point:
            lines += [
                f"Operating point for at most {stream['target_fa_per_hour']} false accepts "
                f"per hour: threshold **{point['threshold']:.2f}**, FRR {fmt(point['frr'])}, "
                f"{point['fa_per_hour']:.2f} FA/h.",
                "",
            ]
        else:
            lines += [
                f"No threshold reaches {stream['target_fa_per_hour']} false accepts per hour.",
                "",
            ]
        lines += ["| Threshold | FRR | False accepts | FA per hour |", "|---|---|---|---|"]
        lines += [
            f"| {r['threshold']:.2f} | {fmt(r['frr'])} | {r['false_accepts']} | {fmt(r['fa_per_hour'], 2)} |"
            for r in stream["table"]
        ]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument("--checkpoint", required=True)
    parser.add_argument("--manifest", help="defaults to the manifest the model was trained on")
    parser.add_argument("--split", default="test")
    parser.add_argument("--target-far", type=float, default=0.01, help="clip-level FAR for FRR@FAR")
    parser.add_argument("--stream", action="store_true", help="also run the streaming evaluation")
    parser.add_argument("--target-fa-per-hour", type=float, default=0.5)
    parser.add_argument("--hop-seconds", type=float, default=0.1)
    parser.add_argument("--smooth-windows", type=int, default=3)
    parser.add_argument("--refractory-seconds", type=float, default=2.0)
    parser.add_argument("--onnx", help="score the streaming test with this exported model instead")
    parser.add_argument("--out", help="report folder; defaults to <checkpoint folder>/eval_<split>")
    parser.add_argument("--device", default="auto")
    parser.add_argument("--wandb", action="store_true", help="log the results to Weights & Biases")
    args = parser.parse_args(argv)

    device = pick_device(args.device)
    model, frontend, cfg, label_map, _ = load_checkpoint(args.checkpoint, device)
    manifest = args.manifest or cfg["data"]["manifest"]
    items = read_manifest(manifest, split=args.split)
    if not items:
        raise SystemExit(f"{manifest} has no items with split={args.split}")
    out = Path(args.out) if args.out else Path(args.checkpoint).parent / f"eval_{args.split}"
    out.mkdir(parents=True, exist_ok=True)

    dataset = eval_dataset(items, label_map, cfg)
    flat, raw = evaluate_split(model, frontend, dataset, device, args.target_far, args.split)
    report = {
        "checkpoint": str(args.checkpoint),
        "manifest": str(manifest),
        "split": args.split,
        "num_items": len(items),
        "target_far": args.target_far,
        "clip": {"loss": flat[f"{args.split}/loss"], **raw["clip"]},
        "recall": M.per_class_recall(raw["probs"], raw["targets"], label_map.classes),
        "groups": raw["groups"],
    }
    has_plot = plot_det(raw["scores"], raw["is_pos"], out / "det.png")

    if args.stream:
        stream_cfg = StreamConfig(
            sample_rate=cfg["features"]["sample_rate"],
            window_seconds=cfg["data"]["window_seconds"],
            hop_seconds=args.hop_seconds,
            smooth_windows=args.smooth_windows,
            refractory_seconds=args.refractory_seconds,
        )
        if args.onnx:
            from vitakws.config import feature_config

            infer = onnx_infer_fn(args.onnx, feature_config(cfg))
        else:
            infer = torch_infer_fn(model, frontend, str(device))
        peaks, tracks, hours = stream_scores(items, infer, label_map, stream_cfg)
        table = stream_table(peaks, tracks, hours, stream_cfg)
        report["stream"] = {
            "num_positives": int(len(peaks)),
            "negative_hours": hours,
            "hop_seconds": args.hop_seconds,
            "smooth_windows": args.smooth_windows,
            "target_fa_per_hour": args.target_fa_per_hour,
            "operating_point": pick_operating_point(table, args.target_fa_per_hour),
            "table": table,
        }

    (out / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    write_report(out / "report.md", report)
    print((out / "report.md").read_text(encoding="utf-8"))
    print(f"report written to {out}")

    if args.wandb:
        cfg = {**cfg, "run_name": f"{cfg['run_name']}-eval-{args.split}"}
        logger = RunLogger(out, cfg, job_type="eval")
        logger.log(flat, step=0)
        for field, groups in raw["groups"].items():
            logger.table(
                f"{args.split}/by_{field}",
                ["group", "num_pos", "frr", "num_neg", "far"],
                [[g, r["num_pos"], r["frr"], r["num_neg"], r["far"]] for g, r in groups.items()],
            )
        if "stream" in report:
            logger.table(
                f"{args.split}/stream",
                ["threshold", "frr", "false_accepts", "fa_per_hour"],
                [
                    [r["threshold"], r["frr"], r["false_accepts"], r["fa_per_hour"]]
                    for r in report["stream"]["table"]
                ],
            )
        if has_plot:
            logger.image(f"{args.split}/det", out / "det.png")
        logger.close()


if __name__ == "__main__":
    main()