midah commited on
Commit
bf36b21
·
verified ·
1 Parent(s): 337c768

Add scripts/cloud/process_full_corpus.py

Browse files
Files changed (1) hide show
  1. scripts/cloud/process_full_corpus.py +342 -0
scripts/cloud/process_full_corpus.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Process the full 2007–2022 IMPACT corpus — one year at a time.
2
+
3
+ For each year:
4
+ 1. Download PatentsView text TSVs from S3 (~500MB-2GB/year)
5
+ 2. Extract with 7-zip (handles deflate64 that Python's zipfile can't)
6
+ 3. Join with IMPACT CSV (enriched parquet with text + viewpoints)
7
+ 4. Embed images via HF Inference Endpoint (no local GPU needed)
8
+ 5. Push enriched parquet + embeddings to HF Hub
9
+ 6. Delete local files before processing next year
10
+
11
+ Net local disk at any time: ~5-7GB (one year)
12
+ Total cloud cost estimate: ~$1.20 for all 3.61M figures (GPU endpoint)
13
+
14
+ Prerequisites:
15
+ - p7zip installed: brew install p7zip
16
+ - HF_TOKEN set in .env with write access to midah/patent-wireframes
17
+ - HF Inference Endpoint running (use create_hf_endpoint.py, or pass --endpoint-url)
18
+
19
+ Usage:
20
+ # Process all years (creates/deletes endpoint per year):
21
+ python scripts/cloud/process_full_corpus.py --years 2007-2022
22
+
23
+ # Single year with existing endpoint:
24
+ python scripts/cloud/process_full_corpus.py --years 2022 \
25
+ --endpoint-url https://your-endpoint.huggingface.cloud
26
+
27
+ # Text enrichment only (no embedding):
28
+ python scripts/cloud/process_full_corpus.py --years 2022 --text-only
29
+ """
30
+
31
+ import argparse
32
+ import ast
33
+ import csv
34
+ import os
35
+ import subprocess
36
+ import tempfile
37
+ import time
38
+ from pathlib import Path
39
+
40
+ import pandas as pd
41
+ import requests
42
+ from dotenv import load_dotenv
43
+ from huggingface_hub import HfApi, hf_hub_download
44
+ from tqdm import tqdm
45
+
46
+ load_dotenv(".env")
47
+ HF_TOKEN = os.environ.get("HF_TOKEN")
48
+ HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
49
+ OUT_REPO = "midah/patent-wireframes"
50
+
51
+ PATENTSVIEW_URLS = {
52
+ "drawing_desc": "https://s3.amazonaws.com/data.patentsview.org/draw-description-text/g_draw_desc_text_{year}.tsv.zip",
53
+ "detail_desc": "https://s3.amazonaws.com/data.patentsview.org/detail-description-text/g_detail_desc_text_{year}.tsv.zip",
54
+ "brf_sum": "https://s3.amazonaws.com/data.patentsview.org/brief-summary-text/g_brf_sum_text_{year}.tsv.zip",
55
+ "claims": "https://s3.amazonaws.com/data.patentsview.org/claims/g_claims_{year}.tsv.zip",
56
+ "patent_meta": "https://s3.amazonaws.com/data.patentsview.org/download/g_patent.tsv.zip",
57
+ }
58
+
59
+ CHUNK = 8 * 1024 * 1024
60
+
61
+
62
+ # ── Utilities ────────────────────────────────────────────────────────────────
63
+
64
+ def download_file(url: str, dest: Path) -> Path:
65
+ if dest.exists() and dest.stat().st_size > 1024:
66
+ print(f" Cached: {dest.name}")
67
+ return dest
68
+ print(f" Downloading {dest.name}...")
69
+ r = requests.get(url, stream=True, timeout=120)
70
+ r.raise_for_status()
71
+ total = int(r.headers.get("content-length", 0))
72
+ with open(dest, "wb") as f, tqdm(total=total, unit="B", unit_scale=True) as pbar:
73
+ for chunk in r.iter_content(CHUNK):
74
+ f.write(chunk); pbar.update(len(chunk))
75
+ return dest
76
+
77
+
78
+ def extract_7z(zip_path: Path, out_dir: Path) -> Path | None:
79
+ """Extract using p7zip (handles deflate64)."""
80
+ result = subprocess.run(
81
+ ["7za", "x", str(zip_path), f"-o{out_dir}", "-y"],
82
+ capture_output=True, text=True,
83
+ )
84
+ if result.returncode != 0:
85
+ print(f" 7za error: {result.stderr[:100]}")
86
+ return None
87
+ tsv_files = list(out_dir.glob("*.tsv"))
88
+ return tsv_files[0] if tsv_files else None
89
+
90
+
91
+ def agg_text(df: pd.DataFrame, id_col: str, text_col: str) -> pd.DataFrame:
92
+ if df.empty or text_col not in df.columns:
93
+ return pd.DataFrame(columns=[id_col, text_col])
94
+ return (
95
+ df.groupby(id_col)[text_col]
96
+ .apply(lambda x: "\n".join(x.dropna().astype(str)))
97
+ .reset_index()
98
+ )
99
+
100
+
101
+ # ── Text enrichment ──────────────────────────────────────────────────────────
102
+
103
+ def enrich_year(year: str, work_dir: Path) -> pd.DataFrame:
104
+ """Download IMPACT CSV + PatentsView text, join, return enriched DataFrame."""
105
+ api = HfApi(token=HF_TOKEN)
106
+
107
+ # IMPACT metadata CSV
108
+ csv_path = hf_hub_download(
109
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
110
+ repo_type="dataset", token=HF_TOKEN, local_dir=str(work_dir),
111
+ )
112
+ impact = pd.read_csv(csv_path, low_memory=False)
113
+ print(f" IMPACT {year}: {len(impact):,} patents")
114
+
115
+ # Explode to figure level
116
+ rows = []
117
+ for _, row in impact.iterrows():
118
+ try:
119
+ fnames = ast.literal_eval(str(row.get("file_names", "[]")))
120
+ fig_descs = ast.literal_eval(str(row.get("fig_desc", "[]")))
121
+ except Exception:
122
+ fnames, fig_descs = [], []
123
+ base = {k: v for k, v in row.items()
124
+ if k not in ("file_names", "fig_desc")}
125
+ if not fnames:
126
+ rows.append({**base, "figure_number": 0, "image_filename": ""})
127
+ else:
128
+ for i, fn in enumerate(fnames):
129
+ rows.append({**base, "figure_number": i, "image_filename": fn})
130
+ df = pd.DataFrame(rows)
131
+ df.rename(columns={"id": "patent_id", "title": "patent_title"}, inplace=True)
132
+ print(f" Exploded: {len(df):,} figures")
133
+
134
+ # Download + extract PatentsView text tables
135
+ text_tables = {}
136
+ for tname, url_tpl in PATENTSVIEW_URLS.items():
137
+ if tname == "patent_meta":
138
+ url = url_tpl
139
+ else:
140
+ url = url_tpl.format(year=year)
141
+ zip_dest = work_dir / url.split("/")[-1]
142
+ try:
143
+ download_file(url, zip_dest)
144
+ tsv = extract_7z(zip_dest, work_dir / tname)
145
+ if tsv:
146
+ text_tables[tname] = pd.read_csv(tsv, sep="\t", dtype=str, low_memory=False)
147
+ print(f" {tname}: {len(text_tables[tname]):,} rows")
148
+ zip_dest.unlink() # free space immediately
149
+ except Exception as e:
150
+ print(f" Skipping {tname}: {e}")
151
+
152
+ # Join text tables
153
+ for canonical, (tname, tcol) in {
154
+ "drawing_description": ("drawing_desc", "draw_desc_text"),
155
+ "detailed_description": ("detail_desc", "detail_desc_text"),
156
+ "brief_summary": ("brf_sum", "brf_sum_text"),
157
+ "claims": ("claims", "claims_text"),
158
+ }.items():
159
+ tdf = text_tables.get(tname, pd.DataFrame())
160
+ if not tdf.empty and tcol in tdf.columns:
161
+ tdf = tdf.rename(columns={"patent_id": "patent_id"})
162
+ agg = agg_text(tdf, "patent_id", tcol).rename(columns={tcol: canonical})
163
+ df = df.merge(agg, on="patent_id", how="left")
164
+ df[canonical] = df.get(canonical, pd.Series("")).fillna("")
165
+
166
+ # Patent metadata
167
+ meta = text_tables.get("patent_meta", pd.DataFrame())
168
+ if not meta.empty:
169
+ meta_cols = ["patent_id"] + [c for c in ["patent_date","patent_type"] if c in meta.columns]
170
+ df = df.merge(meta[meta_cols].drop_duplicates("patent_id"), on="patent_id", how="left")
171
+
172
+ df["year"] = int(year)
173
+ return df
174
+
175
+
176
+ # ── Embedding via HF endpoint ────────────────────────────────────────────────
177
+
178
+ def embed_year_via_endpoint(year: str, df: pd.DataFrame, endpoint_url: str,
179
+ zip_path: str, work_dir: Path) -> pd.DataFrame:
180
+ """Embed all figures using the running HF Inference Endpoint."""
181
+ import base64
182
+ import io
183
+ import zipfile
184
+ import numpy as np
185
+ from PIL import Image
186
+
187
+ def encode_img(img_bytes):
188
+ img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
189
+ w, h = img.size
190
+ scale = min(224 / max(w, h), 1.0)
191
+ if scale < 1.0:
192
+ img = img.resize((int(w*scale), int(h*scale)), Image.LANCZOS)
193
+ buf = io.BytesIO()
194
+ img.save(buf, format="JPEG", quality=85)
195
+ return base64.standard_b64encode(buf.getvalue()).decode()
196
+
197
+ def post_batch(b64s):
198
+ for attempt in range(4):
199
+ try:
200
+ r = requests.post(endpoint_url, headers={**HF_HEADERS, "Content-Type":"application/json"},
201
+ json={"inputs": b64s}, timeout=60)
202
+ if r.status_code == 200:
203
+ data = r.json()
204
+ if isinstance(data, list) and data and isinstance(data[0], list):
205
+ if isinstance(data[0][0], float):
206
+ return data
207
+ if isinstance(data[0][0], list):
208
+ return [d[0] for d in data]
209
+ except Exception:
210
+ pass
211
+ time.sleep(2 ** attempt)
212
+ return None
213
+
214
+ all_ids, all_vecs = [], []
215
+ batch_imgs, batch_ids = [], []
216
+
217
+ def flush():
218
+ if not batch_imgs:
219
+ return
220
+ vecs = post_batch(batch_imgs)
221
+ if vecs:
222
+ all_ids.extend(batch_ids)
223
+ all_vecs.extend(vecs)
224
+ batch_imgs.clear(); batch_ids.clear()
225
+
226
+ with zipfile.ZipFile(zip_path) as zf:
227
+ for _, row in tqdm(df.iterrows(), total=len(df), desc=f"Embedding {year}"):
228
+ fn = str(row.get("image_filename",""))
229
+ parts = fn.split("-D0")
230
+ if len(parts) < 2:
231
+ continue
232
+ inner = f"{year}/{parts[0]}/{fn}"
233
+ try:
234
+ with zf.open(inner) as f:
235
+ img_bytes = f.read()
236
+ batch_ids.append(f"{row['patent_id']}_{row['figure_number']}")
237
+ batch_imgs.append(encode_img(img_bytes))
238
+ if len(batch_imgs) >= 32:
239
+ flush()
240
+ except Exception:
241
+ continue
242
+ flush()
243
+
244
+ print(f" Embedded: {len(all_ids):,} figures")
245
+ if not all_ids:
246
+ return pd.DataFrame()
247
+
248
+ vecs = np.array(all_vecs, dtype=np.float32)
249
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True)
250
+ vecs /= np.maximum(norms, 1e-8)
251
+ return pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
252
+
253
+
254
+ # ── Year processing ─��────────────────────────────────────────────────────────
255
+
256
+ def process_year_full(year: str, endpoint_url: str | None, text_only: bool):
257
+ api = HfApi(token=HF_TOKEN)
258
+
259
+ with tempfile.TemporaryDirectory() as tmpdir:
260
+ work = Path(tmpdir)
261
+ print(f"\n{'='*50}")
262
+ print(f"Processing year {year}")
263
+ print(f"{'='*50}")
264
+
265
+ # Text enrichment
266
+ df = enrich_year(year, work)
267
+
268
+ # Save enriched parquet
269
+ out_parquet = work / f"enriched_{year}.parquet"
270
+ df.to_parquet(out_parquet, index=False)
271
+ size_mb = out_parquet.stat().st_size / 1e6
272
+ print(f" Enriched parquet: {size_mb:.0f}MB, {len(df):,} rows")
273
+
274
+ api.upload_file(
275
+ path_or_fileobj=str(out_parquet),
276
+ path_in_repo=f"data/enriched_{year}.parquet",
277
+ repo_id=OUT_REPO, repo_type="dataset",
278
+ commit_message=f"Add enriched parquet for {year}",
279
+ )
280
+ print(f" Pushed enriched_{year}.parquet → HF")
281
+
282
+ if text_only or not endpoint_url:
283
+ print(" Skipping embedding (--text-only or no endpoint URL)")
284
+ return
285
+
286
+ # Download images zip
287
+ print(f" Downloading IMPACT {year} images (~4.4GB)...")
288
+ zip_path = hf_hub_download(
289
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
290
+ repo_type="dataset", token=HF_TOKEN, local_dir=tmpdir,
291
+ )
292
+
293
+ # Embed
294
+ emb_df = embed_year_via_endpoint(year, df, endpoint_url, zip_path, work)
295
+ if emb_df.empty:
296
+ print(" No embeddings produced")
297
+ return
298
+
299
+ out_emb = work / f"embeddings_{year}_vitl14.parquet"
300
+ emb_df.to_parquet(out_emb, index=False)
301
+ api.upload_file(
302
+ path_or_fileobj=str(out_emb),
303
+ path_in_repo=f"embeddings/embeddings_{year}_vitl14.parquet",
304
+ repo_id=OUT_REPO, repo_type="dataset",
305
+ commit_message=f"Add CLIP embeddings for {year}",
306
+ )
307
+ print(f" Pushed embeddings_{year}_vitl14.parquet → HF")
308
+ print(f" Year {year} complete.")
309
+
310
+
311
+ # ── CLI ──────────────────────────────────────────────────────────────────────
312
+
313
+ def main():
314
+ parser = argparse.ArgumentParser()
315
+ parser.add_argument("--years", default="2022",
316
+ help="Year or range: '2022', '2018-2022', '2007-2022'")
317
+ parser.add_argument("--endpoint-url", default=None,
318
+ help="Running HF Inference Endpoint URL (skips creation)")
319
+ parser.add_argument("--text-only", action="store_true",
320
+ help="Only do text enrichment, skip embedding")
321
+ parser.add_argument("--out-repo", default=OUT_REPO)
322
+ args = parser.parse_args()
323
+
324
+ # Parse year range
325
+ if "-" in args.years and args.years.count("-") == 1:
326
+ start, end = args.years.split("-")
327
+ years = [str(y) for y in range(int(start), int(end)+1)]
328
+ else:
329
+ years = [args.years]
330
+
331
+ print(f"Processing years: {years}")
332
+ print(f"Text only: {args.text_only}")
333
+ print(f"Endpoint: {args.endpoint_url or '(none — text only)'}")
334
+
335
+ for year in reversed(years): # newest first
336
+ process_year_full(year, args.endpoint_url, args.text_only)
337
+
338
+ print("\nAll years complete.")
339
+
340
+
341
+ if __name__ == "__main__":
342
+ main()