File size: 11,980 Bytes
520af59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""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

# ── viewpoint parsing (shared with 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]:
    """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"


# ── prompt construction ───────────────────────────────────────────────────────

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  # can't evaluate without ground truth

    # Numeric context (if available)
    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


# ── main ──────────────────────────────────────────────────────────────────────

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 parquet provided, restrict to those patent_ids
    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")

    # Pick same eligible patents as track_a (perspective + front + ≥3 figs)
    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])  # [correct, total]
    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

            # ── TASK 1 (Condition C): text-only viewpoint identification ──────
            # Input:  masked drawing_description (FIM on text) + numeric features
            # Output: predicted viewpoint type
            # No image is shown — this is a pure language model inference task
            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")

    # ── Summary ───────────────────────────────────────────────────────────────
    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()