amobionovo commited on
Commit
5290133
·
verified ·
1 Parent(s): 5dc3025

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +72 -65
handler.py CHANGED
@@ -1,65 +1,72 @@
1
- from typing import Dict, Any
2
- import base64
3
- import io
4
- from PIL import Image
5
- import torch
6
-
7
- class EndpointHandler:
8
- """
9
- Hugging Face Inference Endpoint handler for LocustGuard YOLO model.
10
-
11
- Expected JSON:
12
- {
13
- "image": "<base64 encoded image>",
14
- "conf": 0.25,
15
- "iou": 0.45
16
- }
17
-
18
- Returns:
19
- {
20
- "detections": [
21
- {
22
- "label": str,
23
- "confidence": float,
24
- "coordinates": [xmin, ymin, xmax, ymax]
25
- }
26
- ]
27
- }
28
- """
29
-
30
- def __init__(self, path: str = "."):
31
- self.model = torch.hub.load(
32
- "ultralytics/yolov5",
33
- "custom",
34
- path=f"{path}/best.pt",
35
- force_reload=False
36
- )
37
-
38
- def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
39
- image_b64 = data["image"]
40
- conf = float(data.get("conf", 0.25))
41
- iou = float(data.get("iou", 0.45))
42
-
43
- image_bytes = base64.b64decode(image_b64)
44
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
45
-
46
- self.model.conf = conf
47
- self.model.iou = iou
48
-
49
- results = self.model(image, size=640)
50
- r = results.pandas().xyxy[0]
51
-
52
- detections = []
53
- for _, row in r.iterrows():
54
- detections.append({
55
- "label": row["name"],
56
- "confidence": float(row["confidence"]),
57
- "coordinates": [
58
- round(float(row["xmin"]), 2),
59
- round(float(row["ymin"]), 2),
60
- round(float(row["xmax"]), 2),
61
- round(float(row["ymax"]), 2),
62
- ]
63
- })
64
-
65
- return {"detections": detections}
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ import base64
3
+ import io
4
+ from PIL import Image
5
+ from ultralytics import YOLO
6
+
7
+ class EndpointHandler:
8
+ """
9
+ Hugging Face Inference Endpoint handler for LocustGuard YOLO model.
10
+
11
+ Expected JSON:
12
+ {
13
+ "image": "<base64 encoded image>",
14
+ "conf": 0.25,
15
+ "iou": 0.45
16
+ }
17
+
18
+ Returns:
19
+ {
20
+ "detections": [
21
+ {
22
+ "label": str,
23
+ "confidence": float,
24
+ "coordinates": [xmin, ymin, xmax, ymax]
25
+ }
26
+ ]
27
+ }
28
+ """
29
+
30
+ def __init__(self, path: str = "."):
31
+ # Native ultralytics loader (NO torch.hub)
32
+ self.model = YOLO(f"{path}/best.pt")
33
+
34
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
35
+ image_b64 = data["image"]
36
+ conf = float(data.get("conf", 0.25))
37
+ iou = float(data.get("iou", 0.45))
38
+
39
+ image_bytes = base64.b64decode(image_b64)
40
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
41
+
42
+ # Run inference
43
+ results = self.model(
44
+ image,
45
+ conf=conf,
46
+ iou=iou,
47
+ imgsz=640,
48
+ verbose=False
49
+ )
50
+
51
+ r = results[0]
52
+ detections = []
53
+
54
+ if r.boxes is not None:
55
+ for box in r.boxes:
56
+ x1, y1, x2, y2 = box.xyxy[0].tolist()
57
+ cls_id = int(box.cls[0])
58
+ conf_score = float(box.conf[0])
59
+ label = self.model.names[cls_id]
60
+
61
+ detections.append({
62
+ "label": label,
63
+ "confidence": round(conf_score, 3),
64
+ "coordinates": [
65
+ round(float(x1), 2),
66
+ round(float(y1), 2),
67
+ round(float(x2), 2),
68
+ round(float(y2), 2),
69
+ ]
70
+ })
71
+
72
+ return {"detections": detections}