Download entrenamiento/evaluar_conteo.py from EagleDev-Innovation/Modelos-EagleDev-Innovation: direct link, hf CLI and curl.
- Browser
- Download file 6.07 kB
-
https://huggingface.co/EagleDev-Innovation/Modelos-EagleDev-Innovation/resolve/main/entrenamiento/evaluar_conteo.py
- Command line
-
hf download hf://EagleDev-Innovation/Modelos-EagleDev-Innovation/entrenamiento/evaluar_conteo.py
-
curl -L -o evaluar_conteo.py https://huggingface.co/EagleDev-Innovation/Modelos-EagleDev-Innovation/resolve/main/entrenamiento/evaluar_conteo.py
6.07 kB
| """Mide el error del conteo con SAM 3 y elige el umbral de confianza con datos. | |
| uv run python -m entrenamiento.evaluar_conteo # 25 fotos por material | |
| uv run python -m entrenamiento.evaluar_conteo 60 # 60 fotos por material | |
| SAM 3 no se entrena, pero sí se puede medir: se usan datasets de detección donde cada | |
| recuadro etiquetado es una pieza (Fuente.piezas), así se sabe la cantidad real de cada foto. | |
| 1. Se ejecuta SAM 3 con un umbral bajo (0.1) y se guardan todas las detecciones. | |
| 2. Para cada umbral entre 0.1 y 0.9 se recalcula la cantidad (sin volver a ejecutar SAM 3) | |
| y se mide el error medio. Se elige el umbral con menor error. | |
| 3. Se escribe modelos_entrenados/conteo/informe.md y umbral.json; el servicio usa ese | |
| umbral si existe (CONTEO_UMBRAL del .env tiene prioridad si se define). | |
| """ | |
| import json | |
| import random | |
| import re | |
| import sys | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image, ImageOps | |
| from app.core.config import settings | |
| from app.ml.materiales import MATERIAL_POR_CODIGO | |
| from app.ml.vision.contador_piezas import ContadorSam3, Pieza, filtrar_piezas | |
| from entrenamiento.descargar import MARCA | |
| from entrenamiento.fuentes import FUENTES | |
| from entrenamiento.rutas import CRUDOS | |
| SALIDA = settings.ruta_modelos / "conteo" | |
| UMBRALES = [round(u, 2) for u in np.arange(0.1, 0.91, 0.05)] | |
| LADO = 1024 | |
| def muestras(por_material: int) -> dict[str, list[tuple[Path, int]]]: | |
| """(foto, cantidad real) por material, de las fuentes con piezas etiquetadas.""" | |
| rng = random.Random(7) | |
| resultado: dict[str, list[tuple[Path, int]]] = defaultdict(list) | |
| for fuente in FUENTES: | |
| carpeta = CRUDOS / fuente.nombre | |
| if not fuente.piezas or not (carpeta / MARCA).is_file(): | |
| continue | |
| candidatas = [] | |
| for archivo in carpeta.rglob("_annotations.coco.json"): | |
| coco = json.loads(archivo.read_text(encoding="utf-8")) | |
| ids_pieza = { | |
| c["id"] for c in coco["categories"] if re.search(fuente.piezas, c["name"], re.I) | |
| } | |
| cuenta = defaultdict(int) | |
| for a in coco["annotations"]: | |
| if a["category_id"] in ids_pieza: | |
| cuenta[a["image_id"]] += 1 | |
| for img in coco["images"]: | |
| ruta = archivo.parent / img["file_name"] | |
| # Variantes aumentadas de Roboflow fuera: solo una por foto original. | |
| if ruta.is_file() and ".rf." in ruta.name and 1 <= cuenta[img["id"]] <= 40: | |
| candidatas.append((ruta, cuenta[img["id"]])) | |
| vistas: set[str] = set() | |
| unicas = [] | |
| for ruta, n in candidatas: | |
| clave = ruta.name.split(".rf.")[0] | |
| if clave not in vistas: | |
| vistas.add(clave) | |
| unicas.append((ruta, n)) | |
| rng.shuffle(unicas) | |
| # Las fuentes por recortes no tienen `material`: se usa el de sus recortes. | |
| materiales = {fuente.material} if fuente.material else set(fuente.recortes.values()) | |
| if len(materiales) != 1: | |
| raise SystemExit(f"{fuente.nombre}: las piezas deben ser de un solo material") | |
| resultado[materiales.pop()] += unicas | |
| return {m: lista[:por_material] for m, lista in resultado.items()} | |
| def main(por_material: int) -> None: | |
| SALIDA.mkdir(parents=True, exist_ok=True) | |
| datos = muestras(por_material) | |
| if not datos: | |
| raise SystemExit("No hay fuentes de conteo descargadas (Fuente.piezas).") | |
| contador = ContadorSam3(settings.conteo_modelo, settings.ruta_modelos, umbral=0.1) | |
| detecciones: dict[str, list[tuple[int, list[Pieza]]]] = defaultdict(list) | |
| tiempos = [] | |
| for material, lista in datos.items(): | |
| consultas = MATERIAL_POR_CODIGO[material].consultas_conteo | |
| for i, (ruta, real) in enumerate(lista, 1): | |
| with Image.open(ruta) as original: | |
| imagen = ImageOps.exif_transpose(original).convert("RGB") | |
| imagen.thumbnail((LADO, LADO)) | |
| inicio = time.time() | |
| piezas = contador.detectar(imagen, consultas) | |
| tiempos.append(time.time() - inicio) | |
| detecciones[material].append((real, piezas)) | |
| print( | |
| f"{material} {i}/{len(lista)}: real {real}, detectadas (≥0.1) {len(piezas)}", | |
| flush=True, | |
| ) | |
| def errores(umbral: float, material: str | None = None) -> np.ndarray: | |
| filas = [ | |
| abs(len(filtrar_piezas([p for p in piezas if p.confianza >= umbral])) - real) | |
| for m, lista in detecciones.items() | |
| if material in (None, m) | |
| for real, piezas in lista | |
| ] | |
| return np.array(filas) | |
| mejor = min(UMBRALES, key=lambda u: errores(u).mean()) | |
| lineas = [ | |
| "# Evaluación del conteo (SAM 3, sin entrenar)", | |
| "", | |
| f"- Fotos: {sum(len(v) for v in detecciones.values())} · Tiempo medio por foto (CPU): {np.mean(tiempos):.1f} s", | |
| f"- **Umbral elegido: {mejor}** (menor error medio)", | |
| "", | |
| "| Material | Fotos | Error medio (piezas) | Exacto | ±1 pieza |", | |
| "|---|---|---|---|---|", | |
| ] | |
| for material in [*detecciones, None]: | |
| e = errores(mejor, material) | |
| nombre = material or "**Total**" | |
| lineas.append( | |
| f"| {nombre} | {len(e)} | {e.mean():.2f} | {(e == 0).mean():.0%} | {(e <= 1).mean():.0%} |" | |
| ) | |
| lineas += ["", "Error medio según el umbral:", "", "| Umbral | Error medio |", "|---|---|"] | |
| lineas += [f"| {u} | {errores(u).mean():.2f} |" for u in UMBRALES] | |
| informe = "\n".join(lineas) + "\n" | |
| (SALIDA / "informe.md").write_text(informe, encoding="utf-8") | |
| (SALIDA / "umbral.json").write_text(json.dumps({"umbral": mejor}), encoding="utf-8") | |
| print("\n" + informe) | |
| if __name__ == "__main__": | |
| main(int(sys.argv[1]) if len(sys.argv) > 1 else 25) | |