File size: 7,578 Bytes
2d1298e | 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 | """CLIP embedding via HF Inference API — no local GPU, no local image storage.
Streams images from IMPACT HF dataset one batch at a time, sends to
HF Inference API for feature extraction, accumulates embeddings in memory,
pushes final parquet to HF Hub.
Disk usage at any time: ~0 (images streamed, embeddings are ~30MB total).
Requirements (run from any machine with network access):
pip install huggingface_hub datasets requests pillow pandas numpy tqdm
Usage:
export HF_TOKEN=hf_...
python scripts/cloud/embed_hf_api.py \
--year 2022 \
--model openai/clip-vit-large-patch14 \
--out-repo midah/patent-wireframes \
--out-file embeddings_2022_vitl14.parquet \
--batch 8 \
--workers 4
"""
import argparse
import base64
import io
import json
import os
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import numpy as np
import pandas as pd
import requests
from datasets import load_dataset
from huggingface_hub import HfApi
from PIL import Image
from tqdm import tqdm
HF_INFERENCE_URL = "https://api-inference.huggingface.co/models/{model}"
def encode_image(img: Image.Image, max_edge: int = 224) -> str:
"""Resize and base64-encode an image for the inference API."""
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)
img = img.convert("RGB")
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=85)
return base64.standard_b64encode(buf.getvalue()).decode()
def get_embedding(b64: str, model: str, token: str, retries: int = 4) -> list[float] | None:
"""Call HF Inference API feature-extraction endpoint for one image."""
url = HF_INFERENCE_URL.format(model=model)
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
payload = {"inputs": {"image": b64}}
for attempt in range(retries):
try:
r = requests.post(url, headers=headers, json=payload, timeout=30)
if r.status_code == 200:
data = r.json()
# Response shape varies: [[...]] or [...]
vec = data[0] if isinstance(data[0], list) else data
return vec
elif r.status_code == 503:
# Model loading — wait and retry
wait = min(30, 5 * (2 ** attempt))
time.sleep(wait)
elif r.status_code == 429:
wait = 2 ** attempt
time.sleep(wait)
else:
return None
except Exception:
time.sleep(2 ** attempt)
return None
def stream_and_embed(
year: str,
model: str,
token: str,
batch_size: int,
workers: int,
max_images: int | None,
) -> tuple[list[str], np.ndarray]:
"""Stream IMPACT dataset and embed all figures."""
print(f"Loading IMPACT {year} metadata...")
# Load metadata (CSV) — small, no images
import csv, ast, zipfile
from huggingface_hub import hf_hub_download
csv_path = hf_hub_download(
repo_id="AI4Patents/IMPACT",
filename=f"{year}.csv",
repo_type="dataset",
token=token,
)
rows = []
with open(csv_path) as f:
reader = csv.DictReader(f)
for row in reader:
try:
fnames = ast.literal_eval(row["file_names"])
patent_id = row["id"]
for fname in fnames:
rows.append({"patent_id": patent_id, "image_filename": fname})
except Exception:
pass
if max_images:
rows = rows[:max_images]
print(f"Total figures to embed: {len(rows):,}")
# Download the zip to a temp location for extraction
print(f"Downloading IMPACT {year} images (~4.4GB)...")
zip_path = hf_hub_download(
repo_id="AI4Patents/IMPACT",
filename=f"{year}.zip",
repo_type="dataset",
token=token,
)
print(f"Zip downloaded to: {zip_path}")
# Extract and embed in batches
import mmap, struct, zlib
fig_ids = []
vecs = []
def process_batch(batch_rows):
"""Extract images from zip and embed via API."""
results = []
for row in batch_rows:
fn = row["image_filename"]
# Construct path inside zip
parts = fn.split("-D0")
if len(parts) < 2:
continue
dir_name = parts[0]
zip_inner_path = f"{year}/{dir_name}/{fn}"
try:
import zipfile as zf
with zf.ZipFile(zip_path) as z:
with z.open(zip_inner_path) as f:
tif_bytes = f.read()
img = Image.open(io.BytesIO(tif_bytes))
b64 = encode_image(img)
vec = get_embedding(b64, model, token)
if vec is not None:
results.append((row["patent_id"] + "_" + fn.split("-D0")[1].split(".")[0], vec))
except Exception:
pass
return results
# Process in parallel batches
batches = [rows[i: i + batch_size] for i in range(0, len(rows), batch_size)]
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(process_batch, b): b for b in batches}
for future in tqdm(as_completed(futures), total=len(batches), desc="Embedding"):
for fig_id, vec in future.result():
fig_ids.append(fig_id)
vecs.append(vec)
vecs_arr = np.array(vecs, dtype=np.float32)
# Normalize to unit vectors
norms = np.linalg.norm(vecs_arr, axis=1, keepdims=True)
vecs_arr /= np.maximum(norms, 1e-8)
return fig_ids, vecs_arr
def push_to_hub(fig_ids: list[str], vecs: np.ndarray, out_repo: str, out_file: str, token: str):
"""Save embeddings as parquet and push to HF Hub."""
print(f"Building parquet ({len(fig_ids):,} embeddings, dim={vecs.shape[1]})...")
df = pd.DataFrame({
"figure_id": fig_ids,
"embedding": list(vecs),
})
tmp = Path("/tmp/embeddings_tmp.parquet")
df.to_parquet(tmp, index=False)
size_mb = tmp.stat().st_size / 1e6
print(f"Parquet size: {size_mb:.1f} MB")
api = HfApi(token=token)
api.upload_file(
path_or_fileobj=str(tmp),
path_in_repo=out_file,
repo_id=out_repo,
repo_type="dataset",
)
print(f"Pushed → hf://datasets/{out_repo}/{out_file}")
tmp.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("--out-repo", default="midah/patent-wireframes")
parser.add_argument("--out-file", default="embeddings_2022_vitl14.parquet")
parser.add_argument("--batch", type=int, default=8)
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--max-images", type=int, default=None)
args = parser.parse_args()
token = os.environ.get("HF_TOKEN")
if not token:
raise RuntimeError("Set HF_TOKEN environment variable")
fig_ids, vecs = stream_and_embed(
args.year, args.model, token,
args.batch, args.workers, args.max_images,
)
print(f"\nEmbedded {len(fig_ids):,} figures, shape {vecs.shape}")
push_to_hub(fig_ids, vecs, args.out_repo, args.out_file, token)
if __name__ == "__main__":
main()
|