patent-wireframes / scripts /eval /track_a_multiview.py
midah's picture
Reorganize: scripts/eval/track_a_multiview.py
e3da7b2 verified
"""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()