"""Task 3 — Intent Elicitation: recover what the designer intended. Given N-1 views of a patent (as text descriptions, no images), produce a structured schema describing the patent's design intent. Score against the gold drawing description using text embedding cosine similarity. Two sub-tasks: MC — select the correct component description from a pool of candidates Free — fill in the structured schema; score vs. gold via cosine similarity The structured schema forces outputs into comparable format regardless of writing style, reducing noise in the free-form comparison. Schema: { "viewpoint_set": "what views the patent shows and why", "primary_view": "which view is the reference/primary", "component_vocab": ["list", "of", "component", "names"], "spatial_layout": "how components relate to each other", "design_intent": "what the designer is communicating about the object" } Usage: python scripts/eval/intent_elicitation.py \ --enriched data/enriched/enriched_2022.parquet \ --n 18 --out results/intent_elicitation_results.json """ import argparse import json import re import time from pathlib import Path import numpy as np import pandas as pd import sys sys.path.insert(0, str(Path(__file__).parent)) from provider import chat, get_client, get_model # ── Prompts ─────────────────────────────────────────────────────────────────── FREE_FORM_PROMPT = """You are analyzing a US design patent. Patent title: {title} The patent has {n_figs} figures described as follows (some viewpoints may be redacted): {drawing_description} Based on this, fill in the design intent schema below as specifically as possible: {{ "viewpoint_set": "...", "primary_view": "...", "component_vocab": ["...", "..."], "spatial_layout": "...", "design_intent": "..." }} Rules: - viewpoint_set: name which projection types appear and what each reveals - primary_view: which single view best communicates the overall form - component_vocab: list the distinct named parts of this design - spatial_layout: describe how parts are arranged relative to each other - design_intent: what visual/functional story is the designer communicating? Reply with the JSON only.""" MC_PROMPT = """You are analyzing a US design patent to identify its design intent. Patent title: {title} Drawing description (N-1 views shown, one view's label is redacted): {drawing_description} Which of the following best describes the OVERALL design intent of this patent? {choices} Reply with just the letter (A-D).""" # ── Scoring ─────────────────────────────────────────────────────────────────── def schema_to_text(schema: dict) -> str: """Flatten schema to a single text string for embedding.""" parts = [] for k, v in schema.items(): if isinstance(v, list): parts.append(f"{k}: {', '.join(str(x) for x in v)}") else: parts.append(f"{k}: {v}") return " | ".join(parts) def cosine_sim(a: np.ndarray, b: np.ndarray) -> float: a = a / (np.linalg.norm(a) + 1e-8) b = b / (np.linalg.norm(b) + 1e-8) return float(np.dot(a, b)) def embed_text(text: str, client) -> np.ndarray | None: """Get text embedding via the chat model's implicit representation. Falls back to a bag-of-words overlap score if embedding API unavailable. """ # Use the model to score text similarity via a direct comparison prompt # (proper embedding would use a dedicated embedding model) return None # placeholder — see scoring below def token_overlap_score(pred: str, gold: str) -> float: """Token-level F1 between predicted and gold text (no embedding needed).""" pred_tokens = set(re.findall(r"\w+", pred.lower())) gold_tokens = set(re.findall(r"\w+", gold.lower())) if not gold_tokens: return 0.0 precision = len(pred_tokens & gold_tokens) / max(len(pred_tokens), 1) recall = len(pred_tokens & gold_tokens) / len(gold_tokens) if precision + recall == 0: return 0.0 return 2 * precision * recall / (precision + recall) # ── Main eval ───────────────────────────────────────────────────────────────── def run(enriched_path: str, n: int, out_path: str, seed: int = 42): import random client = get_client() df = pd.read_parquet(enriched_path) # Parse viewpoints and find eligible patents def parse_vp(desc, fig_num): m = re.compile( rf"FIG\.\s*{fig_num+1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)", re.I ).search(desc or "") return m.group(1).strip().lower() if m else "" df["vp"] = df.apply(lambda r: parse_vp(r.get("drawing_description", ""), r["figure_number"]), axis=1) eligible = df.groupby("patent_id").filter( lambda g: g["vp"].str.contains("perspective").any() and (g["vp"].str.contains("front elev") | g["vp"].isin(["front elevation","front plan"])).any() and len(g) >= 3 )["patent_id"].unique().tolist() rng = random.Random(seed) rng.shuffle(eligible) eval_pids = eligible[:n] print(f"Evaluating {len(eval_pids)} patents | model: {get_model()}") results = [] free_scores, mc_correct, mc_total = [], 0, 0 for pid in eval_pids: group = df[df["patent_id"] == pid].sort_values("figure_number") title = str(group["patent_title"].iloc[0]) draw_desc = str(group["drawing_description"].iloc[0]) n_figs = int(group["n_figures_in_patent"].iloc[0]) if "n_figures_in_patent" in group.columns else len(group) # ── Task 3a: Free-form intent elicitation ───────────────────────────── # Input: drawing_description (text) + patent title # Output: structured schema # Score: token F1 against gold drawing_description prompt = FREE_FORM_PROMPT.format( title=title, n_figs=n_figs, drawing_description=draw_desc[:1000], # truncate for context ) msgs = [{"role": "user", "content": prompt}] response = chat(client, msgs, max_tokens=400) predicted_schema = None try: m = re.search(r"\{.*\}", response, re.DOTALL) if m: predicted_schema = json.loads(m.group()) except Exception: pass pred_text = schema_to_text(predicted_schema) if predicted_schema else response score = token_overlap_score(pred_text, draw_desc) free_scores.append(score) time.sleep(0.5) # ── Task 3b: MC intent selection ────────────────────────────────────── # Build 4 candidates: gold description + 3 distractors from other patents other_pids = [p for p in eligible if p != pid] rng.shuffle(other_pids) distractor_descs = [] for dpid in other_pids[:3]: dg = df[df["patent_id"] == dpid] if not dg.empty: distractor_descs.append(str(dg["drawing_description"].iloc[0])[:200]) correct_pos = rng.randint(0, 3) choices_list = distractor_descs[:3] choices_list.insert(correct_pos, draw_desc[:200]) letters = "ABCD" choices_str = "\n".join(f"({letters[i]}) {c[:150]}" for i, c in enumerate(choices_list)) mc_prompt = MC_PROMPT.format( title=title, drawing_description=draw_desc[:500], choices=choices_str, ) mc_msgs = [{"role": "user", "content": mc_prompt}] mc_response = chat(client, mc_msgs, max_tokens=5) chosen_letter = re.search(r"\b([ABCD])\b", mc_response.upper()) chosen_idx = letters.index(chosen_letter.group()) if chosen_letter else -1 mc_ok = chosen_idx == correct_pos mc_correct += int(mc_ok) mc_total += 1 time.sleep(0.5) result = { "patent_id": pid, "patent_title": title, "free_form_score": float(score), "predicted_schema": predicted_schema, "mc_correct": mc_ok, "mc_chosen": chosen_idx, "mc_correct_pos": correct_pos, } results.append(result) print( f"[{pid}] {title[:35]} | " f"free F1={score:.2f} | " f"MC={'✓' if mc_ok else '✗'} | " f"running MC: {mc_correct}/{mc_total} ({mc_correct/mc_total:.1%})" ) avg_free = sum(free_scores) / max(len(free_scores), 1) mc_acc = mc_correct / max(mc_total, 1) print(f"\n=== INTENT ELICITATION RESULTS ===") print(f"Free-form token F1: {avg_free:.3f} (higher = describes drawing better)") print(f"MC accuracy: {mc_acc:.1%} (chance = 25.0%)") output = { "model": get_model(), "summary": { "free_form_avg_f1": avg_free, "mc_acc": mc_acc, "mc_chance": 0.25, "n": len(results), }, "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"Results → {out_path}") def main(): parser = argparse.ArgumentParser() parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet") parser.add_argument("--n", type=int, default=18) parser.add_argument("--out", default="results/intent_elicitation_results.json") args = parser.parse_args() run(args.enriched, args.n, args.out) if __name__ == "__main__": main()