midah commited on
Commit
cda514c
·
verified ·
1 Parent(s): b4fa005

Add eval script: condition_d_grounded.py

Browse files
Files changed (1) hide show
  1. scripts/condition_d_grounded.py +257 -0
scripts/condition_d_grounded.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Condition D: Vision + grounded annotation — image AND masked text description.
2
+
3
+ Task 1 — Viewpoint Identification:
4
+ Given a representation of one patent figure, name its viewpoint type.
5
+ Ground truth: parsed from drawing_description text.
6
+
7
+ Condition D setup:
8
+ The VLM sees BOTH:
9
+ 1. The image of the target figure (visual signal)
10
+ 2. The drawing description with the target viewpoint MASKED (FIM text context)
11
+ e.g. "FIG. 1 is perspective; FIG. 3 is rear elevational; FIG. 2 is ___ view"
12
+ 3. Numeric features (ink density, edge transitions, aspect ratio)
13
+
14
+ This is the CadVLM setup: image + structured text together.
15
+ Hypothesis: Condition D > Condition A (image only) because the text context
16
+ scaffolds convention knowledge onto the visual signal.
17
+
18
+ Comparison targets:
19
+ Condition A (vision only): 23.3% overall, 5.3% front elev
20
+ Condition C (text FIM, no image): see condition_c_results.json
21
+ Condition D (vision + text FIM): this script
22
+
23
+ Usage:
24
+ python scripts/eval/condition_d_grounded.py \
25
+ --enriched data/enriched/enriched_2022.parquet \
26
+ --images /tmp/patent_sample/2022 \
27
+ --n 18 \
28
+ --out results/condition_d_results.json
29
+ """
30
+
31
+ import argparse
32
+ import json
33
+ import re
34
+ import time
35
+ from collections import defaultdict
36
+ from pathlib import Path
37
+
38
+ import pandas as pd
39
+
40
+ import sys
41
+ sys.path.insert(0, str(Path(__file__).parent))
42
+ from provider import chat, encode_image, get_client
43
+
44
+ # ── shared helpers (same as condition_c and track_a) ─────────────────────────
45
+
46
+ def parse_viewpoint(desc: str, fig_num: int) -> str:
47
+ pat = re.compile(
48
+ rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
49
+ re.IGNORECASE,
50
+ )
51
+ m = pat.search(desc or "")
52
+ return m.group(1).strip().lower() if m else ""
53
+
54
+
55
+ def mask_viewpoint(desc: str, fig_num: int) -> tuple[str, str]:
56
+ pat = re.compile(
57
+ rf"(FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?)(.{{5,80}}?)(\s*(?:view|thereof|;|\n|$))",
58
+ re.IGNORECASE,
59
+ )
60
+ vp = parse_viewpoint(desc, fig_num)
61
+ masked = pat.sub(r"\1___\3", desc or "", count=1)
62
+ return masked, vp
63
+
64
+
65
+ def viewpoint_match(predicted: str, ground_truth: str) -> bool:
66
+ DIRECTIONS = {"front","rear","back","left","right","top","bottom","side",
67
+ "perspective","plan","elevation","elevational","isometric",
68
+ "oblique","reference","detail","enlarged","cross","section"}
69
+ pred_w = set(re.findall(r"\w+", predicted.lower())) & DIRECTIONS
70
+ gt_w = set(re.findall(r"\w+", ground_truth.lower())) & DIRECTIONS
71
+ if not gt_w: return False
72
+ return len(pred_w & gt_w) / len(gt_w) >= 0.5
73
+
74
+
75
+ VP_BUCKETS = [
76
+ ("perspective", lambda v: "perspective" in v),
77
+ ("front_elev", lambda v: "front elev" in v),
78
+ ("rear_elev", lambda v: "rear elev" in v or "rear elevation" in v),
79
+ ("side_elev", lambda v: "side elev" in v or "side elevation" in v),
80
+ ("top_plan", lambda v: "top plan" in v or v == "top view"),
81
+ ("bottom_plan", lambda v: "bottom plan" in v or "bottom" in v),
82
+ ("other", lambda v: True),
83
+ ]
84
+
85
+ def bucket(vp: str) -> str:
86
+ for name, fn in VP_BUCKETS:
87
+ if fn(vp): return name
88
+ return "other"
89
+
90
+
91
+ def find_image(images_dir: Path, image_filename: str) -> Path | None:
92
+ parts = image_filename.split("-D0")
93
+ if len(parts) < 2: return None
94
+ p = images_dir / parts[0] / image_filename
95
+ return p if p.exists() else None
96
+
97
+
98
+ # ── Condition D prompt: image + masked text + numeric features ────────────────
99
+
100
+ TASK1_D_PROMPT = """\
101
+ You are an engineer reading a US design patent.
102
+
103
+ Patent title: {title}
104
+
105
+ The patent has {n_figs} figures. Here is the drawing description with one \
106
+ figure's viewpoint type replaced by ___:
107
+
108
+ {masked_desc}
109
+
110
+ {numeric_context}
111
+
112
+ The image above shows FIG. {fig_num} of this patent.
113
+
114
+ Using both the image and the context of what other figures show, what type \
115
+ of view is FIG. {fig_num}?
116
+ Give the viewpoint label only (2-5 words).
117
+ Examples: "front elevational view", "perspective view", "top plan view"
118
+ """
119
+
120
+
121
+ def run(enriched_path: str, images_dir: str, n: int, out_path: str, seed: int = 42):
122
+ import random
123
+ client = get_client()
124
+ images = Path(images_dir)
125
+
126
+ df = pd.read_parquet(enriched_path)
127
+ df["vp"] = df.apply(
128
+ lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]),
129
+ axis=1,
130
+ )
131
+ df["img_path"] = df["image_filename"].apply(lambda fn: find_image(images, fn))
132
+
133
+ has_persp = df.groupby("patent_id")["vp"].apply(lambda x: x.str.contains("perspective").any())
134
+ has_front = df.groupby("patent_id")["vp"].apply(
135
+ lambda x: (x.str.contains("front elev") | x.isin(["front elevation","front plan"])).any()
136
+ )
137
+ has_img = df.groupby("patent_id")["img_path"].apply(lambda x: x.notna().any())
138
+ eligible = has_persp.index[has_persp & has_front & has_img].tolist()
139
+
140
+ rng = random.Random(seed)
141
+ rng.shuffle(eligible)
142
+ eval_pids = eligible[:n]
143
+ print(f"Eligible patents with images: {len(eligible)}, evaluating: {len(eval_pids)}")
144
+
145
+ results, by_vp = [], defaultdict(lambda: [0, 0])
146
+ total_correct = total_n = 0
147
+
148
+ for pid in eval_pids:
149
+ group = df[df["patent_id"] == pid].sort_values("figure_number")
150
+ patent_results = []
151
+
152
+ for _, row in group.iterrows():
153
+ img_path = row.get("img_path")
154
+ if img_path is None:
155
+ continue
156
+
157
+ desc = str(row.get("drawing_description") or "")
158
+ fig_num = int(row.get("figure_number", 0))
159
+ masked_desc, ground_truth = mask_viewpoint(desc, fig_num)
160
+ if not ground_truth:
161
+ continue
162
+
163
+ # Numeric context
164
+ numeric_parts = []
165
+ for col, label in [("ink_frac","ink density"),("edge_transitions","edges"),
166
+ ("img_aspect","aspect ratio")]:
167
+ val = row.get(col)
168
+ if val is not None and not pd.isna(val):
169
+ if col == "ink_frac": numeric_parts.append(f" {label}: {float(val):.2%}")
170
+ elif col == "edge_transitions": numeric_parts.append(f" {label}: {int(val):,}")
171
+ else: numeric_parts.append(f" {label}: {float(val):.2f}")
172
+ numeric_context = ("Image statistics:\n" + "\n".join(numeric_parts)
173
+ if numeric_parts else "")
174
+
175
+ text_prompt = TASK1_D_PROMPT.format(
176
+ title=str(row.get("patent_title", "")),
177
+ n_figs=int(row.get("n_figures_in_patent", 0)),
178
+ masked_desc=masked_desc.strip(),
179
+ numeric_context=numeric_context,
180
+ fig_num=fig_num + 1,
181
+ )
182
+
183
+ # ── TASK 1 (Condition D): image + grounded text ───────────────────
184
+ # Input: image of the figure (visual) + masked drawing description
185
+ # (FIM text context) + numeric features
186
+ # Output: predicted viewpoint type
187
+ # Model uses BOTH the visual appearance AND the set context
188
+ b64, media = encode_image(Path(img_path))
189
+ from provider import multi_image_message
190
+ msgs = multi_image_message(
191
+ images=[(b64, media)],
192
+ text_after=text_prompt,
193
+ )
194
+ predicted = chat(client, msgs, max_tokens=30).lower().strip()
195
+
196
+ correct = viewpoint_match(predicted, ground_truth)
197
+ vp_label = bucket(ground_truth)
198
+ by_vp[vp_label][1] += 1
199
+ if correct: by_vp[vp_label][0] += 1
200
+ total_correct += int(correct)
201
+ total_n += 1
202
+
203
+ patent_results.append({
204
+ "fig": fig_num, "ground_truth": ground_truth,
205
+ "predicted": predicted, "correct": correct, "vp_bucket": vp_label,
206
+ })
207
+ time.sleep(0.3)
208
+
209
+ if patent_results:
210
+ n_c = sum(r["correct"] for r in patent_results)
211
+ results.append({"patent_id": pid,
212
+ "patent_title": str(group["patent_title"].iloc[0]),
213
+ "figures": patent_results})
214
+ print(f"[{pid}] {str(group['patent_title'].iloc[0])[:45]} — "
215
+ f"{n_c}/{len(patent_results)} correct")
216
+
217
+ print()
218
+ print("=" * 60)
219
+ print("CONDITION D — VISION + GROUNDED ANNOTATION RESULTS")
220
+ print("Input: image + masked drawing description (FIM) + numeric features")
221
+ print("=" * 60)
222
+ print(f"Overall: {total_correct}/{total_n} = {total_correct/max(total_n,1):.1%}")
223
+ print()
224
+ for label, (c, t) in sorted(by_vp.items(), key=lambda x: -x[1][1]):
225
+ if t == 0: continue
226
+ print(f" {label:<14} {c:>3}/{t:<3} {c/t:>5.1%}")
227
+
228
+ output = {
229
+ "condition": "D_vision_plus_text",
230
+ "task": "Task 1 — Viewpoint Identification",
231
+ "input": "image + drawing_description FIM + numeric features",
232
+ "summary": {
233
+ "overall_acc": total_correct / max(total_n, 1),
234
+ "n": total_n,
235
+ "by_viewpoint": {k: {"correct": v[0], "total": v[1], "acc": v[0]/v[1] if v[1] else 0}
236
+ for k, v in by_vp.items()},
237
+ },
238
+ "results": results,
239
+ }
240
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
241
+ with open(out_path, "w") as f:
242
+ json.dump(output, f, indent=2)
243
+ print(f"\nResults → {out_path}")
244
+
245
+
246
+ def main():
247
+ parser = argparse.ArgumentParser()
248
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
249
+ parser.add_argument("--images", default="/tmp/patent_sample/2022")
250
+ parser.add_argument("--n", type=int, default=18)
251
+ parser.add_argument("--out", default="results/condition_d_results.json")
252
+ args = parser.parse_args()
253
+ run(args.enriched, args.images, args.n, args.out)
254
+
255
+
256
+ if __name__ == "__main__":
257
+ main()