File size: 10,004 Bytes
35e4d12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""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()