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

Reorganize: scripts/eval/condition_c_text_only.py

Browse files
Files changed (1) hide show
  1. scripts/eval/condition_c_text_only.py +287 -0
scripts/eval/condition_c_text_only.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Condition C: Text-only viewpoint identification — no image.
2
+
3
+ The four conditions being tested across the benchmark:
4
+ A — Vision only: VLM sees image, no text
5
+ B — Drawing program: LLM sees SVG path tokens, no image (future)
6
+ C — Text description: LLM sees drawing description + numeric features, no image
7
+ D — Vision + text: VLM sees image AND drawing description (future)
8
+
9
+ This script runs Condition C.
10
+
11
+ TASK 1 — Viewpoint Identification:
12
+ Given a representation of a single patent figure, name its viewpoint type
13
+ (e.g. "front elevational view", "perspective view", "top plan view").
14
+ Ground truth: viewpoint label parsed from drawing_description text.
15
+ Scoring: loose keyword overlap (same as Vision condition A).
16
+ Current Vision (A) result: 23.3% overall, 5.3% on front elevational.
17
+
18
+ TASK 1 Condition C setup:
19
+ Input: patent title + full drawing_description with the TARGET FIGURE's viewpoint
20
+ word MASKED (replaced with ___). The model sees what all OTHER figures show, but
21
+ must predict what the target figure's viewpoint is.
22
+ This is FIM (Fill-in-the-Middle) on the drawing description text — exactly
23
+ analogous to code FIM where prefix/suffix constrain the middle.
24
+
25
+ Numeric features (ink_frac, edge_transitions, img_aspect) are also provided
26
+ as a supplementary signal when available.
27
+
28
+ TASK 2 — Cross-view Correspondence (text version):
29
+ Given drawing descriptions of N-1 views of a patent, plus a candidate set of
30
+ view descriptions (with viewpoint labels masked), identify which candidate is
31
+ the front elevational view.
32
+ Currently deferred — Task 2 is broken with the thinking model in the vision
33
+ condition; running text version here would not be a fair comparison.
34
+
35
+ Usage:
36
+ python scripts/eval/condition_c_text_only.py \
37
+ --enriched data/enriched/enriched_2022.parquet \
38
+ --sample data/sample/eval_sample.parquet \
39
+ --n 18 \
40
+ --out results/condition_c_results.json
41
+ """
42
+
43
+ import argparse
44
+ import json
45
+ import re
46
+ import time
47
+ from collections import defaultdict
48
+ from pathlib import Path
49
+
50
+ import pandas as pd
51
+
52
+ import sys
53
+ sys.path.insert(0, str(Path(__file__).parent))
54
+ from provider import chat, get_client
55
+
56
+ # ── viewpoint parsing (shared with track_a) ──────────────────────────────────
57
+
58
+ def parse_viewpoint(desc: str, fig_num: int) -> str:
59
+ pat = re.compile(
60
+ rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
61
+ re.IGNORECASE,
62
+ )
63
+ m = pat.search(desc or "")
64
+ return m.group(1).strip().lower() if m else ""
65
+
66
+
67
+ def mask_viewpoint(desc: str, fig_num: int) -> tuple[str, str]:
68
+ """Replace the target figure's viewpoint with ___ and return (masked_desc, original_vp)."""
69
+ pat = re.compile(
70
+ rf"(FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?)(.{{5,80}}?)(\s*(?:view|thereof|;|\n|$))",
71
+ re.IGNORECASE,
72
+ )
73
+ vp = parse_viewpoint(desc, fig_num)
74
+ masked = pat.sub(r"\1___\3", desc or "", count=1)
75
+ return masked, vp
76
+
77
+
78
+ def viewpoint_match(predicted: str, ground_truth: str) -> bool:
79
+ DIRECTIONS = {"front","rear","back","left","right","top","bottom","side",
80
+ "perspective","plan","elevation","elevational","isometric",
81
+ "oblique","reference","detail","enlarged","cross","section"}
82
+ pred_w = set(re.findall(r"\w+", predicted.lower())) & DIRECTIONS
83
+ gt_w = set(re.findall(r"\w+", ground_truth.lower())) & DIRECTIONS
84
+ if not gt_w:
85
+ return False
86
+ return len(pred_w & gt_w) / len(gt_w) >= 0.5
87
+
88
+
89
+ VP_BUCKETS = [
90
+ ("perspective", lambda v: "perspective" in v),
91
+ ("front_elev", lambda v: "front elev" in v),
92
+ ("rear_elev", lambda v: "rear elev" in v or "rear elevation" in v),
93
+ ("side_elev", lambda v: "side elev" in v or "side elevation" in v),
94
+ ("top_plan", lambda v: "top plan" in v or v == "top view"),
95
+ ("bottom_plan", lambda v: "bottom plan" in v or "bottom" in v),
96
+ ("other", lambda v: True),
97
+ ]
98
+
99
+ def bucket(vp: str) -> str:
100
+ for name, fn in VP_BUCKETS:
101
+ if fn(vp):
102
+ return name
103
+ return "other"
104
+
105
+
106
+ # ── prompt construction ───────────────────────────────────────────────────────
107
+
108
+ TASK1_C_PROMPT = """\
109
+ You are an engineer reading a US design patent.
110
+
111
+ Patent title: {title}
112
+
113
+ The patent has {n_figs} figures. Here is the drawing description with one figure's viewpoint type replaced by ___:
114
+
115
+ {masked_desc}
116
+
117
+ {numeric_context}
118
+
119
+ What type of view is FIG. {fig_num}? Give the viewpoint label only (2-5 words).
120
+ Examples: "front elevational view", "perspective view", "top plan view", "rear elevational view"
121
+ """
122
+
123
+ def make_prompt(row: pd.Series) -> str | None:
124
+ """Build the text-only Task 1 prompt for one figure."""
125
+ desc = str(row.get("drawing_description") or "")
126
+ fig_num = int(row.get("figure_number", 0))
127
+ title = str(row.get("patent_title") or "")
128
+ n_figs = int(row.get("n_figures_in_patent", 0))
129
+
130
+ masked_desc, vp = mask_viewpoint(desc, fig_num)
131
+ if not vp:
132
+ return None, None # can't evaluate without ground truth
133
+
134
+ # Numeric context (if available)
135
+ numeric_parts = []
136
+ for col, label in [("ink_frac","ink density"), ("edge_transitions","edge transitions"),
137
+ ("img_aspect","aspect ratio")]:
138
+ val = row.get(col)
139
+ if val is not None and not pd.isna(val):
140
+ if col == "ink_frac":
141
+ numeric_parts.append(f" {label}: {float(val):.2%}")
142
+ elif col == "edge_transitions":
143
+ numeric_parts.append(f" {label}: {int(val):,}")
144
+ else:
145
+ numeric_parts.append(f" {label}: {float(val):.2f}")
146
+ numeric_context = ("Image statistics for FIG. {}:\n{}".format(fig_num + 1, "\n".join(numeric_parts))
147
+ if numeric_parts else "")
148
+
149
+ prompt = TASK1_C_PROMPT.format(
150
+ title=title,
151
+ n_figs=n_figs,
152
+ masked_desc=masked_desc.strip(),
153
+ numeric_context=numeric_context,
154
+ fig_num=fig_num + 1,
155
+ )
156
+ return prompt, vp
157
+
158
+
159
+ # ── main ──────────────────────────────────────────────────────────────────────
160
+
161
+ def run(enriched_path: str, sample_path: str | None, n: int, out_path: str, seed: int = 42):
162
+ client = get_client()
163
+
164
+ df = pd.read_parquet(enriched_path)
165
+
166
+ # If sample parquet provided, restrict to those patent_ids
167
+ if sample_path and Path(sample_path).exists():
168
+ sample = pd.read_parquet(sample_path)
169
+ df = df[df["patent_id"].isin(sample["patent_id"].unique())]
170
+ print(f"Restricted to {df['patent_id'].nunique()} sample patents")
171
+
172
+ # Pick same eligible patents as track_a (perspective + front + ≥3 figs)
173
+ df["vp"] = df.apply(lambda r: parse_viewpoint(r.get("drawing_description",""), r["figure_number"]), axis=1)
174
+ has_persp = df.groupby("patent_id")["vp"].apply(lambda x: x.str.contains("perspective").any())
175
+ has_front = df.groupby("patent_id")["vp"].apply(lambda x: (x.str.contains("front elev") | x.isin(["front elevation","front plan"])).any())
176
+ eligible = has_persp.index[has_persp & has_front].tolist()
177
+
178
+ import random
179
+ rng = random.Random(seed)
180
+ rng.shuffle(eligible)
181
+ eval_pids = eligible[:n]
182
+ print(f"Eligible patents: {len(eligible)}, evaluating: {len(eval_pids)}")
183
+
184
+ results = []
185
+ by_vp = defaultdict(lambda: [0, 0]) # [correct, total]
186
+ total_correct = total_n = 0
187
+
188
+ for pid in eval_pids:
189
+ group = df[df["patent_id"] == pid].sort_values("figure_number")
190
+ patent_results = []
191
+
192
+ for _, row in group.iterrows():
193
+ prompt, ground_truth = make_prompt(row)
194
+ if prompt is None:
195
+ continue
196
+
197
+ # ── TASK 1 (Condition C): text-only viewpoint identification ──────
198
+ # Input: masked drawing_description (FIM on text) + numeric features
199
+ # Output: predicted viewpoint type
200
+ # No image is shown — this is a pure language model inference task
201
+ msgs = [{"role": "user", "content": prompt}]
202
+ predicted = chat(client, msgs, max_tokens=30).lower().strip()
203
+
204
+ correct = viewpoint_match(predicted, ground_truth)
205
+ vp_label = bucket(ground_truth)
206
+ by_vp[vp_label][1] += 1
207
+ if correct:
208
+ by_vp[vp_label][0] += 1
209
+ total_correct += int(correct)
210
+ total_n += 1
211
+
212
+ patent_results.append({
213
+ "fig": int(row["figure_number"]),
214
+ "ground_truth": ground_truth,
215
+ "predicted": predicted,
216
+ "correct": correct,
217
+ "vp_bucket": vp_label,
218
+ })
219
+ time.sleep(0.3)
220
+
221
+ if patent_results:
222
+ n_correct = sum(r["correct"] for r in patent_results)
223
+ results.append({
224
+ "patent_id": pid,
225
+ "patent_title": str(group["patent_title"].iloc[0]),
226
+ "figures": patent_results,
227
+ })
228
+ print(f"[{pid}] {str(group['patent_title'].iloc[0])[:45]} — "
229
+ f"{n_correct}/{len(patent_results)} correct")
230
+
231
+ # ── Summary ───────────────────────────────────────────────────────────────
232
+ print()
233
+ print("=" * 60)
234
+ print("CONDITION C — TEXT-ONLY TASK 1 RESULTS")
235
+ print("Input: drawing description (FIM, viewpoint masked) + numeric features")
236
+ print("No image shown")
237
+ print("=" * 60)
238
+ print(f"Overall: {total_correct}/{total_n} = {total_correct/max(total_n,1):.1%}")
239
+ print()
240
+ print(f"{'Viewpoint':<16} {'Correct':>8} {'Total':>6} {'Acc':>6}")
241
+ for label, (c, t) in sorted(by_vp.items(), key=lambda x: -x[1][1]):
242
+ if t == 0: continue
243
+ print(f" {label:<14} {c:>8} {t:>6} {c/t:>5.1%}")
244
+
245
+ print()
246
+ print("COMPARISON TABLE")
247
+ print(f" Condition A (vision only): 23.3% overall | 5.3% front elev")
248
+ print(f" Condition C (text only): {total_correct/max(total_n,1):>5.1%} overall |"
249
+ f" {by_vp['front_elev'][0]/max(by_vp['front_elev'][1],1):>4.1%} front elev")
250
+ print(f" Human baseline (est): ~95%")
251
+
252
+ output = {
253
+ "condition": "C_text_only",
254
+ "task": "Task 1 — Viewpoint Identification",
255
+ "input": "drawing_description (FIM: target viewpoint masked) + numeric features",
256
+ "no_image": True,
257
+ "summary": {
258
+ "overall_acc": total_correct / max(total_n, 1),
259
+ "n": total_n,
260
+ "by_viewpoint": {k: {"correct": v[0], "total": v[1], "acc": v[0]/v[1] if v[1] else 0}
261
+ for k, v in by_vp.items()},
262
+ },
263
+ "results": results,
264
+ "comparison": {
265
+ "condition_A_vision_only": {"overall": 0.233, "front_elev": 0.053},
266
+ "condition_C_text_only": {"overall": total_correct/max(total_n,1),
267
+ "front_elev": by_vp["front_elev"][0]/max(by_vp["front_elev"][1],1)},
268
+ }
269
+ }
270
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
271
+ with open(out_path, "w") as f:
272
+ json.dump(output, f, indent=2)
273
+ print(f"\nResults → {out_path}")
274
+
275
+
276
+ def main():
277
+ parser = argparse.ArgumentParser()
278
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
279
+ parser.add_argument("--sample", default="data/sample/eval_sample.parquet")
280
+ parser.add_argument("--n", type=int, default=18)
281
+ parser.add_argument("--out", default="results/condition_c_results.json")
282
+ args = parser.parse_args()
283
+ run(args.enriched, args.sample, args.n, args.out)
284
+
285
+
286
+ if __name__ == "__main__":
287
+ main()