Hadimeeee commited on
Commit
e397040
·
verified ·
1 Parent(s): d8a6de2

Upload runpod_handler.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. runpod_handler.py +64 -0
runpod_handler.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ import os
4
+
5
+ import runpod
6
+ from PIL import Image
7
+
8
+ from pipeline import load_pipeline
9
+
10
+
11
+ PIPELINE = load_pipeline(os.getenv("LORA_PATH", "."))
12
+
13
+
14
+ def _as_bool(value, default: bool = True) -> bool:
15
+ if value is None:
16
+ return default
17
+ if isinstance(value, bool):
18
+ return value
19
+ if isinstance(value, str):
20
+ return value.lower() in {"1", "true", "yes", "on"}
21
+ return bool(value)
22
+
23
+
24
+ def _decode_image(data: str) -> Image.Image:
25
+ if data.startswith("data:image"):
26
+ data = data.split(",", 1)[1]
27
+ return Image.open(io.BytesIO(base64.b64decode(data))).convert("RGB")
28
+
29
+
30
+ def _encode_png(image: Image.Image) -> str:
31
+ buffer = io.BytesIO()
32
+ image.save(buffer, format="PNG")
33
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
34
+
35
+
36
+ def handler(event):
37
+ payload = event.get("input", {})
38
+ image_b64 = payload.get("image")
39
+ if not image_b64:
40
+ return {"error": "Missing input.image base64 PNG/JPEG data."}
41
+
42
+ image = _decode_image(image_b64)
43
+ seed = payload.get("seed")
44
+ if seed is not None:
45
+ seed = int(seed)
46
+
47
+ output = PIPELINE(
48
+ image=image,
49
+ num_inference_steps=int(payload.get("num_inference_steps", 50)),
50
+ guidance_scale=float(payload.get("guidance_scale", 7.5)),
51
+ controlnet_conditioning_scale=float(payload.get("controlnet_conditioning_scale", 0.8)),
52
+ strength=float(payload.get("strength", 0.75)),
53
+ quantize=_as_bool(payload.get("quantize"), True),
54
+ n_colors=int(payload.get("n_colors", 32)),
55
+ seed=seed,
56
+ )
57
+
58
+ return {
59
+ "image": _encode_png(output["image"]),
60
+ "rembg_ok": output["rembg_ok"],
61
+ }
62
+
63
+
64
+ runpod.serverless.start({"handler": handler})