patent-wireframes / scripts /cloud /patentsview_pipeline.py
midah's picture
Reorganize: scripts/cloud/patentsview_pipeline.py
7392570 verified
Raw
History Blame Contribute Delete
7.43 kB
"""Download, extract, and join PatentsView text files — no local storage.
Runs on any machine with network access. Downloads PatentsView text TSVs,
extracts with 7-zip (deflate64), joins with IMPACT, pushes enriched parquet
to HF Hub. Nothing stays on the local machine.
Requirements:
pip install huggingface_hub requests pandas tqdm
brew install p7zip (macOS) or apt install p7zip-full (Linux)
Usage:
export HF_TOKEN=hf_...
python scripts/cloud/patentsview_pipeline.py --year 2022
"""
import argparse
import os
import subprocess
import tempfile
from pathlib import Path
import pandas as pd
import requests
from huggingface_hub import HfApi, hf_hub_download
from tqdm import tqdm
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",
"brief_summary": "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 # 8MB download chunks
def download_file(url: str, dest: Path) -> Path:
if dest.exists():
print(f" Cached: {dest.name}")
return dest
print(f" Downloading {dest.name}...")
r = requests.get(url, stream=True, timeout=60)
r.raise_for_status()
total = int(r.headers.get("content-length", 0))
with open(dest, "wb") as f:
with tqdm(total=total, unit="B", unit_scale=True, desc=f" {dest.name}") as pbar:
for chunk in r.iter_content(chunk_size=CHUNK):
f.write(chunk)
pbar.update(len(chunk))
return dest
def extract_deflate64(zip_path: Path, out_dir: Path) -> Path | None:
"""Extract using 7-zip (handles deflate64 that Python's zipfile can't)."""
result = subprocess.run(
["7z", "x", str(zip_path), f"-o{out_dir}", "-y"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(f" 7z failed: {result.stderr[:200]}")
return None
# Find the extracted TSV
tsv_files = list(out_dir.glob("*.tsv"))
return tsv_files[0] if tsv_files else None
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--year", default="2022")
parser.add_argument("--out-repo", default="midah/patent-wireframes")
parser.add_argument("--out-file", default="enriched_{year}_full.parquet")
args = parser.parse_args()
token = os.environ.get("HF_TOKEN")
if not token:
raise RuntimeError("Set HF_TOKEN")
year = args.year
out_file = args.out_file.format(year=year)
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
print(f"Working directory: {tmp}")
# ── Download and extract PatentsView tables ───────────────────────────
tables = {}
for table_name, url_template in PATENTSVIEW_URLS.items():
url = url_template.format(year=year)
zip_dest = tmp / url.split("/")[-1]
zip_path = download_file(url, zip_dest)
print(f" Extracting {zip_path.name}...")
tsv_path = extract_deflate64(zip_path, tmp / table_name)
if tsv_path:
tables[table_name] = pd.read_csv(tsv_path, sep="\t", dtype=str, low_memory=False)
print(f" {table_name}: {len(tables[table_name]):,} rows")
zip_path.unlink() # free space immediately
else:
print(f" WARNING: could not extract {table_name}")
tables[table_name] = pd.DataFrame()
# ── Download existing enriched parquet from Hub ───────────────────────
print("\nDownloading existing enriched parquet from HF Hub...")
try:
base_parquet = hf_hub_download(
repo_id=args.out_repo,
filename=f"enriched_{year}.parquet",
repo_type="dataset",
token=token,
)
df = pd.read_parquet(base_parquet)
print(f" Loaded {len(df):,} rows")
except Exception:
print(" No existing parquet — starting from IMPACT CSV")
impact_csv = hf_hub_download(
repo_id="AI4Patents/IMPACT",
filename=f"{year}.csv",
repo_type="dataset",
token=token,
)
df = pd.read_csv(impact_csv)
print(f" Loaded {len(df):,} rows from IMPACT CSV")
# ── Join text tables ──────────────────────────────────────────────────
def agg_text(tdf: pd.DataFrame, id_col: str, text_col: str) -> pd.DataFrame:
if tdf.empty or text_col not in tdf.columns:
return pd.DataFrame(columns=[id_col, text_col])
return (
tdf.groupby(id_col)[text_col]
.apply(lambda x: "\n".join(x.dropna().astype(str)))
.reset_index()
)
id_col = "patent_id" if "patent_id" in df.columns else "id"
df[id_col] = df[id_col].astype(str)
for canonical, (tname, tcol) in {
"detailed_description": ("detail_desc", "detail_desc_text"),
"brief_summary": ("brief_summary", "brf_sum_text"),
"claims": ("claims", "claims_text"),
}.items():
tdf = tables.get(tname, pd.DataFrame())
if not tdf.empty and tcol in tdf.columns:
tdf[id_col] = tdf[id_col].astype(str)
agg = agg_text(tdf, id_col, tcol).rename(columns={tcol: canonical})
df = df.merge(agg, on=id_col, how="left")
df[canonical] = df[canonical].fillna("")
print(f" Joined {canonical}: {(df[canonical] != '').sum():,} non-empty")
# Patent metadata (date, type)
meta = tables.get("patent_meta", pd.DataFrame())
if not meta.empty:
meta[id_col] = meta[id_col].astype(str)
meta_cols = [id_col] + [c for c in ["patent_date","patent_type","wipo_kind"] if c in meta.columns]
df = df.merge(meta[meta_cols].drop_duplicates(id_col), on=id_col, how="left")
print(f" Joined patent_meta: {df['patent_date'].notna().sum():,} dates")
# ── Push to Hub ───────────────────────────────────────────────────────
out_path = tmp / out_file
df.to_parquet(out_path, index=False)
size_mb = out_path.stat().st_size / 1e6
print(f"\nSaving {size_mb:.1f}MB parquet ({len(df):,} rows)...")
api = HfApi(token=token)
api.upload_file(
path_or_fileobj=str(out_path),
path_in_repo=out_file,
repo_id=args.out_repo,
repo_type="dataset",
)
print(f"Pushed → hf://datasets/{args.out_repo}/{out_file}")
if __name__ == "__main__":
main()