Drazcat-AI commited on
Commit
7fe2588
·
verified ·
1 Parent(s): e9c00fc

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +67 -0
handler.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+ from typing import Dict, List, Any
3
+ from ultralytics import YOLO
4
+ import json
5
+ import urllib.request
6
+ import cv2
7
+ from io import BytesIO
8
+ import numpy as np
9
+ class EndpointHandler():
10
+ def __init__(self, path=""):
11
+ hf_hub_download(repo_id="Drazcat-AI/flejes", filename="flejes-16/runs/detect/train/weights/best.pt")
12
+ self.model = YOLO(hf_hub_download(repo_id="Drazcat-AI/flejes", filename="flejes-16/runs/detect/train/weights/best.pt", local_files_only=True))
13
+
14
+ def predict_objects(self, image_path, image_size_m):
15
+ results = self.model(image_path, imgsz=[1280, 960])
16
+ predictions = []
17
+ for box in results[0].boxes:
18
+ class_id = results[0].names[box.cls[0].item()]
19
+ cords = box.xywh[0].tolist()
20
+ #cords = [round(x) for x in cords]
21
+ conf = box.conf[0].item()
22
+ prediction = {
23
+ "x": round(cords[0]*image_size_m[0]),
24
+ "y": round(cords[1]*image_size_m[1]),
25
+ "width": round(cords[2]*image_size_m[0]),
26
+ "height": round(cords[3]*image_size_m[1]),
27
+ "confidence": conf,
28
+ "class": class_id
29
+ }
30
+ predictions.append(prediction)
31
+ predictions_array = {"predictions": predictions}
32
+
33
+ return predictions_array
34
+
35
+ def __call__(self, event):
36
+ if "inputs" not in event:
37
+ return {
38
+ "statusCode": 400,
39
+ "body": json.dumps("Error: Please provide an 'inputs' parameter."),
40
+ }
41
+
42
+ image_path = event["inputs"]
43
+
44
+ try:
45
+ with urllib.request.urlopen(image_path) as response:
46
+ image_content = np.asarray(bytearray(response.read()), dtype=np.uint8)
47
+ image = cv2.imdecode(image_content, cv2.IMREAD_COLOR)
48
+ """
49
+ image_size = image.shape
50
+ if image.shape[0]>image.shape[0]:
51
+ x, y = 1280, 960
52
+ else:
53
+ y, x = 1280, 960
54
+ image = cv2.resize(image, (x, y))
55
+
56
+ predictions = self.predict_objects(image, [image_size[0]/x,image_size[1]/y])
57
+ """
58
+ predictions = self.predict_objects(image, (1,1))
59
+ return {
60
+ "statusCode": 200,
61
+ "body": json.dumps(predictions),
62
+ }
63
+ except Exception as e:
64
+ return {
65
+ "statusCode": 500,
66
+ "body": json.dumps(f"Error: {str(e)}"),
67
+ }