midah commited on
Commit
e37bd2f
·
verified ·
1 Parent(s): d126496

Reorganize: scripts/eval/build_sample.py

Browse files
Files changed (1) hide show
  1. scripts/eval/build_sample.py +374 -0
scripts/eval/build_sample.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build a stratified evaluation sample with full observables per figure.
2
+
3
+ Sampling strategy:
4
+ - Select DOMAIN_COUNT Locarno chapters (by patent count)
5
+ - Within each chapter, sample N_PER_DOMAIN patents stratified by text richness
6
+ - Within each patent, include all figures
7
+ - Compute all observables: text features, structural features, image complexity
8
+
9
+ Produces: data/sample/eval_sample.parquet (figures)
10
+ data/sample/eval_sample_patents.parquet (per-patent aggregates)
11
+
12
+ Usage:
13
+ python scripts/eval/build_sample.py \
14
+ --enriched data/enriched/enriched_2022.parquet \
15
+ --images /tmp/patent_sample/2022 \
16
+ --out data/sample \
17
+ --domains 8 \
18
+ --per-domain 100
19
+ """
20
+
21
+ import argparse
22
+ import re
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ from PIL import Image
28
+ from tqdm import tqdm
29
+
30
+
31
+ # ── Locarno chapter labels ────────────────────────────────────────────────────
32
+
33
+ CHAPTER_LABELS = {
34
+ 'D14': 'Screens/electronics',
35
+ 'D24': 'Medical',
36
+ 'D12': 'Construction',
37
+ 'D23': 'Fluid/sanitation',
38
+ 'D21': 'Games/sports',
39
+ 'D13': 'Transport',
40
+ 'D26': 'Lighting',
41
+ 'D29': 'Fire/accident prevention',
42
+ 'D32': 'Graphic symbols/logos',
43
+ 'D15': 'Machines',
44
+ 'D10': 'Clocks/watches',
45
+ 'D28': 'Pharma/cosmetics',
46
+ 'D11': 'Ornamental articles',
47
+ 'D27': 'Tobacco/recreation',
48
+ 'D8': 'Tools/hardware',
49
+ 'D9': 'Packaging',
50
+ 'D16': 'Photo/optical',
51
+ }
52
+
53
+
54
+ # ── viewpoint parsing ─────────────────────────────────────────────────────────
55
+
56
+ VP_BUCKETS = [
57
+ ('perspective', lambda v: 'perspective' in v),
58
+ ('front_elev', lambda v: 'front elev' in v or v in ('front elevation','front plan','front view')),
59
+ ('rear_elev', lambda v: 'rear elev' in v or 'rear elevation' in v),
60
+ ('side_elev', lambda v: 'side elev' in v or 'side elevation' in v),
61
+ ('top_plan', lambda v: 'top plan' in v or v == 'top view'),
62
+ ('bottom_plan', lambda v: 'bottom plan' in v or 'bottom' in v),
63
+ ('cross_section', lambda v: 'cross' in v or 'section' in v),
64
+ ('enlarged', lambda v: 'enlarg' in v or 'detail' in v),
65
+ ('exploded', lambda v: 'explod' in v),
66
+ ('reference', lambda v: 'reference' in v),
67
+ ('unknown', lambda v: True),
68
+ ]
69
+
70
+ DIFFICULTY = {
71
+ 'perspective': 'baseline',
72
+ 'front_elev': 'easy',
73
+ 'rear_elev': 'easy',
74
+ 'side_elev': 'easy',
75
+ 'top_plan': 'medium',
76
+ 'bottom_plan': 'medium',
77
+ 'enlarged': 'hard',
78
+ 'cross_section': 'very_hard',
79
+ 'exploded': 'hard',
80
+ 'reference': 'baseline',
81
+ 'unknown': 'unknown',
82
+ }
83
+
84
+
85
+ def parse_vp(desc: str, fig_num: int) -> str:
86
+ pat = re.compile(
87
+ rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
88
+ re.IGNORECASE,
89
+ )
90
+ m = pat.search(desc or "")
91
+ return m.group(1).strip().lower() if m else ""
92
+
93
+
94
+ def bucket_vp(vp: str) -> str:
95
+ for name, fn in VP_BUCKETS:
96
+ if fn(vp):
97
+ return name
98
+ return "unknown"
99
+
100
+
101
+ # ── image observables ─────────────────────────────────────────────────────────
102
+
103
+ def find_image(images_dir: Path, image_filename: str) -> Path | None:
104
+ parts = image_filename.split("-D0")
105
+ if len(parts) < 2:
106
+ return None
107
+ p = images_dir / parts[0] / image_filename
108
+ return p if p.exists() else None
109
+
110
+
111
+ def image_observables(img_path: Path) -> dict:
112
+ """Compute pixel-level features from a bilevel patent TIF."""
113
+ try:
114
+ img = Image.open(img_path)
115
+ arr = np.array(img) # mode 1: True=white, False=black
116
+ h, w = arr.shape
117
+ total = h * w
118
+
119
+ ink_frac = (~arr).sum() / total
120
+
121
+ # Edge transitions (white→black per row, sampled)
122
+ transitions = int(sum(
123
+ np.sum(row[1:] < row[:-1])
124
+ for row in arr[::4] # sample every 4th row
125
+ ))
126
+
127
+ # Perceptual hash proxy: 8×8 mean block comparison
128
+ from PIL import Image as PILImage
129
+ small = img.resize((32, 32), PILImage.LANCZOS).convert("L")
130
+ small_arr = np.array(small)
131
+ phash_var = float(small_arr.var())
132
+
133
+ return {
134
+ "ink_frac": float(ink_frac),
135
+ "edge_transitions": transitions,
136
+ "img_width": w,
137
+ "img_height": h,
138
+ "img_aspect": float(w / h) if h > 0 else 1.0,
139
+ "phash_var": phash_var, # higher = more detail/complexity
140
+ }
141
+ except Exception:
142
+ return {
143
+ "ink_frac": None,
144
+ "edge_transitions": None,
145
+ "img_width": None,
146
+ "img_height": None,
147
+ "img_aspect": None,
148
+ "phash_var": None,
149
+ }
150
+
151
+
152
+ # ── text observables ──────────────────────────────────────────────────────────
153
+
154
+ def text_observables(row: pd.Series) -> dict:
155
+ draw = str(row.get("drawing_description") or "")
156
+ detail = str(row.get("detailed_description") or "")
157
+ claims = str(row.get("claims") or "")
158
+ summary = str(row.get("brief_summary") or "")
159
+ caption = str(row.get("caption") or "")
160
+
161
+ # Count FIG. references in draw_desc
162
+ n_fig_refs = len(re.findall(r"FIG\.\s*\d+", draw, re.IGNORECASE))
163
+
164
+ return {
165
+ "draw_desc_chars": len(draw),
166
+ "draw_desc_words": len(draw.split()),
167
+ "draw_desc_fig_refs": n_fig_refs,
168
+ "detail_desc_chars": len(detail),
169
+ "claims_chars": len(claims),
170
+ "summary_chars": len(summary),
171
+ "caption_chars": len(caption),
172
+ # Text richness quartile (filled in at patent level)
173
+ }
174
+
175
+
176
+ # ── main ──────────────────────────────────────────────────────────────────────
177
+
178
+ def main():
179
+ parser = argparse.ArgumentParser()
180
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
181
+ parser.add_argument("--images", default="/tmp/patent_sample/2022")
182
+ parser.add_argument("--out", default="data/sample")
183
+ parser.add_argument("--domains", type=int, default=8,
184
+ help="Number of top Locarno chapters to include")
185
+ parser.add_argument("--per-domain", type=int, default=100,
186
+ help="Max patents per domain")
187
+ parser.add_argument("--seed", type=int, default=42)
188
+ args = parser.parse_args()
189
+
190
+ rng = np.random.default_rng(args.seed)
191
+ images_dir = Path(args.images)
192
+ out_dir = Path(args.out)
193
+ out_dir.mkdir(parents=True, exist_ok=True)
194
+
195
+ print("Loading enriched data...")
196
+ df = pd.read_parquet(args.enriched)
197
+
198
+ # Parse chapter and viewpoint
199
+ df["locarno_chapter"] = (
200
+ df["class"].astype(str)
201
+ .str.extract(r"^(D\s*\d{1,2})", expand=False)
202
+ .str.replace(" ", "", regex=False)
203
+ .fillna("other")
204
+ )
205
+ df["vp_raw"] = df.apply(
206
+ lambda r: parse_vp(r.get("drawing_description", ""), r["figure_number"]),
207
+ axis=1,
208
+ )
209
+ df["vp_bucket"] = df["vp_raw"].apply(bucket_vp)
210
+ df["difficulty"] = df["vp_bucket"].map(DIFFICULTY)
211
+
212
+ # Text features at figure level
213
+ df["draw_desc_chars"] = df["drawing_description"].fillna("").str.len()
214
+ df["draw_desc_words"] = df["drawing_description"].fillna("").str.split().str.len()
215
+
216
+ # Image path
217
+ df["img_path"] = df["image_filename"].apply(lambda fn: find_image(images_dir, fn))
218
+
219
+ # Per-patent aggregates for richness quartile
220
+ patent_agg = df.groupby("patent_id").agg(
221
+ draw_len=("draw_desc_chars", "first"),
222
+ n_figs=("figure_id", "count"),
223
+ n_vp_types=("vp_bucket", "nunique"),
224
+ has_perspective=("vp_bucket", lambda x: "perspective" in x.values),
225
+ has_front=("vp_bucket", lambda x: "front_elev" in x.values),
226
+ has_cross=("vp_bucket", lambda x: "cross_section" in x.values),
227
+ parse_rate=("vp_bucket", lambda x: (x != "unknown").mean()),
228
+ chapter=("locarno_chapter", "first"),
229
+ ).reset_index()
230
+
231
+ patent_agg["text_richness_q"] = pd.qcut(
232
+ patent_agg["draw_len"], 4,
233
+ labels=["sparse", "moderate", "rich", "very_rich"]
234
+ ).astype(str)
235
+
236
+ # Select top domains
237
+ top_chapters = (
238
+ patent_agg[patent_agg["chapter"] != "other"]
239
+ .groupby("chapter")["patent_id"].count()
240
+ .sort_values(ascending=False)
241
+ .head(args.domains)
242
+ .index.tolist()
243
+ )
244
+ print(f"\nSelected domains: {top_chapters}")
245
+
246
+ # Stratified sample: within each domain, stratify by text richness
247
+ sampled_pids = []
248
+ for chapter in top_chapters:
249
+ chap_patents = patent_agg[patent_agg["chapter"] == chapter]
250
+ n = min(args.per_domain, len(chap_patents))
251
+ # Stratified by text richness (equal from each quartile if possible)
252
+ per_q = n // 4
253
+ chunk = []
254
+ for q in ["sparse", "moderate", "rich", "very_rich"]:
255
+ pool = chap_patents[chap_patents["text_richness_q"] == q]["patent_id"].tolist()
256
+ rng.shuffle(pool)
257
+ chunk.extend(pool[: per_q])
258
+ # Top up to n from the full pool
259
+ remaining = set(chap_patents["patent_id"]) - set(chunk)
260
+ remaining = list(remaining)
261
+ rng.shuffle(remaining)
262
+ chunk.extend(remaining[: n - len(chunk)])
263
+ sampled_pids.extend(chunk[:n])
264
+ label = CHAPTER_LABELS.get(chapter, chapter)
265
+ print(f" {chapter} ({label}): {len(chunk[:n])} patents sampled")
266
+
267
+ print(f"\nTotal patents sampled: {len(sampled_pids)}")
268
+
269
+ # Filter to sampled patents
270
+ sample_df = df[df["patent_id"].isin(set(sampled_pids))].copy()
271
+ # Merge patent-level features
272
+ sample_df = sample_df.merge(
273
+ patent_agg[["patent_id", "text_richness_q", "n_vp_types",
274
+ "has_perspective", "has_front", "has_cross", "parse_rate"]],
275
+ on="patent_id", how="left"
276
+ )
277
+ sample_df["domain_label"] = sample_df["locarno_chapter"].map(CHAPTER_LABELS).fillna(sample_df["locarno_chapter"])
278
+
279
+ print(f"Total figures in sample: {len(sample_df):,}")
280
+ print(f"Images available: {sample_df['img_path'].notna().sum():,}")
281
+
282
+ # Compute image observables on all available images
283
+ print("\nComputing image observables...")
284
+ img_obs_list = []
285
+ for _, row in tqdm(sample_df.iterrows(), total=len(sample_df)):
286
+ p = row["img_path"]
287
+ obs = image_observables(p) if p is not None else {}
288
+ obs["figure_id"] = row["figure_id"]
289
+ img_obs_list.append(obs)
290
+
291
+ img_obs_df = pd.DataFrame(img_obs_list)
292
+ sample_df = sample_df.merge(img_obs_df, on="figure_id", how="left")
293
+
294
+ # Summary
295
+ print("\n=== SAMPLE SUMMARY ===")
296
+ print(f"{'Domain':<6} {'Label':<22} {'Patents':>8} {'Figs':>8}")
297
+ for chap in top_chapters:
298
+ g = sample_df[sample_df["locarno_chapter"] == chap]
299
+ label = CHAPTER_LABELS.get(chap, chap)
300
+ print(f" {chap:<6} {label:<22} {g['patent_id'].nunique():>8} {len(g):>8}")
301
+
302
+ print()
303
+ print("=== VIEWPOINT DISTRIBUTION IN SAMPLE ===")
304
+ vp_dist = sample_df["vp_bucket"].value_counts()
305
+ for vp, n in vp_dist.items():
306
+ print(f" {vp:<16} {n:>6,} ({n/len(sample_df):.1%})")
307
+
308
+ print()
309
+ print("=== TEXT RICHNESS IN SAMPLE ===")
310
+ for q, g in sample_df.groupby("text_richness_q", observed=True):
311
+ print(f" {q:<12} {g['patent_id'].nunique():>5} patents "
312
+ f"draw_len median: {g['draw_desc_chars'].median():.0f} chars")
313
+
314
+ # Save
315
+ cols_to_save = [
316
+ "figure_id", "patent_id", "figure_number", "n_figures_in_patent",
317
+ "sibling_figure_ids", "patent_title", "caption",
318
+ "drawing_description", "detailed_description", "brief_summary", "claims",
319
+ "vp_raw", "vp_bucket", "difficulty",
320
+ "locarno_chapter", "domain_label", "text_richness_q",
321
+ "draw_desc_chars", "draw_desc_words",
322
+ "detail_desc_chars" if "detail_desc_chars" in sample_df.columns else None,
323
+ "claims_chars" if "claims_chars" in sample_df.columns else None,
324
+ "n_vp_types", "has_perspective", "has_front", "has_cross", "parse_rate",
325
+ "ink_frac", "edge_transitions", "img_width", "img_height",
326
+ "img_aspect", "phash_var",
327
+ "image_filename", "year",
328
+ ]
329
+ cols_to_save = [c for c in cols_to_save if c and c in sample_df.columns]
330
+ sample_df[cols_to_save].to_parquet(out_dir / "eval_sample.parquet", index=False)
331
+
332
+ # Per-patent summary
333
+ patent_summary = sample_df.groupby("patent_id").agg(
334
+ n_figs=("figure_id", "count"),
335
+ locarno_chapter=("locarno_chapter", "first"),
336
+ domain_label=("domain_label", "first"),
337
+ text_richness_q=("text_richness_q", "first"),
338
+ draw_desc_chars=("draw_desc_chars", "first"),
339
+ n_vp_types=("n_vp_types", "first"),
340
+ has_perspective=("has_perspective", "first"),
341
+ has_front=("has_front", "first"),
342
+ has_cross=("has_cross", "first"),
343
+ parse_rate=("parse_rate", "first"),
344
+ median_ink_frac=("ink_frac", "median"),
345
+ median_edge_transitions=("edge_transitions", "median"),
346
+ median_phash_var=("phash_var", "median"),
347
+ patent_title=("patent_title", "first"),
348
+ ).reset_index()
349
+ patent_summary.to_parquet(out_dir / "eval_sample_patents.parquet", index=False)
350
+
351
+ print(f"\nSaved:")
352
+ print(f" {out_dir}/eval_sample.parquet ({len(sample_df):,} figures)")
353
+ print(f" {out_dir}/eval_sample_patents.parquet ({len(patent_summary):,} patents)")
354
+ print()
355
+ print("=== OBSERVABLES CAPTURED ===")
356
+ obs_fields = {
357
+ "TEXT (draw_desc)": ["draw_desc_chars", "draw_desc_words", "text_richness_q"],
358
+ "TEXT (missing — need re-download)": ["detail_desc_chars", "claims_chars", "summary_chars"],
359
+ "STRUCTURAL": ["n_figures_in_patent", "n_vp_types", "has_perspective", "has_front", "has_cross", "parse_rate"],
360
+ "IMAGE": ["ink_frac", "edge_transitions", "img_aspect", "phash_var"],
361
+ "METADATA": ["locarno_chapter", "domain_label", "year"],
362
+ }
363
+ for group, fields in obs_fields.items():
364
+ available = [f for f in fields if f in sample_df.columns and sample_df[f].notna().any()]
365
+ missing = [f for f in fields if f not in available]
366
+ print(f" {group}:")
367
+ if available:
368
+ print(f" ✓ {', '.join(available)}")
369
+ if missing:
370
+ print(f" ✗ {', '.join(missing)} (not in current data)")
371
+
372
+
373
+ if __name__ == "__main__":
374
+ main()