Bhatbot commited on
Commit
9edd4b5
·
verified ·
1 Parent(s): 47ef69a

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +46 -0
handler.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DINOv2 image embedding handler for HF Inference Endpoints.
3
+ Accepts base64-encoded images via {"inputs": "<base64_string>"}.
4
+ Returns a 768-dim CLS token embedding as a flat list of floats.
5
+ """
6
+ import base64
7
+ import os
8
+ from io import BytesIO
9
+
10
+ import torch
11
+ from PIL import Image
12
+ from transformers import AutoImageProcessor, AutoModel
13
+
14
+
15
+ class EndpointHandler:
16
+ def __init__(self, path=""):
17
+ # If the repo contains model weights, use them; otherwise load from HF Hub.
18
+ has_weights = path and os.path.exists(os.path.join(path, "config.json"))
19
+ model_id = path if has_weights else "facebook/dinov2-base"
20
+ self.processor = AutoImageProcessor.from_pretrained(model_id)
21
+ self.model = AutoModel.from_pretrained(model_id)
22
+ self.model.eval()
23
+
24
+ def __call__(self, data: dict) -> list:
25
+ """
26
+ data: {"inputs": "<base64_string>"}
27
+ Returns: [float x 768] — DINOv2 CLS token embedding
28
+ """
29
+ raw = data.get("inputs", "")
30
+
31
+ if isinstance(raw, str):
32
+ img_bytes = base64.b64decode(raw)
33
+ elif isinstance(raw, bytes):
34
+ img_bytes = raw
35
+ else:
36
+ raise ValueError(f"Unexpected input type: {type(raw)}")
37
+
38
+ image = Image.open(BytesIO(img_bytes)).convert("RGB")
39
+
40
+ with torch.no_grad():
41
+ inputs = self.processor(images=image, return_tensors="pt")
42
+ outputs = self.model(**inputs)
43
+ # last_hidden_state: [1, seq_len, 768] — take CLS token at index 0
44
+ embedding = outputs.last_hidden_state[:, 0, :].squeeze().tolist()
45
+
46
+ return embedding