File size: 3,446 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Would a stricter decision rule fix the early starts? CPU only.

Uses the saved per-frame probabilities of the held-out run (eval/results/controller/pred)
and the recorded events. Rule: START fires in a frame when p(START) >= threshold
("argmax" = START is the most likely label, which is what the endpoint used).

The thresholds are compared on the same held-out set they would be chosen on, so the
best row is optimistic. Frames after the labelled START window cannot be judged offline
(the agent's own audio starts there), so a rule that needs several frames in a row is
not evaluated.

  python -m tools.decision_sweep --data data/out/dataset --pred eval/results/controller/pred --out eval/results/controller/decision_sweep.json
"""
import argparse
import json
from pathlib import Path

import numpy as np

from duplex.spec import FRAME, START, write_json


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", required=True)
    ap.add_argument("--pred", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    data = Path(args.data)
    rules = ["argmax", 0.5, 0.7, 0.9, 0.95, 0.99]
    tally = {str(r): {"pause_quiet": 0, "pauses": 0, "turn_end_caught": 0, "turn_ends": 0, "turn_clean": 0, "turns": 0, "delays": []} for r in rules}
    for it in json.loads((data / "index_test.json").read_text()):
        probs = np.load(Path(args.pred) / f"{it['id']}.npz")["probs"].astype(np.float32)
        events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
        for r in rules:
            fire = probs.argmax(-1) == START if r == "argmax" else probs[:, START] >= r
            t = tally[str(r)]
            for e in events:
                if e["type"] == "pause" and e["f1"] > e["f0"]:
                    t["pauses"] += 1
                    t["pause_quiet"] += not fire[e["f0"]: e["f1"]].any()
                elif e["type"] == "start":
                    hit = np.nonzero(fire[e["f0"]: e["f1"]])[0]
                    t["turn_ends"] += 1
                    t["turn_end_caught"] += len(hit) > 0
                    if len(hit):
                        t["delays"].append((int(hit[0]) + 1) * 80)
                elif e["type"] == "caller_turn":       # the whole turn, pauses included: no START before the caller has finished
                    t["turns"] += 1
                    t["turn_clean"] += not fire[e["start"] // FRAME: e["end"] // FRAME].any()
    out = {}
    for r, t in tally.items():
        out[r] = {
            "pause_handling": t["pause_quiet"] / t["pauses"], "turn_end_caught": t["turn_end_caught"] / t["turn_ends"],
            "caller_turns_with_no_start_before_their_end": t["turn_clean"] / t["turns"],
            "start_delay_ms_p50": float(np.median(t["delays"])) if t["delays"] else None,
            "counts": {k: t[k] for k in ("pause_quiet", "pauses", "turn_end_caught", "turn_ends", "turn_clean", "turns")},
        }
        print(f"p(START) >= {r:>6}: pauses kept quiet {t['pause_quiet']}/{t['pauses']} ({out[r]['pause_handling']:.3f}) | turn ends caught "
              f"{t['turn_end_caught']}/{t['turn_ends']} ({out[r]['turn_end_caught']:.3f}) | whole caller turns with no early START "
              f"{t['turn_clean']}/{t['turns']} ({out[r]['caller_turns_with_no_start_before_their_end']:.3f}) | delay p50 {out[r]['start_delay_ms_p50']} ms")
    write_json(args.out, out)


if __name__ == "__main__":
    main()