Update handler.py
Browse files- handler.py +40 -66
handler.py
CHANGED
|
@@ -1,79 +1,53 @@
|
|
| 1 |
-
from typing import Dict,
|
| 2 |
-
import
|
| 3 |
-
import requests
|
| 4 |
from io import BytesIO
|
| 5 |
-
|
| 6 |
-
import
|
| 7 |
-
from torchvision import transforms
|
| 8 |
-
from transformers import AutoModelForImageSegmentation
|
| 9 |
-
|
| 10 |
-
# --- Configuraci贸n ---
|
| 11 |
-
torch.set_float32_matmul_precision(["high", "highest"][0])
|
| 12 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
|
| 14 |
class EndpointHandler():
|
| 15 |
def __init__(self, path=''):
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
'zhengpeng7/BiRefNet',
|
| 19 |
-
trust_remote_code=True
|
| 20 |
-
)
|
| 21 |
-
self.model.to(device)
|
| 22 |
-
self.model.eval()
|
| 23 |
-
self.model.half() # Usamos media precisi贸n para velocidad
|
| 24 |
|
| 25 |
def __call__(self, data: Dict[str, Any]):
|
| 26 |
-
# 1.
|
| 27 |
image_src = data["inputs"]
|
| 28 |
image = None
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
image = Image.open(BytesIO(image_src))
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
# 2.
|
| 47 |
-
# Convertimos a RGB puro para eliminar cualquier rareza del archivo original
|
| 48 |
image = image.convert("RGB")
|
| 49 |
-
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
#
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 59 |
-
])
|
| 60 |
-
|
| 61 |
-
input_tensor = transform(image).unsqueeze(0).to(device).half()
|
| 62 |
-
|
| 63 |
-
with torch.no_grad():
|
| 64 |
-
# Predicci贸n
|
| 65 |
-
preds = self.model(input_tensor)[-1].sigmoid().cpu()
|
| 66 |
-
|
| 67 |
-
# 4. M脕SCARA (Sin Numpy, Solo PIL)
|
| 68 |
-
pred = preds[0].squeeze()
|
| 69 |
-
mask_pil = transforms.ToPILImage()(pred)
|
| 70 |
-
|
| 71 |
-
# Redimensionamos la m谩scara al tama帽o EXACTO de la imagen original
|
| 72 |
-
mask_pil = mask_pil.resize(orig_size, resample=Image.Resampling.LANCZOS)
|
| 73 |
-
|
| 74 |
-
# 5. APLICACI脫N FINAL
|
| 75 |
-
# Tomamos la imagen RGB original y le "inyectamos" la m谩scara en el canal Alfa.
|
| 76 |
-
# NO tocamos los colores. Solo decimos qu茅 es transparente.
|
| 77 |
-
image.putalpha(mask_pil)
|
| 78 |
-
|
| 79 |
return image
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
+
from PIL import Image, ImageDraw
|
|
|
|
| 3 |
from io import BytesIO
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
class EndpointHandler():
|
| 8 |
def __init__(self, path=''):
|
| 9 |
+
# No cargamos ning煤n modelo pesado para esta prueba
|
| 10 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def __call__(self, data: Dict[str, Any]):
|
| 13 |
+
# 1. Intentar leer la imagen de todas las formas posibles
|
| 14 |
image_src = data["inputs"]
|
| 15 |
image = None
|
| 16 |
|
| 17 |
+
try:
|
| 18 |
+
# Caso A: Hugging Face ya la decodific贸 como Objeto Imagen
|
| 19 |
+
if isinstance(image_src, Image.Image):
|
| 20 |
+
image = image_src
|
| 21 |
+
# Caso B: Es una URL o Ruta
|
| 22 |
+
elif isinstance(image_src, str):
|
| 23 |
+
if image_src.startswith('http'):
|
| 24 |
+
image = Image.open(BytesIO(requests.get(image_src).content))
|
| 25 |
+
elif os.path.exists(image_src):
|
| 26 |
+
image = Image.open(image_src)
|
| 27 |
+
else:
|
| 28 |
+
# Es una cadena de bytes (base64 decodeada string?)
|
| 29 |
+
pass
|
| 30 |
+
# Caso C: Son bytes crudos
|
| 31 |
+
else:
|
| 32 |
image = Image.open(BytesIO(image_src))
|
| 33 |
+
except Exception as e:
|
| 34 |
+
# Si falla la lectura, creamos una imagen de ERROR con texto
|
| 35 |
+
img_err = Image.new('RGB', (500, 500), color='yellow')
|
| 36 |
+
return img_err
|
| 37 |
+
|
| 38 |
+
if not image:
|
| 39 |
+
# Si no se pudo cargar, devolvemos imagen AZUL (Diagn贸stico)
|
| 40 |
+
return Image.new('RGB', (500, 500), color='blue')
|
| 41 |
|
| 42 |
+
# 2. Si la imagen se ley贸 bien, la convertimos a RGB
|
|
|
|
| 43 |
image = image.convert("RGB")
|
| 44 |
+
|
| 45 |
+
# 3. DIBUJAR UN CUADRO ROJO EN EL CENTRO
|
| 46 |
+
# Esto nos confirma que el servidor manipul贸 la imagen
|
| 47 |
+
draw = ImageDraw.Draw(image)
|
| 48 |
+
w, h = image.size
|
| 49 |
+
# Cuadro rojo de 100x100 en el centro
|
| 50 |
+
draw.rectangle([w//2 - 50, h//2 - 50, w//2 + 50, h//2 + 50], fill="red", outline="white")
|
| 51 |
+
|
| 52 |
+
# Devolvemos la imagen original pintada
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return image
|