Commit
·
cf71c98
1
Parent(s):
d02cc08
Create handler.py
Browse files- handler.py +52 -0
handler.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import hf_hub_download
|
| 2 |
+
from typing import Dict, List, Any
|
| 3 |
+
from ultralytics import YOLO
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
class EndpointHandler():
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
hf_hub_download(repo_id="Drazcat-AI/nectar", filename="yolov8_nectar/runs/detect/train/weights/best.pt")
|
| 9 |
+
self.model = YOLO(hf_hub_download(repo_id="Drazcat-AI/nectar", filename="yolov8_nectar/runs/detect/train/weights/best.pt", local_files_only=True))
|
| 10 |
+
|
| 11 |
+
def predict_objects(self, image_path):
|
| 12 |
+
results = self.model(image_path, imgsz=800)
|
| 13 |
+
predictions = []
|
| 14 |
+
for box in results[0].boxes:
|
| 15 |
+
class_id = results[0].names[box.cls[0].item()]
|
| 16 |
+
cords = box.xywh[0].tolist()
|
| 17 |
+
cords = [round(x) for x in cords]
|
| 18 |
+
conf = round(box.conf[0].item(), 2)
|
| 19 |
+
prediction = {
|
| 20 |
+
"label": class_id,
|
| 21 |
+
"score": conf,
|
| 22 |
+
"box":{
|
| 23 |
+
"x": cords[0],
|
| 24 |
+
"y": cords[1],
|
| 25 |
+
"width": cords[2],
|
| 26 |
+
"height": cords[3]}
|
| 27 |
+
}
|
| 28 |
+
predictions.append(prediction)
|
| 29 |
+
predictions_array = {"predictions": predictions}
|
| 30 |
+
|
| 31 |
+
return predictions_array
|
| 32 |
+
|
| 33 |
+
def __call__(self, event):
|
| 34 |
+
if "inputs" not in event:
|
| 35 |
+
return {
|
| 36 |
+
"statusCode": 400,
|
| 37 |
+
"body": json.dumps("Error: Please provide an 'inputs' parameter."),
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
image_path = event["inputs"]
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
predictions = self.predict_objects(image_path)
|
| 44 |
+
return {
|
| 45 |
+
"statusCode": 200,
|
| 46 |
+
"body": json.dumps(predictions),
|
| 47 |
+
}
|
| 48 |
+
except Exception as e:
|
| 49 |
+
return {
|
| 50 |
+
"statusCode": 500,
|
| 51 |
+
"body": json.dumps(f"Error: {str(e)}"),
|
| 52 |
+
}
|