torinriley
commited on
Commit
•
1e11062
1
Parent(s):
a3af870
Update handler.py
Browse files- handler.py +13 -9
handler.py
CHANGED
@@ -1,13 +1,16 @@
|
|
|
|
1 |
import torch
|
2 |
from torchvision import transforms
|
3 |
from PIL import Image
|
4 |
import io
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
8 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
|
10 |
-
# Load Faster R-CNN model
|
11 |
def load_model(model_path, num_classes):
|
12 |
from torchvision.models.detection import fasterrcnn_resnet50_fpn
|
13 |
model = fasterrcnn_resnet50_fpn(pretrained=False, num_classes=num_classes)
|
@@ -17,13 +20,13 @@ def load_model(model_path, num_classes):
|
|
17 |
model.eval()
|
18 |
return model
|
19 |
|
|
|
|
|
20 |
transform = transforms.Compose([
|
21 |
transforms.Resize((640, 640)),
|
22 |
transforms.ToTensor(),
|
23 |
])
|
24 |
|
25 |
-
model = load_model(MODEL_PATH, NUM_CLASSES)
|
26 |
-
|
27 |
def detect_objects(image_bytes):
|
28 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
29 |
input_tensor = transform(image).unsqueeze(0).to(DEVICE)
|
@@ -45,12 +48,13 @@ def detect_objects(image_bytes):
|
|
45 |
return {"predictions": results}
|
46 |
|
47 |
def inference(payload):
|
|
|
48 |
try:
|
49 |
if "image" not in payload:
|
50 |
-
return {"error": "No image provided. Please send
|
51 |
-
|
52 |
-
image_bytes = payload["image"]
|
53 |
-
|
54 |
results = detect_objects(image_bytes)
|
55 |
return results
|
56 |
except Exception as e:
|
|
|
1 |
+
import os
|
2 |
import torch
|
3 |
from torchvision import transforms
|
4 |
from PIL import Image
|
5 |
import io
|
6 |
|
7 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
8 |
+
MODEL_FILENAME = "model.pt"
|
9 |
+
MODEL_PATH = os.path.join(BASE_DIR, MODEL_FILENAME)
|
10 |
+
|
11 |
+
NUM_CLASSES = 4
|
12 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
13 |
|
|
|
14 |
def load_model(model_path, num_classes):
|
15 |
from torchvision.models.detection import fasterrcnn_resnet50_fpn
|
16 |
model = fasterrcnn_resnet50_fpn(pretrained=False, num_classes=num_classes)
|
|
|
20 |
model.eval()
|
21 |
return model
|
22 |
|
23 |
+
model = load_model(MODEL_PATH, NUM_CLASSES)
|
24 |
+
|
25 |
transform = transforms.Compose([
|
26 |
transforms.Resize((640, 640)),
|
27 |
transforms.ToTensor(),
|
28 |
])
|
29 |
|
|
|
|
|
30 |
def detect_objects(image_bytes):
|
31 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
32 |
input_tensor = transform(image).unsqueeze(0).to(DEVICE)
|
|
|
48 |
return {"predictions": results}
|
49 |
|
50 |
def inference(payload):
|
51 |
+
import base64
|
52 |
try:
|
53 |
if "image" not in payload:
|
54 |
+
return {"error": "No image provided. Please send a Base64-encoded image."}
|
55 |
+
|
56 |
+
image_bytes = base64.b64decode(payload["image"])
|
57 |
+
|
58 |
results = detect_objects(image_bytes)
|
59 |
return results
|
60 |
except Exception as e:
|