dsadaq commited on
Commit
d1d54c6
·
verified ·
1 Parent(s): 6466e2b

Upload benchmark/Eval/Reason2GenBench/reason2gen_gpt_eval.py with huggingface_hub

Browse files
benchmark/Eval/Reason2GenBench/reason2gen_gpt_eval.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import argparse
5
+ import base64
6
+ import csv
7
+ import json
8
+ import os
9
+ import re
10
+ import time
11
+ from dataclasses import dataclass
12
+ from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
13
+
14
+ from openai import OpenAI
15
+
16
+ IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
17
+ ID_RE = re.compile(r"(\d{3,4})")
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class TaskItem:
22
+ task: str
23
+ ex_id: int
24
+ image_input: str
25
+ image_target: str
26
+ instruction: str
27
+
28
+
29
+ def _guess_mime(path: str) -> str:
30
+ ext = os.path.splitext(path)[1].lower()
31
+ if ext in {".jpg", ".jpeg"}:
32
+ return "image/jpeg"
33
+ if ext == ".webp":
34
+ return "image/webp"
35
+ return "image/png"
36
+
37
+
38
+ def _encode_image_to_data_url(path: str) -> str:
39
+ with open(path, "rb") as f:
40
+ data = f.read()
41
+ b64 = base64.b64encode(data).decode("utf-8")
42
+ return f"data:{_guess_mime(path)};base64,{b64}"
43
+
44
+
45
+ def _safe_int(x, default: int = 0) -> int:
46
+ try:
47
+ return int(x)
48
+ except Exception:
49
+ return default
50
+
51
+
52
+ def _read_json(path: str):
53
+ with open(path, "r", encoding="utf-8") as f:
54
+ return json.load(f)
55
+
56
+
57
+ def _list_tasks(base_dir: str, tasks_filter: Optional[Set[str]] = None) -> List[str]:
58
+ out: List[str] = []
59
+ for name in sorted(os.listdir(base_dir)):
60
+ task_dir = os.path.join(base_dir, name)
61
+ if not os.path.isdir(task_dir):
62
+ continue
63
+ if tasks_filter is not None and name not in tasks_filter:
64
+ continue
65
+ json_path = os.path.join(task_dir, f"{name}.json")
66
+ if os.path.isfile(json_path):
67
+ out.append(name)
68
+ return out
69
+
70
+
71
+ def _load_task_items(base_dir: str, task: str, max_samples: int = 0) -> List[TaskItem]:
72
+ json_path = os.path.join(base_dir, task, f"{task}.json")
73
+ data = _read_json(json_path)
74
+ if not isinstance(data, list):
75
+ raise ValueError(f"Task JSON is not a list: {json_path}")
76
+
77
+ items: List[TaskItem] = []
78
+ for obj in data:
79
+ if not isinstance(obj, dict):
80
+ continue
81
+ ex_id = _safe_int(obj.get("id"), default=-1)
82
+ if ex_id < 0:
83
+ continue
84
+ image_input = str(obj.get("image_input") or "")
85
+ image_target = str(obj.get("image_target") or "")
86
+ instruction = str(obj.get("instruction") or "")
87
+ if not image_input or not image_target or not instruction:
88
+ continue
89
+ items.append(TaskItem(task=task, ex_id=ex_id, image_input=image_input, image_target=image_target, instruction=instruction))
90
+ if max_samples and len(items) >= max_samples:
91
+ break
92
+ return items
93
+
94
+
95
+ def _iter_image_files(root: str) -> Iterable[str]:
96
+ if not os.path.isdir(root):
97
+ return
98
+ for dirpath, _, filenames in os.walk(root):
99
+ for fn in filenames:
100
+ if os.path.splitext(fn)[1].lower() in IMG_EXTS:
101
+ yield os.path.join(dirpath, fn)
102
+
103
+
104
+ def _pick_better_path(current: Optional[str], cand: str, image_suffix: str) -> str:
105
+ if current is None:
106
+ return cand
107
+ cur_bn = os.path.basename(current)
108
+ cand_bn = os.path.basename(cand)
109
+ if image_suffix:
110
+ cur_match = cur_bn.endswith(image_suffix)
111
+ cand_match = cand_bn.endswith(image_suffix)
112
+ if cand_match and not cur_match:
113
+ return cand
114
+ if cur_match and not cand_match:
115
+ return current
116
+ if (len(cand_bn), cand_bn) < (len(cur_bn), cur_bn):
117
+ return cand
118
+ return current
119
+
120
+
121
+ def _build_pred_index(pred_dir: str, image_suffix: str) -> Dict[int, str]:
122
+ idx: Dict[int, str] = {}
123
+ for p in _iter_image_files(pred_dir):
124
+ bn = os.path.basename(p)
125
+ ms = ID_RE.findall(bn)
126
+ if not ms:
127
+ continue
128
+ ex_id = int(ms[-1])
129
+ idx[ex_id] = _pick_better_path(idx.get(ex_id), p, image_suffix=image_suffix)
130
+ return idx
131
+
132
+
133
+ def _build_task_pred_index(result_root: str, task: str, method_name: str, image_suffix: str) -> Dict[int, str]:
134
+ idx: Dict[int, str] = {}
135
+ cand_dirs = [
136
+ os.path.join(result_root, task, method_name),
137
+ os.path.join(result_root, task, method_name, "edited"),
138
+ ]
139
+ for d in cand_dirs:
140
+ if not os.path.isdir(d):
141
+ continue
142
+ sub = _build_pred_index(d, image_suffix=image_suffix)
143
+ for ex_id, p in sub.items():
144
+ idx[ex_id] = _pick_better_path(idx.get(ex_id), p, image_suffix=image_suffix)
145
+ return idx
146
+
147
+
148
+ def _call_gpt_judge(
149
+ client: OpenAI,
150
+ model: str,
151
+ instruction: str,
152
+ q_path: str,
153
+ gt_path: str,
154
+ pred_path: str,
155
+ json_mode: bool,
156
+ max_retries: int,
157
+ retry_min_seconds: float,
158
+ retry_max_seconds: float,
159
+ ) -> Tuple[int, str, str]:
160
+ q_url = _encode_image_to_data_url(q_path)
161
+ gt_url = _encode_image_to_data_url(gt_path)
162
+ pred_url = _encode_image_to_data_url(pred_path)
163
+
164
+ messages = [
165
+ {"role": "system", "content": "You are a strict, deterministic visual judge. Return only JSON."},
166
+ {
167
+ "role": "user",
168
+ "content": [
169
+ {
170
+ "type": "text",
171
+ "text": (
172
+ "Evaluate whether model_output is a correct solution to the task.\n\n"
173
+ "Task instruction (for context):\n"
174
+ f"{instruction}\n\n"
175
+ "You will see three images: question_input, ground_truth, model_output.\n"
176
+ "Use ground_truth as the reference for correctness. Minor stylistic differences are allowed, "
177
+ "but the final answer/state must match the ground truth.\n\n"
178
+ "Return a single JSON object with fields: label (1 or 0), reason (one short sentence)."
179
+ ),
180
+ },
181
+ {"type": "text", "text": "question_input:"},
182
+ {"type": "image_url", "image_url": {"url": q_url}},
183
+ {"type": "text", "text": "ground_truth:"},
184
+ {"type": "image_url", "image_url": {"url": gt_url}},
185
+ {"type": "text", "text": "model_output:"},
186
+ {"type": "image_url", "image_url": {"url": pred_url}},
187
+ ],
188
+ },
189
+ ]
190
+
191
+ last_err: Optional[Exception] = None
192
+ for attempt in range(max_retries + 1):
193
+ try:
194
+ kwargs = {"model": model, "messages": messages, "temperature": 0}
195
+ if json_mode:
196
+ kwargs["response_format"] = {"type": "json_object"}
197
+ resp = client.chat.completions.create(**kwargs)
198
+ raw = resp.choices[0].message.content or ""
199
+ txt = raw.strip()
200
+
201
+ try:
202
+ obj = json.loads(txt)
203
+ except Exception:
204
+ obj = None
205
+
206
+ if isinstance(obj, dict):
207
+ label = _safe_int(obj.get("label"), default=0)
208
+ if label not in (0, 1):
209
+ label = 0
210
+ reason = str(obj.get("reason") or "").strip().replace("\n", " ")
211
+ reason = re.sub(r"\s+", " ", reason)[:200]
212
+ return label, reason, txt
213
+
214
+ return 0, "PARSE_FAILED", txt
215
+ except Exception as e:
216
+ last_err = e
217
+ if attempt >= max_retries:
218
+ break
219
+ time.sleep(min(retry_min_seconds * (2**attempt), retry_max_seconds))
220
+
221
+ return 0, f"ERROR: {type(last_err).__name__}", ""
222
+
223
+
224
+ def _ensure_parent_dir(path: str) -> None:
225
+ parent = os.path.dirname(os.path.abspath(path))
226
+ if parent and not os.path.isdir(parent):
227
+ os.makedirs(parent, exist_ok=True)
228
+
229
+
230
+ def _load_done_keys(csv_path: str) -> Set[Tuple[str, int, str]]:
231
+ if not os.path.isfile(csv_path):
232
+ return set()
233
+ done: Set[Tuple[str, int, str]] = set()
234
+ with open(csv_path, "r", encoding="utf-8", newline="") as f:
235
+ reader = csv.DictReader(f)
236
+ for row in reader:
237
+ task = (row.get("task") or "").strip()
238
+ method = (row.get("method") or "").strip()
239
+ ex_id = _safe_int(row.get("id"), default=-1)
240
+ if task and method and ex_id >= 0:
241
+ done.add((task, ex_id, method))
242
+ return done
243
+
244
+
245
+ def main(argv: Optional[Sequence[str]] = None) -> int:
246
+ parser = argparse.ArgumentParser()
247
+ parser.add_argument("--base_dir", required=True, help="Path to benchmark/Reason2Gen")
248
+ parser.add_argument("--result_root", required=True, help="Path to prediction root")
249
+ parser.add_argument("--method_name", required=True, help="Method name under each task")
250
+ parser.add_argument("--image_suffix", default="", help="Prefer predictions that end with this suffix")
251
+ parser.add_argument("--model", default="gpt-4o-mini", help="OpenAI model name")
252
+ parser.add_argument("--max_samples_per_task", type=int, default=0, help="0 means no limit")
253
+ parser.add_argument("--tasks", default="", help="Comma-separated task names (optional)")
254
+ parser.add_argument("--out_csv", default="", help="CSV output path (optional)")
255
+ parser.add_argument("--json_mode", action="store_true", help="Use response_format=json_object")
256
+ parser.add_argument("--max_retries", type=int, default=5)
257
+ parser.add_argument("--retry_min_seconds", type=float, default=1.0)
258
+ parser.add_argument("--retry_max_seconds", type=float, default=20.0)
259
+
260
+ args = parser.parse_args(argv)
261
+
262
+ tasks_filter: Optional[Set[str]] = None
263
+ if args.tasks.strip():
264
+ tasks_filter = {t.strip() for t in args.tasks.split(",") if t.strip()}
265
+
266
+ out_csv = args.out_csv.strip() or os.path.join(args.result_root, f"{args.method_name}_gpt_eval.csv")
267
+ _ensure_parent_dir(out_csv)
268
+
269
+ done = _load_done_keys(out_csv)
270
+ client = OpenAI()
271
+
272
+ fieldnames = ["task", "id", "method", "q_path", "gt_path", "pred_path", "label", "reason", "raw_judge"]
273
+ need_header = not os.path.isfile(out_csv)
274
+
275
+ with open(out_csv, "a", encoding="utf-8", newline="") as f:
276
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
277
+ if need_header:
278
+ writer.writeheader()
279
+
280
+ tasks = _list_tasks(args.base_dir, tasks_filter=tasks_filter)
281
+ total_correct = 0
282
+ total_eval = 0
283
+
284
+ for task in tasks:
285
+ items = _load_task_items(args.base_dir, task, max_samples=args.max_samples_per_task)
286
+ pred_index = _build_task_pred_index(args.result_root, task, args.method_name, image_suffix=args.image_suffix)
287
+
288
+ task_correct = 0
289
+ task_eval = 0
290
+
291
+ for it in items:
292
+ key = (it.task, it.ex_id, args.method_name)
293
+ if key in done:
294
+ continue
295
+
296
+ q_path = os.path.join(args.base_dir, task, "question", it.image_input)
297
+ gt_path = os.path.join(args.base_dir, task, "answer", it.image_target)
298
+ pred_path = pred_index.get(it.ex_id)
299
+
300
+ if not os.path.isfile(q_path) or not os.path.isfile(gt_path) or not pred_path or not os.path.isfile(pred_path):
301
+ writer.writerow({"task": task, "id": it.ex_id, "method": args.method_name, "q_path": q_path, "gt_path": gt_path, "pred_path": pred_path or "", "label": "", "reason": "MISSING_IMAGE", "raw_judge": ""})
302
+ f.flush()
303
+ done.add(key)
304
+ continue
305
+
306
+ label, reason, raw = _call_gpt_judge(
307
+ client=client,
308
+ model=args.model,
309
+ instruction=it.instruction,
310
+ q_path=q_path,
311
+ gt_path=gt_path,
312
+ pred_path=pred_path,
313
+ json_mode=bool(args.json_mode),
314
+ max_retries=args.max_retries,
315
+ retry_min_seconds=args.retry_min_seconds,
316
+ retry_max_seconds=args.retry_max_seconds,
317
+ )
318
+
319
+ writer.writerow({"task": task, "id": it.ex_id, "method": args.method_name, "q_path": q_path, "gt_path": gt_path, "pred_path": pred_path, "label": label, "reason": reason, "raw_judge": raw})
320
+ f.flush()
321
+
322
+ done.add(key)
323
+ task_eval += 1
324
+ total_eval += 1
325
+ if label == 1:
326
+ task_correct += 1
327
+ total_correct += 1
328
+
329
+ if task_eval:
330
+ print(f"[TASK] {task}: {task_correct}/{task_eval} = {task_correct / task_eval:.4f}")
331
+ else:
332
+ print(f"[TASK] {task}: no evaluated samples")
333
+
334
+ if total_eval:
335
+ print(f"[ALL] {total_correct}/{total_eval} = {total_correct / total_eval:.4f}")
336
+ else:
337
+ print("[ALL] no evaluated samples")
338
+
339
+ print(f"Saved: {out_csv}")
340
+ return 0
341
+
342
+
343
+ if __name__ == "__main__":
344
+ raise SystemExit(main())