Zhipeng Claude Sonnet 4.6 commited on
Commit
8795764
·
1 Parent(s): 966d9af

add inference endpoint handler and requirements

Browse files

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (2) hide show
  1. handler.py +58 -0
  2. requirements.txt +3 -0
handler.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+ from models import register_ultralytics_modules
11
+
12
+
13
+ class EndpointHandler:
14
+ def __init__(self, path: str = ""):
15
+ register_ultralytics_modules()
16
+
17
+ from ultralytics import YOLO
18
+
19
+ weights = Path(path) / "weights" / "symbolic_capsule_network_segmentation.pt"
20
+ self.model = YOLO(str(weights))
21
+
22
+ def __call__(self, data: dict) -> list[dict]:
23
+ """
24
+ Args:
25
+ data: {"inputs": <PIL Image | bytes | str path>}
26
+
27
+ Returns:
28
+ List of dicts compatible with HF image-segmentation pipeline:
29
+ [{"score": float, "label": str, "mask": "<base64 PNG>"}]
30
+ """
31
+ image = data.get("inputs")
32
+ if isinstance(image, bytes):
33
+ image = Image.open(io.BytesIO(image)).convert("RGB")
34
+
35
+ results = self.model.predict(image, imgsz=640, conf=0.25, verbose=False)
36
+ r = results[0]
37
+
38
+ if r.boxes is None or r.masks is None:
39
+ return []
40
+
41
+ h, w = r.orig_shape
42
+ output = []
43
+ for box, mask_tensor in zip(r.boxes, r.masks.data):
44
+ # Resize binary mask back to original image size
45
+ mask_np = (mask_tensor.cpu().numpy() * 255).astype(np.uint8)
46
+ mask_img = Image.fromarray(mask_np).resize((w, h), Image.NEAREST)
47
+
48
+ buf = io.BytesIO()
49
+ mask_img.save(buf, format="PNG")
50
+ mask_b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
51
+
52
+ output.append({
53
+ "score": round(float(box.conf), 4),
54
+ "label": self.model.names[int(box.cls)],
55
+ "mask": mask_b64,
56
+ })
57
+
58
+ return output
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ultralytics>=8.4.9
2
+ Pillow
3
+ numpy