Download mail/compare.py from luokelabs/luoke-bench: direct link, hf CLI and curl.
- Browser
- Download file 6.82 kB
-
https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/compare.py
- Command line
-
hf download hf://datasets/luokelabs/luoke-bench/mail/compare.py
-
curl -L -o compare.py https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/compare.py
6.82 kB
| #!/usr/bin/env python3 | |
| """Compare two triage results item by item. | |
| python3 mail/compare.py mail/results/triage/real/A.json mail/results/triage/real/B.json | |
| Prints the scores side by side, which items changed between right and wrong on the action, and how many items | |
| differ in each field. Before anything else it says when the two results are not like for like: a different | |
| question set (its hash), a different app commit, a different engine. Reads only the two files; stdlib only. | |
| Exit code 1 when the question sets differ, since the scores then do not compare. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| FIELDS = ("action", "suspicious", "priority", "due_date", "event_date", "category") | |
| SCORES = ("basic", "hard", "action", "safety", "false_alarm", "dates", "false_due", "priority", "json_first_try") | |
| def field(t: dict | None, name: str): | |
| if not t: | |
| return None | |
| if name == "event_date": | |
| return (t.get("event") or {}).get("date") | |
| return t.get(name) | |
| def like_for_like(a: dict, b: dict) -> list[str]: | |
| """What differs between the two runs besides the answers. Empty when nothing recorded differs.""" | |
| ra, rb = a.get("run") or {}, b.get("run") or {} | |
| notes = [] | |
| if not ra or not rb: | |
| notes.append("one of the results has no record of what was run (older than runmeta); only the answers are compared") | |
| sa, sb = a.get("set_sha256"), b.get("set_sha256") | |
| if sa and sb and sa != sb: | |
| notes.append(f"QUESTION SETS DIFFER ({sa[:12]} vs {sb[:12]}): the scores do not compare") | |
| elif not (sa and sb): | |
| notes.append("one of the results has no set_sha256: cannot tell whether the questions are the same") | |
| for what, key in (("app commit", ("app", "commit")), ("engine", ("engine", "server"))): | |
| va, vb = (ra.get(key[0]) or {}).get(key[1]), (rb.get(key[0]) or {}).get(key[1]) | |
| if va != vb and (va or vb): | |
| notes.append(f"{what} differs: {va} vs {vb}") | |
| ea, eb = (ra.get("engine") or {}).get("status", {}).get("version"), (rb.get("engine") or {}).get("status", {}).get("version") | |
| if ea != eb and (ea or eb): | |
| notes.append(f"engine version differs: {ea} vs {eb}") | |
| if a.get("model") != b.get("model"): | |
| notes.append(f"model differs: {a.get('model')} vs {b.get('model')}") | |
| if (a.get("machine") or {}).get("cpu") != (b.get("machine") or {}).get("cpu"): | |
| notes.append(f"machine differs: {(a.get('machine') or {}).get('cpu')} vs {(b.get('machine') or {}).get('cpu')} (timings do not compare)") | |
| return notes | |
| def compare(a: dict, b: dict) -> dict: | |
| ta = {r["tag"]: r for r in a["results"]} | |
| tb = {r["tag"]: r for r in b["results"]} | |
| both = [t for t in ta if t in tb] | |
| out = {"only_a": sorted(set(ta) - set(tb)), "only_b": sorted(set(tb) - set(ta)), "n": len(both), | |
| "fields": {}, "lost": [], "gained": [], "lost_watch": [], "gained_watch": [], "errors": []} | |
| for name in FIELDS: | |
| out["fields"][name] = sorted(t for t in both if field(ta[t].get("triage"), name) != field(tb[t].get("triage"), name)) | |
| for t in both: | |
| if bool(ta[t].get("error")) != bool(tb[t].get("error")): | |
| out["errors"].append(t) | |
| oa, ob = ta[t].get("action_ok"), tb[t].get("action_ok") | |
| if oa is None or ob is None: | |
| continue | |
| # observed-only questions do not count in the score: list them apart | |
| watched = bool(ta[t].get("watch") or tb[t].get("watch")) | |
| if oa and not ob: | |
| out["lost_watch" if watched else "lost"].append(t) | |
| elif ob and not oa: | |
| out["gained_watch" if watched else "gained"].append(t) | |
| out["judged"] = sum(1 for t in both if ta[t].get("action_ok") is not None and tb[t].get("action_ok") is not None) | |
| # results from before the runners marked observed questions cannot be split | |
| out["watch_known"] = all("watch" in r for r in list(ta.values()) + list(tb.values()) if r.get("action_ok") is not None) | |
| return out | |
| def load(path: str) -> dict: | |
| with open(path, encoding="utf-8") as f: | |
| d = json.load(f) | |
| if not isinstance(d, dict) or not isinstance(d.get("results"), list) or any("tag" not in r for r in d["results"]): | |
| raise SystemExit(f"{path}: not a triage result (compare.py reads the files run_triage.py writes; results of run_tasks.py " | |
| "and run_text.py have another shape)") | |
| return d | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("a") | |
| ap.add_argument("b") | |
| args = ap.parse_args() | |
| a, b = load(args.a), load(args.b) | |
| notes = like_for_like(a, b) | |
| for n in notes: | |
| print("!", n) | |
| la, lb = a.get("label", "A"), b.get("label", "B") | |
| print(f"\n{'':16s}{la[:22]:>24s}{lb[:22]:>24s}") | |
| for k in SCORES: | |
| if k in a.get("score", {}) or k in b.get("score", {}): | |
| print(f"{k:16s}{str(a.get('score', {}).get(k, '-')):>24s}{str(b.get('score', {}).get(k, '-')):>24s}") | |
| for k in ("avg_seconds", "wall_seconds"): | |
| print(f"{k:16s}{str(a.get('score', {}).get(k, '-')):>24s}{str(b.get('score', {}).get(k, '-')):>24s}") | |
| c = compare(a, b) | |
| print(f"\n{c['n']} items in both" + (f"; only in {la}: {len(c['only_a'])}" if c["only_a"] else "") + (f"; only in {lb}: {len(c['only_b'])}" if c["only_b"] else "")) | |
| if c["judged"]: | |
| print(f"verdicts on {c['judged']}/{c['n']} items") | |
| if c["judged"] < c["n"]: | |
| print(f"! only {c['judged']} of the {c['n']} shared items have a verdict in both results: the lists below cover those, not the whole set") | |
| scored = "" if c["watch_known"] else " (may include observed-only questions, which the score leaves out)" | |
| print(f"action right in {la}, wrong in {lb} ({len(c['lost'])}){scored}: {', '.join(c['lost']) or '-'}") | |
| print(f"action wrong in {la}, right in {lb} ({len(c['gained'])}){scored}: {', '.join(c['gained']) or '-'}") | |
| if c["lost_watch"] or c["gained_watch"]: | |
| print(f"observed only, right in {la}, wrong in {lb} ({len(c['lost_watch'])}): {', '.join(c['lost_watch']) or '-'}") | |
| print(f"observed only, wrong in {la}, right in {lb} ({len(c['gained_watch'])}): {', '.join(c['gained_watch']) or '-'}") | |
| else: | |
| print("no per-item verdicts recorded (results older than runmeta): field differences only") | |
| for name in FIELDS: | |
| tags = c["fields"][name] | |
| print(f"{name:12s} differs on {len(tags):3d}" + (": " + ", ".join(tags[:12]) + (" …" if len(tags) > 12 else "") if tags else "")) | |
| if c["errors"]: | |
| print("failed in one only:", ", ".join(c["errors"])) | |
| sys.exit(1 if any(n.startswith("QUESTION SETS DIFFER") for n in notes) else 0) | |
| if __name__ == "__main__": | |
| main() | |