File size: 14,049 Bytes
e3da7b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""Track A: Multi-view correspondence eval on design patent rasters.

Two tasks:
  Task 1 — Viewpoint identification: given one figure, name the viewpoint.
  Task 2 — Cross-view retrieval: given figure_0, select the correct
            "front elevational" view from 4 candidates (1 correct + 3 distractors
            from other patents in the same Locarno class).

Usage:
    export ANTHROPIC_API_KEY=...
    python scripts/eval/track_a_multiview.py \
        --enriched data/enriched/enriched_2022.parquet \
        --images /tmp/patent_sample/2022 \
        --n 30 \
        --out results/track_a_results.json

Results printed to stdout and saved to --out.
"""

import argparse
import json
import os
import random
import re
import time
from pathlib import Path

import pandas as pd
from PIL import Image
from tqdm import tqdm

from provider import chat, encode_image, get_client, image_message, multi_image_message


# ── viewpoint parsing ────────────────────────────────────────────────────────

VIEWPOINT_RE = re.compile(
    r"FIG\.\s*{n}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
    re.IGNORECASE,
)

def parse_viewpoint(drawing_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(drawing_desc or "")
    return m.group(1).strip().lower() if m else ""


FRONT_KEYWORDS = {"front elevational", "front view", "front elevation", "front plan"}

def is_front_view(vp: str) -> bool:
    vp = vp.lower()
    return any(k in vp for k in FRONT_KEYWORDS)


def is_perspective_view(vp: str) -> bool:
    return "perspective" in vp.lower()


# ── image loading ─────────────────────────────────────────────────────────────

def find_image_path(images_dir: Path, image_filename: str) -> Path | None:
    """Resolve image_filename → path under images_dir.

    IMPACT stores images as:
        {images_dir}/USD0949851-20220426/USD0949851-20220426-D00001.TIF
    The directory name is the filename prefix up to '-D00'.
    """
    parts = image_filename.split("-D0")
    if len(parts) < 2:
        return None
    dir_name = parts[0]  # e.g. "USD0949851-20220426"
    candidate = images_dir / dir_name / image_filename
    return candidate if candidate.exists() else None


def load_image_b64(path: Path) -> tuple[str, str]:
    return encode_image(path)


# ── Claude API calls ─────────────────────────────────────────────────────────

def ask_viewpoint(client, img_b64: str, media_type: str) -> str:
    """Task 1: identify the viewpoint of a single patent figure."""
    msgs = image_message(img_b64, media_type,
        "This is a technical drawing from a US design patent. "
        "In 2–5 words, what viewpoint or perspective does this figure show? "
        "(e.g. 'front elevational view', 'perspective view', 'top plan view') "
        "Reply with the viewpoint label only, nothing else."
    )
    return chat(client, msgs, max_tokens=80).lower()


def ask_cross_view(
    client,
    query_b64: str,
    query_media: str,
    candidates: list[tuple[str, str]],
    target_label: str = "front elevational view",
) -> int:
    """Task 2: sequential yes/no — ask about each candidate independently.

    Avoids the multi-image A/B/C/D format that causes thinking-model parse
    failures. For each candidate we ask a binary question; the one (and only
    one) that gets YES is the answer. Returns 0-indexed position, or -1 if
    zero or multiple candidates say YES.
    """
    yes_indices = []
    for i, (cand_b64, cand_media) in enumerate(candidates):
        msgs = multi_image_message(
            images=[(query_b64, query_media), (cand_b64, cand_media)],
            text_after=(
                f"Image 1 is a perspective view of a design patent object. "
                f"Image 2 is another figure from the same patent. "
                f"Is Image 2 the {target_label} of this object? "
                f"Reply with YES or NO only."
            ),
        )
        answer = chat(client, msgs, max_tokens=10).upper().strip()
        is_yes = answer.startswith("YES")
        if is_yes:
            yes_indices.append(i)
        time.sleep(0.3)

    if len(yes_indices) == 1:
        return yes_indices[0]
    # Ambiguous (0 or >1 YES): fall back to the first YES if multiple,
    # or -1 if none.
    return yes_indices[0] if yes_indices else -1


# ── scoring helpers ───────────────────────────────────────────────────────────

def viewpoint_match(predicted: str, ground_truth: str) -> bool:
    """Loose match: check if key directional words overlap."""
    DIRECTIONS = {"front", "rear", "back", "left", "right", "top", "bottom",
                  "side", "perspective", "plan", "elevation", "elevational",
                  "isometric", "oblique", "reference", "detail"}
    pred_words = set(re.findall(r"\w+", predicted.lower())) & DIRECTIONS
    gt_words = set(re.findall(r"\w+", ground_truth.lower())) & DIRECTIONS
    if not gt_words:
        return False
    return len(pred_words & gt_words) / len(gt_words) >= 0.5


# ── dataset preparation ───────────────────────────────────────────────────────

def build_sample_pool(df: pd.DataFrame, images_dir: Path) -> pd.DataFrame:
    """Enrich dataframe with parsed viewpoints and resolved image paths."""
    df = df.copy()
    df["viewpoint_parsed"] = df.apply(
        lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]),
        axis=1,
    )
    df["image_path"] = df["image_filename"].apply(
        lambda fn: find_image_path(images_dir, fn)
    )
    return df


def select_patents(df: pd.DataFrame, n: int, seed: int = 42) -> list[str]:
    """Select n patents that have: ≥3 figures, a perspective view, and a front view."""
    rng = random.Random(seed)
    eligible = []
    for patent_id, group in df.groupby("patent_id"):
        vps = group["viewpoint_parsed"].tolist()
        paths = group["image_path"].tolist()
        has_perspective = any(is_perspective_view(v) for v in vps)
        has_front = any(is_front_view(v) for v in vps)
        all_images = all(p is not None for p in paths)
        if has_perspective and has_front and all_images and len(group) >= 3:
            eligible.append(patent_id)
    rng.shuffle(eligible)
    print(f"Eligible patents: {len(eligible)}, selecting {min(n, len(eligible))}")
    return eligible[:n]


# ── main eval loop ────────────────────────────────────────────────────────────

def run_eval(
    enriched_path: str,
    images_dir: str,
    n: int,
    out_path: str,
    seed: int = 42,
):
    client = get_client()
    images_dir = Path(images_dir)

    print("Loading enriched data...")
    df = pd.read_parquet(enriched_path)
    df = build_sample_pool(df, images_dir)

    patents = select_patents(df, n, seed=seed)
    if not patents:
        print("ERROR: No eligible patents found. Check images_dir and enriched data.")
        return

    # Build distractor pool keyed by Locarno class
    class_to_patent = {}
    for pid, g in df.groupby("patent_id"):
        cls = g["locarno_class"].iloc[0] if "locarno_class" in g.columns else "unknown"
        class_to_patent.setdefault(cls, []).append(pid)

    results = []
    t1_correct = t1_total = 0
    t2_correct = t2_total = 0

    for patent_id in tqdm(patents, desc="Evaluating patents"):
        group = df[df["patent_id"] == patent_id].sort_values("figure_number")
        rows = group.to_dict("records")

        # Pick perspective (query) and front (target) rows
        perspective_row = next((r for r in rows if is_perspective_view(r["viewpoint_parsed"])), None)
        front_rows = [r for r in rows if is_front_view(r["viewpoint_parsed"])]
        if not perspective_row or not front_rows:
            continue
        front_row = front_rows[0]

        # ── Task 1: viewpoint identification on every figure ────────────────
        t1_results = []
        for row in rows:
            if not row["image_path"]:
                continue
            b64, media = load_image_b64(row["image_path"])
            predicted = ask_viewpoint(client, b64, media)
            correct = viewpoint_match(predicted, row["viewpoint_parsed"])
            t1_results.append({
                "fig": row["figure_number"],
                "ground_truth": row["viewpoint_parsed"],
                "predicted": predicted,
                "correct": correct,
            })
            t1_total += 1
            t1_correct += int(correct)
            time.sleep(0.3)  # rate limit courtesy

        # ── Task 2: pick front view from 4 options ───────────────────────────
        query_b64, query_media = load_image_b64(perspective_row["image_path"])

        # Build 3 distractors: front views from other patents in same Locarno class
        cls = group["locarno_class"].iloc[0] if "locarno_class" in group.columns else "unknown"
        distractor_pids = [p for p in class_to_patent.get(cls, []) if p != patent_id]
        random.Random(seed + hash(patent_id)).shuffle(distractor_pids)

        distractors = []
        for dpid in distractor_pids:
            dg = df[df["patent_id"] == dpid]
            dfront = dg[dg["viewpoint_parsed"].apply(is_front_view)]
            if not dfront.empty and dfront.iloc[0]["image_path"]:
                distractors.append(dfront.iloc[0]["image_path"])
            if len(distractors) == 3:
                break

        if len(distractors) < 3:
            # Fall back to any other patent's figure
            other_pids = [p for p in df["patent_id"].unique() if p != patent_id]
            random.Random(seed).shuffle(other_pids)
            for op in other_pids:
                og = df[df["patent_id"] == op]
                if og.iloc[0]["image_path"]:
                    distractors.append(og.iloc[0]["image_path"])
                if len(distractors) == 3:
                    break

        if len(distractors) < 3:
            continue

        # Insert correct answer at random position
        rng = random.Random(seed + hash(patent_id) + 1)
        correct_pos = rng.randint(0, 3)
        candidate_paths = distractors[:3]
        candidate_paths.insert(correct_pos, front_row["image_path"])

        candidates = [load_image_b64(p) for p in candidate_paths]
        chosen = ask_cross_view(client, query_b64, query_media, candidates)

        t2_correct += int(chosen == correct_pos)
        t2_total += 1

        result = {
            "patent_id": patent_id,
            "patent_title": group["patent_title"].iloc[0] if "patent_title" in group.columns else "",
            "locarno_class": cls,
            "task1": t1_results,
            "task2": {
                "correct_pos": correct_pos,
                "model_choice": chosen,
                "correct": chosen == correct_pos,
            },
        }
        results.append(result)

        # Print running totals
        print(f"\n[{patent_id}] {result['patent_title'][:50]}")
        print(f"  T1: {sum(r['correct'] for r in t1_results)}/{len(t1_results)} viewpoints correct")
        print(f"  T2: {'✓' if result['task2']['correct'] else '✗'} (chose {chosen}, correct was {correct_pos})")
        print(f"  Running: T1={t1_correct}/{t1_total} ({t1_correct/max(t1_total,1):.0%})  "
              f"T2={t2_correct}/{t2_total} ({t2_correct/max(t2_total,1):.0%})")

        time.sleep(0.5)

    # ── Summary ───────────────────────────────────────────────────────────────
    print("\n" + "=" * 60)
    print("RESULTS SUMMARY")
    print("=" * 60)
    print(f"Task 1 — Viewpoint identification: {t1_correct}/{t1_total} = {t1_correct/max(t1_total,1):.1%}")
    print(f"Task 2 — Cross-view retrieval:     {t2_correct}/{t2_total} = {t2_correct/max(t2_total,1):.1%}")
    print(f"Chance baseline (Task 2):          1/4 = 25.0%")
    print(f"Human baseline (Task 2):           ~95% (estimated)")

    output = {
        "summary": {
            "task1_acc": t1_correct / max(t1_total, 1),
            "task2_acc": t2_correct / max(t2_total, 1),
            "task1_n": t1_total,
            "task2_n": t2_total,
        },
        "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"\nFull results → {out_path}")


# ── CLI ───────────────────────────────────────────────────────────────────────

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=30)
    parser.add_argument("--out", default="results/track_a_results.json")
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()
    run_eval(args.enriched, args.images, args.n, args.out, args.seed)


if __name__ == "__main__":
    main()