Upload handler.py
Browse files- handler.py +43 -0
handler.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
class EndpointHandler():
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
# load the optimized model
|
| 9 |
+
self.model = torch.load(path)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
| 15 |
+
"""
|
| 16 |
+
Args:
|
| 17 |
+
data (:obj:):
|
| 18 |
+
includes the input data and the parameters for the inference.
|
| 19 |
+
Return:
|
| 20 |
+
A :obj:`list`:. The object returned should be a list of one list like [[{"label": 0.9939950108528137}]] containing :
|
| 21 |
+
- "label": A string representing what the label/class is. There can be multiple labels.
|
| 22 |
+
- "score": A score between 0 and 1 describing how confident the model is for this label/class.
|
| 23 |
+
"""
|
| 24 |
+
inputs = data.pop("inputs", data)
|
| 25 |
+
img = inputs["image"]
|
| 26 |
+
|
| 27 |
+
# Load the image
|
| 28 |
+
img = np.float32(img) / 255. # Load and normalize the image
|
| 29 |
+
|
| 30 |
+
# Convert to torch tensor and add batch dimension
|
| 31 |
+
img_tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0)
|
| 32 |
+
|
| 33 |
+
# Padding if necessary (to make image dimensions multiples of 4)
|
| 34 |
+
b, c, h, w = img_tensor.shape
|
| 35 |
+
factor = 4 # Assuming factor is 4, based on the code context
|
| 36 |
+
H, W = ((h + factor) // factor) * factor, ((w + factor) // factor) * factor
|
| 37 |
+
padh = H - h if h % factor != 0 else 0
|
| 38 |
+
padw = W - w if w % factor != 0 else 0
|
| 39 |
+
img_tensor = F.pad(img_tensor, (0, padw, 0, padh), 'reflect')
|
| 40 |
+
|
| 41 |
+
restored = self.model(img_tensor)
|
| 42 |
+
# postprocess the prediction
|
| 43 |
+
return "OKAY"
|