File size: 9,534 Bytes
ab9dacf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Score a VLM output JSON for the BEAR benchmark and report the final accuracy.

The inference runners (run_api_model.py / run_image_model.py) produce a JSON list
where each item keeps its original fields and adds `direct_reply` and (for API
models) `cot_reply`. This script turns those free-form replies into a final score:

  * Multiple-choice tasks (default): an **LLM judge** (default: gpt-4o-mini) reads
    the model's reply plus the options and returns the chosen letter A/B/C/D, which
    is compared against the ground-truth `gt`.
  * Pointing tasks:  the predicted (x, y) must fall inside the ground-truth mask.
  * Bounding-box tasks:  IoU between the predicted box and the ground-truth mask.

Requires OPENAI_API_KEY in the environment (used only for multiple-choice grading).

Usage:
    export OPENAI_API_KEY=sk-...
    python eval.py --input_json final_gpt-4o_evaluate_next_action_prediction_official.json
    # -> writes  *_scored.json  and  *_scored_summary.json, prints the summary.

    # long-horizon (episode-level strict accuracy):
    python eval.py --input_json final_gpt-4o_evaluate_vqa_all_episodes.json --episode
"""
import os
import re
import json
import argparse
from collections import defaultdict

import numpy as np
from PIL import Image
from openai import OpenAI

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "EMPTY"))


# --------------------------------------------------------------------------- #
# Extraction helpers
# --------------------------------------------------------------------------- #
def extract_xy(reply):
    """Extract a normalized (x, y) point from a reply string, or None."""
    if not isinstance(reply, str):
        return None
    m = re.search(r"\(\s*([\d.]+)\s*,\s*([\d.]+)\s*\)", reply)
    if not m:
        return None
    try:
        return float(m.group(1)), float(m.group(2))
    except ValueError:
        return None


def extract_bbox(reply):
    """Extract a normalized (x1, y1, x2, y2) box from a reply string, or None."""
    if not isinstance(reply, str):
        return None
    m = re.search(
        r"\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)", reply
    )
    if not m:
        return None
    try:
        return tuple(float(g) for g in m.groups())
    except ValueError:
        return None


def point_in_mask(mask_path, xy, normalize=True):
    """True if the (normalized) point lands on a non-zero mask pixel."""
    if xy is None:
        return False
    mask = np.array(Image.open(mask_path).convert("L"))
    h, w = mask.shape
    x, y = xy
    if normalize:
        x, y = int(x * w), int(y * h)
    else:
        x, y = int(x), int(y)
    if x < 0 or x >= w or y < 0 or y >= h:
        return False
    return bool(mask[y, x] > 0)


def bbox_iou(mask_path, bbox, normalize=True):
    """IoU between a (normalized) predicted box and a ground-truth mask."""
    if bbox is None:
        return 0.0
    mask = np.array(Image.open(mask_path).convert("L"))
    h, w = mask.shape
    x1, y1, x2, y2 = bbox
    if normalize:
        x1, x2 = int(x1 * w), int(x2 * w)
        y1, y2 = int(y1 * h), int(y2 * h)
    else:
        x1, y1, x2, y2 = map(int, (x1, y1, x2, y2))
    x1, x2 = max(0, min(x1, w - 1)), max(0, min(x2, w - 1))
    y1, y2 = max(0, min(y1, h - 1)), max(0, min(y2, h - 1))
    if x2 <= x1 or y2 <= y1:
        return 0.0
    pred = np.zeros_like(mask)
    pred[y1:y2 + 1, x1:x2 + 1] = 1
    gt = (mask > 0).astype(np.uint8)
    inter = np.logical_and(pred, gt).sum()
    union = np.logical_or(pred, gt).sum()
    return float(inter / union) if union else 0.0


# --------------------------------------------------------------------------- #
# LLM judge for multiple-choice answers
# --------------------------------------------------------------------------- #
def options_to_text(options):
    if isinstance(options, dict):
        return " ".join(f"{k}. {v}" for k, v in options.items() if str(v).strip())
    return str(options)


def judge_option(reply, options_text, model):
    """Use an LLM to extract the chosen option letter (A/B/C/D) from `reply`."""
    if not reply or not isinstance(reply, str):
        return None
    messages = [
        {
            "role": "system",
            "content": "You extract the chosen option from a model's answer. "
                       "Reply with ONLY one uppercase letter: A, B, C, or D.",
        },
        {
            "role": "user",
            "content": f"The model's answer:\n{reply}\n\n"
                       f"The options were:\n{options_text}\n\n"
                       "Which option (A, B, C, or D) did the model choose? "
                       "Reply with a single letter.",
        },
    ]
    for _ in range(3):
        try:
            r = client.chat.completions.create(
                model=model, messages=messages, temperature=0
            )
            ans = r.choices[0].message.content.strip().upper()
            m = re.search(r"[ABCD]", ans)
            if m:
                return m.group(0)
        except Exception:
            continue
    return None


# --------------------------------------------------------------------------- #
# Scoring
# --------------------------------------------------------------------------- #
REPLIES = ["direct_reply", "cot_reply"]


def score(items, judge_model):
    tallies = {
        r: defaultdict(lambda: {"n": 0, "correct": 0, "iou_sum": 0.0}) for r in REPLIES
    }
    for item in items:
        cat = item.get("category", "")
        kind = "pointing" if cat == "pointing" else "bbox" if cat == "bbox" else "mcq"
        for r in REPLIES:
            if r not in item:
                continue
            prefix = r.split("_")[0]  # "direct" / "cot"
            reply = item.get(r, "")
            t = tallies[r][kind]
            t["n"] += 1
            if kind == "pointing":
                hit = point_in_mask(item.get("mask"), extract_xy(reply))
                item[f"{prefix}_hit"] = int(hit)
                t["correct"] += int(hit)
            elif kind == "bbox":
                iou = bbox_iou(item.get("mask"), extract_bbox(reply))
                item[f"{prefix}_iou"] = iou
                t["iou_sum"] += iou
            else:
                pred = judge_option(
                    reply, options_to_text(item.get("options", {})), judge_model
                )
                gt = str(item.get("gt", "")).strip().upper()
                hit = pred is not None and pred == gt
                item[f"{prefix}_pred"] = pred
                item[f"{prefix}_hit"] = int(hit)
                t["correct"] += int(hit)
    return tallies


def summarize(tallies):
    out = {}
    for r, kinds in tallies.items():
        rep = {}
        for kind, t in kinds.items():
            if not t["n"]:
                continue
            if kind == "bbox":
                rep[kind] = {"n": t["n"], "mean_iou": round(t["iou_sum"] / t["n"], 4)}
            else:
                rep[kind] = {"n": t["n"], "accuracy": round(t["correct"] / t["n"], 4)}
        out[r] = rep
    return out


def episode_strict(items, policy="direct"):
    """Long-horizon: an episode is correct only if ALL its questions are correct."""
    key = f"{policy}_hit"
    ep = defaultdict(list)
    for it in items:
        if "episode_id" in it and key in it:
            ep[str(it["episode_id"])].append(it[key])
    per = {e: all(h == 1 for h in hits) for e, hits in ep.items()}
    full = sum(1 for v in per.values() if v)
    return {
        "total_episodes": len(per),
        "fully_correct_episodes": full,
        "episode_level_acc": round(full / len(per), 4) if per else 0.0,
        "policy": policy,
    }


# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
    ap = argparse.ArgumentParser(
        description="Score BEAR VLM outputs (LLM judge for MCQ, geometric for pointing/bbox)."
    )
    ap.add_argument("--input_json", required=True,
                    help="VLM output JSON produced by run_api_model.py / run_image_model.py.")
    ap.add_argument("--output_json", default=None,
                    help="Scored per-item JSON. Default: <input>_scored.json")
    ap.add_argument("--judge_model", default="gpt-4o-mini",
                    help="OpenAI model used to extract the chosen option for MCQ tasks.")
    ap.add_argument("--episode", action="store_true",
                    help="Also compute episode-level strict accuracy (long_horizon).")
    args = ap.parse_args()

    if os.environ.get("OPENAI_API_KEY", "EMPTY") in (None, "", "EMPTY"):
        print("WARNING: OPENAI_API_KEY is not set — multiple-choice grading will fail.")

    with open(args.input_json) as f:
        items = json.load(f)

    tallies = score(items, args.judge_model)
    summary = summarize(tallies)
    if args.episode:
        summary["episode_strict"] = {p: episode_strict(items, p) for p in ("direct", "cot")}

    out_json = args.output_json or (os.path.splitext(args.input_json)[0] + "_scored.json")
    with open(out_json, "w") as f:
        json.dump(items, f, indent=2, ensure_ascii=False)
    summary_path = os.path.splitext(out_json)[0] + "_summary.json"
    with open(summary_path, "w") as f:
        json.dump(summary, f, indent=2, ensure_ascii=False)

    print(json.dumps(summary, indent=2, ensure_ascii=False))
    print(f"\nScored items -> {out_json}\nSummary      -> {summary_path}")