add custom handler
Browse files- __pycache__/handler.cpython-38.pyc +0 -0
- handler.py +36 -0
- requirements.txt +3 -0
__pycache__/handler.cpython-38.pyc
ADDED
Binary file (1.57 kB). View file
|
|
handler.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
|
3 |
+
import base64
|
4 |
+
import numpy as np
|
5 |
+
from tensorflow import keras
|
6 |
+
from keras_cv.models.generative.stable_diffusion.decoder import Decoder
|
7 |
+
|
8 |
+
class EndpointHandler():
|
9 |
+
def __init__(self, path=""):
|
10 |
+
img_height = 512
|
11 |
+
img_width = 512
|
12 |
+
img_height = round(img_height / 128) * 128
|
13 |
+
img_width = round(img_width / 128) * 128
|
14 |
+
|
15 |
+
self.decoder = Decoder(img_height, img_width)
|
16 |
+
decoder_weights_fpath = keras.utils.get_file(
|
17 |
+
origin="https://huggingface.co/fchollet/stable-diffusion/resolve/main/kcv_decoder.h5",
|
18 |
+
file_hash="ad350a65cc8bc4a80c8103367e039a3329b4231c2469a1093869a345f55b1962",
|
19 |
+
)
|
20 |
+
self.decoder.load_weights(decoder_weights_fpath)
|
21 |
+
|
22 |
+
def __call__(self, data: Dict[str, Any]) -> str:
|
23 |
+
# get inputs
|
24 |
+
latent = data.pop("inputs", data)
|
25 |
+
latent = base64.b64decode(latent)
|
26 |
+
latent = np.frombuffer(latent, dtype="float32")
|
27 |
+
latent = np.reshape(latent, (1, 64, 64, 4))
|
28 |
+
|
29 |
+
decoded = self.decoder.predict_on_batch(latent)
|
30 |
+
decoded = ((decoded + 1) / 2) * 255
|
31 |
+
images = np.clip(decoded, 0, 255).astype("uint8")
|
32 |
+
|
33 |
+
images_b64 = base64.b64encode(images.tobytes())
|
34 |
+
images_b64str = images_b64.decode()
|
35 |
+
|
36 |
+
return images_b64str
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
keras-cv
|
2 |
+
tensorflow
|
3 |
+
tensorflow_datasets
|