File size: 7,066 Bytes
ff1fb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Evaluate a GPT model on PhysCount with the paper's independent-QA prompt."""

from __future__ import annotations

import argparse
import base64
import io
import json
import os
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
from pathlib import Path

from openai import OpenAI
from PIL import Image, ImageOps


PROMPT = """Answer the following counting question about this image. Carefully distinguish
visual appearances from physical entities, including appearances formed by
reflections or seen through glass, and use appearance-entity correspondences
when required by the question. Follow the counting target specified in the
question. Return exactly one non-negative integer, with no labels or prose.

Question: {question}"""

INTEGER_RE = re.compile(r"^\s*(\d+)\s*$")
MAX_VALID_COUNT = 10_000
_CLIENT_LOCAL = threading.local()


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-root", type=Path, default=Path(__file__).parents[1])
    parser.add_argument("--model", required=True, help="OpenAI API model identifier")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument(
        "--reasoning-effort",
        required=True,
        choices=("none", "low", "medium", "high", "xhigh"),
        help="Use the strongest level supported by the selected model",
    )
    parser.add_argument("--max-output-tokens", type=int, default=32768)
    parser.add_argument("--temperature", type=float)
    parser.add_argument("--top-p", type=float)
    parser.add_argument("--long-edge", type=int, default=4096)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--retries", type=int, default=3)
    parser.add_argument("--limit", type=int)
    return parser.parse_args()


def client() -> OpenAI:
    if not hasattr(_CLIENT_LOCAL, "client"):
        _CLIENT_LOCAL.client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
    return _CLIENT_LOCAL.client


@lru_cache(maxsize=16)
def prepare_image(path_text: str, long_edge: int) -> tuple[str, list[int], list[int]]:
    path = Path(path_text)
    with Image.open(path) as opened:
        original_size = list(opened.size)
        image = ImageOps.exif_transpose(opened)
        if max(image.size) <= long_edge:
            payload = path.read_bytes()
            suffix = path.suffix.lower()
            mime = "image/png" if suffix == ".png" else "image/jpeg"
            sent_size = list(image.size)
        else:
            scale = long_edge / max(image.size)
            sent_size = [round(image.width * scale), round(image.height * scale)]
            image = image.convert("RGB").resize(tuple(sent_size), Image.Resampling.LANCZOS)
            buffer = io.BytesIO()
            image.save(buffer, format="JPEG", quality=95, subsampling=0)
            payload = buffer.getvalue()
            mime = "image/jpeg"
    encoded = base64.b64encode(payload).decode("ascii")
    return f"data:{mime};base64,{encoded}", original_size, sent_size


def parse_prediction(text: str) -> tuple[int | None, bool]:
    match = INTEGER_RE.fullmatch(text)
    if match is None:
        return None, False
    value = int(match.group(1))
    if value >= MAX_VALID_COUNT:
        return None, False
    return value, True


def evaluate_one(row: dict, args: argparse.Namespace) -> dict:
    image_path = (args.data_root / row["image"]).resolve()
    image_url, original_size, sent_size = prepare_image(
        str(image_path), args.long_edge
    )
    request = {
        "model": args.model,
        "input": [
            {
                "role": "user",
                "content": [
                    {"type": "input_image", "image_url": image_url},
                    {
                        "type": "input_text",
                        "text": PROMPT.format(question=row["question"]),
                    },
                ],
            }
        ],
        "max_output_tokens": args.max_output_tokens,
    }
    if args.reasoning_effort != "none":
        request["reasoning"] = {"effort": args.reasoning_effort}
    if args.temperature is not None:
        request["temperature"] = args.temperature
    if args.top_p is not None:
        request["top_p"] = args.top_p

    last_error = None
    for attempt in range(args.retries):
        started = time.monotonic()
        try:
            response = client().responses.create(**request)
            raw_output = response.output_text
            prediction, valid = parse_prediction(raw_output)
            return {
                "question_id": row["question_id"],
                "group_id": row["group_id"],
                "model": args.model,
                "prediction": prediction,
                "valid": valid,
                "raw_output": raw_output,
                "original_size": original_size,
                "sent_size": sent_size,
                "elapsed_seconds": round(time.monotonic() - started, 3),
            }
        except Exception as exc:  # API errors are retained in the public result log.
            last_error = f"{type(exc).__name__}: {exc}"
            if attempt + 1 < args.retries:
                time.sleep(2**attempt)
    return {
        "question_id": row["question_id"],
        "group_id": row["group_id"],
        "model": args.model,
        "prediction": None,
        "valid": False,
        "raw_output": "",
        "original_size": original_size,
        "sent_size": sent_size,
        "error": last_error,
    }


def read_jsonl(path: Path) -> list[dict]:
    with path.open("r", encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def main() -> None:
    args = parse_args()
    if not os.environ.get("OPENAI_API_KEY"):
        raise SystemExit("OPENAI_API_KEY is not set")

    questions = read_jsonl(args.data_root / "data" / "questions.jsonl")
    if args.limit is not None:
        questions = questions[: args.limit]

    completed: set[str] = set()
    if args.output.exists():
        completed = {row["question_id"] for row in read_jsonl(args.output)}
    pending = [row for row in questions if row["question_id"] not in completed]
    args.output.parent.mkdir(parents=True, exist_ok=True)

    with args.output.open("a", encoding="utf-8", newline="\n") as handle:
        with ThreadPoolExecutor(max_workers=args.workers) as executor:
            futures = {executor.submit(evaluate_one, row, args): row for row in pending}
            for index, future in enumerate(as_completed(futures), start=1):
                result = future.result()
                handle.write(json.dumps(result, ensure_ascii=False) + "\n")
                handle.flush()
                print(
                    f"[{index}/{len(pending)}] {result['question_id']} "
                    f"prediction={result['prediction']} valid={result['valid']}",
                    flush=True,
                )


if __name__ == "__main__":
    main()