File size: 12,512 Bytes
41af2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f94f27
 
 
 
 
41af2b1
 
 
 
8f94f27
 
 
 
 
 
 
 
 
 
 
 
 
 
53edeff
8f94f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53edeff
 
 
 
 
 
 
 
 
 
 
 
41af2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f94f27
 
41af2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)