midah commited on
Commit
69770c7
·
verified ·
1 Parent(s): 6a92b70

Add Modal full-corpus processing job

Browse files
Files changed (1) hide show
  1. scripts/cloud/process_year_modal.py +377 -0
scripts/cloud/process_year_modal.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Process one IMPACT year: download, enrich, embed, push to HF Hub.
2
+
3
+ Runs on Modal GPU — no local disk used. Each year is ~4-5GB of images,
4
+ ~2GB of text. Modal ephemeral storage handles it; everything is deleted
5
+ when the job exits.
6
+
7
+ Pipeline per year:
8
+ 1. Download IMPACT year.zip + CSV from HF (images + metadata)
9
+ 2. Download PatentsView text TSVs from S3 (draw_desc, detail_desc, patent meta)
10
+ 3. Extract text TSVs with 7za (handles deflate64)
11
+ 4. Join: IMPACT metadata × PatentsView text → enriched parquet
12
+ 5. Run CLIP ViT-L/14 on GPU → embeddings parquet
13
+ 6. Push both parquets to midah/patent-wireframes on HF Hub
14
+ 7. Exit — ephemeral storage is cleared automatically
15
+
16
+ Safety:
17
+ - Idempotent: checks HF Hub before downloading anything
18
+ - One year at a time — run sequentially to verify, then parallelize
19
+ - Never touches local machine disk
20
+
21
+ Setup (one-time on any networked machine):
22
+ pip install modal
23
+ modal setup
24
+ modal secret create hf-secret HF_TOKEN=hf_...
25
+
26
+ Run one year (verify first):
27
+ modal run scripts/cloud/process_year_modal.py --year 2021
28
+
29
+ Run all years sequentially:
30
+ for year in 2022 2021 2020 2019 2018 2017 2016 2015 2014 2013 2012 2011 2010 2009 2008 2007; do
31
+ modal run scripts/cloud/process_year_modal.py --year $year
32
+ done
33
+
34
+ Run all years in parallel (after verifying one year works):
35
+ modal run scripts/cloud/process_year_modal.py --all-years
36
+ """
37
+
38
+ import io
39
+ import os
40
+ import re
41
+ import subprocess
42
+ from pathlib import Path
43
+
44
+ import modal
45
+
46
+ # ── Modal image ───────────────────────────────────────────────────────────────
47
+
48
+ image = (
49
+ modal.Image.debian_slim(python_version="3.11")
50
+ .apt_install("p7zip-full") # for deflate64 extraction
51
+ .pip_install(
52
+ "open_clip_torch",
53
+ "huggingface_hub>=0.23",
54
+ "datasets",
55
+ "Pillow",
56
+ "pandas",
57
+ "numpy",
58
+ "tqdm",
59
+ "requests",
60
+ )
61
+ )
62
+
63
+ app = modal.App("patent-process-year", image=image)
64
+ hf_secret = modal.Secret.from_name("hf-secret")
65
+
66
+ PATENTSVIEW_URLS = {
67
+ "draw_desc": "https://s3.amazonaws.com/data.patentsview.org/draw-description-text/g_draw_desc_text_{year}.tsv.zip",
68
+ "detail_desc": "https://s3.amazonaws.com/data.patentsview.org/detail-description-text/g_detail_desc_text_{year}.tsv.zip",
69
+ "brf_sum": "https://s3.amazonaws.com/data.patentsview.org/brief-summary-text/g_brf_sum_text_{year}.tsv.zip",
70
+ "claims": "https://s3.amazonaws.com/data.patentsview.org/claims/g_claims_{year}.tsv.zip",
71
+ }
72
+ PATENT_META_URL = "https://s3.amazonaws.com/data.patentsview.org/download/g_patent.tsv.zip"
73
+
74
+ HF_REPO = "midah/patent-wireframes"
75
+ BATCH_SIZE = 64
76
+
77
+
78
+ # ── helpers ───────────────────────────────────────────────────────────────────
79
+
80
+ def already_on_hub(year: int, token: str) -> bool:
81
+ """Check if this year's outputs are already on HF Hub."""
82
+ from huggingface_hub import list_repo_files
83
+ files = set(list_repo_files(HF_REPO, repo_type="dataset", token=token))
84
+ enriched = f"data/enriched_{year}.parquet"
85
+ embeddings = f"embeddings/embeddings_{year}_vitl14.parquet"
86
+ if enriched in files and embeddings in files:
87
+ print(f"Year {year}: already on Hub, skipping.")
88
+ return True
89
+ return False
90
+
91
+
92
+ def download_file(url: str, dest: Path, chunk_size: int = 8 * 1024 * 1024) -> Path:
93
+ import requests
94
+ print(f" Downloading {url.split('/')[-1]}...")
95
+ r = requests.get(url, stream=True, timeout=120)
96
+ r.raise_for_status()
97
+ with open(dest, "wb") as f:
98
+ for chunk in r.iter_content(chunk_size=chunk_size):
99
+ f.write(chunk)
100
+ size_mb = dest.stat().st_size / 1e6
101
+ print(f" → {dest.name} ({size_mb:.0f}MB)")
102
+ return dest
103
+
104
+
105
+ def extract_zip(zip_path: Path, out_dir: Path) -> Path | None:
106
+ """Extract using 7za (handles deflate64 that Python zipfile can't)."""
107
+ out_dir.mkdir(parents=True, exist_ok=True)
108
+ result = subprocess.run(
109
+ ["7za", "x", str(zip_path), f"-o{out_dir}", "-y"],
110
+ capture_output=True, text=True
111
+ )
112
+ if result.returncode != 0:
113
+ print(f" 7za error: {result.stderr[:200]}")
114
+ return None
115
+ tsv_files = list(out_dir.glob("*.tsv"))
116
+ if tsv_files:
117
+ print(f" Extracted: {tsv_files[0].name} ({tsv_files[0].stat().st_size/1e6:.0f}MB)")
118
+ return tsv_files[0]
119
+ return None
120
+
121
+
122
+ # ── core processing ───────────────────────────────────────────────────────────
123
+
124
+ @app.function(
125
+ gpu="A10G",
126
+ timeout=7200, # 2 hours max per year
127
+ memory=32768, # 32GB RAM
128
+ ephemeral_disk=51200, # 50GB ephemeral disk
129
+ secrets=[hf_secret],
130
+ )
131
+ def process_year(year: int) -> dict:
132
+ import ast
133
+ import csv
134
+ import zipfile
135
+
136
+ import numpy as np
137
+ import open_clip
138
+ import pandas as pd
139
+ import torch
140
+ from huggingface_hub import HfApi, hf_hub_download
141
+ from PIL import Image
142
+ from tqdm import tqdm
143
+
144
+ token = os.environ["HF_TOKEN"]
145
+ api = HfApi(token=token)
146
+ work = Path(f"/tmp/patent_{year}")
147
+ work.mkdir(exist_ok=True)
148
+
149
+ print(f"\n{'='*50}")
150
+ print(f"Processing year {year}")
151
+ print(f"{'='*50}")
152
+
153
+ # ── 0. Idempotency check ─────────────────────────────────────────────────
154
+ if already_on_hub(year, token):
155
+ return {"year": year, "status": "skipped"}
156
+
157
+ # ── 1. Download IMPACT metadata CSV ─────────────────────────────────────
158
+ print("\n[1/5] IMPACT metadata...")
159
+ csv_path = hf_hub_download(
160
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
161
+ repo_type="dataset", token=token, local_dir=str(work)
162
+ )
163
+ impact_df = pd.read_csv(csv_path)
164
+ print(f" {len(impact_df):,} patents")
165
+
166
+ # Explode to figure level
167
+ rows = []
168
+ for _, row in impact_df.iterrows():
169
+ try:
170
+ fnames = ast.literal_eval(str(row["file_names"]))
171
+ fig_descs = ast.literal_eval(str(row["fig_desc"])) if pd.notna(row.get("fig_desc")) else []
172
+ except Exception:
173
+ continue
174
+ for i, fname in enumerate(fnames):
175
+ rows.append({
176
+ "patent_id": "D" + str(row["id"]).replace("D","").lstrip("0").zfill(7),
177
+ "figure_number": i,
178
+ "image_filename": fname,
179
+ "patent_title": row.get("title",""),
180
+ "caption": row.get("caption",""),
181
+ "class": row.get("class",""),
182
+ "year": year,
183
+ })
184
+ df = pd.DataFrame(rows)
185
+ print(f" Exploded to {len(df):,} figures")
186
+
187
+ # ── 2. Download PatentsView text TSVs ────────────────────────────────────
188
+ print("\n[2/5] PatentsView text tables...")
189
+ pv_dir = work / "patentsview"
190
+ pv_dir.mkdir(exist_ok=True)
191
+
192
+ text_dfs = {}
193
+ for table, url_template in PATENTSVIEW_URLS.items():
194
+ url = url_template.format(year=year)
195
+ zip_path = pv_dir / url.split("/")[-1]
196
+ try:
197
+ download_file(url, zip_path)
198
+ tsv_path = extract_zip(zip_path, pv_dir / table)
199
+ if tsv_path:
200
+ tdf = pd.read_csv(tsv_path, sep="\t", dtype=str, low_memory=False)
201
+ tdf["patent_id"] = tdf["patent_id"].apply(
202
+ lambda x: "D" + str(x).replace("D","").lstrip("0").zfill(7)
203
+ )
204
+ text_dfs[table] = tdf
205
+ zip_path.unlink() # free space immediately
206
+ except Exception as e:
207
+ print(f" {table}: skipped ({e})")
208
+
209
+ # Patent metadata (year-independent, check if already fetched)
210
+ meta_path = pv_dir / "g_patent.tsv"
211
+ if not meta_path.exists():
212
+ try:
213
+ zip_path = pv_dir / "g_patent.tsv.zip"
214
+ download_file(PATENT_META_URL, zip_path)
215
+ extract_zip(zip_path, pv_dir)
216
+ zip_path.unlink()
217
+ except Exception as e:
218
+ print(f" patent meta: skipped ({e})")
219
+
220
+ # ── 3. Join ──────────────────────────────────────────────────────────────
221
+ print("\n[3/5] Joining text tables...")
222
+ col_map = {
223
+ "draw_desc": ("draw_desc_text", "drawing_description"),
224
+ "detail_desc": ("detail_desc_text", "detailed_description"),
225
+ "brf_sum": ("brf_sum_text", "brief_summary"),
226
+ "claims": ("claims_text", "claims"),
227
+ }
228
+ for table, (src_col, dst_col) in col_map.items():
229
+ tdf = text_dfs.get(table, pd.DataFrame())
230
+ if not tdf.empty and src_col in tdf.columns:
231
+ agg = (tdf.groupby("patent_id")[src_col]
232
+ .apply(lambda x: "\n".join(x.dropna().astype(str)))
233
+ .reset_index().rename(columns={src_col: dst_col}))
234
+ df = df.merge(agg, on="patent_id", how="left")
235
+ df[dst_col] = df[dst_col].fillna("")
236
+ else:
237
+ df[dst_col] = ""
238
+ filled = (df[dst_col] != "").sum()
239
+ print(f" {dst_col}: {filled:,}/{len(df):,} filled")
240
+
241
+ # Merge patent metadata
242
+ meta_path = pv_dir / "g_patent.tsv"
243
+ if meta_path.exists():
244
+ meta = pd.read_csv(meta_path, sep="\t", dtype=str, low_memory=False)
245
+ meta["patent_id"] = meta["patent_id"].apply(
246
+ lambda x: "D" + str(x).replace("D","").lstrip("0").zfill(7)
247
+ )
248
+ for col in ["patent_date", "patent_type"]:
249
+ if col in meta.columns:
250
+ df = df.merge(meta[["patent_id", col]].drop_duplicates("patent_id"),
251
+ on="patent_id", how="left")
252
+
253
+ # Figure ID + siblings
254
+ df["figure_id"] = df["patent_id"] + "_" + df["figure_number"].astype(str)
255
+ patent_groups = df.groupby("patent_id")["figure_id"].apply(list).to_dict()
256
+ df["n_figures_in_patent"] = df["patent_id"].map(df.groupby("patent_id").size())
257
+ df["sibling_figure_ids"] = df.apply(
258
+ lambda r: [f for f in patent_groups[r["patent_id"]] if f != r["figure_id"]],
259
+ axis=1
260
+ )
261
+
262
+ # ── 4. CLIP embeddings ───────────────────────────────────────────────────
263
+ print("\n[4/5] CLIP embeddings...")
264
+ device = "cuda" if torch.cuda.is_available() else "cpu"
265
+ print(f" Device: {device}")
266
+
267
+ model, _, preprocess = open_clip.create_model_and_transforms(
268
+ "ViT-L-14", pretrained="openai"
269
+ )
270
+ model = model.to(device).eval()
271
+
272
+ # Download IMPACT zip
273
+ print(" Downloading IMPACT images (~4-5GB)...")
274
+ zip_path = hf_hub_download(
275
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
276
+ repo_type="dataset", token=token, local_dir=str(work)
277
+ )
278
+ print(f" Zip: {Path(zip_path).stat().st_size/1e9:.1f}GB")
279
+
280
+ all_ids, all_vecs = [], []
281
+
282
+ def load_image(fname: str) -> Image.Image | None:
283
+ parts = fname.split("-D0")
284
+ if len(parts) < 2:
285
+ return None
286
+ inner = f"{year}/{parts[0]}/{fname}"
287
+ try:
288
+ with zipfile.ZipFile(zip_path) as z:
289
+ with z.open(inner) as f:
290
+ return Image.open(io.BytesIO(f.read())).convert("RGB")
291
+ except Exception:
292
+ return None
293
+
294
+ batch_imgs, batch_ids = [], []
295
+
296
+ def flush():
297
+ if not batch_imgs:
298
+ return
299
+ tensors = torch.stack([preprocess(im) for im in batch_imgs]).to(device)
300
+ with torch.no_grad():
301
+ feats = model.encode_image(tensors)
302
+ feats = feats / feats.norm(dim=-1, keepdim=True)
303
+ all_vecs.append(feats.cpu().numpy())
304
+ all_ids.extend(batch_ids)
305
+ batch_imgs.clear()
306
+ batch_ids.clear()
307
+
308
+ for _, row in tqdm(df.iterrows(), total=len(df), desc=" Embedding"):
309
+ img = load_image(row["image_filename"])
310
+ if img is None:
311
+ continue
312
+ batch_imgs.append(img)
313
+ batch_ids.append(row["figure_id"])
314
+ if len(batch_imgs) >= BATCH_SIZE:
315
+ flush()
316
+ flush()
317
+
318
+ vecs = np.vstack(all_vecs).astype(np.float32)
319
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True)
320
+ vecs /= np.maximum(norms, 1e-8)
321
+ print(f" Embedded {len(all_ids):,} figures, shape {vecs.shape}")
322
+
323
+ emb_df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
324
+
325
+ # ── 5. Push to Hub ───────────────────────────────────────────────────────
326
+ print("\n[5/5] Pushing to HF Hub...")
327
+
328
+ enriched_path = work / f"enriched_{year}.parquet"
329
+ df.to_parquet(enriched_path, index=False)
330
+ api.upload_file(
331
+ path_or_fileobj=str(enriched_path),
332
+ path_in_repo=f"data/enriched_{year}.parquet",
333
+ repo_id=HF_REPO, repo_type="dataset",
334
+ commit_message=f"Add enriched_{year}.parquet ({len(df):,} figures)"
335
+ )
336
+ print(f" Pushed data/enriched_{year}.parquet")
337
+
338
+ emb_path = work / f"embeddings_{year}_vitl14.parquet"
339
+ emb_df.to_parquet(emb_path, index=False)
340
+ api.upload_file(
341
+ path_or_fileobj=str(emb_path),
342
+ path_in_repo=f"embeddings/embeddings_{year}_vitl14.parquet",
343
+ repo_id=HF_REPO, repo_type="dataset",
344
+ commit_message=f"Add embeddings_{year}_vitl14.parquet"
345
+ )
346
+ print(f" Pushed embeddings/embeddings_{year}_vitl14.parquet")
347
+
348
+ return {
349
+ "year": year,
350
+ "status": "done",
351
+ "n_figures": len(df),
352
+ "n_embedded": len(all_ids),
353
+ }
354
+
355
+
356
+ # ── entrypoints ───────────────────────────────────────────────────────────────
357
+
358
+ @app.local_entrypoint()
359
+ def main(year: int = 2021, all_years: bool = False):
360
+ """
361
+ Test with one year first:
362
+ modal run scripts/cloud/process_year_modal.py --year 2021
363
+
364
+ Then run all years:
365
+ modal run scripts/cloud/process_year_modal.py --all-years
366
+ """
367
+ if all_years:
368
+ years = list(range(2007, 2023)) # 2007–2022
369
+ print(f"Processing all {len(years)} years: {years}")
370
+ # Sequential for safety — can switch to .map() after verifying one year
371
+ for y in years:
372
+ result = process_year.remote(y)
373
+ print(f"Year {y}: {result}")
374
+ else:
375
+ print(f"Processing year {year} (test run)...")
376
+ result = process_year.remote(year)
377
+ print(f"Result: {result}")