GUI-LongDep / score.py
M-Ma's picture
Add files using upload-large-folder tool
fa1c809 verified
Raw History Blame Contribute Delete
16.6 kB
#!/usr/bin/env python
"""Deterministic scorer for GUI-LongDep, a long-range dependency benchmark for GUI agents.
Standard library only. No LLM judge is called.
A sample is correct iff
1. the first canonical predicted call has the same action as the first canonical gold call
(``type`` followed by ``key enter`` is one ``type`` call), and
2. every entry of ``requirements`` passes (``aggregation = "all"``).
Requirement types (text checks look only at the first canonical call's text):
norm every span occurs in the predicted text after normalization, on token
boundaries (``700`` does not match inside ``7000``, ``0.19`` not inside
``0.199``); each span consumes its own occurrence.
norm_ordered as ``norm``, and the spans occur in the listed order.
num the number at the span's position is within ``tolerance_abs`` of ``value``.
The position is the whole text when the gold text is a single field,
otherwise the same tab-separated field as in the gold text.
box the first predicted call is the required pointer action and its point
lies inside ``target_box`` (pixels, inclusive).
key the prediction is exactly one ``key`` call with the required keys.
Role rules derived from the gold text:
* tab fields if the gold ``type`` text is a tab-separated row and a span equals one
whole field, the same predicted field must equal the span.
* binding all spans of the requirement must occur in one segment of the
prediction split on , ; tab and newline.
* missing_value the whole predicted text (or its tab field) must equal the span.
* allowed_variants a span also passes if one of its listed literal variants passes.
Text normalization: Unicode NFKC, typographic quotes to ASCII, case folding, valid
thousands separators removed, whitespace runs collapsed.
Predictions are model-independent: a list of actions in the dataset's action format (see
README.md), with coordinates in **pixels** of the 1920x1080 screenshot. Predictions file
(JSONL), one line per sample:
{"sample_id": "lr-0000", "actions": [{"action": "type", "text": "1884"}]}
{"sample_id": "lr-0001", "actions": [{"action": "left_click", "coordinate": [169, 248]}]}
To score raw model replies instead, give ``--adapter <name>``: lines then carry
``{"sample_id": ..., "response": "<raw reply>"}`` and ``adapters/<name>``'s
``to_actions(response, width, height)`` converts each reply to pixel actions.
Usage:
python score.py --predictions preds.jsonl [--out report.json]
python score.py --predictions replies.jsonl --adapter evocua
python score.py --self-check # gold must score 264/264
"""
from __future__ import annotations
import argparse
import importlib
import json
import re
import sys
import unicodedata
from collections import defaultdict
from pathlib import Path
HERE = Path(__file__).resolve().parent
SCREEN = (1920, 1080) # every screenshot of the benchmark
# --------------------------------------------------------------------------- #
# Action canonicalization
# --------------------------------------------------------------------------- #
_ALIASES = {"click": "left_click", "drag": "left_click_drag"}
_KEY_ALIASES = {"return": "enter", "escape": "esc"}
_CLICKS = {"left_click", "right_click", "middle_click", "double_click", "triple_click"}
def _clean_keys(raw_keys):
keys = raw_keys if isinstance(raw_keys, list) else [raw_keys]
out = []
for key in keys:
if isinstance(key, str):
if key.startswith("keys=["):
key = key[6:]
if key.endswith("]"):
key = key[:-1]
if key.startswith("['") or key.startswith('["'):
key = key[2:] if len(key) > 2 else key
if key.endswith("']") or key.endswith('"]'):
key = key[:-2] if len(key) > 2 else key
key = key.strip()
out.append(key)
return out
def _point(v):
try:
return float(v[0]), float(v[1])
except (TypeError, IndexError, ValueError, KeyError):
return None
def _norm_keys(keys):
out = []
for k in _clean_keys(keys if isinstance(keys, list) else [keys]):
k = str(k)
if len(k) > 1:
k = _KEY_ALIASES.get(k.lower(), k.lower())
out.append(k)
return out
def _canon_one(a):
a = dict(a)
name = _ALIASES.get(str(a["action"]), str(a["action"]))
if name == "click":
name = "left_click"
a["action"] = name
if name in ("key", "key_down", "key_up"):
a["keys"] = _norm_keys(a.get("keys", []))
if name == "terminate":
a["status"] = "failure" if str(a.get("status", "success")).lower() == "failure" else "success"
return a
def canonical_calls(calls):
"""Normalize names / keys and merge multi-call patterns that execute as one action."""
c = [_canon_one(a) for a in (calls or [])]
out, i = [], 0
while i < len(c):
a = c[i]
nxt = c[i + 1] if i + 1 < len(c) else None
if a["action"] == "mouse_move" and nxt is not None and nxt["action"] == "scroll":
out.append({**nxt, "coordinate": a.get("coordinate")})
i += 2
continue
if a["action"] == "mouse_move" and nxt is not None and nxt["action"] == "left_click_drag":
out.append({**nxt, "start": a.get("coordinate")})
i += 2
continue
if (a["action"] == "key_down" and i + 2 < len(c) and c[i + 1]["action"] in _CLICKS
and c[i + 2]["action"] == "key_up" and c[i + 2]["keys"] == a["keys"]):
out.append({**c[i + 1], "modifiers": list(a["keys"])})
i += 3
continue
if (a["action"] == "type" and nxt is not None and nxt["action"] == "key"
and nxt["keys"] == ["enter"]):
out.append({**a, "text": str(a.get("text", "")) + "\n"})
i += 2
continue
out.append(a)
i += 1
return out
# --------------------------------------------------------------------------- #
# Text normalization and boundary-aware search
# --------------------------------------------------------------------------- #
_SEGMENT = re.compile(r"[,;\t\n]")
_QUOTES = str.maketrans({"‘": "'", "’": "'", "‚": "'", "‛": "'",
"“": '"', "”": '"', "„": '"', "‟": '"'})
_THOUSANDS = re.compile(r"(?<![\d.,])\d{1,3}(?:,\d{3})+(?![\d,]|\.\d*,)")
_NUMBER = re.compile(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)%?")
def norm(s):
s = unicodedata.normalize("NFKC", str(s if s is not None else "")).translate(_QUOTES)
s = _THOUSANDS.sub(lambda m: m.group(0).replace(",", ""), s)
return re.sub(r"\s+", " ", s).strip().casefold()
def _ascii_alnum(c):
return c.isascii() and c.isalnum()
def _boundary_ok(text, i, j):
"""``text[i:j]`` is not glued to a neighbouring ASCII token or to a decimal part."""
if i > 0 and _ascii_alnum(text[i]):
p = text[i - 1]
if _ascii_alnum(p):
return False
if p in ".," and text[i].isdigit() and i > 1 and text[i - 2].isdigit():
return False
if j < len(text) and _ascii_alnum(text[j - 1]):
n = text[j]
if _ascii_alnum(n):
return False
if n in ".," and text[j - 1].isdigit() and j + 1 < len(text) and text[j + 1].isdigit():
return False
return True
def find_all(text, span):
out, start = [], 0
if not span:
return out
while (i := text.find(span, start)) >= 0:
if _boundary_ok(text, i, i + len(span)):
out.append((i, i + len(span)))
start = i + 1
return out
def _fields(text):
return [norm(f) for f in str(text).rstrip("\n").split("\t")]
# --------------------------------------------------------------------------- #
# Requirement checks
# --------------------------------------------------------------------------- #
def _parse_number(s, unit):
s = norm(s).replace(" ", "")
if not _NUMBER.fullmatch(s):
return None
pct = s.endswith("%")
v = float(s.rstrip("%"))
if pct:
if not re.search(r"proportion|fraction", unit or "", re.I):
return None
v /= 100
return v
class _Text:
"""The predicted text with the occurrences already claimed by earlier spans."""
def __init__(self, raw):
self.raw = raw
self.text = norm(raw)
self.fields = _fields(raw)
self.used = []
def take(self, span, after=-1):
for i, j in find_all(self.text, span):
if i < after or any(i < b and a < j for a, b in self.used):
continue
return i, j
return None
def _span_ok(t, span, field, whole, after):
if field is not None:
ok = field < len(t.fields) and t.fields[field] == span
return after if ok else None
if whole:
return len(t.text) if t.text == span else None
hit = t.take(span, after)
if hit is None:
return None
t.used.append(hit)
return hit[1]
def check_requirement(req, pred, t, fields):
"""One requirement against the canonical predicted calls; ``(passed, reason)``."""
m = req["match"]
first = pred[0] if pred else None
if m == "key":
want = _norm_keys(req.get("keys") or [])
ok = len(pred) == 1 and first["action"] == "key" and first.get("keys") == want
return ok, "ok" if ok else "key"
if m == "box":
if first is None or first["action"] != _canon_one({"action": req.get("action", "left_click")})["action"]:
return False, "box_action"
p = _point(first.get("coordinate"))
if p is None:
return False, "box_coord"
x0, y0, x1, y1 = req["target_box"]
ok = x0 <= p[0] <= x1 and y0 <= p[1] <= y1
return ok, "ok" if ok else "box"
if t is None:
return False, "not_type"
if m == "num":
field = fields.get(id(req), [None])[0]
if field is not None:
src = t.fields[field] if field < len(t.fields) else None
else:
src = t.text if len(t.fields) == 1 else None
if src is None:
return False, "num_position"
v = _parse_number(src, req.get("unit", ""))
if v is None:
return False, "num_parse"
ok = abs(v - float(req["value"])) <= float(req["tolerance_abs"]) + 1e-9
return ok, "ok" if ok else "num_tol"
if m not in ("norm", "norm_ordered"):
return False, f"unknown_match:{m}"
spans = [norm(s) for s in req.get("span") or []]
variants = {norm(k): [norm(v) for v in vs] for k, vs in (req.get("allowed_variants") or {}).items()}
req_fields = fields.get(id(req), [None] * len(spans))
whole = bool(req.get("missing_value"))
ordered = m == "norm_ordered"
texts = [t]
if req.get("binding"):
raw = _THOUSANDS.sub(lambda mm: mm.group(0).replace(",", ""),
unicodedata.normalize("NFKC", t.raw))
texts = [_Text(part) for part in _SEGMENT.split(raw)]
for seg in texts:
used0, after, ok = list(seg.used), -1, True
for span, field in zip(spans, req_fields):
res = None
for cand in [span] + variants.get(span, []):
f = field if seg is t else None
res = _span_ok(seg, cand, f, whole and f is None, after if ordered else -1)
if res is not None:
break
if res is None:
ok = False
break
after = res
if ok:
return True, "ok"
seg.used = used0
return False, "binding" if req.get("binding") else "span"
def _assign_fields(sample, gold_text):
"""Gold tab-field index of each span that equals a whole gold field."""
out = {}
if gold_text is None or "\t" not in str(gold_text).rstrip("\n"):
return out
gf, taken = _fields(gold_text), set()
for req in sample["requirements"]:
if req["match"] not in ("norm", "norm_ordered", "num"):
continue
idx = []
for s in req.get("span") or []:
hits = [k for k, f in enumerate(gf) if f == norm(s)]
free = [k for k in hits if k not in taken]
k = (free or hits or [None])[0]
if k is not None:
taken.add(k)
idx.append(k)
out[id(req)] = idx
return out
def score(sample, pred_actions):
"""Score one prediction (pixel actions): ``correct`` / ``action`` (0/1) and reasons."""
gold = canonical_calls(sample["gold_action"])
pred = canonical_calls(pred_actions)
if not pred:
return {"correct": 0, "action": 0, "reasons": ["no_call"]}
action_ok = pred[0]["action"] == gold[0]["action"]
gold_text = gold[0].get("text") if gold[0]["action"] == "type" else None
t = _Text(pred[0].get("text", "")) if pred[0]["action"] == "type" else None
fields = _assign_fields(sample, gold_text)
reasons = [check_requirement(r, pred, t, fields)[1]
for r in sample["requirements"]]
passed = action_ok and all(r == "ok" for r in reasons)
return {"correct": int(passed), "action": int(action_ok),
"reasons": reasons if action_ok else ["action"] + reasons}
# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def _read_jsonl(path):
with open(path, encoding="utf-8") as fh:
return [json.loads(line) for line in fh if line.strip()]
def summarize(samples, per_sample):
groups = defaultdict(list)
for s in samples:
r = per_sample.get(s["sample_id"])
v = r["correct"] if r is not None else 0
groups["all"].append(v)
groups[f"rule:{s['rule']}"].append(v)
groups[f"source:{s['source']}"].append(v)
return {g: {"n": len(v), "accuracy": sum(v) / len(v)} for g, v in sorted(groups.items())}
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--samples", default=str(HERE / "data/test.jsonl"))
ap.add_argument("--predictions", help="JSONL with sample_id + actions (or response, with --adapter)")
ap.add_argument("--adapter", help="model adapter in adapters/ that parses raw replies, e.g. evocua")
ap.add_argument("--self-check", action="store_true", help="score gold against itself")
ap.add_argument("--out", help="write the full report (with per-sample results) as JSON")
args = ap.parse_args(argv)
samples = _read_jsonl(args.samples)
if args.self_check:
fails = [s["sample_id"] for s in samples
if not score(s, s["gold_action"])["correct"]]
print(f"self-check: {len(samples) - len(fails)}/{len(samples)} gold actions pass")
if fails:
print("failing:", fails[:20])
return 1 if fails else 0
if not args.predictions:
ap.error("--predictions is required unless --self-check")
to_actions = None
if args.adapter:
sys.path.insert(0, str(HERE))
to_actions = importlib.import_module(f"adapters.{args.adapter}").to_actions
by_id = {s["sample_id"]: s for s in samples}
per_sample, unknown, duplicate = {}, 0, 0
for p in _read_jsonl(args.predictions):
sid = p.get("sample_id")
if sid not in by_id:
unknown += 1
continue
if sid in per_sample:
duplicate += 1
actions = to_actions(p.get("response"), *SCREEN) if to_actions else p.get("actions")
per_sample[sid] = score(by_id[sid], actions)
missing = len(samples) - len(per_sample)
report = {"n_samples": len(samples), "n_predicted": len(per_sample), "missing_scored_wrong": missing,
"unknown_ids": unknown, "duplicate_ids": duplicate,
"groups": summarize(samples, per_sample)}
for g, r in report["groups"].items():
print(f"{g:32s} n={r['n']:4d} accuracy={r['accuracy']:.4f}")
if missing or unknown or duplicate:
print(f"warning: {missing} samples without prediction (scored wrong), "
f"{unknown} unknown ids, {duplicate} duplicate ids", file=sys.stderr)
if args.out:
with open(args.out, "w", encoding="utf-8") as fh:
json.dump({**report, "per_sample": per_sample}, fh, indent=1, ensure_ascii=False)
return 0
if __name__ == "__main__":
sys.exit(main())