Spaces:
Sleeping
Sleeping
Download app.py from ogaf301721/ucmtest: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/spaces/ogaf301721/ucmtest/resolve/main/app.py
- Command line
-
hf download hf://spaces/ogaf301721/ucmtest/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ogaf301721/ucmtest/resolve/main/app.py
2.06 kB
| import os | |
| import tempfile | |
| import gradio as gr | |
| from PIL import Image | |
| from ultralytics import YOLO | |
| model = YOLO("best.pt") | |
| print("Modelo cargado correctamente") | |
| print("Clases del modelo:", model.names) | |
| def detect(image): | |
| if image is None: | |
| return None, "No has subido ninguna imagen todavía." | |
| with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp: | |
| temp_path = tmp.name | |
| image = image.convert("RGB") | |
| image.save(temp_path, format="JPEG") | |
| try: | |
| results = model.predict( | |
| source=temp_path, | |
| imgsz=640, | |
| conf=0.001, | |
| iou=0.5, | |
| verbose=False, | |
| device="cpu" | |
| ) | |
| result = results[0] | |
| num_det = 0 if result.boxes is None else len(result.boxes) | |
| if num_det == 0: | |
| status = ( | |
| "No se han detectado objetos. " | |
| "Si esta misma imagen sí funcionaba en Colab, casi seguro que " | |
| "el best.pt subido al Space no es el mismo, o el modelo se entrenó mal." | |
| ) | |
| else: | |
| etiquetas = [] | |
| for box in result.boxes[:10]: | |
| cls_id = int(box.cls[0]) | |
| conf = float(box.conf[0]) | |
| nombre = model.names.get(cls_id, str(cls_id)) | |
| etiquetas.append(f"{nombre} ({conf:.2f})") | |
| status = f"Detecciones encontradas: {num_det}. " + " | ".join(etiquetas) | |
| plotted_bgr = result.plot() | |
| plotted_rgb = plotted_bgr[..., ::-1] | |
| return plotted_rgb, status | |
| finally: | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| demo = gr.Interface( | |
| fn=detect, | |
| inputs=gr.Image(type="pil", label="Sube una imagen"), | |
| outputs=[ | |
| gr.Image(type="numpy", label="Resultado"), | |
| gr.Textbox(label="Diagnóstico") | |
| ], | |
| title="Detector de taza y botella", | |
| description=( | |
| "Demo de inferencia del modelo entrenado en clase. " | |
| "Sube una imagen y verás las cajas detectadas." | |
| ) | |
| ) | |
| demo.launch() |