File size: 13,498 Bytes
a08d02b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
"""Score model predictions against the Korean Multimodal Mind2Web sets.

Predictions are a JSONL file keyed by ``sample_id``::

    {"sample_id": "0714_Kaggle_1#2", "operation": "CLICK", "point": [0.78, 0.03]}
    {"sample_id": "0714_Kaggle_1#5", "operation": "TYPE", "bbox": [0.1, 0.2, 0.3, 0.25],
     "value": "covid-19"}

Coordinates may be given either normalised to [0, 1] or in screenshot pixels;
the scorer detects which by checking whether every value is <= 1.

Metrics
-------
All three are scored over the same ``steps/samples.jsonl``; they differ only in
what they demand of a step.

element accuracy  the target element was hit โ€” predicted point inside the gold
                  box (default) or IoU >= --iou.  Only steps with
                  ``has_element`` count towards it.
step success      the element was hit AND the operation and its value are right.
                  Only steps with ``scored`` count โ€” WAIT and FINISH are left
                  out, since neither is an agent decision about the page.
task success      every scored step of the task counts as a step success

More than one right answer
--------------------------
Some steps have two.  A typed form submits either by clicking its button or by
pressing Enter, and the annotator recorded whichever they happened to do; the
other is in ``alt_actions`` and is just as correct.  A prediction counts if it
matches **any** of them โ€” the recorded action or an alternative โ€” and each
alternative brings its own box, so a click on the submit button is scored
against that button, not against whatever the recorded action pointed at.

Pass ``--ignore-alt`` to score only the recorded action (the pre-alt_actions
numbers, for comparison).

Usage:
    python evaluate.py --pred preds.jsonl
    python evaluate.py --pred preds.jsonl --match iou --iou 0.5 --by-website
    python evaluate.py --pred preds.jsonl --ignore-alt
    python evaluate.py --pred preds.jsonl --type-verdicts type_verdicts.jsonl
"""

from __future__ import annotations

import argparse
import json
import os
import re
from collections import defaultdict
from typing import Any

# Operations whose textual argument is compared when scoring step success.
VALUE_OPS = {"TYPE", "SCROLL", "HOTKEY", "GOTO"}


def load_jsonl(path: str) -> list[dict]:
    rows = []
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def norm_text(value: Any) -> str:
    if value is None:
        return ""
    return re.sub(r"\s+", " ", str(value)).strip().lower()


GRID = 999


def to_grid999(coords, size):
    """์˜ˆ์ธก ์ขŒํ‘œ -> 0-999 ๊ทธ๋ฆฌ๋“œ. โ˜…์ฑ„์ ์€ ์ „๋ถ€ ์ด ์ขŒํ‘œ๊ณ„์—์„œ ํ•œ๋‹คโ˜….

    ๊ณจ๋“ ์ด `gold_bbox_999`(0-999 ์ •์ˆ˜)์ด๋ฏ€๋กœ ์˜ˆ์ธก๋„ ๊ฐ™์€ ๊ฒฉ์ž๋กœ ์˜ฎ๊ฒจ ๋น„๊ตํ•œ๋‹ค.
      ์ „๋ถ€ <= 1.0  -> 0-1 ์ •๊ทœํ™”     -> x 999
      ๊ทธ ์™ธ        -> ์Šคํฌ๋ฆฐ์ƒท ํ”ฝ์…€  -> / image_size x 999
    """
    if coords is None:
        return None
    coords = [float(c) for c in coords]
    if all(c <= 1.0 for c in coords):
        return [c * GRID for c in coords]
    w, h = size
    return [c / (w if i % 2 == 0 else h) * GRID for i, c in enumerate(coords)]


def point_in_box(point, box) -> bool:
    x, y = point
    return box[0] <= x <= box[2] and box[1] <= y <= box[3]


