Gjm1234 commited on
Commit
93b4067
·
verified ·
1 Parent(s): 9d0e5c5

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +57 -0
handler.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel
3
+ from diffusers.utils import load_image
4
+ import base64
5
+ import io
6
+ from PIL import Image
7
+
8
+ class EndpointHandler:
9
+ def __init__(self, model_dir=None):
10
+ # Load ControlNet (Depth)
11
+ self.controlnet = ControlNetModel.from_pretrained(
12
+ "diffusers/controlnet-depth-sdxl-1.0",
13
+ torch_dtype=torch.float16
14
+ )
15
+
16
+ # Load Juggernaut XL as base model (from HuggingFace)
17
+ self.pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
18
+ "RunDiffusion/Juggernaut-XL-v9",
19
+ controlnet=self.controlnet,
20
+ torch_dtype=torch.float16
21
+ ).to("cuda")
22
+
23
+ self.pipe.enable_xformers_memory_efficient_attention()
24
+
25
+ def __call__(self, data):
26
+ # Parse prompt
27
+ prompt = data.get("prompt", "")
28
+
29
+ # Optional negative prompt
30
+ negative_prompt = data.get("negative_prompt", "bad quality, distortions")
31
+
32
+ # Handle uploaded image (base64 or raw bytes)
33
+ image_bytes = data.get("image")
34
+
35
+ if isinstance(image_bytes, str):
36
+ image_bytes = base64.b64decode(image_bytes)
37
+
38
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
39
+
40
+ # Generate 10 images
41
+ results = self.pipe(
42
+ prompt=prompt,
43
+ negative_prompt=negative_prompt,
44
+ image=image,
45
+ num_inference_steps=35,
46
+ guidance_scale=7.5,
47
+ controlnet_conditioning_scale=1.0,
48
+ num_images_per_prompt=10
49
+ )
50
+
51
+ output_images = []
52
+ for img in results.images:
53
+ buffer = io.BytesIO()
54
+ img.save(buffer, format="JPEG")
55
+ output_images.append(base64.b64encode(buffer.getvalue()).decode())
56
+
57
+ return { "images": output_images }