midah commited on
Commit
337c768
·
verified ·
1 Parent(s): 69770c7

Add scripts/cloud/create_hf_endpoint.py

Browse files
Files changed (1) hide show
  1. scripts/cloud/create_hf_endpoint.py +286 -0
scripts/cloud/create_hf_endpoint.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Create, use, and delete an HF Inference Endpoint for CLIP embedding.
2
+
3
+ Creates a temporary dedicated endpoint for batch CLIP embedding,
4
+ processes all images from the IMPACT dataset, pushes embeddings
5
+ to HF Hub, then deletes the endpoint.
6
+
7
+ Cost estimate:
8
+ DesignCLIP / ViT-L-14 on T4: ~$0.08/hr
9
+ 103k images (2022) at batch=64: ~25 min = ~$0.03
10
+ 3.61M images (all years) at batch=64: ~15 hrs = ~$1.20 total
11
+
12
+ Usage:
13
+ export HF_TOKEN=hf_...
14
+ python scripts/cloud/create_hf_endpoint.py \
15
+ --year 2022 \
16
+ --model openai/clip-vit-large-patch14 \
17
+ --instance-type aws-us-east-1-t4g-small \
18
+ --out-repo midah/patent-wireframes
19
+ """
20
+
21
+ import argparse
22
+ import base64
23
+ import io
24
+ import os
25
+ import time
26
+ from pathlib import Path
27
+
28
+ import requests
29
+ from dotenv import load_dotenv
30
+
31
+ load_dotenv(".env")
32
+
33
+ HF_ENDPOINTS_API = "https://api.endpoints.huggingface.cloud/v2/endpoint"
34
+ HF_TOKEN = os.environ.get("HF_TOKEN")
35
+ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
36
+
37
+
38
+ # ── Endpoint lifecycle ────────────────────────────────────────────────────────
39
+
40
+ def create_endpoint(name: str, model: str, instance_type: str) -> dict:
41
+ """Create a dedicated inference endpoint for the given model."""
42
+ payload = {
43
+ "accountId": None,
44
+ "compute": {
45
+ "accelerator": "gpu" if "t4" in instance_type or "a10g" in instance_type else "cpu",
46
+ "instanceSize": instance_type.split("-")[-1] if "-" in instance_type else "large",
47
+ "instanceType": instance_type,
48
+ "scaling": {"maxReplica": 1, "minReplica": 1},
49
+ },
50
+ "model": {
51
+ "framework": "pytorch",
52
+ "image": {"huggingface": {"env": {}}},
53
+ "repository": model,
54
+ "revision": "main",
55
+ "task": "feature-extraction",
56
+ },
57
+ "name": name,
58
+ "provider": {"region": "us-east-1", "vendor": "aws"},
59
+ "type": "protected",
60
+ }
61
+ r = requests.post(
62
+ f"{HF_ENDPOINTS_API}/midah",
63
+ headers=HEADERS,
64
+ json=payload,
65
+ timeout=30,
66
+ )
67
+ r.raise_for_status()
68
+ return r.json()
69
+
70
+
71
+ def wait_for_endpoint(name: str, timeout: int = 600) -> str:
72
+ """Poll until the endpoint is running. Returns the endpoint URL."""
73
+ start = time.time()
74
+ while time.time() - start < timeout:
75
+ r = requests.get(f"{HF_ENDPOINTS_API}/midah/{name}", headers=HEADERS, timeout=15)
76
+ r.raise_for_status()
77
+ data = r.json()
78
+ state = data.get("status", {}).get("state", "unknown")
79
+ url = data.get("status", {}).get("url", "")
80
+ print(f" State: {state} ({int(time.time()-start)}s elapsed)")
81
+ if state == "running":
82
+ return url
83
+ if state in ("failed", "scaledToZero"):
84
+ raise RuntimeError(f"Endpoint failed: {state}")
85
+ time.sleep(20)
86
+ raise TimeoutError("Endpoint did not start within timeout")
87
+
88
+
89
+ def delete_endpoint(name: str):
90
+ r = requests.delete(f"{HF_ENDPOINTS_API}/midah/{name}", headers=HEADERS, timeout=15)
91
+ if r.status_code not in (200, 204):
92
+ print(f" Warning: delete returned {r.status_code}")
93
+ else:
94
+ print(f" Deleted endpoint: {name}")
95
+
96
+
97
+ # ── Embedding via endpoint ────────────────────────────────────────────────────
98
+
99
+ def encode_image(img_bytes: bytes, max_edge: int = 224) -> str:
100
+ from PIL import Image
101
+ img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
102
+ w, h = img.size
103
+ scale = min(max_edge / max(w, h), 1.0)
104
+ if scale < 1.0:
105
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
106
+ buf = io.BytesIO()
107
+ img.save(buf, format="JPEG", quality=85)
108
+ return base64.standard_b64encode(buf.getvalue()).decode()
109
+
110
+
111
+ def embed_batch(endpoint_url: str, b64_images: list[str]) -> list[list[float]] | None:
112
+ """Call the endpoint with a batch of base64 images."""
113
+ payload = {"inputs": b64_images}
114
+ for attempt in range(4):
115
+ try:
116
+ r = requests.post(
117
+ endpoint_url,
118
+ headers={**HEADERS, "Content-Type": "application/json"},
119
+ json=payload,
120
+ timeout=60,
121
+ )
122
+ if r.status_code == 200:
123
+ data = r.json()
124
+ # Response shape: list of embeddings or list of list of list
125
+ if isinstance(data, list) and data:
126
+ if isinstance(data[0], list) and isinstance(data[0][0], float):
127
+ return data # already [[float, ...], ...]
128
+ if isinstance(data[0], list) and isinstance(data[0][0], list):
129
+ return [d[0] for d in data] # [[[float]], ...]
130
+ return None
131
+ elif r.status_code in (429, 503):
132
+ time.sleep(2 ** attempt)
133
+ except Exception as e:
134
+ print(f" Batch error (attempt {attempt+1}): {e}")
135
+ time.sleep(2 ** attempt)
136
+ return None
137
+
138
+
139
+ # ── Main processing ───────────────────────────────────────────────────────────
140
+
141
+ def process_year(year: str, endpoint_url: str, out_repo: str, batch_size: int = 32):
142
+ """Stream images from IMPACT and embed via the endpoint."""
143
+ import ast
144
+ import csv
145
+ import zipfile
146
+
147
+ import numpy as np
148
+ import pandas as pd
149
+ from huggingface_hub import HfApi, hf_hub_download
150
+
151
+ token = HF_TOKEN
152
+ api = HfApi(token=token)
153
+
154
+ print(f"\nDownloading IMPACT {year} CSV...")
155
+ csv_path = hf_hub_download(
156
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.csv",
157
+ repo_type="dataset", token=token,
158
+ )
159
+
160
+ print(f"Downloading IMPACT {year} images zip (~4.4GB)...")
161
+ zip_path = hf_hub_download(
162
+ repo_id="AI4Patents/IMPACT", filename=f"{year}.zip",
163
+ repo_type="dataset", token=token,
164
+ )
165
+
166
+ # Build figure list
167
+ figures = []
168
+ with open(csv_path) as f:
169
+ for row in csv.DictReader(f):
170
+ try:
171
+ fnames = ast.literal_eval(row["file_names"])
172
+ pid = row["id"]
173
+ for i, fn in enumerate(fnames):
174
+ figures.append({"patent_id": pid, "figure_num": i, "filename": fn})
175
+ except Exception:
176
+ pass
177
+
178
+ print(f"Total figures: {len(figures):,}")
179
+
180
+ all_ids, all_vecs = [], []
181
+ n_failed = 0
182
+
183
+ # Process in batches using zip
184
+ with zipfile.ZipFile(zip_path) as zf:
185
+ batch_imgs, batch_ids = [], []
186
+
187
+ def flush():
188
+ nonlocal n_failed
189
+ if not batch_imgs:
190
+ return
191
+ vecs = embed_batch(endpoint_url, batch_imgs)
192
+ if vecs:
193
+ all_vecs.extend(vecs)
194
+ all_ids.extend(batch_ids)
195
+ else:
196
+ n_failed += len(batch_imgs)
197
+ batch_imgs.clear()
198
+ batch_ids.clear()
199
+
200
+ from tqdm import tqdm
201
+ for fig in tqdm(figures, desc=f"Embedding {year}"):
202
+ fn = fig["filename"]
203
+ parts = fn.split("-D0")
204
+ if len(parts) < 2:
205
+ continue
206
+ inner = f"{year}/{parts[0]}/{fn}"
207
+ try:
208
+ with zf.open(inner) as f:
209
+ img_bytes = f.read()
210
+ b64 = encode_image(img_bytes)
211
+ pid = fig["patent_id"].lstrip("D").zfill(7)
212
+ batch_ids.append(f"D{pid}_{fig['figure_num']}")
213
+ batch_imgs.append(b64)
214
+ if len(batch_imgs) >= batch_size:
215
+ flush()
216
+ except Exception:
217
+ continue
218
+
219
+ flush()
220
+
221
+ print(f"Embedded: {len(all_ids):,} | Failed: {n_failed}")
222
+
223
+ if not all_ids:
224
+ print("No embeddings produced — check endpoint")
225
+ return
226
+
227
+ # Normalize and save
228
+ vecs = np.array(all_vecs, dtype=np.float32)
229
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True)
230
+ vecs /= np.maximum(norms, 1e-8)
231
+
232
+ df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
233
+ out_file = f"embeddings_{year}_vitl14.parquet"
234
+ local_out = Path(f"/tmp/{out_file}")
235
+ df.to_parquet(local_out, index=False)
236
+ size_mb = local_out.stat().st_size / 1e6
237
+ print(f"Parquet: {size_mb:.1f}MB")
238
+
239
+ api.upload_file(
240
+ path_or_fileobj=str(local_out),
241
+ path_in_repo=f"embeddings/{out_file}",
242
+ repo_id=out_repo,
243
+ repo_type="dataset",
244
+ commit_message=f"Add CLIP embeddings for {year}",
245
+ )
246
+ print(f"Pushed → hf://datasets/{out_repo}/embeddings/{out_file}")
247
+ local_out.unlink()
248
+
249
+
250
+ def main():
251
+ parser = argparse.ArgumentParser()
252
+ parser.add_argument("--year", default="2022")
253
+ parser.add_argument("--model", default="openai/clip-vit-large-patch14")
254
+ parser.add_argument("--instance-type", default="aws-us-east-1-t4g-small",
255
+ help="HF endpoint instance type. See: hf.co/docs/inference-endpoints")
256
+ parser.add_argument("--out-repo", default="midah/patent-wireframes")
257
+ parser.add_argument("--batch", type=int, default=32)
258
+ parser.add_argument("--keep-endpoint", action="store_true",
259
+ help="Don't delete endpoint after finishing (useful for multi-year runs)")
260
+ args = parser.parse_args()
261
+
262
+ if not HF_TOKEN:
263
+ raise RuntimeError("HF_TOKEN not set")
264
+
265
+ endpoint_name = f"patent-clip-{args.year}-{int(time.time())}"
266
+ endpoint_url = None
267
+
268
+ try:
269
+ print(f"Creating endpoint: {endpoint_name}")
270
+ print(f" Model: {args.model}")
271
+ print(f" Instance: {args.instance_type}")
272
+ data = create_endpoint(endpoint_name, args.model, args.instance_type)
273
+ print(f" Created. Waiting for running state...")
274
+ endpoint_url = wait_for_endpoint(endpoint_name)
275
+ print(f" Endpoint ready: {endpoint_url}")
276
+
277
+ process_year(args.year, endpoint_url, args.out_repo, args.batch)
278
+
279
+ finally:
280
+ if not args.keep_endpoint and endpoint_name:
281
+ print(f"\nCleaning up endpoint: {endpoint_name}")
282
+ delete_endpoint(endpoint_name)
283
+
284
+
285
+ if __name__ == "__main__":
286
+ main()