def iou(a, b) -> float:
    ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
    ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
    if ix2 <= ix1 or iy2 <= iy1:
        return 0.0
    inter = (ix2 - ix1) * (iy2 - iy1)
    area_a = (a[2] - a[0]) * (a[3] - a[1])
    area_b = (b[2] - b[0]) * (b[3] - b[1])
    return inter / (area_a + area_b - inter)


def candidates(gold: dict, use_alt: bool = True) -> list[dict]:
    """Every action that counts as correct for this step, recorded one first.

    Each entry is flattened to ``{operation, value, gold_bbox}`` so the scoring
    below does not have to care whether it came from ``action`` or from
    ``alt_actions``.
    """
    out = [{"operation": gold["action"]["operation"],
            "value": gold["action"].get("value"),
            # โ˜…0-999 ๊ทธ๋ฆฌ๋“œ ๊ณจ๋“ โ˜… โ€” ์ฑ„์  ์ขŒํ‘œ๊ณ„๊ฐ€ ํ”ฝ์…€์—์„œ ๊ทธ๋ฆฌ๋“œ๋กœ ๋ฐ”๋€Œ์—ˆ๋‹ค.
            "gold_bbox": gold.get("gold_bbox_999")}]
    if use_alt:
        for alt in gold.get("alt_actions") or []:
            if alt.get("status") not in (None, "ready"):
                continue           # ์ขŒํ‘œ๊ฐ€ ์•„์ง ์—†๋Š” ๋Œ€์•ˆ์€ ์ฑ„์ ์— ๋„ฃ์ง€ ์•Š๋Š”๋‹ค
            out.append({"operation": alt["operation"], "value": alt.get("value"),
                        "gold_bbox": alt.get("gold_bbox_999")})
    return out


def hits_box(pred: dict, box, size, match: str, iou_thr: float) -> bool:
    """Does the prediction land on this box?"""
    if box is None:
        return False
    if match == "iou":
        pbox = to_grid999(pred.get("bbox"), size)
        return bool(pbox) and iou(pbox, box) >= iou_thr

    # default: "point" โ€” a predicted point (or the centre of a predicted box)
    # must fall inside the box.  ๋‘˜ ๋‹ค 0-999 ๊ทธ๋ฆฌ๋“œ๋‹ค.
    point = to_grid999(pred.get("point"), size)
    if point is None:
        pbox = to_grid999(pred.get("bbox"), size)
        if pbox is None:
            return False
        point = [(pbox[0] + pbox[2]) / 2, (pbox[1] + pbox[3]) / 2]
    return point_in_box(point, box)


def matches_actionless(pred: dict, gold: dict, use_alt: bool = True,
                       type_ok: bool | None = None) -> bool:
    """Did the prediction pick a correct answer that has no place on screen?

    Pressing Enter to submit a form is one of the two right answers on 388
    steps, and it points at nothing.  It is still a right answer, so it counts
    as a hit โ€” the step asked "how do you submit this form", and both answers
    do it.
    """
    for c in candidates(gold, use_alt):
        if c["gold_bbox"] is not None:
            continue
        if norm_text(pred.get("operation")) != norm_text(c["operation"]):
            continue
        if c["operation"] in VALUE_OPS \
                and norm_text(pred.get("value")) != norm_text(c["value"]):
            # ์™„์ „ ์ผ์น˜๋Š” ์‹คํŒจํ–ˆ์ง€๋งŒ LLM judge ๊ฐ€ ๊ฐ™์€ ๋œป์ด๋ผ๊ณ  ๋ณธ TYPE ์ด๋ฉด ํ†ต๊ณผ์‹œํ‚จ๋‹ค
            # (eval_type.py ์ฐธ๊ณ ). judge ๋Š” ๊ตฌ์ œ๋งŒ ํ•˜๊ณ  ํ†ต๊ณผํ•œ ๊ฒƒ์„ ๋–จ์–ด๋œจ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
            if not (type_ok and c["operation"] == "TYPE"):
                continue
        return True
    return False


