File size: 10,078 Bytes
09d0e17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()