hafsa000 commited on
Commit
02e49ec
1 Parent(s): d0fc6e4

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +48 -0
handler.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from PIL import Image
3
+ from io import BytesIO
4
+ import torch
5
+ import base64
6
+ from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler
7
+
8
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
+
10
+ class EndpointHandler():
11
+ def __init__(self, path=""):
12
+ model_id = "timbrooks/instruct-pix2pix"
13
+ self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, safety_checker=None)
14
+ self.pipe.to(device)
15
+ self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
16
+
17
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
18
+ """
19
+ data args:
20
+ inputs (:obj:`string`)
21
+ parameters (:obj:)
22
+ Return:
23
+ A :obj:`string`:. image string
24
+ """
25
+
26
+
27
+ image_data = data.pop('inputs', data)
28
+ # decode base64 image to PIL
29
+ image = Image.open(BytesIO(base64.b64decode(image_data)))
30
+
31
+ parameters = data.pop('parameters', [])
32
+ prompt = parameters.pop('prompt', None)
33
+ negative_prompt = parameters.pop('negative_prompt', None)
34
+ num_inference_steps = parameters.pop('num_inference_steps', 10)
35
+ image_guidance_scale = parameters.pop('image_guidance_scale', 1.5)
36
+ guidance_scale = parameters.pop('guidance_scale', 7.5)
37
+
38
+
39
+ images = self.pipe(
40
+ prompt,
41
+ image = image,
42
+ negative_prompt = negative_prompt,
43
+ num_inference_steps = num_inference_steps,
44
+ image_guidance_scale = image_guidance_scale,
45
+ guidance_scale = guidance_scale
46
+ ).images
47
+
48
+ return images[0]