Update handler.py
Browse files- handler.py +47 -35
handler.py
CHANGED
|
@@ -1,35 +1,47 @@
|
|
| 1 |
-
# handler.py
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
self.
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# handler.py
|
| 2 |
+
# Save only the weights
|
| 3 |
+
torch.save(model.state_dict(), "UNet_Model.pth")
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from torchvision import transforms
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
import io
|
| 10 |
+
import base64
|
| 11 |
+
|
| 12 |
+
# Define your UNet class here (shortened version for example)
|
| 13 |
+
class UNet(nn.Module):
|
| 14 |
+
def __init__(self): # Add your actual init params
|
| 15 |
+
super(UNet, self).__init__()
|
| 16 |
+
# Define layers...
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
# Implement forward pass
|
| 20 |
+
return x
|
| 21 |
+
|
| 22 |
+
class EndpointHandler:
|
| 23 |
+
def __init__(self, path=""):
|
| 24 |
+
model_path = hf_hub_download(repo_id="whitney0507/unet-model", filename="UNet_Model.pth")
|
| 25 |
+
self.model = UNet() # Instantiate model
|
| 26 |
+
self.model.load_state_dict(torch.load(model_path, map_location="cpu"))
|
| 27 |
+
self.model.eval()
|
| 28 |
+
self.transform = transforms.Compose([
|
| 29 |
+
transforms.Resize((256, 256)),
|
| 30 |
+
transforms.ToTensor()
|
| 31 |
+
])
|
| 32 |
+
|
| 33 |
+
def __call__(self, data):
|
| 34 |
+
image_bytes = base64.b64decode(data["inputs"])
|
| 35 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 36 |
+
input_tensor = self.transform(image).unsqueeze(0)
|
| 37 |
+
|
| 38 |
+
with torch.no_grad():
|
| 39 |
+
output = self.model(input_tensor)
|
| 40 |
+
pred = output.argmax(dim=1).squeeze().byte().cpu().numpy()
|
| 41 |
+
|
| 42 |
+
# Convert to base64
|
| 43 |
+
output_img = Image.fromarray(pred * 255)
|
| 44 |
+
buffer = io.BytesIO()
|
| 45 |
+
output_img.save(buffer, format="PNG")
|
| 46 |
+
return {"prediction": base64.b64encode(buffer.getvalue()).decode("utf-8")}
|
| 47 |
+
|