File size: 34,037 Bytes
5d4c3a0
 
 
 
 
 
 
 
23535ef
5d4c3a0
23535ef
5d4c3a0
 
23535ef
5d4c3a0
 
cac536a
5d4c3a0
 
 
 
23535ef
cac536a
 
 
 
 
23535ef
cac536a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
cac536a
 
 
23535ef
 
 
 
cac536a
 
 
 
23535ef
cac536a
 
23535ef
 
 
cac536a
 
23535ef
 
 
cac536a
 
 
 
 
 
 
 
 
 
 
 
23535ef
cac536a
23535ef
cac536a
23535ef
 
 
cac536a
 
 
23535ef
 
cac536a
 
23535ef
 
cac536a
23535ef
 
cac536a
23535ef
 
 
 
 
 
5d4c3a0
 
 
 
 
 
d3997d0
 
 
 
 
 
 
 
 
 
 
 
 
 
5d4c3a0
23535ef
5d4c3a0
 
 
23535ef
 
 
 
 
 
 
5d4c3a0
 
23535ef
cac536a
 
d3997d0
 
 
 
 
23535ef
 
d3997d0
 
 
23535ef
5d4c3a0
 
 
 
23535ef
d3997d0
 
5d4c3a0
 
 
 
 
 
 
 
d3997d0
23535ef
 
 
 
 
5d4c3a0
 
cac536a
5d4c3a0
 
 
 
 
 
 
 
cac536a
5d4c3a0
23535ef
5d4c3a0
 
 
cac536a
 
5d4c3a0
 
 
 
 
 
 
23535ef
5d4c3a0
 
 
 
cac536a
5d4c3a0
 
 
 
 
 
cac536a
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
 
5d4c3a0
 
 
cac536a
5d4c3a0
 
 
 
23535ef
d3997d0
 
23535ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d4c3a0
23535ef
5d4c3a0
23535ef
d3997d0
 
 
5d4c3a0
23535ef
5d4c3a0
 
 
 
 
 
 
 
 
 
 
23535ef
 
d3997d0
 
23535ef
 
 
 
 
 
d3997d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
 
 
d3997d0
23535ef
d3997d0
23535ef
 
5d4c3a0
 
 
d3997d0
5d4c3a0
 
 
d3997d0
5d4c3a0
 
 
d3997d0
 
 
 
 
 
 
 
 
 
5d4c3a0
d3997d0
5d4c3a0
 
d3997d0
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
d3997d0
 
 
 
 
 
 
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3997d0
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3997d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
5d4c3a0
 
 
23535ef
 
 
 
 
5d4c3a0
d3997d0
 
 
 
 
 
 
5d4c3a0
 
d3997d0
 
5d4c3a0
 
 
 
 
 
d3997d0
 
 
 
 
 
 
5d4c3a0
 
 
23535ef
5d4c3a0
 
 
 
 
 
23535ef
 
 
5d4c3a0
 
 
23535ef
5d4c3a0
 
 
 
 
 
 
 
 
23535ef
 
5d4c3a0
 
 
 
 
 
 
23535ef
5d4c3a0
23535ef
 
 
5d4c3a0
23535ef
 
 
 
5d4c3a0
 
23535ef
5d4c3a0
23535ef
5d4c3a0
23535ef
 
 
 
 
 
 
 
5d4c3a0
23535ef
5d4c3a0
23535ef
 
 
 
 
 
 
 
5d4c3a0
 
 
 
 
cac536a
d3997d0
23535ef
 
cac536a
 
 
 
 
23535ef
 
cac536a
5d4c3a0
 
23535ef
d3997d0
23535ef
5d4c3a0
 
 
 
 
 
 
cac536a
 
 
 
 
 
 
 
 
 
 
 
23535ef
cac536a
23535ef
5d4c3a0
23535ef
 
5d4c3a0
23535ef
5d4c3a0
 
 
 
23535ef
cac536a
 
 
 
 
 
 
 
 
 
23535ef
 
 
 
5d4c3a0
 
23535ef
 
d3997d0
23535ef
d3997d0
 
 
5d4c3a0
 
 
 
 
 
 
23535ef
 
 
 
 
 
 
 
 
5d4c3a0
 
23535ef
 
 
5d4c3a0
d3997d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
5d4c3a0
 
 
 
23535ef
5d4c3a0
 
 
 
23535ef
 
 
 
d3997d0
5d4c3a0
d3997d0
23535ef
 
cac536a
 
 
 
5d4c3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23535ef
d3997d0
23535ef
 
 
 
 
 
 
 
d3997d0
 
 
 
23535ef
 
 
5d4c3a0
 
23535ef
 
5d4c3a0
 
 
 
23535ef
 
5d4c3a0
 
d3997d0
 
 
 
 
 
 
 
 
 
 
 
5d4c3a0
 
 
 
d3997d0
 
 
 
 
 
5d4c3a0
 
 
 
 
 
 
3c7d713
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
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)