midah commited on
Commit
e3da7b2
·
verified ·
1 Parent(s): e37bd2f

Reorganize: scripts/eval/track_a_multiview.py

Browse files
Files changed (1) hide show
  1. scripts/eval/track_a_multiview.py +343 -0
scripts/eval/track_a_multiview.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Track A: Multi-view correspondence eval on design patent rasters.
2
+
3
+ Two tasks:
4
+ Task 1 — Viewpoint identification: given one figure, name the viewpoint.
5
+ Task 2 — Cross-view retrieval: given figure_0, select the correct
6
+ "front elevational" view from 4 candidates (1 correct + 3 distractors
7
+ from other patents in the same Locarno class).
8
+
9
+ Usage:
10
+ export ANTHROPIC_API_KEY=...
11
+ python scripts/eval/track_a_multiview.py \
12
+ --enriched data/enriched/enriched_2022.parquet \
13
+ --images /tmp/patent_sample/2022 \
14
+ --n 30 \
15
+ --out results/track_a_results.json
16
+
17
+ Results printed to stdout and saved to --out.
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import random
24
+ import re
25
+ import time
26
+ from pathlib import Path
27
+
28
+ import pandas as pd
29
+ from PIL import Image
30
+ from tqdm import tqdm
31
+
32
+ from provider import chat, encode_image, get_client, image_message, multi_image_message
33
+
34
+
35
+ # ── viewpoint parsing ────────────────────────────────────────────────────────
36
+
37
+ VIEWPOINT_RE = re.compile(
38
+ r"FIG\.\s*{n}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
39
+ re.IGNORECASE,
40
+ )
41
+
42
+ def parse_viewpoint(drawing_desc: str, fig_num: int) -> str:
43
+ pat = re.compile(
44
+ rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
45
+ re.IGNORECASE,
46
+ )
47
+ m = pat.search(drawing_desc or "")
48
+ return m.group(1).strip().lower() if m else ""
49
+
50
+
51
+ FRONT_KEYWORDS = {"front elevational", "front view", "front elevation", "front plan"}
52
+
53
+ def is_front_view(vp: str) -> bool:
54
+ vp = vp.lower()
55
+ return any(k in vp for k in FRONT_KEYWORDS)
56
+
57
+
58
+ def is_perspective_view(vp: str) -> bool:
59
+ return "perspective" in vp.lower()
60
+
61
+
62
+ # ── image loading ─────────────────────────────────────────────────────────────
63
+
64
+ def find_image_path(images_dir: Path, image_filename: str) -> Path | None:
65
+ """Resolve image_filename → path under images_dir.
66
+
67
+ IMPACT stores images as:
68
+ {images_dir}/USD0949851-20220426/USD0949851-20220426-D00001.TIF
69
+ The directory name is the filename prefix up to '-D00'.
70
+ """
71
+ parts = image_filename.split("-D0")
72
+ if len(parts) < 2:
73
+ return None
74
+ dir_name = parts[0] # e.g. "USD0949851-20220426"
75
+ candidate = images_dir / dir_name / image_filename
76
+ return candidate if candidate.exists() else None
77
+
78
+
79
+ def load_image_b64(path: Path) -> tuple[str, str]:
80
+ return encode_image(path)
81
+
82
+
83
+ # ── Claude API calls ─────────────────────────────────────────────────────────
84
+
85
+ def ask_viewpoint(client, img_b64: str, media_type: str) -> str:
86
+ """Task 1: identify the viewpoint of a single patent figure."""
87
+ msgs = image_message(img_b64, media_type,
88
+ "This is a technical drawing from a US design patent. "
89
+ "In 2–5 words, what viewpoint or perspective does this figure show? "
90
+ "(e.g. 'front elevational view', 'perspective view', 'top plan view') "
91
+ "Reply with the viewpoint label only, nothing else."
92
+ )
93
+ return chat(client, msgs, max_tokens=80).lower()
94
+
95
+
96
+ def ask_cross_view(
97
+ client,
98
+ query_b64: str,
99
+ query_media: str,
100
+ candidates: list[tuple[str, str]],
101
+ target_label: str = "front elevational view",
102
+ ) -> int:
103
+ """Task 2: sequential yes/no — ask about each candidate independently.
104
+
105
+ Avoids the multi-image A/B/C/D format that causes thinking-model parse
106
+ failures. For each candidate we ask a binary question; the one (and only
107
+ one) that gets YES is the answer. Returns 0-indexed position, or -1 if
108
+ zero or multiple candidates say YES.
109
+ """
110
+ yes_indices = []
111
+ for i, (cand_b64, cand_media) in enumerate(candidates):
112
+ msgs = multi_image_message(
113
+ images=[(query_b64, query_media), (cand_b64, cand_media)],
114
+ text_after=(
115
+ f"Image 1 is a perspective view of a design patent object. "
116
+ f"Image 2 is another figure from the same patent. "
117
+ f"Is Image 2 the {target_label} of this object? "
118
+ f"Reply with YES or NO only."
119
+ ),
120
+ )
121
+ answer = chat(client, msgs, max_tokens=10).upper().strip()
122
+ is_yes = answer.startswith("YES")
123
+ if is_yes:
124
+ yes_indices.append(i)
125
+ time.sleep(0.3)
126
+
127
+ if len(yes_indices) == 1:
128
+ return yes_indices[0]
129
+ # Ambiguous (0 or >1 YES): fall back to the first YES if multiple,
130
+ # or -1 if none.
131
+ return yes_indices[0] if yes_indices else -1
132
+
133
+
134
+ # ── scoring helpers ──────────────────────────────────────────────��────────────
135
+
136
+ def viewpoint_match(predicted: str, ground_truth: str) -> bool:
137
+ """Loose match: check if key directional words overlap."""
138
+ DIRECTIONS = {"front", "rear", "back", "left", "right", "top", "bottom",
139
+ "side", "perspective", "plan", "elevation", "elevational",
140
+ "isometric", "oblique", "reference", "detail"}
141
+ pred_words = set(re.findall(r"\w+", predicted.lower())) & DIRECTIONS
142
+ gt_words = set(re.findall(r"\w+", ground_truth.lower())) & DIRECTIONS
143
+ if not gt_words:
144
+ return False
145
+ return len(pred_words & gt_words) / len(gt_words) >= 0.5
146
+
147
+
148
+ # ── dataset preparation ───────────────────────────────────────────────────────
149
+
150
+ def build_sample_pool(df: pd.DataFrame, images_dir: Path) -> pd.DataFrame:
151
+ """Enrich dataframe with parsed viewpoints and resolved image paths."""
152
+ df = df.copy()
153
+ df["viewpoint_parsed"] = df.apply(
154
+ lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]),
155
+ axis=1,
156
+ )
157
+ df["image_path"] = df["image_filename"].apply(
158
+ lambda fn: find_image_path(images_dir, fn)
159
+ )
160
+ return df
161
+
162
+
163
+ def select_patents(df: pd.DataFrame, n: int, seed: int = 42) -> list[str]:
164
+ """Select n patents that have: ≥3 figures, a perspective view, and a front view."""
165
+ rng = random.Random(seed)
166
+ eligible = []
167
+ for patent_id, group in df.groupby("patent_id"):
168
+ vps = group["viewpoint_parsed"].tolist()
169
+ paths = group["image_path"].tolist()
170
+ has_perspective = any(is_perspective_view(v) for v in vps)
171
+ has_front = any(is_front_view(v) for v in vps)
172
+ all_images = all(p is not None for p in paths)
173
+ if has_perspective and has_front and all_images and len(group) >= 3:
174
+ eligible.append(patent_id)
175
+ rng.shuffle(eligible)
176
+ print(f"Eligible patents: {len(eligible)}, selecting {min(n, len(eligible))}")
177
+ return eligible[:n]
178
+
179
+
180
+ # ── main eval loop ────────────────────────────────────────────────────────────
181
+
182
+ def run_eval(
183
+ enriched_path: str,
184
+ images_dir: str,
185
+ n: int,
186
+ out_path: str,
187
+ seed: int = 42,
188
+ ):
189
+ client = get_client()
190
+ images_dir = Path(images_dir)
191
+
192
+ print("Loading enriched data...")
193
+ df = pd.read_parquet(enriched_path)
194
+ df = build_sample_pool(df, images_dir)
195
+
196
+ patents = select_patents(df, n, seed=seed)
197
+ if not patents:
198
+ print("ERROR: No eligible patents found. Check images_dir and enriched data.")
199
+ return
200
+
201
+ # Build distractor pool keyed by Locarno class
202
+ class_to_patent = {}
203
+ for pid, g in df.groupby("patent_id"):
204
+ cls = g["locarno_class"].iloc[0] if "locarno_class" in g.columns else "unknown"
205
+ class_to_patent.setdefault(cls, []).append(pid)
206
+
207
+ results = []
208
+ t1_correct = t1_total = 0
209
+ t2_correct = t2_total = 0
210
+
211
+ for patent_id in tqdm(patents, desc="Evaluating patents"):
212
+ group = df[df["patent_id"] == patent_id].sort_values("figure_number")
213
+ rows = group.to_dict("records")
214
+
215
+ # Pick perspective (query) and front (target) rows
216
+ perspective_row = next((r for r in rows if is_perspective_view(r["viewpoint_parsed"])), None)
217
+ front_rows = [r for r in rows if is_front_view(r["viewpoint_parsed"])]
218
+ if not perspective_row or not front_rows:
219
+ continue
220
+ front_row = front_rows[0]
221
+
222
+ # ── Task 1: viewpoint identification on every figure ────────────────
223
+ t1_results = []
224
+ for row in rows:
225
+ if not row["image_path"]:
226
+ continue
227
+ b64, media = load_image_b64(row["image_path"])
228
+ predicted = ask_viewpoint(client, b64, media)
229
+ correct = viewpoint_match(predicted, row["viewpoint_parsed"])
230
+ t1_results.append({
231
+ "fig": row["figure_number"],
232
+ "ground_truth": row["viewpoint_parsed"],
233
+ "predicted": predicted,
234
+ "correct": correct,
235
+ })
236
+ t1_total += 1
237
+ t1_correct += int(correct)
238
+ time.sleep(0.3) # rate limit courtesy
239
+
240
+ # ── Task 2: pick front view from 4 options ───────────────────────────
241
+ query_b64, query_media = load_image_b64(perspective_row["image_path"])
242
+
243
+ # Build 3 distractors: front views from other patents in same Locarno class
244
+ cls = group["locarno_class"].iloc[0] if "locarno_class" in group.columns else "unknown"
245
+ distractor_pids = [p for p in class_to_patent.get(cls, []) if p != patent_id]
246
+ random.Random(seed + hash(patent_id)).shuffle(distractor_pids)
247
+
248
+ distractors = []
249
+ for dpid in distractor_pids:
250
+ dg = df[df["patent_id"] == dpid]
251
+ dfront = dg[dg["viewpoint_parsed"].apply(is_front_view)]
252
+ if not dfront.empty and dfront.iloc[0]["image_path"]:
253
+ distractors.append(dfront.iloc[0]["image_path"])
254
+ if len(distractors) == 3:
255
+ break
256
+
257
+ if len(distractors) < 3:
258
+ # Fall back to any other patent's figure
259
+ other_pids = [p for p in df["patent_id"].unique() if p != patent_id]
260
+ random.Random(seed).shuffle(other_pids)
261
+ for op in other_pids:
262
+ og = df[df["patent_id"] == op]
263
+ if og.iloc[0]["image_path"]:
264
+ distractors.append(og.iloc[0]["image_path"])
265
+ if len(distractors) == 3:
266
+ break
267
+
268
+ if len(distractors) < 3:
269
+ continue
270
+
271
+ # Insert correct answer at random position
272
+ rng = random.Random(seed + hash(patent_id) + 1)
273
+ correct_pos = rng.randint(0, 3)
274
+ candidate_paths = distractors[:3]
275
+ candidate_paths.insert(correct_pos, front_row["image_path"])
276
+
277
+ candidates = [load_image_b64(p) for p in candidate_paths]
278
+ chosen = ask_cross_view(client, query_b64, query_media, candidates)
279
+
280
+ t2_correct += int(chosen == correct_pos)
281
+ t2_total += 1
282
+
283
+ result = {
284
+ "patent_id": patent_id,
285
+ "patent_title": group["patent_title"].iloc[0] if "patent_title" in group.columns else "",
286
+ "locarno_class": cls,
287
+ "task1": t1_results,
288
+ "task2": {
289
+ "correct_pos": correct_pos,
290
+ "model_choice": chosen,
291
+ "correct": chosen == correct_pos,
292
+ },
293
+ }
294
+ results.append(result)
295
+
296
+ # Print running totals
297
+ print(f"\n[{patent_id}] {result['patent_title'][:50]}")
298
+ print(f" T1: {sum(r['correct'] for r in t1_results)}/{len(t1_results)} viewpoints correct")
299
+ print(f" T2: {'✓' if result['task2']['correct'] else '✗'} (chose {chosen}, correct was {correct_pos})")
300
+ print(f" Running: T1={t1_correct}/{t1_total} ({t1_correct/max(t1_total,1):.0%}) "
301
+ f"T2={t2_correct}/{t2_total} ({t2_correct/max(t2_total,1):.0%})")
302
+
303
+ time.sleep(0.5)
304
+
305
+ # ── Summary ───────────────────────────────────────────────────────────────
306
+ print("\n" + "=" * 60)
307
+ print("RESULTS SUMMARY")
308
+ print("=" * 60)
309
+ print(f"Task 1 — Viewpoint identification: {t1_correct}/{t1_total} = {t1_correct/max(t1_total,1):.1%}")
310
+ print(f"Task 2 — Cross-view retrieval: {t2_correct}/{t2_total} = {t2_correct/max(t2_total,1):.1%}")
311
+ print(f"Chance baseline (Task 2): 1/4 = 25.0%")
312
+ print(f"Human baseline (Task 2): ~95% (estimated)")
313
+
314
+ output = {
315
+ "summary": {
316
+ "task1_acc": t1_correct / max(t1_total, 1),
317
+ "task2_acc": t2_correct / max(t2_total, 1),
318
+ "task1_n": t1_total,
319
+ "task2_n": t2_total,
320
+ },
321
+ "results": results,
322
+ }
323
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
324
+ with open(out_path, "w") as f:
325
+ json.dump(output, f, indent=2)
326
+ print(f"\nFull results → {out_path}")
327
+
328
+
329
+ # ── CLI ───────────────────────────────────────────────────────────────────────
330
+
331
+ def main():
332
+ parser = argparse.ArgumentParser()
333
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
334
+ parser.add_argument("--images", default="/tmp/patent_sample/2022")
335
+ parser.add_argument("--n", type=int, default=30)
336
+ parser.add_argument("--out", default="results/track_a_results.json")
337
+ parser.add_argument("--seed", type=int, default=42)
338
+ args = parser.parse_args()
339
+ run_eval(args.enriched, args.images, args.n, args.out, args.seed)
340
+
341
+
342
+ if __name__ == "__main__":
343
+ main()