def element_hit(pred: dict, gold: dict, match: str, iou_thr: float,
                use_alt: bool = True, type_ok: bool | None = None) -> bool:
    """True when the prediction picks any acceptable answer for this step.

    Usually that means landing on one of the accepted boxes.  Where an accepted
    answer has no box at all โ€” Enter submits the form just as the button does โ€”
    naming that action counts too; there is nothing to land on.
    """
    size = gold["image_size"]
    if any(hits_box(pred, c["gold_bbox"], size, match, iou_thr)
           for c in candidates(gold, use_alt)):
        return True
    return matches_actionless(pred, gold, use_alt, type_ok)


def grounded(gold: dict, use_alt: bool = True) -> bool:
    """Is there any correct answer for this step that has a box?

    ``has_element`` answers this for the recorded action only.  A step whose
    gold is Enter but whose alternative is "click the submit button" does have
    a right answer with coordinates, so a model that clicks it should get the
    credit.
    """
    return any(c["gold_bbox"] is not None for c in candidates(gold, use_alt))


def step_hit(pred: dict, gold: dict, match: str, iou_thr: float,
             use_alt: bool = True, type_ok: bool | None = None) -> bool:
    """True when the prediction matches one of the step's correct actions.

    Operation, value and element are checked against the *same* candidate โ€” a
    prediction cannot borrow the operation from one answer and the box from
    another.
    """
    size = gold["image_size"]
    for c in candidates(gold, use_alt):
        if norm_text(pred.get("operation")) != norm_text(c["operation"]):
            continue
        if c["operation"] in VALUE_OPS \
                and norm_text(pred.get("value")) != norm_text(c["value"]):
            # ์™„์ „ ์ผ์น˜๋Š” ์‹คํŒจํ–ˆ์ง€๋งŒ LLM judge ๊ฐ€ ๊ฐ™์€ ๋œป์ด๋ผ๊ณ  ๋ณธ TYPE ์ด๋ฉด ํ†ต๊ณผ์‹œํ‚จ๋‹ค
            # (eval_type.py ์ฐธ๊ณ ). judge ๋Š” ๊ตฌ์ œ๋งŒ ํ•˜๊ณ  ํ†ต๊ณผํ•œ ๊ฒƒ์„ ๋–จ์–ด๋œจ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
            if not (type_ok and c["operation"] == "TYPE"):
                continue
        if c["gold_bbox"] is not None \
                and not hits_box(pred, c["gold_bbox"], size, match, iou_thr):
            continue
        return True
    return False


def summarise(counts: dict[str, list[int]]) -> dict:
    return {
        key: {
            "correct": hit,
            "total": total,
            "score": round(hit / total, 4) if total else None,
        }
        for key, (hit, total) in sorted(counts.items())
    }


