File size: 10,300 Bytes
337c768 | 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 | """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()
|