File size: 13,495 Bytes
bf36b21 | 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 | """Process the full 2007–2022 IMPACT corpus — one year at a time.
For each year:
1. Download PatentsView text TSVs from S3 (~500MB-2GB/year)
2. Extract with 7-zip (handles deflate64 that Python's zipfile can't)
3. Join with IMPACT CSV (enriched parquet with text + viewpoints)
4. Embed images via HF Inference Endpoint (no local GPU needed)
5. Push enriched parquet + embeddings to HF Hub
6. Delete local files before processing next year
Net local disk at any time: ~5-7GB (one year)
Total cloud cost estimate: ~$1.20 for all 3.61M figures (GPU endpoint)
Prerequisites:
- p7zip installed: brew install p7zip
- HF_TOKEN set in .env with write access to midah/patent-wireframes
- HF Inference Endpoint running (use create_hf_endpoint.py, or pass --endpoint-url)
Usage:
# Process all years (creates/deletes endpoint per year):
python scripts/cloud/process_full_corpus.py --years 2007-2022
# Single year with existing endpoint:
python scripts/cloud/process_full_corpus.py --years 2022 \
--endpoint-url https://your-endpoint.huggingface.cloud
# Text enrichment only (no embedding):
python scripts/cloud/process_full_corpus.py --years 2022 --text-only
"""
import argparse
import ast
import csv
import os
import subprocess
import tempfile
import time
from pathlib import Path
import pandas as pd
import requests
from dotenv import load_dotenv
from huggingface_hub import HfApi, hf_hub_download
from tqdm import tqdm
load_dotenv(".env")
HF_TOKEN = os.environ.get("HF_TOKEN")
HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
OUT_REPO = "midah/patent-wireframes"
PATENTSVIEW_URLS = {
"drawing_desc": "https://s3.amazonaws.com/data.patentsview.org/draw-description-text/g_draw_desc_text_{year}.tsv.zip",
"detail_desc": "https://s3.amazonaws.com/data.patentsview.org/detail-description-text/g_detail_desc_text_{year}.tsv.zip",
"brf_sum": "https://s3.amazonaws.com/data.patentsview.org/brief-summary-text/g_brf_sum_text_{year}.tsv.zip",
"claims": "https://s3.amazonaws.com/data.patentsview.org/claims/g_claims_{year}.tsv.zip",
"patent_meta": "https://s3.amazonaws.com/data.patentsview.org/download/g_patent.tsv.zip",
}
CHUNK = 8 * 1024 * 1024
# ── Utilities ────────────────────────────────────────────────────────────────
def download_file(url: str, dest: Path) -> Path:
if dest.exists() and dest.stat().st_size > 1024:
print(f" Cached: {dest.name}")
return dest
print(f" Downloading {dest.name}...")
r = requests.get(url, stream=True, timeout=120)
r.raise_for_status()
total = int(r.headers.get("content-length", 0))
with open(dest, "wb") as f, tqdm(total=total, unit="B", unit_scale=True) as pbar:
for chunk in r.iter_content(CHUNK):
f.write(chunk); pbar.update(len(chunk))
return dest
def extract_7z(zip_path: Path, out_dir: Path) -> Path | None:
"""Extract using p7zip (handles deflate64)."""
result = subprocess.run(
["7za", "x", str(zip_path), f"-o{out_dir}", "-y"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(f" 7za error: {result.stderr[:100]}")
return None
tsv_files = list(out_dir.glob("*.tsv"))
return tsv_files[0] if tsv_files else None
def agg_text(df: pd.DataFrame, id_col: str, text_col: str) -> pd.DataFrame:
if df.empty or text_col not in df.columns:
return pd.DataFrame(columns=[id_col, text_col])
return (
df.groupby(id_col)[text_col]
.apply(lambda x: "\n".join(x.dropna().astype(str)))
.reset_index()
)
# ── Text enrichment ──────────────────────────────────────────────────────────
def enrich_year(year: str, work_dir: Path) -> pd.DataFrame:
"""Download IMPACT CSV + PatentsView text, join, return enriched DataFrame."""
api = HfApi(token=HF_TOKEN)
# IMPACT metadata CSV
csv_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
repo_type="dataset", token=HF_TOKEN, local_dir=str(work_dir),
)
impact = pd.read_csv(csv_path, low_memory=False)
print(f" IMPACT {year}: {len(impact):,} patents")
# Explode to figure level
rows = []
for _, row in impact.iterrows():
try:
fnames = ast.literal_eval(str(row.get("file_names", "[]")))
fig_descs = ast.literal_eval(str(row.get("fig_desc", "[]")))
except Exception:
fnames, fig_descs = [], []
base = {k: v for k, v in row.items()
if k not in ("file_names", "fig_desc")}
if not fnames:
rows.append({**base, "figure_number": 0, "image_filename": ""})
else:
for i, fn in enumerate(fnames):
rows.append({**base, "figure_number": i, "image_filename": fn})
df = pd.DataFrame(rows)
df.rename(columns={"id": "patent_id", "title": "patent_title"}, inplace=True)
print(f" Exploded: {len(df):,} figures")
# Download + extract PatentsView text tables
text_tables = {}
for tname, url_tpl in PATENTSVIEW_URLS.items():
if tname == "patent_meta":
url = url_tpl
else:
url = url_tpl.format(year=year)
zip_dest = work_dir / url.split("/")[-1]
try:
download_file(url, zip_dest)
tsv = extract_7z(zip_dest, work_dir / tname)
if tsv:
text_tables[tname] = pd.read_csv(tsv, sep="\t", dtype=str, low_memory=False)
print(f" {tname}: {len(text_tables[tname]):,} rows")
zip_dest.unlink() # free space immediately
except Exception as e:
print(f" Skipping {tname}: {e}")
# Join text tables
for canonical, (tname, tcol) in {
"drawing_description": ("drawing_desc", "draw_desc_text"),
"detailed_description": ("detail_desc", "detail_desc_text"),
"brief_summary": ("brf_sum", "brf_sum_text"),
"claims": ("claims", "claims_text"),
}.items():
tdf = text_tables.get(tname, pd.DataFrame())
if not tdf.empty and tcol in tdf.columns:
tdf = tdf.rename(columns={"patent_id": "patent_id"})
agg = agg_text(tdf, "patent_id", tcol).rename(columns={tcol: canonical})
df = df.merge(agg, on="patent_id", how="left")
df[canonical] = df.get(canonical, pd.Series("")).fillna("")
# Patent metadata
meta = text_tables.get("patent_meta", pd.DataFrame())
if not meta.empty:
meta_cols = ["patent_id"] + [c for c in ["patent_date","patent_type"] if c in meta.columns]
df = df.merge(meta[meta_cols].drop_duplicates("patent_id"), on="patent_id", how="left")
df["year"] = int(year)
return df
# ── Embedding via HF endpoint ────────────────────────────────────────────────
def embed_year_via_endpoint(year: str, df: pd.DataFrame, endpoint_url: str,
zip_path: str, work_dir: Path) -> pd.DataFrame:
"""Embed all figures using the running HF Inference Endpoint."""
import base64
import io
import zipfile
import numpy as np
from PIL import Image
def encode_img(img_bytes):
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
w, h = img.size
scale = min(224 / max(w, h), 1.0)
if scale < 1.0:
img = img.resize((int(w*scale), int(h*scale)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=85)
return base64.standard_b64encode(buf.getvalue()).decode()
def post_batch(b64s):
for attempt in range(4):
try:
r = requests.post(endpoint_url, headers={**HF_HEADERS, "Content-Type":"application/json"},
json={"inputs": b64s}, timeout=60)
if r.status_code == 200:
data = r.json()
if isinstance(data, list) and data and isinstance(data[0], list):
if isinstance(data[0][0], float):
return data
if isinstance(data[0][0], list):
return [d[0] for d in data]
except Exception:
pass
time.sleep(2 ** attempt)
return None
all_ids, all_vecs = [], []
batch_imgs, batch_ids = [], []
def flush():
if not batch_imgs:
return
vecs = post_batch(batch_imgs)
if vecs:
all_ids.extend(batch_ids)
all_vecs.extend(vecs)
batch_imgs.clear(); batch_ids.clear()
with zipfile.ZipFile(zip_path) as zf:
for _, row in tqdm(df.iterrows(), total=len(df), desc=f"Embedding {year}"):
fn = str(row.get("image_filename",""))
parts = fn.split("-D0")
if len(parts) < 2:
continue
inner = f"{year}/{parts[0]}/{fn}"
try:
with zf.open(inner) as f:
img_bytes = f.read()
batch_ids.append(f"{row['patent_id']}_{row['figure_number']}")
batch_imgs.append(encode_img(img_bytes))
if len(batch_imgs) >= 32:
flush()
except Exception:
continue
flush()
print(f" Embedded: {len(all_ids):,} figures")
if not all_ids:
return pd.DataFrame()
vecs = np.array(all_vecs, dtype=np.float32)
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
vecs /= np.maximum(norms, 1e-8)
return pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
# ── Year processing ──────────────────────────────────────────────────────────
def process_year_full(year: str, endpoint_url: str | None, text_only: bool):
api = HfApi(token=HF_TOKEN)
with tempfile.TemporaryDirectory() as tmpdir:
work = Path(tmpdir)
print(f"\n{'='*50}")
print(f"Processing year {year}")
print(f"{'='*50}")
# Text enrichment
df = enrich_year(year, work)
# Save enriched parquet
out_parquet = work / f"enriched_{year}.parquet"
df.to_parquet(out_parquet, index=False)
size_mb = out_parquet.stat().st_size / 1e6
print(f" Enriched parquet: {size_mb:.0f}MB, {len(df):,} rows")
api.upload_file(
path_or_fileobj=str(out_parquet),
path_in_repo=f"data/enriched_{year}.parquet",
repo_id=OUT_REPO, repo_type="dataset",
commit_message=f"Add enriched parquet for {year}",
)
print(f" Pushed enriched_{year}.parquet → HF")
if text_only or not endpoint_url:
print(" Skipping embedding (--text-only or no endpoint URL)")
return
# Download images zip
print(f" Downloading IMPACT {year} images (~4.4GB)...")
zip_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
repo_type="dataset", token=HF_TOKEN, local_dir=tmpdir,
)
# Embed
emb_df = embed_year_via_endpoint(year, df, endpoint_url, zip_path, work)
if emb_df.empty:
print(" No embeddings produced")
return
out_emb = work / f"embeddings_{year}_vitl14.parquet"
emb_df.to_parquet(out_emb, index=False)
api.upload_file(
path_or_fileobj=str(out_emb),
path_in_repo=f"embeddings/embeddings_{year}_vitl14.parquet",
repo_id=OUT_REPO, repo_type="dataset",
commit_message=f"Add CLIP embeddings for {year}",
)
print(f" Pushed embeddings_{year}_vitl14.parquet → HF")
print(f" Year {year} complete.")
# ── CLI ──────────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--years", default="2022",
help="Year or range: '2022', '2018-2022', '2007-2022'")
parser.add_argument("--endpoint-url", default=None,
help="Running HF Inference Endpoint URL (skips creation)")
parser.add_argument("--text-only", action="store_true",
help="Only do text enrichment, skip embedding")
parser.add_argument("--out-repo", default=OUT_REPO)
args = parser.parse_args()
# Parse year range
if "-" in args.years and args.years.count("-") == 1:
start, end = args.years.split("-")
years = [str(y) for y in range(int(start), int(end)+1)]
else:
years = [args.years]
print(f"Processing years: {years}")
print(f"Text only: {args.text_only}")
print(f"Endpoint: {args.endpoint_url or '(none — text only)'}")
for year in reversed(years): # newest first
process_year_full(year, args.endpoint_url, args.text_only)
print("\nAll years complete.")
if __name__ == "__main__":
main()
|