Delete handler.py
Browse files- handler.py +0 -58
handler.py
DELETED
@@ -1,58 +0,0 @@
|
|
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 |
-
[
|
18 |
-
transforms.ToImage(),
|
19 |
-
transforms.ToDtype(torch.float32, scale=True),
|
20 |
-
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
21 |
-
]
|
22 |
-
)
|
23 |
-
|
24 |
-
repo_id = "Kiwinicki/sat2map-generator"
|
25 |
-
generator_path = hf_hub_download(repo_id=repo_id, filename="generator.pth")
|
26 |
-
config_path = hf_hub_download(repo_id=repo_id, filename="config.json")
|
27 |
-
model_path = hf_hub_download(repo_id=repo_id, filename="model.py")
|
28 |
-
|
29 |
-
with open(config_path, "r") as f:
|
30 |
-
config_dict = json.load(f)
|
31 |
-
cfg = OmegaConf.create(config_dict)
|
32 |
-
|
33 |
-
self.generator = Generator(cfg)
|
34 |
-
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
35 |
-
self.generator.load_state_dict(torch.load(generator_path, map_location=self.device))
|
36 |
-
self.generator.eval()
|
37 |
-
|
38 |
-
|
39 |
-
def __call__(self, data: dict[str, any]) -> dict[str, str]:
|
40 |
-
base64_image = data.get('inputs')
|
41 |
-
input_tensor = self._decode_base64_image(base64_image)
|
42 |
-
# print('Input tensor shape: ' + str(input_tensor.shape))
|
43 |
-
output_tensor = self.generator(input_tensor.to(self.device))
|
44 |
-
output_tensor = output_tensor.squeeze(0)
|
45 |
-
output_image = transforms.ToPILImage()(output_tensor)
|
46 |
-
output_image = output_image.convert('RGB')
|
47 |
-
output_buffer = io.BytesIO()
|
48 |
-
output_image.save(output_buffer, format="png")
|
49 |
-
base64_output = base64.b64encode(output_buffer.getvalue()).decode('utf-8')
|
50 |
-
return {"output": base64_output}
|
51 |
-
|
52 |
-
|
53 |
-
def _decode_base64_image(self, base64_image: str) -> torch.Tensor:
|
54 |
-
image_decoded = base64.b64decode(base64_image)
|
55 |
-
image = Image.open(io.BytesIO(image_decoded)).convert('RGB')
|
56 |
-
image_tensor: torch.Tensor = self.transform(image)
|
57 |
-
image_tensor = image_tensor.unsqueeze(0)
|
58 |
-
return image_tensor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|