patent-wireframes / scripts /cloud /extend_to_2026.py
midah's picture
Fix ODP API: correct endpoint + API key + response parsing
8f94f27 verified
Raw
History Blame Contribute Delete
12.5 kB
"""Extend IMPACT dataset to 2023–2025 using USPTO bulk grant data.
USPTO publishes "Patent Grant Full Text Data with Embedded TIFF Images"
weekly at data.uspto.gov — design patents (kind code 'S') with TIF figures
embedded as base64 in the XML. This script processes those weekly tars
and produces IMPACT-compatible outputs (year.csv + year.zip) pushed to HF Hub.
Run via Modal for GPU + ephemeral storage (no local disk needed):
modal run scripts/cloud/extend_to_2026.py --year 2023
Or run locally (needs ~10GB free per year):
python scripts/cloud/extend_to_2026.py --year 2023 --local
Output on HF Hub (midah/patent-wireframes):
data/impact_extension/{year}.csv — IMPACT-compatible metadata CSV
data/impact_extension/{year}.zip — figure TIF images (same format as IMPACT)
data/enriched_{year}.parquet — enriched with PatentsView text
"""
import argparse
import ast
import base64
import csv
import io
import os
import re
import subprocess
import tarfile
import tempfile
import zipfile
from pathlib import Path
import modal
import requests
# ── Modal setup ───────────────────────────────────────────────────────────────
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("p7zip-full", "libxml2-dev", "libxslt-dev")
.pip_install("lxml", "huggingface_hub", "pandas", "tqdm", "requests")
)
app = modal.App("patent-extend-2026", image=image)
hf_secret = modal.Secret.from_name("hf-secret")
# USPTO ODP base URL for PTGRDT (Grant Full Text with Embedded Images)
# USPTO ODP API (correct endpoint post March 2026 migration)
# Base: api.uspto.gov/api/v1/ (note: api.uspto.gov, NOT data.uspto.gov)
# API key required — obtain free at: https://developer.uspto.gov/api-catalog
ODP_SEARCH = "https://api.uspto.gov/api/v1/datasets/products/search"
ODP_PRODUCT = "https://api.uspto.gov/api/v1/datasets/products/{product_id}"
# ── USPTO weekly file list ────────────────────────────────────────────────────
def get_weekly_files(year: str, session: requests.Session,
api_key: str | None = None) -> list[dict]:
"""List all weekly tar files for a given year from USPTO ODP API.
Requires a free USPTO ODP API key from https://developer.uspto.gov/api-catalog
Set USPTO_API_KEY in .env to enable.
"""
if not api_key:
print(f" No USPTO_API_KEY set — cannot query ODP API for {year}")
print(" Get a free key at: https://developer.uspto.gov/api-catalog")
return []
# Search for PTGRDT product files in the given date range
headers = {"Accept": "application/json", "X-Api-Key": api_key}
try:
r = session.get(
ODP_SEARCH,
params={
"productIdentifier": "PTGRDT",
"fileDataFromDate": f"{year}-01-01",
"fileDataToDate": f"{year}-12-31",
},
headers=headers,
timeout=30,
)
if r.status_code == 200 and r.text.strip():
data = r.json()
products = data.get("bulkDataProductBag", [[]])[0] if data.get("bulkDataProductBag") else []
for product in (products if isinstance(products, list) else [products]):
file_bag = product.get("productFileBag", {})
file_data = file_bag.get("fileDataBag", [])
tar_files = [f for f in file_data
if isinstance(f, dict) and
f.get("fileName", "").endswith(".tar")]
if tar_files:
return [{"filename": f["fileName"], "url": f["fileDownloadURI"]}
for f in sorted(tar_files, key=lambda x: x["fileName"])]
except Exception as e:
print(f" ODP API error: {e}")
# Fallback: try direct ODP URL listing
try:
base = USPTO_BASE.format(year=year)
r = session.get(base, timeout=30)
if r.status_code == 200:
tars = re.findall(rf'href="(I{year}\d{{4}}[^"]*\.tar)"', r.text)
return [{"filename": t, "url": base + t} for t in sorted(tars)]
except Exception:
pass
return []
# ── XML parsing ───────────────────────────────────────────────────────────────
def extract_design_patents(xml_bytes: bytes, week_date: str) -> list[dict]:
"""Parse USPTO grant XML, extract design patents with their figure TIFs."""
from lxml import etree
results = []
# Each weekly file concatenates many XML documents — split on patent boundary
# The separator is `<?xml version="1.0"...` or `<us-patent-grant`
sections = re.split(rb'(?=<us-patent-grant[ >])', xml_bytes)
for section in sections:
if not section.strip():
continue
try:
# Wrap in root if needed
if not section.startswith(b'<us-patent-grant'):
continue
root = etree.fromstring(b'<root>' + section + b'</root>')
grant = root.find('us-patent-grant')
if grant is None:
grant = root
# Check kind code — design patents are kind 'S' or 'S1' or 'S2'
kind = grant.findtext('.//kind-code') or grant.findtext('.//kind') or ''
if not kind.startswith('S'):
continue
# Patent ID
doc_num = grant.findtext('.//doc-number') or ''
if not doc_num.startswith('D'):
doc_num = 'D' + doc_num
patent_id = doc_num.strip()
# Metadata
title = grant.findtext('.//invention-title') or ''
date = grant.findtext('.//publication-date') or week_date
if len(date) == 8: # YYYYMMDD -> YYYY-MM-DD
date = f"{date[:4]}-{date[4:6]}-{date[6:8]}"
# Locarno class from US classification
locarno = grant.findtext('.//classification-locarno/main-classification') or ''
# Figure descriptions from drawings description
fig_descs = []
for p in grant.findall('.//description-of-drawings//p'):
text = ''.join(p.itertext()).strip()
if text:
fig_descs.append(text)
# Extract embedded TIF images
figures = []
fig_num = 0
for img in grant.findall('.//img'):
img_format = img.get('img-format', '').lower()
img_content = img.get('img-content', '').lower()
if 'tif' not in img_format and 'drawing' not in img_content:
continue
b64_data = img.text or ''
if not b64_data.strip():
continue
try:
tif_bytes = base64.b64decode(b64_data.strip())
filename = f"{patent_id}-{date.replace('-','')}-D{fig_num:05d}.TIF"
figures.append({"filename": filename, "data": tif_bytes})
fig_num += 1
except Exception:
continue
if not figures:
continue
results.append({
"id": patent_id,
"title": title,
"date": date.replace('-', ''),
"class": locarno,
"no_figs": len(figures),
"fig_desc": str([f["filename"] for f in figures]), # filenames list
"figures": figures,
})
except Exception:
continue
return results
# ── Modal function ────────────────────────────────────────────────────────────
@app.function(
gpu=None, # CPU-only for extraction; GPU not needed
timeout=7200, # 2hr — processing a full year
memory=8192,
secrets=[hf_secret],
)
def process_year(year: str, out_repo: str = "midah/patent-wireframes") -> dict:
import pandas as pd
from huggingface_hub import HfApi
from tqdm import tqdm
token = os.environ["HF_TOKEN"]
api = HfApi(token=token)
session = requests.Session()
print(f"Processing year {year}...")
api_key = os.environ.get("USPTO_API_KEY")
weekly_files = get_weekly_files(year, session, api_key=api_key)
print(f"Found {len(weekly_files)} weekly files")
if not weekly_files:
print("No files found — check USPTO ODP availability for this year")
return {}
# Work in temp dir
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
all_patents = []
zip_out = tmp / f"{year}.zip"
with zipfile.ZipFile(zip_out, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
for wf in tqdm(weekly_files, desc=f"Processing {year} weeks"):
week_date = re.search(r'I(\d{8})', wf['filename'])
week_date = week_date.group(1) if week_date else year + '0101'
# Download tar
tar_path = tmp / wf['filename']
try:
r = session.get(wf['url'], stream=True, timeout=120)
r.raise_for_status()
with open(tar_path, 'wb') as f:
for chunk in r.iter_content(65536):
f.write(chunk)
except Exception as e:
print(f" Failed {wf['filename']}: {e}")
continue
# Extract XML from tar
try:
with tarfile.open(tar_path) as tf:
xml_files = [m for m in tf.getmembers()
if m.name.endswith('.xml') and not m.name.startswith('._')]
for xml_member in xml_files:
with tf.extractfile(xml_member) as xf:
xml_bytes = xf.read()
patents = extract_design_patents(xml_bytes, week_date)
for pat in patents:
# Add TIFs to zip
for fig in pat['figures']:
zf.writestr(
f"{year}/{pat['id']}-{pat['date']}/{fig['filename']}",
fig['data']
)
# Clean up data before storing metadata
pat_meta = {k: v for k, v in pat.items() if k != 'figures'}
pat_meta['file_names'] = str([f['filename'] for f in pat['figures']])
all_patents.append(pat_meta)
tar_path.unlink()
except Exception as e:
print(f" Error processing {wf['filename']}: {e}")
tar_path.unlink(missing_ok=True)
print(f"Extracted {len(all_patents)} design patents, "
f"{sum(p['no_figs'] for p in all_patents)} figures")
if not all_patents:
return {"patents": 0, "figures": 0}
# Save CSV
csv_out = tmp / f"{year}.csv"
df = pd.DataFrame(all_patents)
df = df.drop(columns=['figures'], errors='ignore')
df.to_csv(csv_out, index=False)
# Push to HF Hub
for local, remote in [
(csv_out, f"data/impact_extension/{year}.csv"),
(zip_out, f"data/impact_extension/{year}.zip"),
]:
api.upload_file(
path_or_fileobj=str(local),
path_in_repo=remote,
repo_id=out_repo,
repo_type="dataset",
commit_message=f"Add USPTO extension for {year}: {remote}",
)
print(f"Pushed {remote}")
return {
"year": year,
"patents": len(all_patents),
"figures": sum(p['no_figs'] for p in all_patents),
}
@app.local_entrypoint()
def main(year: str = "2023"):
print(f"Processing USPTO extension for year: {year}")
result = process_year.remote(year)
print("Result:", result)