ProConceptTech commited on
Commit
599338d
·
verified ·
1 Parent(s): b43d0fd

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +39 -0
handler.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from ultralytics import YOLO
3
+ from PIL import Image
4
+ import torch
5
+ import io
6
+
7
+ class EndpointHandler():
8
+ def __init__(self, path=""):
9
+ # Load the YOLO model from the current directory
10
+ # The 'path' argument is provided by Hugging Face automatically
11
+ self.model = YOLO(f"{path}/best.pt")
12
+
13
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
14
+ """
15
+ data args:
16
+ inputs (:obj: `bytes`) : The raw image bytes sent from Supabase
17
+ Return:
18
+ A :obj:`list` | `dict`: The detection results
19
+ """
20
+ # Get inputs
21
+ inputs = data.pop("inputs", data)
22
+
23
+ # Convert bytes to PIL Image
24
+ img = Image.open(io.BytesIO(inputs))
25
+
26
+ # Run inference
27
+ results = self.model(img, conf=0.25)
28
+
29
+ # Format results for your dashboard
30
+ payload = []
31
+ for r in results:
32
+ for box in r.boxes:
33
+ payload.append({
34
+ "label": self.model.names[int(box.cls)],
35
+ "confidence": float(box.conf),
36
+ "points": box.xyxy[0].tolist(), # [x1, y1, x2, y2]
37
+ })
38
+
39
+ return payload