add custom handler
Browse files- handler.py +52 -0
handler.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torchvision import transforms
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
import json
|
| 5 |
+
import io
|
| 6 |
+
import base64
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from omegaconf import OmegaConf
|
| 9 |
+
|
| 10 |
+
from model import Generator
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class EndpointHandler:
|
| 14 |
+
|
| 15 |
+
def __init__(self, path=''):
|
| 16 |
+
self.transform = transforms.Compose([
|
| 17 |
+
transforms.ToTensor()
|
| 18 |
+
])
|
| 19 |
+
|
| 20 |
+
repo_id = "Kiwinicki/sat2map-generator"
|
| 21 |
+
generator_path = hf_hub_download(repo_id=repo_id, filename="generator.pth")
|
| 22 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.json")
|
| 23 |
+
model_path = hf_hub_download(repo_id=repo_id, filename="model.py")
|
| 24 |
+
|
| 25 |
+
with open(config_path, "r") as f:
|
| 26 |
+
config_dict = json.load(f)
|
| 27 |
+
cfg = OmegaConf.create(config_dict)
|
| 28 |
+
|
| 29 |
+
self.generator = Generator(cfg)
|
| 30 |
+
self.generator.load_state_dict(torch.load(generator_path))
|
| 31 |
+
self.generator.eval()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def __call__(self, data: dict[str, any]) -> dict[str, str]:
|
| 35 |
+
base64_image = data.get('inputs')
|
| 36 |
+
image = self._decode_base64_image(base64_image)
|
| 37 |
+
output = self.generator(image)
|
| 38 |
+
output = output.squeeze(0)
|
| 39 |
+
output_image = transforms.ToPILImage()(output)
|
| 40 |
+
output_image = output_image.convert('RGB')
|
| 41 |
+
output_buffer = io.BytesIO()
|
| 42 |
+
output_image.save(output_buffer, format="png")
|
| 43 |
+
base64_output = base64.b64encode(output_buffer.getvalue()).decode('utf-8')
|
| 44 |
+
return {"output": base64_output}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _decode_base64_image(self, base64_image: str) -> torch.Tensor:
|
| 48 |
+
image_decoded = base64.b64decode(base64_image)
|
| 49 |
+
image = Image.open(io.BytesIO(image_decoded)).convert('RGB')
|
| 50 |
+
image_tensor: torch.Tensor = self.transform(image)
|
| 51 |
+
image_tensor = image_tensor.unsqueeze(0)
|
| 52 |
+
return image_tensor
|