add custom handler for swin2sr
Browse files- handler.py +34 -0
- requirements.txt +5 -0
handler.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import pipeline
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import io, base64, requests
|
| 4 |
+
|
| 5 |
+
# Load model once when the container starts
|
| 6 |
+
def load_model():
|
| 7 |
+
print("Loading Swin2SR model...")
|
| 8 |
+
return pipeline("image-to-image", model="sergeipetrov/swin2SR-classical-sr-x2-64")
|
| 9 |
+
|
| 10 |
+
model = load_model()
|
| 11 |
+
|
| 12 |
+
# Hugging Face Inference Endpoint entrypoint
|
| 13 |
+
def __call__(data):
|
| 14 |
+
# data can be dict with "inputs" (URL or base64)
|
| 15 |
+
image_input = data.get("inputs")
|
| 16 |
+
|
| 17 |
+
# If it's a URL
|
| 18 |
+
if isinstance(image_input, str) and image_input.startswith("http"):
|
| 19 |
+
image = Image.open(requests.get(image_input, stream=True).raw).convert("RGB")
|
| 20 |
+
else:
|
| 21 |
+
# assume it's base64
|
| 22 |
+
image_bytes = base64.b64decode(image_input)
|
| 23 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 24 |
+
|
| 25 |
+
# Run inference
|
| 26 |
+
result = model(image)[0]
|
| 27 |
+
|
| 28 |
+
# Convert to base64 for API response
|
| 29 |
+
buffered = io.BytesIO()
|
| 30 |
+
result.save(buffered, format="PNG")
|
| 31 |
+
encoded_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 32 |
+
|
| 33 |
+
return {"image_base64": encoded_image}
|
| 34 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.38.0
|
| 2 |
+
torch
|
| 3 |
+
Pillow
|
| 4 |
+
requests
|
| 5 |
+
|