patent-wireframes / scripts /cloud /create_hf_endpoint.py
midah's picture
Add scripts/cloud/create_hf_endpoint.py
337c768 verified
"""Create, use, and delete an HF Inference Endpoint for CLIP embedding.
Creates a temporary dedicated endpoint for batch CLIP embedding,
processes all images from the IMPACT dataset, pushes embeddings
to HF Hub, then deletes the endpoint.
Cost estimate:
DesignCLIP / ViT-L-14 on T4: ~$0.08/hr
103k images (2022) at batch=64: ~25 min = ~$0.03
3.61M images (all years) at batch=64: ~15 hrs = ~$1.20 total
Usage:
export HF_TOKEN=hf_...
python scripts/cloud/create_hf_endpoint.py \
--year 2022 \
--model openai/clip-vit-large-patch14 \
--instance-type aws-us-east-1-t4g-small \
--out-repo midah/patent-wireframes
"""
import argparse
import base64
import io
import os
import time
from pathlib import Path
import requests
from dotenv import load_dotenv
load_dotenv(".env")
HF_ENDPOINTS_API = "https://api.endpoints.huggingface.cloud/v2/endpoint"
HF_TOKEN = os.environ.get("HF_TOKEN")
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
# ── Endpoint lifecycle ────────────────────────────────────────────────────────
def create_endpoint(name: str, model: str, instance_type: str) -> dict:
"""Create a dedicated inference endpoint for the given model."""
payload = {
"accountId": None,
"compute": {
"accelerator": "gpu" if "t4" in instance_type or "a10g" in instance_type else "cpu",
"instanceSize": instance_type.split("-")[-1] if "-" in instance_type else "large",
"instanceType": instance_type,
"scaling": {"maxReplica": 1, "minReplica": 1},
},
"model": {
"framework": "pytorch",
"image": {"huggingface": {"env": {}}},
"repository": model,
"revision": "main",
"task": "feature-extraction",
},
"name": name,
"provider": {"region": "us-east-1", "vendor": "aws"},
"type": "protected",
}
r = requests.post(
f"{HF_ENDPOINTS_API}/midah",
headers=HEADERS,
json=payload,
timeout=30,
)
r.raise_for_status()
return r.json()
def wait_for_endpoint(name: str, timeout: int = 600) -> str:
"""Poll until the endpoint is running. Returns the endpoint URL."""
start = time.time()
while time.time() - start < timeout:
r = requests.get(f"{HF_ENDPOINTS_API}/midah/{name}", headers=HEADERS, timeout=15)
r.raise_for_status()
data = r.json()
state = data.get("status", {}).get("state", "unknown")
url = data.get("status", {}).get("url", "")
print(f" State: {state} ({int(time.time()-start)}s elapsed)")
if state == "running":
return url
if state in ("failed", "scaledToZero"):
raise RuntimeError(f"Endpoint failed: {state}")
time.sleep(20)
raise TimeoutError("Endpoint did not start within timeout")
def delete_endpoint(name: str):
r = requests.delete(f"{HF_ENDPOINTS_API}/midah/{name}", headers=HEADERS, timeout=15)
if r.status_code not in (200, 204):
print(f" Warning: delete returned {r.status_code}")
else:
print(f" Deleted endpoint: {name}")
# ── Embedding via endpoint ────────────────────────────────────────────────────
def encode_image(img_bytes: bytes, max_edge: int = 224) -> str:
from PIL import Image
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
w, h = img.size
scale = min(max_edge / 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 embed_batch(endpoint_url: str, b64_images: list[str]) -> list[list[float]] | None:
"""Call the endpoint with a batch of base64 images."""
payload = {"inputs": b64_images}
for attempt in range(4):
try:
r = requests.post(
endpoint_url,
headers={**HEADERS, "Content-Type": "application/json"},
json=payload,
timeout=60,
)
if r.status_code == 200:
data = r.json()
# Response shape: list of embeddings or list of list of list
if isinstance(data, list) and data:
if isinstance(data[0], list) and isinstance(data[0][0], float):
return data # already [[float, ...], ...]
if isinstance(data[0], list) and isinstance(data[0][0], list):
return [d[0] for d in data] # [[[float]], ...]
return None
elif r.status_code in (429, 503):
time.sleep(2 ** attempt)
except Exception as e:
print(f" Batch error (attempt {attempt+1}): {e}")
time.sleep(2 ** attempt)
return None
# ── Main processing ───────────────────────────────────────────────────────────
def process_year(year: str, endpoint_url: str, out_repo: str, batch_size: int = 32):
"""Stream images from IMPACT and embed via the endpoint."""
import ast
import csv
import zipfile
import numpy as np
import pandas as pd
from huggingface_hub import HfApi, hf_hub_download
token = HF_TOKEN
api = HfApi(token=token)
print(f"\nDownloading IMPACT {year} CSV...")
csv_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
repo_type="dataset", token=token,
)
print(f"Downloading IMPACT {year} images zip (~4.4GB)...")
zip_path = hf_hub_download(
repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
repo_type="dataset", token=token,
)
# Build figure list
figures = []
with open(csv_path) as f:
for row in csv.DictReader(f):
try:
fnames = ast.literal_eval(row["file_names"])
pid = row["id"]
for i, fn in enumerate(fnames):
figures.append({"patent_id": pid, "figure_num": i, "filename": fn})
except Exception:
pass
print(f"Total figures: {len(figures):,}")
all_ids, all_vecs = [], []
n_failed = 0
# Process in batches using zip
with zipfile.ZipFile(zip_path) as zf:
batch_imgs, batch_ids = [], []
def flush():
nonlocal n_failed
if not batch_imgs:
return
vecs = embed_batch(endpoint_url, batch_imgs)
if vecs:
all_vecs.extend(vecs)
all_ids.extend(batch_ids)
else:
n_failed += len(batch_imgs)
batch_imgs.clear()
batch_ids.clear()
from tqdm import tqdm
for fig in tqdm(figures, desc=f"Embedding {year}"):
fn = fig["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()
b64 = encode_image(img_bytes)
pid = fig["patent_id"].lstrip("D").zfill(7)
batch_ids.append(f"D{pid}_{fig['figure_num']}")
batch_imgs.append(b64)
if len(batch_imgs) >= batch_size:
flush()
except Exception:
continue
flush()
print(f"Embedded: {len(all_ids):,} | Failed: {n_failed}")
if not all_ids:
print("No embeddings produced — check endpoint")
return
# Normalize and save
vecs = np.array(all_vecs, dtype=np.float32)
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
vecs /= np.maximum(norms, 1e-8)
df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
out_file = f"embeddings_{year}_vitl14.parquet"
local_out = Path(f"/tmp/{out_file}")
df.to_parquet(local_out, index=False)
size_mb = local_out.stat().st_size / 1e6
print(f"Parquet: {size_mb:.1f}MB")
api.upload_file(
path_or_fileobj=str(local_out),
path_in_repo=f"embeddings/{out_file}",
repo_id=out_repo,
repo_type="dataset",
commit_message=f"Add CLIP embeddings for {year}",
)
print(f"Pushed → hf://datasets/{out_repo}/embeddings/{out_file}")
local_out.unlink()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--year", default="2022")
parser.add_argument("--model", default="openai/clip-vit-large-patch14")
parser.add_argument("--instance-type", default="aws-us-east-1-t4g-small",
help="HF endpoint instance type. See: hf.co/docs/inference-endpoints")
parser.add_argument("--out-repo", default="midah/patent-wireframes")
parser.add_argument("--batch", type=int, default=32)
parser.add_argument("--keep-endpoint", action="store_true",
help="Don't delete endpoint after finishing (useful for multi-year runs)")
args = parser.parse_args()
if not HF_TOKEN:
raise RuntimeError("HF_TOKEN not set")
endpoint_name = f"patent-clip-{args.year}-{int(time.time())}"
endpoint_url = None
try:
print(f"Creating endpoint: {endpoint_name}")
print(f" Model: {args.model}")
print(f" Instance: {args.instance_type}")
data = create_endpoint(endpoint_name, args.model, args.instance_type)
print(f" Created. Waiting for running state...")
endpoint_url = wait_for_endpoint(endpoint_name)
print(f" Endpoint ready: {endpoint_url}")
process_year(args.year, endpoint_url, args.out_repo, args.batch)
finally:
if not args.keep_endpoint and endpoint_name:
print(f"\nCleaning up endpoint: {endpoint_name}")
delete_endpoint(endpoint_name)
if __name__ == "__main__":
main()