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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/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())