Update handler.py
Browse files- handler.py +55 -0
handler.py
CHANGED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import io
|
| 4 |
+
import base64
|
| 5 |
+
from rembg import remove, new_session
|
| 6 |
+
|
| 7 |
+
class EndpointHandler():
|
| 8 |
+
def __init__(self, path=""):
|
| 9 |
+
# Preload the rembg session.
|
| 10 |
+
# By default, it uses the 'u2net' model.
|
| 11 |
+
# This ensures the model is loaded into memory when the endpoint starts.
|
| 12 |
+
self.session = new_session()
|
| 13 |
+
|
| 14 |
+
def __call__(self, data: Dict[str, Any]) -> Any:
|
| 15 |
+
"""
|
| 16 |
+
Args:
|
| 17 |
+
data (:obj: `Dict`):
|
| 18 |
+
- "inputs": PIL.Image or base64 string
|
| 19 |
+
- "parameters": (Optional) Dict containing rembg options like 'alpha_matting'
|
| 20 |
+
Return:
|
| 21 |
+
A PIL.Image or serialized image.
|
| 22 |
+
"""
|
| 23 |
+
# Get inputs
|
| 24 |
+
inputs = data.get("inputs", None)
|
| 25 |
+
if inputs is None:
|
| 26 |
+
return {"error": "No inputs provided"}
|
| 27 |
+
|
| 28 |
+
# Hugging Face usually passes the image as a PIL object
|
| 29 |
+
# if the request Content-Type is image/*
|
| 30 |
+
if isinstance(inputs, str):
|
| 31 |
+
# Handle base64 string if necessary
|
| 32 |
+
image_data = base64.b64decode(inputs)
|
| 33 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
| 34 |
+
elif isinstance(inputs, Image.Image):
|
| 35 |
+
image = inputs
|
| 36 |
+
else:
|
| 37 |
+
# Fallback for raw bytes
|
| 38 |
+
image = Image.open(io.BytesIO(inputs)).convert("RGB")
|
| 39 |
+
|
| 40 |
+
# Extract optional parameters for rembg.remove
|
| 41 |
+
# e.g., alpha_matting, bgcolor, etc.
|
| 42 |
+
params = data.get("parameters", {})
|
| 43 |
+
|
| 44 |
+
# Execute background removal
|
| 45 |
+
# rembg.remove returns a PIL Image with an alpha channel (RGBA)
|
| 46 |
+
output_image = remove(
|
| 47 |
+
image,
|
| 48 |
+
session=self.session,
|
| 49 |
+
**params
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Return the PIL Image directly.
|
| 53 |
+
# Hugging Face Inference Endpoints will automatically serialize
|
| 54 |
+
# a PIL Image into a response.
|
| 55 |
+
return output_image
|