File size: 2,020 Bytes
57d100e
 
 
 
 
 
 
 
 
 
 
a433645
57d100e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a7e6c6
57d100e
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

import gradio as gr
from transformers import AutoImageProcessor, AutoModelForObjectDetection
import torch
from PIL import Image, ImageDraw

# Cargar modelo desde el Hub (Recomendado) o Local
# Si subiste tu modelo con trainer.push_to_hub(), usa tu ID: NO 'yolo_finetuned_raccoon' local.
# Ejemplo: model_id = "daniihc16/yolo_finetuned_raccoon" (Sustituye por tu usuario)

# AQUÍ DEBES PONER EL ID DE TU MODELO SUBIDO A HUGGINGFACE
model_id = "daniihc16/yolo_finetuned_raccoon"

try:
    image_processor = AutoImageProcessor.from_pretrained(model_id)
    model = AutoModelForObjectDetection.from_pretrained(model_id)
except Exception as e:
    print(f"Error cargando modelo: {e}. Asegúrate de poner el ID correcto.")
    raise e

def predict(image):
    if image is None: return None
    
    inputs = image_processor(images=image, return_tensors="pt")
    
    with torch.no_grad():
        outputs = model(**inputs)
    
    target_sizes = torch.tensor([image.size[::-1]])
    # Usamos un umbral de 0.5 para mostrar solo detecciones firmes
    results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
    
    draw = ImageDraw.Draw(image)
    
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [round(i, 2) for i in box.tolist()]
        x, y, x2, y2 = tuple(box)
        
        # Dibujar caja
        draw.rectangle((x, y, x2, y2), outline="red", width=3)
        
        # Dibujar etiqueta
        label_name = model.config.id2label[label.item()]
        draw.text((x, y), f"{label_name}: {round(score.item(), 2)}", fill="red")
        
    return image

iface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=gr.Image(type="pil"),
    title="Detector de Mapaches (Raccoon Detection)",
    description="Sube una imagen para detectar mapaches usando un modelo YOLOS Finetuned.",
    examples=['raccoon-1.jpg', 'raccoon-12.jpg']
)

if __name__ == "__main__":
    iface.launch()