"""Score a critic's answers on ScreenProof (MIT License). Predictions: a JSONL file, one line per screenshot: {"id": "ct-00012", "answer": {...}} or {"id": ..., "raw": ""}. An answer has the form of prompt.txt: {"follows": bool, "inconsistencies": [{"element", "box", "kind", "aspect"}]}, boxes as [x0, y0, x1, y1] in 0-1000 screen coordinates. A missing or unparsable answer counts as finding nothing. Matching: one-to-one, greedy by IoU, a reported box finds a fault when IoU >= 0.5 (--iou 0.3 for the loose table). precision = matched boxes / all reported boxes (clean pages included) recall = matched faults / all faults; F1 from both consistency recall = recall on "inconsistent" faults (transplanted components, local style faults) general recall = recall on "common" faults false alarm = share of clean pages that the critic flags (follows false, or any box), real and generated apart python evaluate.py --split consistency_test --predictions preds.jsonl [--data-dir .] [--exclude-human-flagged] --exclude-human-flagged leaves out the pages that the label check marked faulty, hidden or fine (the "human" table). Note: the paper's runs sent prompt.txt with its JSON braces doubled ({{ }}); this script reads either form. """ from __future__ import annotations import argparse import glob import json import os import re from pathlib import Path import pyarrow.parquet as pq def parse(raw): if isinstance(raw, dict) or raw is None: return raw raw = re.sub(r".*?", "", str(raw), flags=re.S) start = raw.find("{") if start < 0: return None for text in (raw[start:], raw[start:].replace("{{", "{").replace("}}", "}")): try: return json.JSONDecoder().raw_decode(text)[0] except json.JSONDecodeError: continue return None def box(b): if not isinstance(b, (list, tuple)) or len(b) != 4: return None try: x0, y0, x1, y1 = (float(v) for v in b) except (TypeError, ValueError): return None return [min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)] def iou(a, b): ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) inter = ix * iy union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter return inter / union if union > 0 else 0.0 def match(items, truths, thr): reps = [box(i.get("box")) for i in items] tbs = [box(t.get("box")) for t in truths] cand = sorted(((iou(r, t), i, j) for i, r in enumerate(reps) if r for j, t in enumerate(tbs) if t if iou(r, t) >= thr), reverse=True) used_i, used_t, pairs = set(), set(), [] for _, i, j in cand: if i not in used_i and j not in used_t: used_i.add(i) used_t.add(j) pairs.append((i, j)) return pairs def load_split(data_dir, split): files = sorted(glob.glob(os.path.join(data_dir, "data", f"{split}-*.parquet"))) if not files: raise SystemExit(f"no parquet files for {split} in {data_dir}/data") cols = ["id", "source", "label", "human_check"] rows = [] for f in files: rows += pq.read_table(f, columns=cols).to_pylist() return rows def main(): ap = argparse.ArgumentParser() ap.add_argument("--split", default="consistency_test", choices=["consistency_test", "text_layout_test", "validation"]) ap.add_argument("--predictions", required=True) ap.add_argument("--data-dir", default=os.path.dirname(os.path.abspath(__file__))) ap.add_argument("--iou", type=float, default=0.5) ap.add_argument("--exclude-human-flagged", action="store_true") ap.add_argument("--subset", default="published", choices=["published", "audit_excluded", "structural_quarantine", "convention_sensitivity"]) a = ap.parse_args() if a.subset != "published" and (a.split != "consistency_test" or a.exclude_human_flagged): ap.error("--subset requires consistency_test and cannot be combined with --exclude-human-flagged") rows = load_split(a.data_dir, a.split) if a.exclude_human_flagged: rows = [r for r in rows if r["human_check"] not in ("faulty", "hidden", "fine")] if a.subset != "published": root = Path(a.data_dir) / "robustness" protocol = json.loads((root / "protocol.json").read_text()) records = {r["id"]: r for r in map(json.loads, (root / "records.jsonl").read_text().splitlines()) if r["in_original_release"]} if set(records) != {r["id"] for r in rows}: raise SystemExit("Subset manifest does not match this dataset revision") flags = protocol["pool_exclusions"][a.subset] rows = [r for r in rows if not any(records[r["id"]][f] for f in flags)] preds = {} with open(a.predictions, encoding="utf-8") as fh: for line in fh: if line.strip(): p = json.loads(line) ans = parse(p["answer"]) if "answer" in p else parse(p.get("raw")) if ans is not None or p["id"] not in preds: preds[p["id"]] = ans c = dict.fromkeys(["boxes", "matched", "faults", "con_truth", "con_hit", "gen_truth", "gen_hit", "unparsed", "clean_real", "fa_real", "clean_gen", "fa_gen"], 0) for r in rows: truths = json.loads(r["label"])["inconsistencies"] or [] ans = preds.get(r["id"]) if not isinstance(ans, dict): c["unparsed"] += 1 ans = {"follows": True, "inconsistencies": []} items = [i for i in (ans.get("inconsistencies") or []) if isinstance(i, dict)] pairs = match(items, truths, a.iou) c["boxes"] += len(items) c["matched"] += len(pairs) c["faults"] += len(truths) hit = {j for _, j in pairs} for j, t in enumerate(truths): k = "con" if t.get("kind") == "inconsistent" else "gen" c[f"{k}_truth"] += 1 c[f"{k}_hit"] += j in hit if not truths: s = "gen" if r["source"] == "generated" else "real" c[f"clean_{s}"] += 1 c[f"fa_{s}"] += ans.get("follows") is False or bool(items) p = c["matched"] / c["boxes"] if c["boxes"] else 0.0 rec = c["matched"] / c["faults"] if c["faults"] else 0.0 out = {"protocol": "eval-2026-11-10", "subset": "audit_excluded" if a.exclude_human_flagged else a.subset, "pages": len(rows), "precision": round(p, 4), "recall": round(rec, 4), "f1": round(2 * p * rec / (p + rec), 4) if p + rec else 0.0, "consistency_recall": round(c["con_hit"] / max(1, c["con_truth"]), 4), "general_recall": round(c["gen_hit"] / max(1, c["gen_truth"]), 4), "false_alarm_real": round(c["fa_real"] / max(1, c["clean_real"]), 4), "false_alarm_generated": round(c["fa_gen"] / max(1, c["clean_gen"]), 4), "unparsed": c["unparsed"], "iou": a.iou} print(json.dumps(out, indent=1)) if __name__ == "__main__": main()