yulingxi commited on
Commit
426a20f
·
verified ·
1 Parent(s): a667b5c

Upload eval_metricbench_public.py

Browse files

pip install requests pyarrow huggingface_hub
export METRICBENCH_API_KEY="YOUR_KEY"
python eval_metricbench_public.py \
--base-url https://YOUR_HOST/v1 \
--model YOUR_MODEL \
--output results

Files changed (1) hide show
  1. eval_metricbench_public.py +388 -0
eval_metricbench_public.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Metric-Bench standalone evaluator (Python 3.10+).
3
+ Install: pip install requests pyarrow huggingface_hub
4
+ Example (fill in your own service):
5
+ python eval_metricbench_public.py --base-url https://YOUR_HOST/v1 --model YOUR_MODEL --output results
6
+ API key: --api-key KEY or environment METRICBENCH_API_KEY (--api-key-env changes its name).
7
+ No default endpoint or model. Omit key for unauthenticated services.
8
+ Requires an OpenAI-compatible chat/completions service with image input.
9
+ The default dataset is downloaded automatically from Hugging Face.
10
+ Use --dataset-dir for a local copy, or --score-only for saved predictions.
11
+ Outputs contain service/model settings, questions, ground truth, and model
12
+ responses. Review them before sharing; never put credentials in extra-body.
13
+ Qwen native settings can be supplied using --extra-body-file:
14
+ {"chat_template_kwargs":{"enable_thinking":true,"reasoning_effort":"medium"}}
15
+ No provider-specific thinking options are sent unless explicitly supplied.
16
+
17
+ Sources: https://arxiv.org/html/2609.25841v1 (Table 1, Eqs 7-9, Appendix 8-10)
18
+ https://huggingface.co/datasets/yulingxi/Metric-Bench
19
+ Prompt: long-form spatial reasoning template following the paper-described
20
+ structure; not verified as verbatim paper text.
21
+ The HF card describes a reconstructed release: not a reproduction of paper scores.
22
+
23
+ Both scoring profiles are reported:
24
+ documented: relative error denominator |GT|; GT=0 uses exact match.
25
+ delta1: same-sign magnitude ratio <1.25; both zero pass, one zero fails.
26
+ These signed/zero conventions are explicit extensions not specified in paper.
27
+ legacy: near-zero MRA exception (both magnitudes <0.05, GT!=0)
28
+ and raw signed delta1 ratio, which can accept opposite-sign values, for comparison only.
29
+ Vector scores average components; queries have equal weight. RMSE is sqrt(mean
30
+ query MSE), NOT mean query RMSE. Macro-type MRA is also reported.
31
+ Invalid/truncated answers: zero MRA/delta1; RMSE undefined, so all-query RMSE=null
32
+ if any invalid. Valid-only statistics and coverage are separately labelled.
33
+ No 3D IoU: the release lacks box rotation/camera-axis extents.
34
+ """
35
+ from __future__ import annotations
36
+ import argparse
37
+ import ast
38
+ import base64
39
+ import hashlib
40
+ import json
41
+ import math
42
+ import os
43
+ import re
44
+ import sys
45
+ import time
46
+ from collections import defaultdict
47
+ from concurrent.futures import ThreadPoolExecutor, as_completed
48
+ from pathlib import Path, PurePosixPath, PureWindowsPath
49
+ from urllib.parse import urlsplit
50
+
51
+ SYSTEM_PROMPT = "You are an expert in spatial reasoning, knowing the mechanism of Pinhole imaging mechanism\nand perspective projection, and designed to reason 3D metric measurement of other objects based on a\ngiven image and 3D metric of the anchor objects in 3d space."
52
+
53
+ ANCHOR_TEMPLATE_V2 = "You are given an image along with a textual description that includes\n3D metric information about certain \"anchor\" objects in the scene, represented in the\ncamera coordinate system. Your task is to reason about the 3D spatial layout and infer\nthe metric property (e.g., height) of a specified \"target\" object based on visual cues,\nspatial relations, and provided anchor metric measurement.\nPrerequisite knowledge:\n 1. **The Camera Coordinate System**: Recall that the camera coordinate system has its origin at the optical center, with:\n - **Z-axis** pointing in the imaging direction (forward),\n - **X-axis** parallel to the image horizontal (positive right),\n - **Y-axis** parallel to the image vertical (positive downward).\n All positions and dimensions are in meters.\n 2. **Anchor box Information**: If the 3D bounding box of the anchor object (e.g., a book) is given, the format is `[x, y, z, width, height, length]`, where:\n - `[x, y, z]` is the center position in camera coordinates,\n - `[width, height, length]` correspond to the shorter horizontal dimension, vertical dimension, and longer horizontal dimension, respectively.\nThe question that need to be reasoned:\n{Question}\n\nPlease provide your response in **two parts**: `thinking process` and `final answer`.\n\n* **`thinking process`**: Your analysis where you explain your reasoning step-by-step, which includes but is not limited to the following aspects:\n\n 1. **Define the Reference Anchor and Its Known Physical Quantity**\n - Explicitly specify which object serves as the scale reference (the *Anchor Object*).\n - Provide its known physical quantity (e.g., height, width, distance from camera) along with the unit (e.g., meters).\n - If the anchor is not directly visible in the image, clarify its logical existence and cite the source of its measured value (e.g., given in the problem statement).\n\n 2. **Establish Spatial Pose and Contextual Layout of the Anchor**\n - Describe the anchor's 3D orientation and position relative to the camera and environment (e.g., upright on a table, leaning against a wall, rotated 15 degrees about the Y-axis).\n - Specify its topological relationships with other salient objects (e.g., \"the book is on top of the cabinet,\" \"adjacent to a lamp\").\n - Purpose: Ground all subsequent proportional or geometric reasoning in physically plausible spatial assumptions.\n\n 3. **Identify and Locate the Target Object in Image Space**\n - Clearly identify the target object (e.g., cabinet) by describing its visual appearance\n (color, shape, texture), image position (e.g., bottom-right quadrant), and occlusion\n status (e.g., partially occluded by a chair).\n - Justify why this object is selected as the target (e.g., matches the category and proximity criteria in the prompt).\n - Optionally, reference approximate pixel coordinates or key landmarks (e.g., top edge, base) to support measurement.\n\n 4. **Construct Spatial Relationship Graph (with Optional Intermediates)**\n - Use visual and geometric cues-such as perspective lines, occlusion order, alignment, relative scale, and projection-to link the target to the anchor.\n - If direct comparison is unreliable, introduce intermediate reference objects to form a reasoning chain (e.g., *cabinet -> shelf -> book*).\n - For directional or angular tasks, describe relative orientations (e.g., \"both objects share the same frontal plane\").\n\n 5. **Estimate Relative Quantity Offset or Scaling Ratio**\n - Quantify the proportional relationship between the target and the anchor (or intermediate):\n - E.g., \"the cabinet appears 4x taller than the book in vertical pixel span.\"\n - Specify the estimation method:\n - Pixel ratio under coplanarity assumption,\n - Common-sense priors (e.g., typical book height ~= 0.3 m),\n - Geometric models (e.g., similar triangles using vanishing points).\n - Explicitly state the basis: visual estimation, pixel measurement, or model-based derivation.\n\n 6. **Derive Absolute Quantity via Explicit Calculation Chain**\n - Starting from the anchor's known physical dimension, apply the scaling ratio or offset from Step 5 to compute the target's absolute metric value.\n - Show the full calculation (e.g., *height_cabinet = height_book x (pixel_height_cabinet / pixel_height_book) = 0.32 m x (400 px / 80 px) = 1.6 m*).\n - Avoid leaps or unexplained guesses-every step must be traceable.\n\n 7. **Document Assumptions, Limitations, and Uncertainty Bounds**\n - List critical assumptions (e.g., \"objects are coplanar,\" \"camera is calibrated,\" \"no significant lens distortion,\" \"book is upright\").\n - Provide estimated error margins (e.g., +/-0.1 due to perspective foreshortening) or confidence levels.\n - Discuss how violating key assumptions (e.g., non-coplanarity) would affect the result (e.g., overestimation of height).\n\n* **`final answer`**: Your final numerical estimate for the target object's physical quantity\n (e.g., height in meters), wrapped in `<answer>` tags and formatted as a JSON object\n with the appropriate key.\n\n**Example of the required output format which you should follow:**\n\"<thinking>Step-by-step reasoning following the seven aspects above, grounded in visual analysis and explicit calculation.</thinking>\"\n{Answer}\n"
54
+
55
+ ANSWER_FORMATS = {
56
+ "length": "Please output the result in JSON format: <answer>{'length': <value>}</answer>",
57
+ "width": "Please output the result in JSON format: <answer>{'width': <value>}</answer>",
58
+ "height": "Please output the result in JSON format: <answer>{'height': <value>}</answer>",
59
+ "dimension": "Please output the result in JSON format: <answer>{'dimension': [<w>, <h>, <l>]}</answer>",
60
+ "center": "Please output the result in JSON format: <answer>{'center': [<x>, <y>, <z>]}</answer>",
61
+ "depth": "Please output the result in JSON format: <answer>{'depth': <value>}</answer>",
62
+ "elevation": "Please output the result in JSON format: <answer>{'elevation': <value>}</answer>",
63
+ "box": "Please output the result in JSON format: <answer>{'box': <[x, y, z, w, h, l]>}</answer>",
64
+ "distance": "Please output the result in JSON format: <answer>{'distance': <value>}</answer>"
65
+ }
66
+
67
+ SHAPES = {"length":1,"width":1,"height":1,"depth":1,"elevation":1,"distance":1,
68
+ "dimension":3,"center":3,"box":6}
69
+ CATEGORIES = {k:("Size" if k in ("length","width","height","dimension","elevation")
70
+ else {"center":"Position","depth":"Depth","distance":"Distance","box":"Box"}[k])
71
+ for k in SHAPES}
72
+
73
+
74
+ def build_prompt(row):
75
+ return ANCHOR_TEMPLATE_V2.format(Question=row["question"],
76
+ Answer=ANSWER_FORMATS[row["question_type"]])
77
+
78
+
79
+ def numeric(value, kind):
80
+ n = SHAPES[kind]
81
+ if (n == 1 and isinstance(value,list)) or (n > 1 and not isinstance(value,list)):
82
+ raise ValueError("scalar/vector mismatch")
83
+ vs = value if isinstance(value,list) else [value]
84
+ if len(vs)!=n or any(isinstance(v,bool) or not isinstance(v,(float,int))
85
+ or not math.isfinite(v) for v in vs):
86
+ raise ValueError("wrong shape or non-finite/non-numeric value")
87
+ return [float(v) for v in vs] if n>1 else float(vs[0])
88
+
89
+
90
+ def parse_answer(content, kind):
91
+ text = content or ""
92
+ for tag in ("think","thinking"):
93
+ text = re.sub(rf"<{tag}>.*?</{tag}>","",text,flags=re.S|re.I)
94
+ if re.search(rf"<{tag}>",text,re.I):
95
+ raise ValueError("unfinished reasoning")
96
+ text = re.split(rf"</{tag}>",text,flags=re.I)[-1]
97
+ answers = re.findall(r"<answer>\s*(.*?)\s*</answer>",text,re.S|re.I)
98
+ if len(answers)>1:
99
+ raise ValueError("multiple final answers")
100
+ if answers:
101
+ text = answers[0]
102
+ elif re.search(r"</?answer>",text,re.I):
103
+ raise ValueError("unfinished answer")
104
+ fence = chr(96)*3
105
+ text = re.sub(r"^\s*"+fence+r"(?:json|python)?\s*|\s*"+fence+r"\s*$","",text.strip())
106
+ try:
107
+ obj = json.loads(text)
108
+ except (ValueError,TypeError):
109
+ try:
110
+ obj = ast.literal_eval(text)
111
+ except (ValueError,SyntaxError):
112
+ raise ValueError("no unambiguous final JSON object") from None
113
+ if not isinstance(obj,dict) or set(obj)!={kind}:
114
+ raise ValueError("answer must have exactly the expected key")
115
+ return numeric(obj[kind],kind)
116
+
117
+
118
+ def scalar_metrics(p,g,profile):
119
+ if g==0:
120
+ mra=float(p==0)
121
+ elif profile=="legacy" and abs(g)<.05 and abs(p)<.05:
122
+ mra=1.
123
+ else:
124
+ rel=abs(p-g)/abs(g)
125
+ mra=sum(rel <= (10-i)/20+1e-12 for i in range(10))/10
126
+ if profile=="legacy":
127
+ delta=float(p!=0 and g!=0 and max(p/g,g/p)<1.25)
128
+ elif p==0 or g==0:
129
+ delta=float(p==g)
130
+ else:
131
+ delta=float(p*g>0 and max(abs(p/g),abs(g/p))<1.25)
132
+ return {"mra":mra,"mse":(p-g)**2,"delta1":delta}
133
+
134
+
135
+ def summarize(rows,profile):
136
+ groups=defaultdict(list)
137
+ for row in rows:
138
+ kind=row["question_type"]
139
+ gt=row["ground_truth"]
140
+ if isinstance(gt,str):
141
+ gt=json.loads(gt)
142
+ g=numeric(gt[kind],kind)
143
+ p=row.get("prediction")
144
+ score=None
145
+ if p is not None:
146
+ p=numeric(p,kind)
147
+ pairs=zip(p,g) if isinstance(g,list) else [(p,g)]
148
+ vals=[scalar_metrics(a,b,profile) for a,b in pairs]
149
+ score={k:sum(v[k] for v in vals)/len(vals) for k in vals[0]}
150
+ for group in ("overall","type:"+kind,"category:"+CATEGORIES[kind]):
151
+ groups[group].append(score)
152
+ def aggregate(items):
153
+ valid=[x for x in items if x is not None]
154
+ n,v=len(items),len(valid)
155
+ mra=sum(x["mra"] for x in valid)
156
+ delta=sum(x["delta1"] for x in valid)
157
+ rmse=math.sqrt(sum(x["mse"] for x in valid)/v) if v else None
158
+ return {"count":n,"valid":v,"invalid":n-v,"valid_rate":v/n,
159
+ "mra_percent_all":100*mra/n,"delta1_all":delta/n,
160
+ "mra_percent_valid":100*mra/v if v else None,
161
+ "delta1_valid":delta/v if v else None,
162
+ "rmse_m_valid":rmse,"rmse_m_all":rmse if v==n else None}
163
+ result={k:aggregate(v) for k,v in groups.items()}
164
+ types=[v["mra_percent_all"] for k,v in result.items() if k.startswith("type:")]
165
+ result["macro_type_mra_percent"]=sum(types)/len(types) if types else None
166
+ return result
167
+
168
+
169
+ def make_payload(model,messages,max_tokens,temperature,extra):
170
+ if not isinstance(extra,dict) or set(extra)&{"model","messages","max_tokens","temperature","stream"}:
171
+ raise ValueError("extra-body must be an object without reserved request keys")
172
+ return {"model":model,"messages":messages,"max_tokens":max_tokens,
173
+ "temperature":temperature,"stream":False,**extra}
174
+
175
+
176
+ def digest(data):
177
+ return hashlib.sha256(data).hexdigest()
178
+
179
+
180
+ def image_path(root, name):
181
+ # HF snapshot files can be symlinks into a sibling blobs/ directory.
182
+ # Validate the repository-relative name, not the resolved cache target.
183
+ posix, windows = PurePosixPath(name), PureWindowsPath(name)
184
+ if posix.is_absolute() or windows.drive or windows.root or '..' in posix.parts or '..' in windows.parts:
185
+ raise ValueError(f"Out-of-root image name: {name}")
186
+ path = root/name
187
+ if not path.is_file():
188
+ raise ValueError(f"Missing image: {name}")
189
+ return path
190
+
191
+
192
+ def read_jsonl(path):
193
+ rows=[]
194
+ with Path(path).open(encoding="utf-8") as f:
195
+ for i,line in enumerate(f,1):
196
+ if line.strip():
197
+ try:
198
+ rows.append(json.loads(line))
199
+ except ValueError:
200
+ raise ValueError(f"Malformed JSONL line {i}; repair partial line before resuming") from None
201
+ return rows
202
+
203
+
204
+ def write_reports(rows,out):
205
+ reports={p:summarize(rows,p) for p in ("documented","legacy")}
206
+ (out/"summary.json").write_text(json.dumps(reports,indent=2,allow_nan=False),encoding="utf-8")
207
+ lines=["# Metric-Bench evaluation","","Reconstructed HF release; not a reproduction of paper scores.",
208
+ "MRA: percent; delta1: fraction; RMSE: meters. Invalid outputs count as failures.",
209
+ "RMSE all=null if any invalid; RMSE valid must be read with coverage.",""]
210
+ for profile,report in reports.items():
211
+ if "overall" not in report:
212
+ continue
213
+ overall=report["overall"]
214
+ values=[f'{overall["mra_percent_all"]:.2f}']
215
+ for c in ("Size","Position","Depth","Distance","Box"):
216
+ x=report.get("category:"+c)
217
+ values.append(f'{x["mra_percent_all"]:.2f}' if x else "N/A")
218
+ values += [str(overall["rmse_m_all"]),str(overall["rmse_m_valid"]),
219
+ f'{overall["delta1_all"]:.4f}',f'{overall["valid"]}/{overall["count"]}']
220
+ lines += [f"## {profile}","",
221
+ "| Avg. MRA | Size | Pos. | Dep. | Dis. | Box | RMSE all | RMSE valid | delta1 all | Valid |",
222
+ "|---|---|---|---|---|---|---|---|---|---|","| "+" | ".join(values)+" |",""]
223
+ (out/"table.md").write_text("\n".join(lines),encoding="utf-8")
224
+ print("\n".join(lines))
225
+
226
+
227
+ def main():
228
+ ap=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
229
+ ap.add_argument("--base-url",help="API root including /v1; no default")
230
+ ap.add_argument("--model",help="Service model name/alias")
231
+ ap.add_argument("--api-key",help="Prefer --api-key-env to avoid shell history exposure")
232
+ ap.add_argument("--api-key-env",default="METRICBENCH_API_KEY")
233
+ ap.add_argument("--repo-id",default="yulingxi/Metric-Bench")
234
+ ap.add_argument("--revision",default="main",help="Resolved to immutable HF commit")
235
+ ap.add_argument("--dataset-dir",type=Path,help="Local root with test.parquet and images/")
236
+ ap.add_argument("--output",type=Path,default=Path("metricbench_results"))
237
+ ap.add_argument("--max-tokens",type=int,default=8192)
238
+ ap.add_argument("--temperature",type=float,default=0.)
239
+ ap.add_argument("--workers",type=int,default=4)
240
+ ap.add_argument("--timeout",type=float,default=180.)
241
+ ap.add_argument("--retries",type=int,default=2)
242
+ ap.add_argument("--limit",type=int,help="Smoke subset, not a full benchmark")
243
+ ap.add_argument("--extra-body",default="{}",help="Provider-specific JSON options, no credentials")
244
+ ap.add_argument("--extra-body-file",type=Path,help="JSON file alternative to shell quoting")
245
+ ap.add_argument("--resume",action="store_true")
246
+ ap.add_argument("--score-only",type=Path,help="Score saved predictions without network/dependencies")
247
+ a=ap.parse_args()
248
+ if a.score_only:
249
+ rows=read_jsonl(a.score_only)
250
+ a.output.mkdir(parents=True,exist_ok=True)
251
+ write_reports(rows,a.output)
252
+ return 0
253
+ if not a.base_url or not a.model:
254
+ ap.error("--base-url and --model must be filled in")
255
+ url=urlsplit(a.base_url)
256
+ if url.scheme not in ("http","https") or not url.netloc or url.username or url.password or url.query or url.fragment:
257
+ ap.error("base-url must be HTTP(S), without credentials/query/fragment")
258
+ if a.workers<1 or a.max_tokens<1 or a.timeout<=0 or a.retries<0 or (a.limit is not None and a.limit<1):
259
+ ap.error("invalid workers/max-tokens/timeout/retries/limit")
260
+ extra=json.loads(a.extra_body_file.read_text(encoding="utf-8") if a.extra_body_file else a.extra_body)
261
+ make_payload(a.model,[],a.max_tokens,a.temperature,extra)
262
+ key=a.api_key if a.api_key is not None else os.environ.get(a.api_key_env,"")
263
+ try:
264
+ import requests
265
+ import pyarrow.parquet as pq
266
+ except ImportError:
267
+ ap.error("Install dependencies: pip install requests pyarrow huggingface_hub")
268
+ revision=None
269
+ if a.dataset_dir:
270
+ root=a.dataset_dir.resolve()
271
+ else:
272
+ from huggingface_hub import HfApi,snapshot_download
273
+ revision=HfApi().dataset_info(a.repo_id,revision=a.revision).sha
274
+ root=Path(snapshot_download(repo_id=a.repo_id,repo_type="dataset",revision=revision,
275
+ allow_patterns=["test.parquet","images/**","README.md","dataset_stats.json"]))
276
+ rows=pq.read_table(root/"test.parquet").to_pylist()
277
+ if a.limit:
278
+ rows=rows[:a.limit]
279
+ if not rows:
280
+ raise ValueError("Empty dataset")
281
+ images={}
282
+ ids=set()
283
+ for row in rows:
284
+ uid=str(row["id"])
285
+ if uid in ids:
286
+ raise ValueError("Duplicate sample ID")
287
+ ids.add(uid)
288
+ kind=row["question_type"]
289
+ gt=row["ground_truth"]
290
+ gt=json.loads(gt) if isinstance(gt,str) else gt
291
+ numeric(gt[kind],kind)
292
+ row["ground_truth"]=gt
293
+ if len(row["images"])!=1:
294
+ raise ValueError("Expected exactly one image")
295
+ for name in row["images"]:
296
+ images[name]=image_path(root,name)
297
+ manifest={"script_sha256":digest(Path(__file__).read_bytes()),
298
+ "dataset_repo":a.repo_id,"revision":revision,
299
+ "parquet_sha256":digest((root/"test.parquet").read_bytes()),
300
+ "images_sha256":{k:digest(v.read_bytes()) for k,v in sorted(images.items())},
301
+ "sample_ids":sorted(ids),"model":a.model,"base_url":a.base_url,
302
+ "max_tokens":a.max_tokens,"temperature":a.temperature,"extra_body":extra,
303
+ "system_prompt":SYSTEM_PROMPT,"prompt_template":ANCHOR_TEMPLATE_V2,
304
+ "answer_formats":ANSWER_FORMATS,
305
+ "prompt_provenance":"Long-form spatial reasoning template; paper-structure aligned, not verified verbatim",
306
+ "dataset_warning":"Reconstructed release, not published-score reproduction"}
307
+ # API key deliberately excluded from saved metadata and errors.
308
+ out=a.output
309
+ out.mkdir(parents=True,exist_ok=True)
310
+ mp,pp=out/"manifest.json",out/"predictions.jsonl"
311
+ done={}
312
+ if mp.exists() or pp.exists():
313
+ if not a.resume or not mp.exists():
314
+ raise ValueError("Output exists; choose a new directory or --resume")
315
+ if json.loads(mp.read_text(encoding="utf-8"))!=manifest:
316
+ raise ValueError("Resume manifest mismatch; use a new output directory")
317
+ if pp.exists():
318
+ for r in read_jsonl(pp):
319
+ uid=str(r["id"])
320
+ if uid not in ids or uid in done:
321
+ raise ValueError("Unknown/duplicate prediction ID")
322
+ done[uid]=r
323
+ else:
324
+ mp.write_text(json.dumps(manifest,indent=2),encoding="utf-8")
325
+ headers={"Content-Type":"application/json"}
326
+ if key:
327
+ headers["Authorization"]="Bearer "+key
328
+
329
+ def evaluate(row):
330
+ path=images[row["images"][0]]
331
+ mime="image/png" if path.suffix.lower()==".png" else "image/jpeg"
332
+ image_url=f"data:{mime};base64,"+base64.b64encode(path.read_bytes()).decode("ascii")
333
+ messages=[{"role":"system","content":SYSTEM_PROMPT},
334
+ {"role":"user","content":[{"type":"image_url","image_url":{"url":image_url}},
335
+ {"type":"text","text":build_prompt(row)}]}]
336
+ payload=make_payload(a.model,messages,a.max_tokens,a.temperature,extra)
337
+ result={"id":row["id"],"question_type":row["question_type"],"question":row["question"],
338
+ "ground_truth":row["ground_truth"],"prediction":None,"status":"api_error"}
339
+ for attempt in range(a.retries+1):
340
+ try:
341
+ response=requests.post(a.base_url.rstrip("/")+"/chat/completions",headers=headers,
342
+ json=payload,timeout=a.timeout,allow_redirects=False)
343
+ if response.status_code>=300:
344
+ result["error"]=f"HTTP {response.status_code}"
345
+ if response.status_code not in (429,500,502,503,504):
346
+ return result
347
+ raise requests.RequestException("retryable HTTP error")
348
+ body=response.json()
349
+ choice=body["choices"][0]
350
+ content=choice["message"].get("content") or ""
351
+ result.update(content=content,finish_reason=choice.get("finish_reason"),
352
+ usage=body.get("usage"),status="invalid")
353
+ if choice.get("finish_reason")=="length":
354
+ result["error"]="truncated"
355
+ else:
356
+ try:
357
+ result["prediction"]=parse_answer(content,row["question_type"])
358
+ result["status"]="ok"
359
+ result.pop("error",None)
360
+ except ValueError as e:
361
+ result["error"]=str(e)
362
+ return result
363
+ except (requests.RequestException,ValueError,KeyError,IndexError,TypeError) as e:
364
+ result.setdefault("error",type(e).__name__)
365
+ if attempt<a.retries:
366
+ time.sleep(min(2**attempt,8))
367
+ return result
368
+
369
+ pending=[r for r in rows if str(r["id"]) not in done]
370
+ with pp.open("a",encoding="utf-8") as f, ThreadPoolExecutor(max_workers=a.workers) as pool:
371
+ futures=[pool.submit(evaluate,r) for r in pending]
372
+ for future in as_completed(futures):
373
+ record=future.result()
374
+ f.write(json.dumps(record,ensure_ascii=False,allow_nan=False)+"\n")
375
+ f.flush()
376
+ done[str(record["id"])]=record
377
+ print(f'{len(done)}/{len(rows)} id={record["id"]} {record["status"]}',flush=True)
378
+ results=[done[str(row["id"])] for row in rows]
379
+ write_reports(results,out)
380
+ failed=sum(r["status"]=="api_error" for r in results)
381
+ if failed:
382
+ print(f"WARNING: {failed} API failures counted as invalid. Retry in a new output directory.",file=sys.stderr)
383
+ return 2 if failed else 0
384
+
385
+
386
+ if __name__=="__main__":
387
+ raise SystemExit(main())
388
+