patent-wireframes / scripts /cloud /process_year_modal.py
midah's picture
Add Modal full-corpus processing job
69770c7 verified
"""Process one IMPACT year: download, enrich, embed, push to HF Hub.
Runs on Modal GPU — no local disk used. Each year is ~4-5GB of images,
~2GB of text. Modal ephemeral storage handles it; everything is deleted
when the job exits.
Pipeline per year:
1. Download IMPACT year.zip + CSV from HF (images + metadata)
2. Download PatentsView text TSVs from S3 (draw_desc, detail_desc, patent meta)
3. Extract text TSVs with 7za (handles deflate64)
4. Join: IMPACT metadata × PatentsView text → enriched parquet
5. Run CLIP ViT-L/14 on GPU → embeddings parquet
6. Push both parquets to midah/patent-wireframes on HF Hub
7. Exit — ephemeral storage is cleared automatically
Safety:
- Idempotent: checks HF Hub before downloading anything
- One year at a time — run sequentially to verify, then parallelize
- Never touches local machine disk
Setup (one-time on any networked machine):
pip install modal
modal setup
modal secret create hf-secret HF_TOKEN=hf_...
Run one year (verify first):
modal run scripts/cloud/process_year_modal.py --year 2021
Run all years sequentially:
for year in 2022 2021 2020 2019 2018 2017 2016 2015 2014 2013 2012 2011 2010 2009 2008 2007; do
modal run scripts/cloud/process_year_modal.py --year $year
done
Run all years in parallel (after verifying one year works):
modal run scripts/cloud/process_year_modal.py --all-years
"""
import io
import os
import re
import subprocess
from pathlib import Path
import modal
# ── Modal image ───────────────────────────────────────────────────────────────
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("p7zip-full") # for deflate64 extraction
.pip_install(
"open_clip_torch",
"huggingface_hub>=0.23",
"datasets",
"Pillow",
"pandas",
"numpy",
"tqdm",
"requests",
)
)
app = modal.App("patent-process-year", image=image)
hf_secret = modal.Secret.from_name("hf-secret")
PATENTSVIEW_URLS = {
"draw_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_URL = "https://s3.amazonaws.com/data.patentsview.org/download/g_patent.tsv.zip"
HF_REPO = "midah/patent-wireframes"
BATCH_SIZE = 64
# ── helpers ───────────────────────────────────────────────────────────────────
def already_on_hub(year: int, token: str) -> bool:
"""Check if this year's outputs are already on HF Hub."""
from huggingface_hub import list_repo_files
files = set(list_repo_files(HF_REPO, repo_type="dataset", token=token))
enriched = f"data/enriched_{year}.parquet"
embeddings = f"embeddings/embeddings_{year}_vitl14.parquet"
if enriched in files and embeddings in files:
print(f"Year {year}: already on Hub, skipping.")
return True
return False
def download_file(url: str, dest: Path, chunk_size: int = 8 * 1024 * 1024) -> Path:
import requests
print(f" Downloading {url.split('/')[-1]}...")
r = requests.get(url, stream=True, timeout=120)
r.raise_for_status()
with open(dest, "wb") as f:
for chunk in r.iter_content(chunk_size=chunk_size):
f.write(chunk)
size_mb = dest.stat().st_size / 1e6
print(f" → {dest.name} ({size_mb:.0f}MB)")
return dest
def extract_zip(zip_path: Path, out_dir: Path) -> Path | None:
"""Extract using 7za (handles deflate64 that Python zipfile can't)."""
out_dir.mkdir(parents=True, exist_ok=True)
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[:200]}")
return None
tsv_files = list(out_dir.glob("*.tsv"))
if tsv_files:
print(f" Extracted: {tsv_files[0].name} ({tsv_files[0].stat().st_size/1e6:.0f}MB)")
return tsv_files[0]
return None
# ── core processing ───────────────────────────────────────────────────────────
@app.function(
gpu="A10G",
timeout=7200, # 2 hours max per year
memory=32768, # 32GB RAM
ephemeral_disk=51200, # 50GB ephemeral disk
secrets=[hf_secret],
)
def process_year(year: int) -> dict:
import ast
import csv
import zipfile
import numpy as np
import open_clip
import pandas as pd
import torch
from huggingface_hub import HfApi, hf_hub_download
from PIL import Image
from tqdm import tqdm
token = os.environ["HF_TOKEN"]
api = HfApi(token=token)
work = Path(f"/tmp/patent_{year}")
work.mkdir(exist_ok=True)
print(f"\n{'='*50}")
print(f"Processing year {year}")
print(f"{'='*50}")
# ── 0. Idempotency check ─────────────────────────────────────────────────
if already_on_hub(year, token):
return {"year": year, "status": "skipped"}
# ── 1. Download IMPACT metadata CSV ─────────────────────────────────────
print("\n[1/5] IMPACT metadata...")
csv_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
repo_type="dataset", token=token, local_dir=str(work)
)
impact_df = pd.read_csv(csv_path)
print(f" {len(impact_df):,} patents")
# Explode to figure level
rows = []
for _, row in impact_df.iterrows():
try:
fnames = ast.literal_eval(str(row["file_names"]))
fig_descs = ast.literal_eval(str(row["fig_desc"])) if pd.notna(row.get("fig_desc")) else []
except Exception:
continue
for i, fname in enumerate(fnames):
rows.append({
"patent_id": "D" + str(row["id"]).replace("D","").lstrip("0").zfill(7),
"figure_number": i,
"image_filename": fname,
"patent_title": row.get("title",""),
"caption": row.get("caption",""),
"class": row.get("class",""),
"year": year,
})
df = pd.DataFrame(rows)
print(f" Exploded to {len(df):,} figures")
# ── 2. Download PatentsView text TSVs ────────────────────────────────────
print("\n[2/5] PatentsView text tables...")
pv_dir = work / "patentsview"
pv_dir.mkdir(exist_ok=True)
text_dfs = {}
for table, url_template in PATENTSVIEW_URLS.items():
url = url_template.format(year=year)
zip_path = pv_dir / url.split("/")[-1]
try:
download_file(url, zip_path)
tsv_path = extract_zip(zip_path, pv_dir / table)
if tsv_path:
tdf = pd.read_csv(tsv_path, sep="\t", dtype=str, low_memory=False)
tdf["patent_id"] = tdf["patent_id"].apply(
lambda x: "D" + str(x).replace("D","").lstrip("0").zfill(7)
)
text_dfs[table] = tdf
zip_path.unlink() # free space immediately
except Exception as e:
print(f" {table}: skipped ({e})")
# Patent metadata (year-independent, check if already fetched)
meta_path = pv_dir / "g_patent.tsv"
if not meta_path.exists():
try:
zip_path = pv_dir / "g_patent.tsv.zip"
download_file(PATENT_META_URL, zip_path)
extract_zip(zip_path, pv_dir)
zip_path.unlink()
except Exception as e:
print(f" patent meta: skipped ({e})")
# ── 3. Join ──────────────────────────────────────────────────────────────
print("\n[3/5] Joining text tables...")
col_map = {
"draw_desc": ("draw_desc_text", "drawing_description"),
"detail_desc": ("detail_desc_text", "detailed_description"),
"brf_sum": ("brf_sum_text", "brief_summary"),
"claims": ("claims_text", "claims"),
}
for table, (src_col, dst_col) in col_map.items():
tdf = text_dfs.get(table, pd.DataFrame())
if not tdf.empty and src_col in tdf.columns:
agg = (tdf.groupby("patent_id")[src_col]
.apply(lambda x: "\n".join(x.dropna().astype(str)))
.reset_index().rename(columns={src_col: dst_col}))
df = df.merge(agg, on="patent_id", how="left")
df[dst_col] = df[dst_col].fillna("")
else:
df[dst_col] = ""
filled = (df[dst_col] != "").sum()
print(f" {dst_col}: {filled:,}/{len(df):,} filled")
# Merge patent metadata
meta_path = pv_dir / "g_patent.tsv"
if meta_path.exists():
meta = pd.read_csv(meta_path, sep="\t", dtype=str, low_memory=False)
meta["patent_id"] = meta["patent_id"].apply(
lambda x: "D" + str(x).replace("D","").lstrip("0").zfill(7)
)
for col in ["patent_date", "patent_type"]:
if col in meta.columns:
df = df.merge(meta[["patent_id", col]].drop_duplicates("patent_id"),
on="patent_id", how="left")
# Figure ID + siblings
df["figure_id"] = df["patent_id"] + "_" + df["figure_number"].astype(str)
patent_groups = df.groupby("patent_id")["figure_id"].apply(list).to_dict()
df["n_figures_in_patent"] = df["patent_id"].map(df.groupby("patent_id").size())
df["sibling_figure_ids"] = df.apply(
lambda r: [f for f in patent_groups[r["patent_id"]] if f != r["figure_id"]],
axis=1
)
# ── 4. CLIP embeddings ───────────────────────────────────────────────────
print("\n[4/5] CLIP embeddings...")
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f" Device: {device}")
model, _, preprocess = open_clip.create_model_and_transforms(
"ViT-L-14", pretrained="openai"
)
model = model.to(device).eval()
# Download IMPACT zip
print(" Downloading IMPACT images (~4-5GB)...")
zip_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
repo_type="dataset", token=token, local_dir=str(work)
)
print(f" Zip: {Path(zip_path).stat().st_size/1e9:.1f}GB")
all_ids, all_vecs = [], []
def load_image(fname: str) -> Image.Image | None:
parts = fname.split("-D0")
if len(parts) < 2:
return None
inner = f"{year}/{parts[0]}/{fname}"
try:
with zipfile.ZipFile(zip_path) as z:
with z.open(inner) as f:
return Image.open(io.BytesIO(f.read())).convert("RGB")
except Exception:
return None
batch_imgs, batch_ids = [], []
def flush():
if not batch_imgs:
return
tensors = torch.stack([preprocess(im) for im in batch_imgs]).to(device)
with torch.no_grad():
feats = model.encode_image(tensors)
feats = feats / feats.norm(dim=-1, keepdim=True)
all_vecs.append(feats.cpu().numpy())
all_ids.extend(batch_ids)
batch_imgs.clear()
batch_ids.clear()
for _, row in tqdm(df.iterrows(), total=len(df), desc=" Embedding"):
img = load_image(row["image_filename"])
if img is None:
continue
batch_imgs.append(img)
batch_ids.append(row["figure_id"])
if len(batch_imgs) >= BATCH_SIZE:
flush()
flush()
vecs = np.vstack(all_vecs).astype(np.float32)
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
vecs /= np.maximum(norms, 1e-8)
print(f" Embedded {len(all_ids):,} figures, shape {vecs.shape}")
emb_df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
# ── 5. Push to Hub ───────────────────────────────────────────────────────
print("\n[5/5] Pushing to HF Hub...")
enriched_path = work / f"enriched_{year}.parquet"
df.to_parquet(enriched_path, index=False)
api.upload_file(
path_or_fileobj=str(enriched_path),
path_in_repo=f"data/enriched_{year}.parquet",
repo_id=HF_REPO, repo_type="dataset",
commit_message=f"Add enriched_{year}.parquet ({len(df):,} figures)"
)
print(f" Pushed data/enriched_{year}.parquet")
emb_path = work / f"embeddings_{year}_vitl14.parquet"
emb_df.to_parquet(emb_path, index=False)
api.upload_file(
path_or_fileobj=str(emb_path),
path_in_repo=f"embeddings/embeddings_{year}_vitl14.parquet",
repo_id=HF_REPO, repo_type="dataset",
commit_message=f"Add embeddings_{year}_vitl14.parquet"
)
print(f" Pushed embeddings/embeddings_{year}_vitl14.parquet")
return {
"year": year,
"status": "done",
"n_figures": len(df),
"n_embedded": len(all_ids),
}
# ── entrypoints ───────────────────────────────────────────────────────────────
@app.local_entrypoint()
def main(year: int = 2021, all_years: bool = False):
"""
Test with one year first:
modal run scripts/cloud/process_year_modal.py --year 2021
Then run all years:
modal run scripts/cloud/process_year_modal.py --all-years
"""
if all_years:
years = list(range(2007, 2023)) # 2007–2022
print(f"Processing all {len(years)} years: {years}")
# Sequential for safety — can switch to .map() after verifying one year
for y in years:
result = process_year.remote(y)
print(f"Year {y}: {result}")
else:
print(f"Processing year {year} (test run)...")
result = process_year.remote(year)
print(f"Result: {result}")