| """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 |
|
|
|
|
| |
|
|
| 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', |
| } |
|
|
|
|
| |
|
|
| 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" |
|
|
|
|
| |
|
|
| 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) |
| h, w = arr.shape |
| total = h * w |
|
|
| ink_frac = (~arr).sum() / total |
|
|
| |
| transitions = int(sum( |
| np.sum(row[1:] < row[:-1]) |
| for row in arr[::4] |
| )) |
|
|
| |
| 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, |
| } |
| except Exception: |
| return { |
| "ink_frac": None, |
| "edge_transitions": None, |
| "img_width": None, |
| "img_height": None, |
| "img_aspect": None, |
| "phash_var": None, |
| } |
|
|
|
|
| |
|
|
| 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 "") |
|
|
| |
| 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), |
| |
| } |
|
|
|
|
| |
|
|
| 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) |
|
|
| |
| 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) |
|
|
| |
| df["draw_desc_chars"] = df["drawing_description"].fillna("").str.len() |
| df["draw_desc_words"] = df["drawing_description"].fillna("").str.split().str.len() |
|
|
| |
| df["img_path"] = df["image_filename"].apply(lambda fn: find_image(images_dir, fn)) |
|
|
| |
| 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) |
|
|
| |
| 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}") |
|
|
| |
| sampled_pids = [] |
| for chapter in top_chapters: |
| chap_patents = patent_agg[patent_agg["chapter"] == chapter] |
| n = min(args.per_domain, len(chap_patents)) |
| |
| 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]) |
| |
| 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)}") |
|
|
| |
| sample_df = df[df["patent_id"].isin(set(sampled_pids))].copy() |
| |
| 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():,}") |
|
|
| |
| 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") |
|
|
| |
| 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") |
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|