| """Condition C: Text-only viewpoint identification — no image. |
| |
| The four conditions being tested across the benchmark: |
| A — Vision only: VLM sees image, no text |
| B — Drawing program: LLM sees SVG path tokens, no image (future) |
| C — Text description: LLM sees drawing description + numeric features, no image |
| D — Vision + text: VLM sees image AND drawing description (future) |
| |
| This script runs Condition C. |
| |
| TASK 1 — Viewpoint Identification: |
| Given a representation of a single patent figure, name its viewpoint type |
| (e.g. "front elevational view", "perspective view", "top plan view"). |
| Ground truth: viewpoint label parsed from drawing_description text. |
| Scoring: loose keyword overlap (same as Vision condition A). |
| Current Vision (A) result: 23.3% overall, 5.3% on front elevational. |
| |
| TASK 1 Condition C setup: |
| Input: patent title + full drawing_description with the TARGET FIGURE's viewpoint |
| word MASKED (replaced with ___). The model sees what all OTHER figures show, but |
| must predict what the target figure's viewpoint is. |
| This is FIM (Fill-in-the-Middle) on the drawing description text — exactly |
| analogous to code FIM where prefix/suffix constrain the middle. |
| |
| Numeric features (ink_frac, edge_transitions, img_aspect) are also provided |
| as a supplementary signal when available. |
| |
| TASK 2 — Cross-view Correspondence (text version): |
| Given drawing descriptions of N-1 views of a patent, plus a candidate set of |
| view descriptions (with viewpoint labels masked), identify which candidate is |
| the front elevational view. |
| Currently deferred — Task 2 is broken with the thinking model in the vision |
| condition; running text version here would not be a fair comparison. |
| |
| Usage: |
| python scripts/eval/condition_c_text_only.py \ |
| --enriched data/enriched/enriched_2022.parquet \ |
| --sample data/sample/eval_sample.parquet \ |
| --n 18 \ |
| --out results/condition_c_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, get_client |
|
|
| |
|
|
| 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]: |
| """Replace the target figure's viewpoint with ___ and return (masked_desc, original_vp).""" |
| 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" |
|
|
|
|
| |
|
|
| TASK1_C_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} |
| |
| 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", "rear elevational view" |
| """ |
|
|
| def make_prompt(row: pd.Series) -> str | None: |
| """Build the text-only Task 1 prompt for one figure.""" |
| desc = str(row.get("drawing_description") or "") |
| fig_num = int(row.get("figure_number", 0)) |
| title = str(row.get("patent_title") or "") |
| n_figs = int(row.get("n_figures_in_patent", 0)) |
|
|
| masked_desc, vp = mask_viewpoint(desc, fig_num) |
| if not vp: |
| return None, None |
|
|
| |
| numeric_parts = [] |
| for col, label in [("ink_frac","ink density"), ("edge_transitions","edge transitions"), |
| ("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 for FIG. {}:\n{}".format(fig_num + 1, "\n".join(numeric_parts)) |
| if numeric_parts else "") |
|
|
| prompt = TASK1_C_PROMPT.format( |
| title=title, |
| n_figs=n_figs, |
| masked_desc=masked_desc.strip(), |
| numeric_context=numeric_context, |
| fig_num=fig_num + 1, |
| ) |
| return prompt, vp |
|
|
|
|
| |
|
|
| def run(enriched_path: str, sample_path: str | None, n: int, out_path: str, seed: int = 42): |
| client = get_client() |
|
|
| df = pd.read_parquet(enriched_path) |
|
|
| |
| if sample_path and Path(sample_path).exists(): |
| sample = pd.read_parquet(sample_path) |
| df = df[df["patent_id"].isin(sample["patent_id"].unique())] |
| print(f"Restricted to {df['patent_id'].nunique()} sample patents") |
|
|
| |
| df["vp"] = df.apply(lambda r: parse_viewpoint(r.get("drawing_description",""), r["figure_number"]), axis=1) |
| 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()) |
| eligible = has_persp.index[has_persp & has_front].tolist() |
|
|
| import random |
| rng = random.Random(seed) |
| rng.shuffle(eligible) |
| eval_pids = eligible[:n] |
| print(f"Eligible patents: {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(): |
| prompt, ground_truth = make_prompt(row) |
| if prompt is None: |
| continue |
|
|
| |
| |
| |
| |
| msgs = [{"role": "user", "content": 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": int(row["figure_number"]), |
| "ground_truth": ground_truth, |
| "predicted": predicted, |
| "correct": correct, |
| "vp_bucket": vp_label, |
| }) |
| time.sleep(0.3) |
|
|
| if patent_results: |
| n_correct = 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_correct}/{len(patent_results)} correct") |
|
|
| |
| print() |
| print("=" * 60) |
| print("CONDITION C — TEXT-ONLY TASK 1 RESULTS") |
| print("Input: drawing description (FIM, viewpoint masked) + numeric features") |
| print("No image shown") |
| print("=" * 60) |
| print(f"Overall: {total_correct}/{total_n} = {total_correct/max(total_n,1):.1%}") |
| print() |
| print(f"{'Viewpoint':<16} {'Correct':>8} {'Total':>6} {'Acc':>6}") |
| for label, (c, t) in sorted(by_vp.items(), key=lambda x: -x[1][1]): |
| if t == 0: continue |
| print(f" {label:<14} {c:>8} {t:>6} {c/t:>5.1%}") |
|
|
| print() |
| print("COMPARISON TABLE") |
| print(f" Condition A (vision only): 23.3% overall | 5.3% front elev") |
| print(f" Condition C (text only): {total_correct/max(total_n,1):>5.1%} overall |" |
| f" {by_vp['front_elev'][0]/max(by_vp['front_elev'][1],1):>4.1%} front elev") |
| print(f" Human baseline (est): ~95%") |
|
|
| output = { |
| "condition": "C_text_only", |
| "task": "Task 1 — Viewpoint Identification", |
| "input": "drawing_description (FIM: target viewpoint masked) + numeric features", |
| "no_image": True, |
| "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, |
| "comparison": { |
| "condition_A_vision_only": {"overall": 0.233, "front_elev": 0.053}, |
| "condition_C_text_only": {"overall": total_correct/max(total_n,1), |
| "front_elev": by_vp["front_elev"][0]/max(by_vp["front_elev"][1],1)}, |
| } |
| } |
| 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("--sample", default="data/sample/eval_sample.parquet") |
| parser.add_argument("--n", type=int, default=18) |
| parser.add_argument("--out", default="results/condition_c_results.json") |
| args = parser.parse_args() |
| run(args.enriched, args.sample, args.n, args.out) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|