|
from typing import Dict, List, Any |
|
import base64 |
|
from PIL import Image |
|
from io import BytesIO |
|
from diffusers import StableDiffusionImg2ImgPipeline |
|
import torch |
|
|
|
|
|
import numpy as np |
|
|
|
|
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
if device.type != 'cuda': |
|
raise ValueError("need to run on GPU") |
|
|
|
dtype = torch.bfloat16 if torch.cuda.get_device_capability()[ |
|
0] == 8 else torch.float16 |
|
|
|
model_id = "nitrosocke/Ghibli-Diffusion" |
|
|
|
|
|
class EndpointHandler(): |
|
def __init__(self, path=""): |
|
|
|
|
|
self.pipe = StableDiffusionImg2ImgPipeline.from_pretrained("nitrosocke/Ghibli-Diffusion", torch_dtype=torch.float16).to( |
|
device |
|
) |
|
|
|
|
|
self.generator = torch.Generator(device=device).manual_seed(1024) |
|
|
|
def __call__(self, data: Any) -> List[List[Dict[str, float]]]: |
|
""" |
|
:param data: A dictionary contains `inputs` and optional `image` field. |
|
:return: A dictionary with `image` field contains image in base64. |
|
""" |
|
prompt = data.pop("inputs", None) |
|
image = data.pop("image", None) |
|
|
|
|
|
|
|
|
|
if prompt is None and image is None: |
|
return {"error": "Please provide a prompt and base64 encoded image."} |
|
|
|
|
|
|
|
guidance_scale = data.pop("guidance_scale", 7.5) |
|
strength = data.pop("strength", 7.5) |
|
negative_prompt = data.pop("negative_prompt", None) |
|
|
|
|
|
|
|
|
|
|
|
|
|
image = self.decode_base64_image(image) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
out = self.pipe( |
|
prompt=prompt, |
|
image=image, |
|
negative_prompt=negative_prompt, |
|
strength=strength, |
|
guidance_scale=guidance_scale, |
|
generator=self.generator |
|
) |
|
|
|
|
|
return out.images[0] |
|
|
|
|
|
def decode_base64_image(self, image_string): |
|
base64_image = base64.b64decode(image_string) |
|
buffer = BytesIO(base64_image) |
|
image = Image.open(buffer).convert("RGB") |
|
|
|
return image |
|
|