karimbenharrak commited on
Commit
4efc065
1 Parent(s): 1a0f9ed

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +58 -0
handler.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ import torch
3
+ from diffusers import DPMSolverMultistepScheduler, StableDiffusionInpaintPipeline
4
+ from PIL import Image
5
+ import base64
6
+ from io import BytesIO
7
+
8
+
9
+ # set device
10
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
+
12
+ if device.type != 'cuda':
13
+ raise ValueError("need to run on GPU")
14
+
15
+ class EndpointHandler():
16
+ def __init__(self, path=""):
17
+ # load StableDiffusionInpaintPipeline pipeline
18
+ self.pipe = StableDiffusionInpaintPipeline.from_pretrained(
19
+ "runwayml/stable-diffusion-inpainting",
20
+ revision="fp16",
21
+ torch_dtype=torch.float16,
22
+ )
23
+ # use DPMSolverMultistepScheduler
24
+ self.pipe.scheduler = DPMSolverMultistepScheduler.from_config(self.pipe.scheduler.config)
25
+ # move to device
26
+ self.pipe = self.pipe.to(device)
27
+
28
+
29
+ def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
30
+ """
31
+ :param data: A dictionary contains `inputs` and optional `image` field.
32
+ :return: A dictionary with `image` field contains image in base64.
33
+ """
34
+ encoded_image = data.pop("image", None)
35
+ encoded_mask_image = data.pop("mask_image", None)
36
+
37
+ prompt = data.pop("prompt", "")
38
+
39
+ # process image
40
+ if encoded_image is not None and encoded_mask_image is not None:
41
+ image = self.decode_base64_image(encoded_image)
42
+ mask_image = self.decode_base64_image(encoded_mask_image)
43
+ else:
44
+ image = None
45
+ mask_image = None
46
+
47
+ # run inference pipeline
48
+ out = self.pipe(prompt=prompt, image=image, mask_image=mask_image)
49
+
50
+ # return first generate PIL image
51
+ return out.images[0]
52
+
53
+ # helper to decode input image
54
+ def decode_base64_image(self, image_string):
55
+ base64_image = base64.b64decode(image_string)
56
+ buffer = BytesIO(base64_image)
57
+ image = Image.open(buffer)
58
+ return image