File size: 14,767 Bytes
e37bd2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Build a stratified evaluation sample with full observables per figure.

Sampling strategy:
  - Select DOMAIN_COUNT Locarno chapters (by patent count)
  - Within each chapter, sample N_PER_DOMAIN patents stratified by text richness
  - Within each patent, include all figures
  - Compute all observables: text features, structural features, image complexity

Produces: data/sample/eval_sample.parquet  (figures)
          data/sample/eval_sample_patents.parquet  (per-patent aggregates)

Usage:
    python scripts/eval/build_sample.py \
        --enriched data/enriched/enriched_2022.parquet \
        --images /tmp/patent_sample/2022 \
        --out data/sample \
        --domains 8 \
        --per-domain 100
"""

import argparse
import re
from pathlib import Path

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


# ── Locarno chapter labels ────────────────────────────────────────────────────

CHAPTER_LABELS = {
    'D14': 'Screens/electronics',
    'D24': 'Medical',
    'D12': 'Construction',
    'D23': 'Fluid/sanitation',
    'D21': 'Games/sports',
    'D13': 'Transport',
    'D26': 'Lighting',
    'D29': 'Fire/accident prevention',
    'D32': 'Graphic symbols/logos',
    'D15': 'Machines',
    'D10': 'Clocks/watches',
    'D28': 'Pharma/cosmetics',
    'D11': 'Ornamental articles',
    'D27': 'Tobacco/recreation',
    'D8':  'Tools/hardware',
    'D9':  'Packaging',
    'D16': 'Photo/optical',
}


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

VP_BUCKETS = [
    ('perspective',   lambda v: 'perspective' in v),
    ('front_elev',    lambda v: 'front elev' in v or v in ('front elevation','front plan','front view')),
    ('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),
    ('cross_section', lambda v: 'cross' in v or 'section' in v),
    ('enlarged',      lambda v: 'enlarg' in v or 'detail' in v),
    ('exploded',      lambda v: 'explod' in v),
    ('reference',     lambda v: 'reference' in v),
    ('unknown',       lambda v: True),
]

DIFFICULTY = {
    'perspective': 'baseline',
    'front_elev':  'easy',
    'rear_elev':   'easy',
    'side_elev':   'easy',
    'top_plan':    'medium',
    'bottom_plan': 'medium',
    'enlarged':    'hard',
    'cross_section': 'very_hard',
    'exploded':    'hard',
    'reference':   'baseline',
    'unknown':     'unknown',
}


def parse_vp(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 bucket_vp(vp: str) -> str:
    for name, fn in VP_BUCKETS:
        if fn(vp):
            return name
    return "unknown"


# ── image observables ─────────────────────────────────────────────────────────

def find_image(images_dir: Path, image_filename: str) -> Path | None:
    parts = image_filename.split("-D0")
    if len(parts) < 2:
        return None
    p = images_dir / parts[0] / image_filename
    return p if p.exists() else None


def image_observables(img_path: Path) -> dict:
    """Compute pixel-level features from a bilevel patent TIF."""
    try:
        img = Image.open(img_path)
        arr = np.array(img)  # mode 1: True=white, False=black
        h, w = arr.shape
        total = h * w

        ink_frac = (~arr).sum() / total

        # Edge transitions (white→black per row, sampled)
        transitions = int(sum(
            np.sum(row[1:] < row[:-1])
            for row in arr[::4]  # sample every 4th row
        ))

        # Perceptual hash proxy: 8×8 mean block comparison
        from PIL import Image as PILImage
        small = img.resize((32, 32), PILImage.LANCZOS).convert("L")
        small_arr = np.array(small)
        phash_var = float(small_arr.var())

        return {
            "ink_frac": float(ink_frac),
            "edge_transitions": transitions,
            "img_width": w,
            "img_height": h,
            "img_aspect": float(w / h) if h > 0 else 1.0,
            "phash_var": phash_var,      # higher = more detail/complexity
        }
    except Exception:
        return {
            "ink_frac": None,
            "edge_transitions": None,
            "img_width": None,
            "img_height": None,
            "img_aspect": None,
            "phash_var": None,
        }


# ── text observables ──────────────────────────────────────────────────────────

def text_observables(row: pd.Series) -> dict:
    draw = str(row.get("drawing_description") or "")
    detail = str(row.get("detailed_description") or "")
    claims = str(row.get("claims") or "")
    summary = str(row.get("brief_summary") or "")
    caption = str(row.get("caption") or "")

    # Count FIG. references in draw_desc
    n_fig_refs = len(re.findall(r"FIG\.\s*\d+", draw, re.IGNORECASE))

    return {
        "draw_desc_chars": len(draw),
        "draw_desc_words": len(draw.split()),
        "draw_desc_fig_refs": n_fig_refs,
        "detail_desc_chars": len(detail),
        "claims_chars": len(claims),
        "summary_chars": len(summary),
        "caption_chars": len(caption),
        # Text richness quartile (filled in at patent level)
    }


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

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("--out",        default="data/sample")
    parser.add_argument("--domains",    type=int, default=8,
                        help="Number of top Locarno chapters to include")
    parser.add_argument("--per-domain", type=int, default=100,
                        help="Max patents per domain")
    parser.add_argument("--seed",       type=int, default=42)
    args = parser.parse_args()

    rng = np.random.default_rng(args.seed)
    images_dir = Path(args.images)
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    print("Loading enriched data...")
    df = pd.read_parquet(args.enriched)

    # Parse chapter and viewpoint
    df["locarno_chapter"] = (
        df["class"].astype(str)
        .str.extract(r"^(D\s*\d{1,2})", expand=False)
        .str.replace(" ", "", regex=False)
        .fillna("other")
    )
    df["vp_raw"] = df.apply(
        lambda r: parse_vp(r.get("drawing_description", ""), r["figure_number"]),
        axis=1,
    )
    df["vp_bucket"] = df["vp_raw"].apply(bucket_vp)
    df["difficulty"] = df["vp_bucket"].map(DIFFICULTY)

    # Text features at figure level
    df["draw_desc_chars"] = df["drawing_description"].fillna("").str.len()
    df["draw_desc_words"] = df["drawing_description"].fillna("").str.split().str.len()

    # Image path
    df["img_path"] = df["image_filename"].apply(lambda fn: find_image(images_dir, fn))

    # Per-patent aggregates for richness quartile
    patent_agg = df.groupby("patent_id").agg(
        draw_len=("draw_desc_chars", "first"),
        n_figs=("figure_id", "count"),
        n_vp_types=("vp_bucket", "nunique"),
        has_perspective=("vp_bucket", lambda x: "perspective" in x.values),
        has_front=("vp_bucket", lambda x: "front_elev" in x.values),
        has_cross=("vp_bucket", lambda x: "cross_section" in x.values),
        parse_rate=("vp_bucket", lambda x: (x != "unknown").mean()),
        chapter=("locarno_chapter", "first"),
    ).reset_index()

    patent_agg["text_richness_q"] = pd.qcut(
        patent_agg["draw_len"], 4,
        labels=["sparse", "moderate", "rich", "very_rich"]
    ).astype(str)

    # Select top domains
    top_chapters = (
        patent_agg[patent_agg["chapter"] != "other"]
        .groupby("chapter")["patent_id"].count()
        .sort_values(ascending=False)
        .head(args.domains)
        .index.tolist()
    )
    print(f"\nSelected domains: {top_chapters}")

    # Stratified sample: within each domain, stratify by text richness
    sampled_pids = []
    for chapter in top_chapters:
        chap_patents = patent_agg[patent_agg["chapter"] == chapter]
        n = min(args.per_domain, len(chap_patents))
        # Stratified by text richness (equal from each quartile if possible)
        per_q = n // 4
        chunk = []
        for q in ["sparse", "moderate", "rich", "very_rich"]:
            pool = chap_patents[chap_patents["text_richness_q"] == q]["patent_id"].tolist()
            rng.shuffle(pool)
            chunk.extend(pool[: per_q])
        # Top up to n from the full pool
        remaining = set(chap_patents["patent_id"]) - set(chunk)
        remaining = list(remaining)
        rng.shuffle(remaining)
        chunk.extend(remaining[: n - len(chunk)])
        sampled_pids.extend(chunk[:n])
        label = CHAPTER_LABELS.get(chapter, chapter)
        print(f"  {chapter} ({label}): {len(chunk[:n])} patents sampled")

    print(f"\nTotal patents sampled: {len(sampled_pids)}")

    # Filter to sampled patents
    sample_df = df[df["patent_id"].isin(set(sampled_pids))].copy()
    # Merge patent-level features
    sample_df = sample_df.merge(
        patent_agg[["patent_id", "text_richness_q", "n_vp_types",
                     "has_perspective", "has_front", "has_cross", "parse_rate"]],
        on="patent_id", how="left"
    )
    sample_df["domain_label"] = sample_df["locarno_chapter"].map(CHAPTER_LABELS).fillna(sample_df["locarno_chapter"])

    print(f"Total figures in sample: {len(sample_df):,}")
    print(f"Images available: {sample_df['img_path'].notna().sum():,}")

    # Compute image observables on all available images
    print("\nComputing image observables...")
    img_obs_list = []
    for _, row in tqdm(sample_df.iterrows(), total=len(sample_df)):
        p = row["img_path"]
        obs = image_observables(p) if p is not None else {}
        obs["figure_id"] = row["figure_id"]
        img_obs_list.append(obs)

    img_obs_df = pd.DataFrame(img_obs_list)
    sample_df = sample_df.merge(img_obs_df, on="figure_id", how="left")

    # Summary
    print("\n=== SAMPLE SUMMARY ===")
    print(f"{'Domain':<6} {'Label':<22} {'Patents':>8} {'Figs':>8}")
    for chap in top_chapters:
        g = sample_df[sample_df["locarno_chapter"] == chap]
        label = CHAPTER_LABELS.get(chap, chap)
        print(f"  {chap:<6} {label:<22} {g['patent_id'].nunique():>8} {len(g):>8}")

    print()
    print("=== VIEWPOINT DISTRIBUTION IN SAMPLE ===")
    vp_dist = sample_df["vp_bucket"].value_counts()
    for vp, n in vp_dist.items():
        print(f"  {vp:<16} {n:>6,}  ({n/len(sample_df):.1%})")

    print()
    print("=== TEXT RICHNESS IN SAMPLE ===")
    for q, g in sample_df.groupby("text_richness_q", observed=True):
        print(f"  {q:<12} {g['patent_id'].nunique():>5} patents  "
              f"draw_len median: {g['draw_desc_chars'].median():.0f} chars")

    # Save
    cols_to_save = [
        "figure_id", "patent_id", "figure_number", "n_figures_in_patent",
        "sibling_figure_ids", "patent_title", "caption",
        "drawing_description", "detailed_description", "brief_summary", "claims",
        "vp_raw", "vp_bucket", "difficulty",
        "locarno_chapter", "domain_label", "text_richness_q",
        "draw_desc_chars", "draw_desc_words",
        "detail_desc_chars" if "detail_desc_chars" in sample_df.columns else None,
        "claims_chars" if "claims_chars" in sample_df.columns else None,
        "n_vp_types", "has_perspective", "has_front", "has_cross", "parse_rate",
        "ink_frac", "edge_transitions", "img_width", "img_height",
        "img_aspect", "phash_var",
        "image_filename", "year",
    ]
    cols_to_save = [c for c in cols_to_save if c and c in sample_df.columns]
    sample_df[cols_to_save].to_parquet(out_dir / "eval_sample.parquet", index=False)

    # Per-patent summary
    patent_summary = sample_df.groupby("patent_id").agg(
        n_figs=("figure_id", "count"),
        locarno_chapter=("locarno_chapter", "first"),
        domain_label=("domain_label", "first"),
        text_richness_q=("text_richness_q", "first"),
        draw_desc_chars=("draw_desc_chars", "first"),
        n_vp_types=("n_vp_types", "first"),
        has_perspective=("has_perspective", "first"),
        has_front=("has_front", "first"),
        has_cross=("has_cross", "first"),
        parse_rate=("parse_rate", "first"),
        median_ink_frac=("ink_frac", "median"),
        median_edge_transitions=("edge_transitions", "median"),
        median_phash_var=("phash_var", "median"),
        patent_title=("patent_title", "first"),
    ).reset_index()
    patent_summary.to_parquet(out_dir / "eval_sample_patents.parquet", index=False)

    print(f"\nSaved:")
    print(f"  {out_dir}/eval_sample.parquet         ({len(sample_df):,} figures)")
    print(f"  {out_dir}/eval_sample_patents.parquet ({len(patent_summary):,} patents)")
    print()
    print("=== OBSERVABLES CAPTURED ===")
    obs_fields = {
        "TEXT (draw_desc)": ["draw_desc_chars", "draw_desc_words", "text_richness_q"],
        "TEXT (missing — need re-download)": ["detail_desc_chars", "claims_chars", "summary_chars"],
        "STRUCTURAL": ["n_figures_in_patent", "n_vp_types", "has_perspective", "has_front", "has_cross", "parse_rate"],
        "IMAGE": ["ink_frac", "edge_transitions", "img_aspect", "phash_var"],
        "METADATA": ["locarno_chapter", "domain_label", "year"],
    }
    for group, fields in obs_fields.items():
        available = [f for f in fields if f in sample_df.columns and sample_df[f].notna().any()]
        missing = [f for f in fields if f not in available]
        print(f"  {group}:")
        if available:
            print(f"    ✓ {', '.join(available)}")
        if missing:
            print(f"    ✗ {', '.join(missing)} (not in current data)")


if __name__ == "__main__":
    main()