RepuestosMOM commited on
Commit
f2b8e83
verified
1 Parent(s): 2d27abc

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +40 -66
handler.py CHANGED
@@ -1,79 +1,53 @@
1
- from typing import Dict, List, Any
2
- import os
3
- import requests
4
  from io import BytesIO
5
- from PIL import Image
6
- import torch
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
- # Cargamos BiRefNet (General)
17
- self.model = AutoModelForImageSegmentation.from_pretrained(
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. RECIBIR IMAGEN (Entrada Blindada)
27
  image_src = data["inputs"]
28
  image = None
29
 
30
- # Detectar si es Bytes, URL o PIL Image
31
- if isinstance(image_src, Image.Image):
32
- image = image_src
33
- elif isinstance(image_src, str):
34
- if os.path.exists(image_src):
35
- image = Image.open(image_src)
36
- elif image_src.startswith('http'):
37
- image = Image.open(BytesIO(requests.get(image_src).content))
38
- else:
39
- # Asumimos bytes
40
- try:
 
 
 
 
41
  image = Image.open(BytesIO(image_src))
42
- except:
43
- # Fallback final
44
- image = Image.fromarray(image_src)
 
 
 
 
 
45
 
46
- # 2. LIMPIEZA DE COLOR (CRUCIAL)
47
- # Convertimos a RGB puro para eliminar cualquier rareza del archivo original
48
  image = image.convert("RGB")
49
-
50
- # Guardamos el tama帽o original para luego
51
- orig_size = image.size
52
-
53
- # 3. PROCESAMIENTO IA
54
- # Transformaci贸n est谩ndar para BiRefNet (1024x1024)
55
- transform = transforms.Compose([
56
- transforms.Resize((1024, 1024)),
57
- transforms.ToTensor(),
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