RepuestosMOM commited on
Commit
be6a051
verified
1 Parent(s): 29594a0

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +56 -10
handler.py CHANGED
@@ -1,18 +1,64 @@
1
  from typing import Dict, Any
2
- from PIL import Image, ImageDraw
3
- import io
 
 
 
 
 
 
 
 
 
4
 
5
  class EndpointHandler():
6
  def __init__(self, path=''):
7
- pass
 
 
 
 
 
 
 
8
 
9
  def __call__(self, data: Dict[str, Any]):
10
- # IGNORAMOS la entrada.
11
- # Creamos una imagen VERDE de 800x800 desde cero.
12
- img = Image.new('RGB', (800, 800), color=(0, 255, 0)) # Verde Brillante
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Le escribimos un texto o dibujamos un c铆rculo azul para confirmar
15
- draw = ImageDraw.Draw(img)
16
- draw.ellipse((200, 200, 600, 600), fill=(0, 0, 255)) # C铆rculo Azul
17
 
18
- return img
 
1
  from typing import Dict, 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 el modelo BiRefNet original (Efectivo y r谩pido)
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()
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
+ if isinstance(image_src, Image.Image):
31
+ image = image_src
32
+ elif isinstance(image_src, str):
33
+ if image_src.startswith('http'):
34
+ image = Image.open(BytesIO(requests.get(image_src).content))
35
+ else:
36
+ image = Image.open(image_src)
37
+ else:
38
+ image = Image.open(BytesIO(image_src))
39
+
40
+ # 2. LIMPIEZA: Aseguramos RGB (Color Real)
41
+ image = image.convert("RGB")
42
+ orig_size = image.size
43
+
44
+ # 3. PROCESAMIENTO IA
45
+ transform = transforms.Compose([
46
+ transforms.Resize((1024, 1024)),
47
+ transforms.ToTensor(),
48
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
49
+ ])
50
+
51
+ input_tensor = transform(image).unsqueeze(0).to(device).half()
52
+
53
+ with torch.no_grad():
54
+ preds = self.model(input_tensor)[-1].sigmoid().cpu()
55
+
56
+ # 4. M脕SCARA
57
+ pred = preds[0].squeeze()
58
+ mask_pil = transforms.ToPILImage()(pred)
59
+ mask_pil = mask_pil.resize(orig_size, resample=Image.Resampling.LANCZOS)
60
 
61
+ # 5. APLICACI脫N FINAL (Sin tocar colores)
62
+ image.putalpha(mask_pil)
 
63
 
64
+ return image