Spaces:
Sleeping
Sleeping
Download app.py from JLERMO/FragUNIApp: direct link, hf CLI and curl.
- Browser
- Download file 34 kB
-
https://huggingface.co/spaces/JLERMO/FragUNIApp/resolve/main/app.py
- Command line
-
hf download hf://spaces/JLERMO/FragUNIApp/app.py
-
curl -L -o app.py https://huggingface.co/spaces/JLERMO/FragUNIApp/resolve/main/app.py
34 kB
| import gradio as gr | |
| import cv2 | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import matplotlib.ticker as mticker | |
| from matplotlib.patches import Patch | |
| import pandas as pd | |
| import gc | |
| import tempfile | |
| import os | |
| from ultralytics import YOLO | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AUTENTICACION | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| USERS = { | |
| "SPCC": "1234", | |
| "demo": "demopass", | |
| "juan": "fragmentapp" | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # IDENTIDAD INSTITUCIONAL | |
| # SOUTHERN PERU COPPER CORPORATION β UNIDAD MINERA CUAJONE | |
| # Colores corporativos: | |
| # Rojo Southern : R 212, G 32, B 42 | |
| # Gris Southern : R 84, G 88, B 90 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SPCC_ROJO = "#D4202A" # RGB(212, 32, 42) | |
| SPCC_GRIS = "#54585A" # RGB(84, 88, 90) | |
| SPCC_GRIS_C = "#9A9CA0" # gris claro para textos secundarios | |
| SPCC_NEGRO = "#000000" | |
| SPCC_BLANCO = "#FFFFFF" | |
| # Mismo rojo, en formato BGR (OpenCV) para dibujar sobre las imagenes | |
| SPCC_ROJO_BGR = (42, 32, 212) | |
| EMPRESA_NOMBRE = "SOUTHERN PERU COPPER CORPORATION" | |
| UNIDAD_NOMBRE = "UNIDAD MINERA CUAJONE" | |
| # Creditos completos: SOLO se muestran en la pantalla de inicio (login) | |
| AUTOR_INICIO = ( | |
| "AUTOR: Superintendencia IngenierΓa Mina β CΓ©sar Guerra Carpio<br>" | |
| "APOYO: Juan Carlos Lermo Layme" | |
| ) | |
| # Credito corto: se usa dentro de la aplicacion y en el pie de pagina | |
| AUTOR_TEXTO = "Superintendencia IngenierΓa Mina β Cuajone" | |
| # Logo corporativo (colocar el archivo junto a este script) | |
| LOGO_PATH = "logo_southern.png" | |
| LOGO_DISPONIBLE = os.path.exists(LOGO_PATH) | |
| CSS_INSTITUCIONAL = f""" | |
| .gradio-container {{ | |
| font-family: 'Inter', 'Segoe UI', sans-serif; | |
| background: {SPCC_BLANCO} !important; | |
| }} | |
| body, .gradio-container, .app, .main, .wrap {{ | |
| background: {SPCC_BLANCO} !important; | |
| }} | |
| #encabezado-spcc {{ | |
| border-bottom: 3px solid {SPCC_ROJO}; | |
| padding-bottom: 8px; | |
| margin-bottom: 6px; | |
| }} | |
| #encabezado-spcc h1 {{ | |
| color: {SPCC_ROJO}; | |
| font-weight: 700; | |
| letter-spacing: 0.5px; | |
| }} | |
| .empresa-nombre {{ | |
| color: {SPCC_GRIS}; | |
| font-weight: 700; | |
| font-size: 15px; | |
| letter-spacing: 1px; | |
| }} | |
| .unidad-nombre {{ | |
| color: {SPCC_ROJO}; | |
| font-weight: 600; | |
| font-size: 14px; | |
| letter-spacing: 1px; | |
| }} | |
| .autor-credito {{ | |
| color: {SPCC_GRIS_C}; | |
| font-size: 13px; | |
| line-height: 1.5; | |
| margin-top: -6px; | |
| }} | |
| button.primary, .gr-button-primary {{ | |
| background: {SPCC_ROJO} !important; | |
| border-color: {SPCC_ROJO} !important; | |
| color: {SPCC_BLANCO} !important; | |
| }} | |
| button.secondary {{ | |
| border-color: {SPCC_ROJO} !important; | |
| color: {SPCC_ROJO} !important; | |
| }} | |
| .section-label {{ | |
| color: {SPCC_ROJO}; | |
| font-weight: 600; | |
| font-size: 14px; | |
| border-left: 4px solid {SPCC_GRIS}; | |
| padding-left: 8px; | |
| margin-top: 10px; | |
| }} | |
| footer {{ visibility: hidden; }} | |
| """ | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CARGA DEL MODELO (una sola vez al iniciar) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODELO_PATH = "best.pt" | |
| modelo = YOLO(MODELO_PATH) | |
| # Confianza fija (ya no es ajustable desde la interfaz) | |
| CONF_DEFAULT = 0.25 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONVERSION DE UNIDADES A PULGADAS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| UNIDADES_A_PULGADAS = { | |
| "m": 39.3700787, | |
| "cm": 0.393700787, | |
| "mm": 0.0393700787, | |
| "in": 1.0, | |
| "ft": 12.0, | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PALETA SIGMAFRAG (bandas de tamano por percentil) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SIGMAFRAG_BANDAS = [ | |
| ("< D01", None, 1, ( 20, 180, 220)), | |
| ("D01 - D05", 1, 5, ( 50, 220, 160)), | |
| ("D05 - D10", 5, 10, ( 50, 200, 50)), | |
| ("D10 - D20", 10, 20, (120, 230, 60)), | |
| ("D20 - D50", 20, 50, ( 50, 210, 210)), | |
| ("D50 - D80", 50, 80, ( 20, 200, 230)), | |
| ("D80 - D90", 80, 90, ( 30, 140, 230)), | |
| ("D90 - D95", 90, 95, ( 0, 60, 200)), | |
| ("> D95", 95, None, ( 0, 30, 160)), | |
| ] | |
| # Borde de los fragmentos: fino y en color institucional (rojo Southern) | |
| COLOR_CONTORNO_BGR = SPCC_ROJO_BGR | |
| GROSOR_CONTORNO = 1 | |
| # Marcado de sobretamaΓ±os / fragmentos anomalos | |
| COLOR_SOBRETAMANO_BGR = (0, 0, 0) # negro, para maximo contraste | |
| GROSOR_SOBRETAMANO = 3 | |
| # Colores de la linea y puntos de calibracion (BGR) | |
| COLOR_PUNTO_1_BGR = (40, 30, 0) | |
| COLOR_PUNTO_2_BGR = (0, 0, 200) | |
| COLOR_LINEA_BGR = (0, 215, 255) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FUNCIONES DE DIBUJO | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def generar_overlay_segmentacion(img_bgr, fragmentos): | |
| """Genera la imagen (array BGR) con las mascaras, contornos finos y el | |
| marcado de sobretamaΓ±os, a resolucion completa.""" | |
| overlay = img_bgr.copy() | |
| mask_color = np.zeros_like(img_bgr, dtype=np.uint8) | |
| for f in fragmentos: | |
| if f["mask"] is not None: | |
| color_bgr = f["color"] | |
| for c in range(3): | |
| mask_color[:, :, c][f["mask"].astype(bool)] = color_bgr[c] | |
| cv2.addWeighted(mask_color, 0.55, overlay, 0.45, 0, overlay) | |
| return overlay | |
| def fig_segmentacion(img_bgr, fragmentos): | |
| overlay = generar_overlay_segmentacion(img_bgr, fragmentos) | |
| overlay_rgb = cv2.cvtColor(overlay, cv2.COLOR_BGR2RGB) | |
| fig, ax = plt.subplots(figsize=(7, 5), facecolor=SPCC_BLANCO) | |
| ax.imshow(overlay_rgb) | |
| ax.axis("off") | |
| bandas_presentes = {f["banda"] for f in fragmentos} | |
| handles = [ | |
| Patch(facecolor=np.array(c[::-1]) / 255, label=e) | |
| for e, _, _, c in SIGMAFRAG_BANDAS if e in bandas_presentes | |
| ] | |
| ax.legend(handles=handles, loc="upper right", fontsize=8, framealpha=0.9, title="Bandas") | |
| ax.set_title("Segmentacion de fragmentos", fontsize=11, fontweight="bold", color=SPCC_ROJO) | |
| plt.tight_layout() | |
| return fig, overlay_rgb | |
| def fig_curva_granulometrica(curva, unidad): | |
| fig, ax = plt.subplots(figsize=(6, 5), facecolor=SPCC_BLANCO) | |
| ax.plot(curva["diametros"], curva["pct_pasante"], color=SPCC_ROJO, linewidth=2.5) | |
| for key, col in [("D50", "#6b7280"), ("D80", "#e67e22"), ("D20", "#27ae60")]: | |
| if key in curva: | |
| v = curva[key] | |
| p = int(key[1:]) | |
| ax.axvline(v, color=col, linestyle="--", linewidth=1.2, alpha=0.8) | |
| ax.axhline(p, color=col, linestyle=":", linewidth=0.8, alpha=0.5) | |
| ax.text(v, p + 2, f" {key}={v:.2f}", fontsize=8, color=col, va="bottom") | |
| ax.set_xlabel(f"Diametro ({unidad})") | |
| ax.set_ylabel("% Pasante") | |
| ax.set_ylim(0, 108) | |
| ax.grid(alpha=0.25) | |
| ax.yaxis.set_major_formatter(mticker.PercentFormatter()) | |
| ax.set_title("Curva granulometrica", fontsize=11, fontweight="bold", color=SPCC_ROJO) | |
| plt.tight_layout() | |
| return fig | |
| def fig_histograma(fragmentos, unidad, umbrales): | |
| diams = np.array([f["diam_equiv"] for f in fragmentos]) | |
| fig, ax = plt.subplots(figsize=(10, 4), facecolor=SPCC_BLANCO) | |
| n, bins, patches = ax.hist(diams, bins=28, edgecolor="white", linewidth=0.6) | |
| def color_bin(d): | |
| for etiq, p_inf, p_sup, color in SIGMAFRAG_BANDAS: | |
| v_inf = umbrales[p_inf] if p_inf is not None else -np.inf | |
| v_sup = umbrales[p_sup] if p_sup is not None else np.inf | |
| if v_inf <= d < v_sup: | |
| return np.array(color[::-1]) / 255 | |
| return np.array(SIGMAFRAG_BANDAS[-1][3][::-1]) / 255 | |
| for patch, left in zip(patches, bins[:-1]): | |
| patch.set_facecolor(color_bin(left)) | |
| ax.set_xlabel(f"Diametro ({unidad})") | |
| ax.set_ylabel("Numero de fragmentos") | |
| ax.grid(alpha=0.25, axis="y") | |
| handles = [Patch(facecolor=np.array(c[::-1]) / 255, label=e) for e, _, _, c in SIGMAFRAG_BANDAS] | |
| ax.legend(handles=handles, fontsize=8, ncol=2, title="Bandas") | |
| ax.set_title("Histograma de tamanos", fontsize=11, fontweight="bold", color=SPCC_ROJO) | |
| plt.tight_layout() | |
| return fig | |
| def dibujar_calibracion(img_bgr, p1x, p1y, p2x, p2y): | |
| """Copia de la imagen (RGB) con los puntos de calibracion y la linea | |
| que los une dibujados encima, sin alterar la imagen original.""" | |
| vista = img_bgr.copy() | |
| radio = max(4, int(0.006 * max(vista.shape[:2]))) | |
| grosor_linea = max(2, int(0.003 * max(vista.shape[:2]))) | |
| if p1x is not None and p1y is not None: | |
| cv2.circle(vista, (int(p1x), int(p1y)), radio, COLOR_PUNTO_1_BGR, -1) | |
| cv2.circle(vista, (int(p1x), int(p1y)), radio, (255, 255, 255), 2) | |
| cv2.putText(vista, "P1", (int(p1x) + radio + 4, int(p1y) - radio), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, COLOR_PUNTO_1_BGR, 2, cv2.LINE_AA) | |
| if p2x is not None and p2y is not None: | |
| cv2.circle(vista, (int(p2x), int(p2y)), radio, COLOR_PUNTO_2_BGR, -1) | |
| cv2.circle(vista, (int(p2x), int(p2y)), radio, (255, 255, 255), 2) | |
| cv2.putText(vista, "P2", (int(p2x) + radio + 4, int(p2y) - radio), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, COLOR_PUNTO_2_BGR, 2, cv2.LINE_AA) | |
| if None not in (p1x, p1y, p2x, p2y): | |
| pt1 = (int(p1x), int(p1y)) | |
| pt2 = (int(p2x), int(p2y)) | |
| dist = int(np.hypot(pt2[0] - pt1[0], pt2[1] - pt1[1])) | |
| n_segmentos = max(dist // 14, 1) | |
| for i in range(n_segmentos): | |
| if i % 2 == 0: | |
| t0 = i / n_segmentos | |
| t1 = (i + 1) / n_segmentos | |
| xa = int(pt1[0] + (pt2[0] - pt1[0]) * t0) | |
| ya = int(pt1[1] + (pt2[1] - pt1[1]) * t0) | |
| xb = int(pt1[0] + (pt2[0] - pt1[0]) * t1) | |
| yb = int(pt1[1] + (pt2[1] - pt1[1]) * t1) | |
| cv2.line(vista, (xa, ya), (xb, yb), COLOR_LINEA_BGR, grosor_linea, cv2.LINE_AA) | |
| return cv2.cvtColor(vista, cv2.COLOR_BGR2RGB) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PREPARACION DE IMAGEN AL CARGARLA | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def preparar_imagen(imagen): | |
| """Redimensiona la imagen apenas se carga y reinicia el estado de | |
| calibracion. Garantiza que las coordenadas de los clics coincidan | |
| exactamente con la imagen usada en el analisis.""" | |
| if imagen is None: | |
| return None, None, None, None, None, None, "Punto 1: no definido", "Punto 2: no definido" | |
| imagen_bgr = cv2.cvtColor(imagen, cv2.COLOR_RGB2BGR) | |
| alto, ancho = imagen_bgr.shape[:2] | |
| max_dim = 1024 | |
| if max(alto, ancho) > max_dim: | |
| escala_img = max_dim / max(alto, ancho) | |
| imagen_bgr = cv2.resize( | |
| imagen_bgr, | |
| (int(ancho * escala_img), int(alto * escala_img)), | |
| interpolation=cv2.INTER_AREA, | |
| ) | |
| imagen_rgb = cv2.cvtColor(imagen_bgr, cv2.COLOR_BGR2RGB) | |
| return ( | |
| imagen_rgb, | |
| imagen_rgb, | |
| None, None, None, None, | |
| "Punto 1: no definido", | |
| "Punto 2: no definido", | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AREA DE INTERES (SECCIONES / FORMAS LIBRES PARA SEGMENTAR) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def aplicar_roi(editor_value, imagen_base): | |
| """Convierte el trazo libre dibujado por el usuario en una mascara | |
| binaria que delimita la zona donde se ejecutara la segmentacion.""" | |
| texto_defecto = "Area de interes: imagen completa (sin restriccion)." | |
| if editor_value is None or imagen_base is None: | |
| return None, texto_defecto | |
| capa = None | |
| if isinstance(editor_value, dict): | |
| capas = editor_value.get("layers") or [] | |
| if capas: | |
| capa = capas[0] | |
| if capa is None: | |
| return None, "No se detecto ningun trazo. Se analizara la imagen completa." | |
| if capa.shape[-1] == 4: | |
| trazo = capa[..., 3] > 10 | |
| else: | |
| trazo = np.any(capa[..., :3] > 10, axis=-1) | |
| if trazo.sum() < 50: | |
| return None, "El area dibujada es muy pequena. Se analizara la imagen completa." | |
| trazo_u8 = (trazo.astype(np.uint8)) * 255 | |
| contornos, _ = cv2.findContours(trazo_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| relleno = np.zeros_like(trazo_u8) | |
| if contornos: | |
| cv2.drawContours(relleno, contornos, -1, 255, thickness=cv2.FILLED) | |
| mascara_final = (relleno > 0) | trazo | |
| h_base, w_base = imagen_base.shape[:2] | |
| if mascara_final.shape[:2] != (h_base, w_base): | |
| mascara_final = cv2.resize( | |
| mascara_final.astype(np.uint8), (w_base, h_base), interpolation=cv2.INTER_NEAREST | |
| ).astype(bool) | |
| porcentaje = 100.0 * mascara_final.sum() / mascara_final.size | |
| return mascara_final, f"Area de interes aplicada ({porcentaje:.1f}% de la imagen)." | |
| def limpiar_roi(): | |
| return None, "Area de interes: imagen completa (sin restriccion)." | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FUNCION PRINCIPAL DE PROCESAMIENTO | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def procesar_imagen(imagen_base, iou, unidad, p1x, p1y, p2x, p2y, distancia_real, roi_mask): | |
| if imagen_base is None: | |
| return None, None, None, None, None, None, None, "Atencion: carga una imagen primero." | |
| imagen_bgr = cv2.cvtColor(imagen_base, cv2.COLOR_RGB2BGR) | |
| alto_px, ancho_px = imagen_bgr.shape[:2] | |
| if any(v is None for v in [p1x, p1y, p2x, p2y]): | |
| return None, None, None, None, None, None, None, "Error: marca los dos puntos de calibracion en la imagen." | |
| dist_px = np.hypot(p2x - p1x, p2y - p1y) | |
| if dist_px < 1: | |
| return None, None, None, None, None, None, None, "Error: los puntos de calibracion estan muy cerca o son iguales." | |
| escala_px = distancia_real / dist_px # unidad_real / px | |
| # Si hay un area de interes dibujada, se restringe la zona analizada | |
| imagen_bgr_infer = imagen_bgr | |
| usar_roi = roi_mask is not None | |
| if usar_roi: | |
| roi = roi_mask | |
| if roi.shape[:2] != (alto_px, ancho_px): | |
| roi = cv2.resize(roi.astype(np.uint8), (ancho_px, alto_px), interpolation=cv2.INTER_NEAREST).astype(bool) | |
| imagen_bgr_infer = imagen_bgr.copy() | |
| imagen_bgr_infer[~roi] = 255 | |
| resultados = modelo.predict( | |
| source=imagen_bgr_infer, conf=CONF_DEFAULT, iou=iou, imgsz=640, verbose=False | |
| ) | |
| if not resultados or resultados[0].masks is None: | |
| return None, None, None, None, None, None, None, "Atencion: no se detectaron fragmentos. Ajusta el IoU o el area de interes." | |
| r = resultados[0] | |
| masks = r.masks.data.cpu().numpy() | |
| fragmentos = [] | |
| for i, mask in enumerate(masks): | |
| mask_r = cv2.resize( | |
| mask.astype(np.uint8), (ancho_px, alto_px), interpolation=cv2.INTER_NEAREST | |
| ) | |
| area_px = float(mask_r.sum()) | |
| if area_px <= 0: | |
| continue | |
| # Si hay area de interes, descartar fragmentos cuyo solape sea menor al 50% | |
| if usar_roi: | |
| solape = float((mask_r.astype(bool) & roi).sum()) | |
| if solape / area_px < 0.5: | |
| continue | |
| diam_px = 2.0 * np.sqrt(area_px / np.pi) | |
| diam_real = diam_px * escala_px | |
| contornos, _ = cv2.findContours(mask_r, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| contorno = max(contornos, key=cv2.contourArea) if contornos else None | |
| fragmentos.append({ | |
| "id": i, | |
| "area_px": area_px, | |
| "diam_equiv": diam_real, | |
| "contorno": contorno, | |
| "mask": mask_r, | |
| }) | |
| if not fragmentos: | |
| return None, None, None, None, None, None, None, "Atencion: no se encontraron fragmentos validos." | |
| diams_all = np.array([f["diam_equiv"] for f in fragmentos]) | |
| umbrales = {p: float(np.percentile(diams_all, p)) for p in [1, 5, 10, 20, 50, 80, 90, 95]} | |
| def asignar_banda(d): | |
| for etiq, p_inf, p_sup, color in SIGMAFRAG_BANDAS: | |
| v_inf = umbrales[p_inf] if p_inf is not None else -np.inf | |
| v_sup = umbrales[p_sup] if p_sup is not None else np.inf | |
| if v_inf <= d < v_sup: | |
| return etiq, color | |
| return SIGMAFRAG_BANDAS[-1][0], SIGMAFRAG_BANDAS[-1][3] | |
| for f in fragmentos: | |
| f["banda"], f["color"] = asignar_banda(f["diam_equiv"]) | |
| # ββ Conversion a pulgadas y deteccion de sobretamanos / anomalos ββ | |
| factor_in = UNIDADES_A_PULGADAS.get(unidad, 1.0) | |
| for f in fragmentos: | |
| f["diam_in"] = f["diam_equiv"] * factor_in | |
| diam_in_arr = np.array([f["diam_in"] for f in fragmentos]) | |
| q1, q3 = np.percentile(diam_in_arr, [25, 75]) | |
| iqr = q3 - q1 | |
| limite_superior_in = q3 + 1.5 * iqr | |
| for f in fragmentos: | |
| f["sobretamano"] = f["diam_in"] > limite_superior_in | |
| diam_in_tipicos = np.array([f["diam_in"] for f in fragmentos if not f["sobretamano"]]) | |
| if diam_in_tipicos.size == 0: | |
| diam_in_tipicos = diam_in_arr | |
| tamano_promedio_in = float(np.mean(diam_in_tipicos)) | |
| n_sobretamanos = int(sum(f["sobretamano"] for f in fragmentos)) | |
| # Curva granulometrica | |
| diams = np.array([f["diam_equiv"] for f in fragmentos]) | |
| areas = np.array([f["area_px"] for f in fragmentos]) | |
| orden = np.argsort(diams) | |
| diams_ord = diams[orden] | |
| areas_ord = areas[orden] | |
| acum = np.cumsum(areas_ord) | |
| pct = 100.0 * acum / acum[-1] | |
| curva = {"diametros": diams_ord, "pct_pasante": pct} | |
| for p in [1, 5, 10, 20, 25, 30, 40, 50, 60, 70, 75, 80, 90, 95]: | |
| idx = min(np.searchsorted(pct, p), len(diams_ord) - 1) | |
| curva[f"D{p}"] = float(diams_ord[idx]) | |
| # Generar figuras | |
| fig_seg, overlay_rgb = fig_segmentacion(imagen_bgr, fragmentos) | |
| fig_curva = fig_curva_granulometrica(curva, unidad) | |
| fig_hist = fig_histograma(fragmentos, unidad, umbrales) | |
| # Guardar la imagen segmentada (resolucion completa, sin leyenda) para descarga | |
| tmp_dir = tempfile.gettempdir() | |
| ruta_descarga = os.path.join(tmp_dir, "fragmentapp_segmentacion.png") | |
| cv2.imwrite(ruta_descarga, cv2.cvtColor(overlay_rgb, cv2.COLOR_RGB2BGR)) | |
| df = pd.DataFrame([{ | |
| "id": f["id"], | |
| "diametro_equiv": round(f["diam_equiv"], 4), | |
| "unidad": unidad, | |
| "diametro_in": round(f["diam_in"], 4), | |
| "area_px": int(f["area_px"]), | |
| "banda": f["banda"], | |
| "sobretamano": "Si" if f["sobretamano"] else "No", | |
| } for f in fragmentos]) | |
| df_sobretamanos = df[df["sobretamano"] == "Si"][["id", "diametro_equiv", "unidad", "diametro_in", "banda"]].reset_index(drop=True) | |
| for f in fragmentos: | |
| f["mask"] = None | |
| f["contorno"] = None | |
| del fragmentos, resultados, masks | |
| gc.collect() | |
| texto_promedio = ( | |
| f"Tamano promedio (casos mas frecuentes, excluye sobretamanos): " | |
| f"{tamano_promedio_in:.2f} in" | |
| ) | |
| info = f"Proceso completado. Fragmentos detectados: {len(df)}. Sobretamanos: {n_sobretamanos}." | |
| return fig_seg, fig_curva, fig_hist, df, ruta_descarga, texto_promedio, df_sobretamanos, info | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AUTENTICACION | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def login(username, password, state): | |
| if USERS.get(username) == password: | |
| new_state = {"authenticated": True, "user": username} | |
| return ( | |
| new_state, | |
| f"Acceso concedido. Bienvenido(a), {username}.", | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| ) | |
| return ( | |
| state, | |
| "Usuario o contrasena incorrectos.", | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| ) | |
| def logout(state): | |
| new_state = {"authenticated": False, "user": None} | |
| return ( | |
| new_state, | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| "", | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CAPTURA DE PUNTOS EN LA IMAGEN | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def capturar_punto(evt: gr.SelectData, imagen_base, px1, py1, px2, py2): | |
| """ | |
| Primer clic -> Punto 1; segundo clic -> Punto 2 (se dibuja la linea | |
| de calibracion entre ambos); tercer clic en adelante -> reinicia | |
| desde Punto 1. | |
| """ | |
| if imagen_base is None: | |
| return px1, py1, px2, py2, "Punto 1: no definido", "Punto 2: no definido", None | |
| x, y = evt.index | |
| if px1 is None: | |
| nx1, ny1, nx2, ny2 = x, y, None, None | |
| elif px2 is None: | |
| nx1, ny1, nx2, ny2 = px1, py1, x, y | |
| else: | |
| nx1, ny1, nx2, ny2 = x, y, None, None | |
| vista = dibujar_calibracion( | |
| cv2.cvtColor(imagen_base, cv2.COLOR_RGB2BGR), nx1, ny1, nx2, ny2 | |
| ) | |
| info1 = f"Punto 1: ({nx1}, {ny1})" if nx1 is not None else "Punto 1: no definido" | |
| info2 = f"Punto 2: ({nx2}, {ny2})" if nx2 is not None else "Punto 2: no definido" | |
| return nx1, ny1, nx2, ny2, info1, info2, vista | |
| def resetear_puntos(imagen_base): | |
| vista = None | |
| if imagen_base is not None: | |
| vista = dibujar_calibracion( | |
| cv2.cvtColor(imagen_base, cv2.COLOR_RGB2BGR), None, None, None, None | |
| ) | |
| return None, None, None, None, "Punto 1: no definido", "Punto 2: no definido", vista | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # INTERFAZ GRADIO | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| tema_spcc = gr.themes.Base( | |
| primary_hue=gr.themes.colors.red, | |
| secondary_hue=gr.themes.colors.gray, | |
| neutral_hue=gr.themes.colors.gray, | |
| ).set( | |
| body_background_fill=SPCC_BLANCO, | |
| body_background_fill_dark=SPCC_BLANCO, | |
| background_fill_primary=SPCC_BLANCO, | |
| block_background_fill=SPCC_BLANCO, | |
| ) | |
| with gr.Blocks(theme=tema_spcc, css=CSS_INSTITUCIONAL, title="FragmentApp - Cuajone") as demo: | |
| session_state = gr.State({"authenticated": False, "user": None}) | |
| imagen_base_state = gr.State(value=None) | |
| roi_mask_state = gr.State(value=None) | |
| p1x = gr.State(value=None) | |
| p1y = gr.State(value=None) | |
| p2x = gr.State(value=None) | |
| p2y = gr.State(value=None) | |
| # ββ PANEL LOGIN ββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Column(visible=True) as login_panel: | |
| if LOGO_DISPONIBLE: | |
| gr.Image( | |
| value=LOGO_PATH, | |
| show_label=False, | |
| container=False, | |
| interactive=False, | |
| show_download_button=False, | |
| height=90, | |
| ) | |
| gr.Markdown("# FragmentApp", elem_id="encabezado-spcc") | |
| gr.Markdown(f"<span class='empresa-nombre'>{EMPRESA_NOMBRE}</span>") | |
| gr.Markdown(f"<span class='unidad-nombre'>{UNIDAD_NOMBRE}</span>") | |
| gr.Markdown("Sistema de Analisis de Fragmentacion de Roca") | |
| gr.Markdown(f"<span class='autor-credito'>{AUTOR_INICIO}</span>") | |
| gr.Markdown("Acceso restringido. Ingrese sus credenciales para continuar.") | |
| with gr.Row(): | |
| username_tb = gr.Textbox(label="Usuario", placeholder="Ingrese su usuario") | |
| password_tb = gr.Textbox(label="Contrasena", type="password", placeholder="Ingrese su contrasena") | |
| login_btn = gr.Button("Ingresar", variant="primary") | |
| login_msg = gr.Textbox(label="Estado de acceso", interactive=False) | |
| # ββ PANEL PRINCIPAL ββββββββββββββββββββββββββββββββββββββ | |
| with gr.Column(visible=False) as main_panel: | |
| with gr.Row(): | |
| with gr.Column(scale=4): | |
| if LOGO_DISPONIBLE: | |
| gr.Image( | |
| value=LOGO_PATH, | |
| show_label=False, | |
| container=False, | |
| interactive=False, | |
| show_download_button=False, | |
| height=60, | |
| ) | |
| gr.Markdown("# FragmentApp", elem_id="encabezado-spcc") | |
| gr.Markdown("Analisis de Fragmentacion de Roca") | |
| gr.Markdown(f"<span class='autor-credito'>{AUTOR_TEXTO}</span>") | |
| with gr.Column(scale=1): | |
| logout_btn = gr.Button("Cerrar sesion", variant="secondary", size="sm") | |
| gr.Markdown( | |
| "Instrucciones: " | |
| "1. Cargue la imagen. " | |
| "2. Haga clic en dos puntos de referencia sobre la imagen para calibrar la escala. " | |
| "3. Ingrese la distancia real entre esos puntos. " | |
| "4. Opcionalmente, dibuje en el panel 'Area de interes' la seccion o forma libre " | |
| "donde desea que se realice la segmentacion; si no dibuja nada se analiza la imagen completa. " | |
| "5. Presione ANALIZAR." | |
| ) | |
| with gr.Row(): | |
| # ββ COLUMNA IZQUIERDA ββββββββββββββββββββββββββββ | |
| with gr.Column(scale=1): | |
| imagen_input = gr.Image( | |
| type="numpy", | |
| label="Imagen original (haga clic aqui para marcar los puntos de calibracion)", | |
| height=350, | |
| ) | |
| gr.Markdown("<span class='section-label'>Vista de calibracion</span>") | |
| vista_calibracion = gr.Image( | |
| type="numpy", | |
| label="Puntos y linea de calibracion", | |
| interactive=False, | |
| height=350, | |
| ) | |
| with gr.Row(): | |
| punto1_info = gr.Textbox(label="Punto 1", interactive=False, value="Punto 1: no definido") | |
| punto2_info = gr.Textbox(label="Punto 2", interactive=False, value="Punto 2: no definido") | |
| reset_btn = gr.Button("Reiniciar puntos", size="sm", variant="secondary") | |
| gr.Markdown("<span class='section-label'>Area de interes (opcional)</span>") | |
| gr.Markdown( | |
| "Dibuje sobre la imagen la seccion o forma libre donde desea que se " | |
| "ejecute la segmentacion. Use la herramienta de pincel del editor." | |
| ) | |
| editor_roi = gr.ImageEditor( | |
| label="Dibujar area de analisis", | |
| type="numpy", | |
| height=350, | |
| ) | |
| with gr.Row(): | |
| aplicar_roi_btn = gr.Button("Aplicar area dibujada", size="sm", variant="secondary") | |
| limpiar_roi_btn = gr.Button("Analizar imagen completa", size="sm", variant="secondary") | |
| roi_info = gr.Textbox( | |
| label="Estado del area de interes", interactive=False, | |
| value="Area de interes: imagen completa (sin restriccion)." | |
| ) | |
| with gr.Accordion("Parametros", open=True): | |
| iou_slider = gr.Slider(0.05, 0.95, value=0.45, step=0.05, label="IoU YOLO") | |
| unidad_drop = gr.Dropdown(["m", "cm", "mm", "in", "ft"], value="cm", label="Unidad") | |
| distancia_real = gr.Number(value=1.0, label="Distancia real entre los dos puntos (en la unidad elegida)") | |
| boton_analizar = gr.Button("ANALIZAR", variant="primary", size="lg") | |
| # ββ COLUMNA DERECHA ββββββββββββββββββββββββββββββ | |
| with gr.Column(scale=2): | |
| with gr.Row(): | |
| salida_seg = gr.Plot(label="Segmentacion") | |
| salida_curva = gr.Plot(label="Curva granulometrica") | |
| salida_hist = gr.Plot(label="Histograma de tamanos") | |
| descarga_seg = gr.File(label="Descargar imagen segmentada (PNG)", interactive=False) | |
| salida_promedio = gr.Textbox(label="Tamano promedio (casos mas frecuentes)", interactive=False) | |
| salida_tabla = gr.Dataframe(label="Datos de fragmentos", interactive=False) | |
| salida_sobretamanos = gr.Dataframe(label="Fragmentos sobretamano / anomalos", interactive=False) | |
| salida_info = gr.Textbox(label="Estado del proceso", interactive=False) | |
| gr.Markdown( | |
| f"<div style='text-align:center;color:{SPCC_GRIS_C};font-size:11px;margin-top:30px;'>" | |
| f"{AUTOR_TEXTO}</div>" | |
| ) | |
| # ββ EVENTOS ββββββββββββββββββββββββββββββββββββββββββββββ | |
| login_btn.click( | |
| fn=login, | |
| inputs=[username_tb, password_tb, session_state], | |
| outputs=[session_state, login_msg, login_panel, main_panel], | |
| ) | |
| logout_btn.click( | |
| fn=logout, | |
| inputs=[session_state], | |
| outputs=[session_state, login_panel, main_panel, login_msg], | |
| ) | |
| # Al cargar una imagen: se redimensiona, se fija como referencia y se | |
| # reinicia la calibracion y el area de interes | |
| imagen_input.upload( | |
| fn=preparar_imagen, | |
| inputs=[imagen_input], | |
| outputs=[imagen_input, imagen_base_state, p1x, p1y, p2x, p2y, punto1_info, punto2_info], | |
| ).then( | |
| fn=lambda base: base, | |
| inputs=[imagen_base_state], | |
| outputs=[vista_calibracion], | |
| ).then( | |
| fn=lambda base: (base, None, "Area de interes: imagen completa (sin restriccion)."), | |
| inputs=[imagen_base_state], | |
| outputs=[editor_roi, roi_mask_state, roi_info], | |
| ) | |
| # Captura de puntos sobre la imagen original (clics) | |
| imagen_input.select( | |
| fn=capturar_punto, | |
| inputs=[imagen_base_state, p1x, p1y, p2x, p2y], | |
| outputs=[p1x, p1y, p2x, p2y, punto1_info, punto2_info, vista_calibracion], | |
| ) | |
| reset_btn.click( | |
| fn=resetear_puntos, | |
| inputs=[imagen_base_state], | |
| outputs=[p1x, p1y, p2x, p2y, punto1_info, punto2_info, vista_calibracion], | |
| ) | |
| aplicar_roi_btn.click( | |
| fn=aplicar_roi, | |
| inputs=[editor_roi, imagen_base_state], | |
| outputs=[roi_mask_state, roi_info], | |
| ) | |
| limpiar_roi_btn.click( | |
| fn=limpiar_roi, | |
| inputs=[], | |
| outputs=[roi_mask_state, roi_info], | |
| ) | |
| # Analizar | |
| boton_analizar.click( | |
| fn=procesar_imagen, | |
| inputs=[ | |
| imagen_base_state, iou_slider, unidad_drop, | |
| p1x, p1y, p2x, p2y, distancia_real, roi_mask_state, | |
| ], | |
| outputs=[ | |
| salida_seg, salida_curva, salida_hist, salida_tabla, | |
| descarga_seg, salida_promedio, salida_sobretamanos, salida_info, | |
| ], | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # LANZAR | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| demo.queue(max_size=5).launch(server_name="0.0.0.0", server_port=7860) |