"""Condition D: Vision + grounded annotation — image AND masked text description. Task 1 — Viewpoint Identification: Given a representation of one patent figure, name its viewpoint type. Ground truth: parsed from drawing_description text. Condition D setup: The VLM sees BOTH: 1. The image of the target figure (visual signal) 2. The drawing description with the target viewpoint MASKED (FIM text context) e.g. "FIG. 1 is perspective; FIG. 3 is rear elevational; FIG. 2 is ___ view" 3. Numeric features (ink density, edge transitions, aspect ratio) This is the CadVLM setup: image + structured text together. Hypothesis: Condition D > Condition A (image only) because the text context scaffolds convention knowledge onto the visual signal. Comparison targets: Condition A (vision only): 23.3% overall, 5.3% front elev Condition C (text FIM, no image): see condition_c_results.json Condition D (vision + text FIM): this script Usage: python scripts/eval/condition_d_grounded.py \ --enriched data/enriched/enriched_2022.parquet \ --images /tmp/patent_sample/2022 \ --n 18 \ --out results/condition_d_results.json """ import argparse import json import re import time from collections import defaultdict from pathlib import Path import pandas as pd import sys sys.path.insert(0, str(Path(__file__).parent)) from provider import chat, encode_image, get_client # ── shared helpers (same as condition_c and track_a) ───────────────────────── def parse_viewpoint(desc: str, fig_num: int) -> str: pat = re.compile( rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)", re.IGNORECASE, ) m = pat.search(desc or "") return m.group(1).strip().lower() if m else "" def mask_viewpoint(desc: str, fig_num: int) -> tuple[str, str]: pat = re.compile( rf"(FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?)(.{{5,80}}?)(\s*(?:view|thereof|;|\n|$))", re.IGNORECASE, ) vp = parse_viewpoint(desc, fig_num) masked = pat.sub(r"\1___\3", desc or "", count=1) return masked, vp def viewpoint_match(predicted: str, ground_truth: str) -> bool: DIRECTIONS = {"front","rear","back","left","right","top","bottom","side", "perspective","plan","elevation","elevational","isometric", "oblique","reference","detail","enlarged","cross","section"} pred_w = set(re.findall(r"\w+", predicted.lower())) & DIRECTIONS gt_w = set(re.findall(r"\w+", ground_truth.lower())) & DIRECTIONS if not gt_w: return False return len(pred_w & gt_w) / len(gt_w) >= 0.5 VP_BUCKETS = [ ("perspective", lambda v: "perspective" in v), ("front_elev", lambda v: "front elev" in v), ("rear_elev", lambda v: "rear elev" in v or "rear elevation" in v), ("side_elev", lambda v: "side elev" in v or "side elevation" in v), ("top_plan", lambda v: "top plan" in v or v == "top view"), ("bottom_plan", lambda v: "bottom plan" in v or "bottom" in v), ("other", lambda v: True), ] def bucket(vp: str) -> str: for name, fn in VP_BUCKETS: if fn(vp): return name return "other" def find_image(images_dir: Path, image_filename: str) -> Path | None: parts = image_filename.split("-D0") if len(parts) < 2: return None p = images_dir / parts[0] / image_filename return p if p.exists() else None # ── Condition D prompt: image + masked text + numeric features ──────────────── TASK1_D_PROMPT = """\ You are an engineer reading a US design patent. Patent title: {title} The patent has {n_figs} figures. Here is the drawing description with one \ figure's viewpoint type replaced by ___: {masked_desc} {numeric_context} The image above shows FIG. {fig_num} of this patent. Using both the image and the context of what other figures show, what type \ of view is FIG. {fig_num}? Give the viewpoint label only (2-5 words). Examples: "front elevational view", "perspective view", "top plan view" """ def run(enriched_path: str, images_dir: str, n: int, out_path: str, seed: int = 42): import random client = get_client() images = Path(images_dir) df = pd.read_parquet(enriched_path) df["vp"] = df.apply( lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]), axis=1, ) df["img_path"] = df["image_filename"].apply(lambda fn: find_image(images, fn)) has_persp = df.groupby("patent_id")["vp"].apply(lambda x: x.str.contains("perspective").any()) has_front = df.groupby("patent_id")["vp"].apply( lambda x: (x.str.contains("front elev") | x.isin(["front elevation","front plan"])).any() ) has_img = df.groupby("patent_id")["img_path"].apply(lambda x: x.notna().any()) eligible = has_persp.index[has_persp & has_front & has_img].tolist() rng = random.Random(seed) rng.shuffle(eligible) eval_pids = eligible[:n] print(f"Eligible patents with images: {len(eligible)}, evaluating: {len(eval_pids)}") results, by_vp = [], defaultdict(lambda: [0, 0]) total_correct = total_n = 0 for pid in eval_pids: group = df[df["patent_id"] == pid].sort_values("figure_number") patent_results = [] for _, row in group.iterrows(): img_path = row.get("img_path") if img_path is None: continue desc = str(row.get("drawing_description") or "") fig_num = int(row.get("figure_number", 0)) masked_desc, ground_truth = mask_viewpoint(desc, fig_num) if not ground_truth: continue # Numeric context numeric_parts = [] for col, label in [("ink_frac","ink density"),("edge_transitions","edges"), ("img_aspect","aspect ratio")]: val = row.get(col) if val is not None and not pd.isna(val): if col == "ink_frac": numeric_parts.append(f" {label}: {float(val):.2%}") elif col == "edge_transitions": numeric_parts.append(f" {label}: {int(val):,}") else: numeric_parts.append(f" {label}: {float(val):.2f}") numeric_context = ("Image statistics:\n" + "\n".join(numeric_parts) if numeric_parts else "") text_prompt = TASK1_D_PROMPT.format( title=str(row.get("patent_title", "")), n_figs=int(row.get("n_figures_in_patent", 0)), masked_desc=masked_desc.strip(), numeric_context=numeric_context, fig_num=fig_num + 1, ) # ── TASK 1 (Condition D): image + grounded text ─────────────────── # Input: image of the figure (visual) + masked drawing description # (FIM text context) + numeric features # Output: predicted viewpoint type # Model uses BOTH the visual appearance AND the set context b64, media = encode_image(Path(img_path)) from provider import multi_image_message msgs = multi_image_message( images=[(b64, media)], text_after=text_prompt, ) predicted = chat(client, msgs, max_tokens=30).lower().strip() correct = viewpoint_match(predicted, ground_truth) vp_label = bucket(ground_truth) by_vp[vp_label][1] += 1 if correct: by_vp[vp_label][0] += 1 total_correct += int(correct) total_n += 1 patent_results.append({ "fig": fig_num, "ground_truth": ground_truth, "predicted": predicted, "correct": correct, "vp_bucket": vp_label, }) time.sleep(0.3) if patent_results: n_c = sum(r["correct"] for r in patent_results) results.append({"patent_id": pid, "patent_title": str(group["patent_title"].iloc[0]), "figures": patent_results}) print(f"[{pid}] {str(group['patent_title'].iloc[0])[:45]} — " f"{n_c}/{len(patent_results)} correct") print() print("=" * 60) print("CONDITION D — VISION + GROUNDED ANNOTATION RESULTS") print("Input: image + masked drawing description (FIM) + numeric features") print("=" * 60) print(f"Overall: {total_correct}/{total_n} = {total_correct/max(total_n,1):.1%}") print() for label, (c, t) in sorted(by_vp.items(), key=lambda x: -x[1][1]): if t == 0: continue print(f" {label:<14} {c:>3}/{t:<3} {c/t:>5.1%}") output = { "condition": "D_vision_plus_text", "task": "Task 1 — Viewpoint Identification", "input": "image + drawing_description FIM + numeric features", "summary": { "overall_acc": total_correct / max(total_n, 1), "n": total_n, "by_viewpoint": {k: {"correct": v[0], "total": v[1], "acc": v[0]/v[1] if v[1] else 0} for k, v in by_vp.items()}, }, "results": results, } Path(out_path).parent.mkdir(parents=True, exist_ok=True) with open(out_path, "w") as f: json.dump(output, f, indent=2) print(f"\nResults → {out_path}") def main(): parser = argparse.ArgumentParser() parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet") parser.add_argument("--images", default="/tmp/patent_sample/2022") parser.add_argument("--n", type=int, default=18) parser.add_argument("--out", default="results/condition_d_results.json") args = parser.parse_args() run(args.enriched, args.images, args.n, args.out) if __name__ == "__main__": main()