def main() -> None:
    here = os.path.dirname(os.path.abspath(__file__))
    parser = argparse.ArgumentParser()
    parser.add_argument("--pred", required=True, help="JSONL of predictions")
    parser.add_argument("--data", default=here, help="dataset root")
    parser.add_argument("--match", choices=["point", "iou"], default="point")
    parser.add_argument("--iou", type=float, default=0.5)
    parser.add_argument("--by-website", action="store_true")
    parser.add_argument("--ignore-alt", action="store_true",
                        help="score only the recorded action, ignoring alt_actions")
    parser.add_argument("--type-verdicts", default=None,
                        help="eval_type.py ๊ฐ€ ๋‚ธ TYPE ํŒ์ • JSONL โ€” ์™„์ „ ์ผ์น˜ ๋Œ€์‹  ์“ด๋‹ค")
    parser.add_argument("--out", default=None, help="write the report to this JSON file")
    opts = parser.parse_args()

    preds = {p["sample_id"]: p for p in load_jsonl(opts.pred)}
    type_ok = {}
    if opts.type_verdicts:
        type_ok = {v["sample_id"]: bool(v.get("correct"))
                   for v in load_jsonl(opts.type_verdicts)}
    step_gold = load_jsonl(os.path.join(opts.data, "steps.jsonl"))
    task_gold = load_jsonl(os.path.join(opts.data, "tasks.jsonl"))

    el_hit = el_total = el_na = 0
    el_by_site: dict[str, list[int]] = defaultdict(lambda: [0, 0])
    step_ok: dict[str, bool] = {}
    step_by_op: dict[str, list[int]] = defaultdict(lambda: [0, 0])

    for gold in step_gold:
        pred = preds.get(gold["sample_id"])

        # Element accuracy: did the prediction land on the target element?
        # Scored wherever some correct answer has a box โ€” which includes the
        # steps whose *alternative* is the click, not just ``has_element``.
        use_alt = not opts.ignore_alt
        if grounded(gold, use_alt):
            tok = type_ok.get(gold["sample_id"])
            hit = bool(pred) and element_hit(pred, gold, opts.match, opts.iou, use_alt, tok)
            # ์ขŒํ‘œ ์—†์ด ์ธ์ •๋œ ๋‹ต(Enter)์ด ๋ช‡ ๊ฐœ์ธ์ง€๋Š” ๋”ฐ๋กœ ์„ธ์–ด ๋ฆฌํฌํŠธ์— ๋‚จ๊ธด๋‹ค
            el_na += bool(hit and pred and matches_actionless(pred, gold, use_alt, tok))
            el_hit += hit
            el_total += 1
            site = el_by_site[gold["website"]]
            site[0] += hit
            site[1] += 1

        # Step success: the same steps, but the operation and value must match
        # too.  WAIT and FINISH are not scored.
        if not gold["scored"]:
            continue
        ok = bool(pred) and step_hit(pred, gold, opts.match, opts.iou,
                                    not opts.ignore_alt,
                                    type_ok.get(gold["sample_id"]))
        step_ok[gold["sample_id"]] = ok
        op = step_by_op[gold["action"]["operation"]]
        op[0] += ok
        op[1] += 1

    task_hit = 0
    for task in task_gold:
        ids = task["scored_step_ids"]
        task_hit += bool(ids) and all(step_ok.get(i, False) for i in ids)

    n_steps = len(step_ok)
    report = {
        "predictions": len(preds),
        "match": opts.match,
        "iou_threshold": opts.iou if opts.match == "iou" else None,
        "alt_actions": "ignored" if opts.ignore_alt else "accepted",
        "type_value_match": ("llm-judge + exact" if opts.type_verdicts else "exact"),
        "element_accuracy": {
            "correct": el_hit,
            "total": el_total,
            "score": round(el_hit / el_total, 4) if el_total else None,
            # ์ขŒํ‘œ ์—†์ด(Enter ๋กœ) ๋งž์€ ๊ฒƒ์œผ๋กœ ์ธ์ •๋œ ์ˆ˜ โ€” ๋ถ„๋ชจ์—๋Š” ๊ทธ๋Œ€๋กœ ๋“ค์–ด ์žˆ๋‹ค
            "credited_without_coordinates": el_na,
        },
        "step_success_rate": {
            "correct": sum(step_ok.values()),
            "total": n_steps,
            "score": round(sum(step_ok.values()) / n_steps, 4) if n_steps else None,
        },
        "task_success_rate": {
            "correct": task_hit,
            "total": len(task_gold),
            "score": round(task_hit / len(task_gold), 4) if task_gold else None,
        },
        "step_success_by_operation": summarise(step_by_op),
    }
    if opts.by_website:
        report["element_accuracy_by_website"] = summarise(el_by_site)

    text = json.dumps(report, ensure_ascii=False, indent=2)
    print(text)
    if opts.out:
        with open(opts.out, "w", encoding="utf-8") as fh:
            fh.write(text)


if __name__ == "__main__":
    main()