Datasets:
Download evaluation/evaluate_gpt.py from lulidong/PhysCount: direct link, hf CLI and curl.
- Browser
- Download file 7.07 kB
-
https://huggingface.co/datasets/lulidong/PhysCount/resolve/main/evaluation/evaluate_gpt.py
- Command line
-
hf download hf://datasets/lulidong/PhysCount/evaluation/evaluate_gpt.py
-
curl -L -o evaluate_gpt.py https://huggingface.co/datasets/lulidong/PhysCount/resolve/main/evaluation/evaluate_gpt.py
7.07 kB
| #!/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 | |
| 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() | |