"""Water Police - Main Application Entry Point.""" import streamlit as st import pandas as pd from auth import setup_authenticator, render_login from models import ( cargar_pipelines, buscar_suministro, predecir, predecir_lote, predecir_lote_nuevos, predecir_cliente_nuevo, obtener_feature_importance, ) from components import render_results, render_results_lote, render_header from components.results import render_info_expander st.set_page_config(page_title="Policia del Agua", page_icon="๐Ÿ’ง", layout="wide") MAX_CSV_ROWS = 500 MAX_CSV_MB = 5 MAX_NUEVOS_ROWS = 200 MAX_NUEVOS_MB = 2 authenticator = setup_authenticator() authentication_status = st.session_state.get("authentication_status") name = st.session_state.get("name") if not authentication_status: render_login(authenticator) st.stop() # ============================================================================= # PROTECTED CONTENT # ============================================================================= render_header(authenticator, name) st.markdown("Sistema de deteccion de fraude en consumo de agua basado en Machine Learning (IF + LOF + PU Bagging)") if 'pipelines' not in st.session_state: with st.spinner("Cargando modelos..."): pipelines, error = cargar_pipelines() st.session_state.pipelines = pipelines st.session_state.es_simulado = pipelines is None if error: st.warning(f"No se pudieron cargar los modelos reales, usando modo demo simulado. Detalle: {error}") else: st.success("Modelos cargados correctamente (Isolation Forest + LOF + PU Bagging)") if pipelines.get('pu_error'): st.warning(f"El modelo PU Bagging no se pudo cargar, se mostrara solo IF + LOF. Detalle: {pipelines['pu_error']}") pipelines = st.session_state.pipelines es_simulado = st.session_state.es_simulado st.markdown("---") st.header("1. Tipo de Cliente") modo_prediccion = st.radio( "Selecciona el tipo de cliente:", ["Suministro Existente", "Cliente Nuevo"], horizontal=True, help="Suministro Existente: cliente ya registrado en la base de datos. Cliente Nuevo: cliente sin historial previo.", ) st.markdown("---") # ============================================================================= # INDIVIDUAL (cliente existente en la base de datos) # ============================================================================= if modo_prediccion == "Suministro Existente": tipo_individual = st.radio( "Forma de ingreso:", ["Prediccion Manual", "Prediccion Masiva (CSV)"], horizontal=True, key="tipo_individual", ) st.markdown("---") # ------------------------------------------------------------------ # Individual โ€” Manual # ------------------------------------------------------------------ if tipo_individual == "Prediccion Manual": st.header("2. Ingresar Datos") col1, col2 = st.columns(2) with col1: nro_suministro = st.number_input( "Numero de Suministro:", value=107396, min_value=0, max_value=99999999, step=1, ) with col2: consumo_actual = st.number_input( "Consumo Actual (m3):", value=10.0, min_value=0.0, max_value=1000.0, step=0.1, ) st.markdown("---") st.header("3. Ejecutar Prediccion") if st.button("Predecir Riesgo", type="primary", use_container_width=True, key="btn_ind_manual"): datos_suministro = buscar_suministro(nro_suministro) if datos_suministro is None: st.error(f"No se encontro el suministro N {nro_suministro}") else: st.info( f"**Suministro encontrado:** {datos_suministro['dir_suministro']} " f"| **Comuna:** {datos_suministro['nombrecomuna']} " f"| **Lat:** {datos_suministro['latitud']:.6f} **Lon:** {datos_suministro['longitud']:.6f}" ) with st.spinner("Calculando prediccion..."): resultado = predecir(pipelines, datos_suministro, consumo_actual, es_simulado) st.session_state.ind_resultado = resultado st.session_state.ind_datos = datos_suministro if 'ind_resultado' in st.session_state and 'ind_datos' in st.session_state: fi_if, fi_lof = obtener_feature_importance(pipelines) render_results( st.session_state.ind_resultado, st.session_state.ind_datos, fi_if=fi_if, fi_lof=fi_lof, ) # ------------------------------------------------------------------ # Individual โ€” Masiva CSV # ------------------------------------------------------------------ else: st.header("2. Cargar CSV de Suministros") st.info( f"Columnas requeridas: **nro_suministro** y **consumo_actual** (o **consumo_real**) \n" f"Limite: **{MAX_CSV_ROWS} suministros** ยท **{MAX_CSV_MB} MB**" ) archivo_csv = st.file_uploader("Selecciona un archivo CSV", type=['csv'], key="uploader_existentes") if archivo_csv is not None: size_mb = archivo_csv.size / (1024 * 1024) if size_mb > MAX_CSV_MB: st.error(f"El archivo pesa {size_mb:.1f} MB. El limite es {MAX_CSV_MB} MB.") else: try: df_entrada = pd.read_csv(archivo_csv) if len(df_entrada) > MAX_CSV_ROWS: st.warning(f"El archivo tiene {len(df_entrada)} filas. Se procesaran solo las primeras {MAX_CSV_ROWS}.") df_entrada = df_entrada.head(MAX_CSV_ROWS) st.success(f"Archivo cargado: {len(df_entrada)} registros ({size_mb:.2f} MB)") tiene_suministro = 'nro_suministro' in df_entrada.columns tiene_consumo = 'consumo_actual' in df_entrada.columns or 'consumo_real' in df_entrada.columns if not tiene_suministro: st.error("Falta la columna: nro_suministro") elif not tiene_consumo: st.error("Falta la columna: consumo_actual (o consumo_real)") else: st.subheader("Vista previa") st.dataframe(df_entrada.head(10), use_container_width=True) st.markdown("---") st.header("3. Ejecutar Prediccion") if st.button("Predecir Todos", type="primary", use_container_width=True, key="btn_lote_exist"): with st.spinner(f"Procesando {len(df_entrada)} suministros..."): df_resultado = predecir_lote(pipelines, df_entrada, es_simulado) st.session_state.resultado_lote = df_resultado if 'resultado_lote' in st.session_state: st.markdown("---") st.header("4. Resultados") render_results_lote(st.session_state.resultado_lote) st.markdown("---") st.subheader("Ver detalle de un suministro") df_ok = st.session_state.resultado_lote if 'estado' in df_ok.columns: df_ok = df_ok[df_ok['estado'] == 'Encontrado'] if df_ok.empty: st.info("No hay suministros encontrados para mostrar detalle.") else: nro_sel = st.selectbox( "Seleccionar suministro:", options=df_ok['nro_suministro'].tolist(), key="lote_sel_nro", ) if st.button("Ver detalle completo", key="lote_btn_detalle"): datos_sel = buscar_suministro(int(nro_sel)) if datos_sel is None: st.error(f"No se pudo cargar el detalle del suministro {nro_sel}") else: fila = df_ok[df_ok['nro_suministro'] == nro_sel].iloc[0] consumo_col = 'consumo_actual' if 'consumo_actual' in fila.index else 'consumo_real' with st.spinner("Cargando detalle..."): resultado_sel = predecir(pipelines, datos_sel, float(fila[consumo_col]), es_simulado) st.session_state.lote_detalle_resultado = resultado_sel st.session_state.lote_detalle_datos = datos_sel if 'lote_detalle_resultado' in st.session_state and 'lote_detalle_datos' in st.session_state: fi_if, fi_lof = obtener_feature_importance(pipelines) render_results( st.session_state.lote_detalle_resultado, st.session_state.lote_detalle_datos, fi_if=fi_if, fi_lof=fi_lof, ) except Exception as e: st.error(f"Error al leer el archivo: {e}") render_info_expander() st.stop() # ============================================================================= # CLIENTE NUEVO (sin historial en la base de datos) # ============================================================================= if modo_prediccion == "Cliente Nuevo": tipo_nuevo = st.radio( "Forma de ingreso:", ["Ingreso Manual", "Carga Masiva (CSV)"], horizontal=True, key="tipo_nuevo", ) st.markdown("---") # ------------------------------------------------------------------ # Cliente Nuevo โ€” Manual # ------------------------------------------------------------------ if tipo_nuevo == "Ingreso Manual": st.header("2. Datos del Cliente Nuevo") col1, col2 = st.columns(2) with col1: nro_nuevo = st.number_input( "Numero de Suministro:", value=999999, min_value=0, max_value=99999999, step=1, help="Identificador del nuevo cliente", ) consumos_input = st.text_input( "Historial de Consumos (m3):", value="12;14;10;11;13;8;6", help="Consumos mensuales separados por punto y coma (;). Minimo 3 lecturas. El ultimo valor es el consumo actual.", ) with col2: lat_nuevo = st.number_input( "Latitud:", value=-32.783, min_value=-90.0, max_value=90.0, step=0.0001, format="%.6f", ) lon_nuevo = st.number_input( "Longitud:", value=-71.216, min_value=-180.0, max_value=180.0, step=0.0001, format="%.6f", ) st.markdown("---") st.header("3. Ejecutar Prediccion") if st.button("Predecir Riesgo", type="primary", use_container_width=True, key="btn_nuevo_manual"): with st.spinner("Calculando prediccion..."): resultado, datos_suministro, error = predecir_cliente_nuevo( pipelines, nro_nuevo, consumos_input, lat_nuevo, lon_nuevo ) if error: st.error(error) else: st.session_state.resultado_nuevo = resultado st.session_state.datos_nuevo = datos_suministro if 'resultado_nuevo' in st.session_state and 'datos_nuevo' in st.session_state: fi_if, fi_lof = obtener_feature_importance(pipelines) render_results( st.session_state.resultado_nuevo, st.session_state.datos_nuevo, fi_if=fi_if, fi_lof=fi_lof, ) # ------------------------------------------------------------------ # Cliente Nuevo โ€” Masiva CSV # ------------------------------------------------------------------ else: st.header("2. Cargar CSV de Clientes Nuevos") st.info( f"Columnas requeridas: **nro_suministro**, **consumos** (separados por `;`), **latitud**, **longitud** \n" f"Limite: **{MAX_NUEVOS_ROWS} clientes** ยท **{MAX_NUEVOS_MB} MB**" ) template_df = pd.DataFrame({ 'nro_suministro': [999001, 999002], 'consumos': ['12;14;10;11;13;8;6', '20;18;15;12;8;5;3'], 'latitud': [-32.783, -32.790], 'longitud': [-71.216, -71.220], }) st.download_button( "Descargar plantilla CSV", template_df.to_csv(index=False).encode('utf-8'), "plantilla_clientes_nuevos.csv", "text/csv", ) archivo_nuevos = st.file_uploader("Selecciona un archivo CSV", type=['csv'], key="uploader_nuevos") if archivo_nuevos is not None: size_mb = archivo_nuevos.size / (1024 * 1024) if size_mb > MAX_NUEVOS_MB: st.error(f"El archivo pesa {size_mb:.1f} MB. El limite es {MAX_NUEVOS_MB} MB.") else: try: df_nuevos = pd.read_csv(archivo_nuevos) if len(df_nuevos) > MAX_NUEVOS_ROWS: st.warning(f"El archivo tiene {len(df_nuevos)} filas. Se procesaran solo las primeras {MAX_NUEVOS_ROWS}.") df_nuevos = df_nuevos.head(MAX_NUEVOS_ROWS) st.success(f"Archivo cargado: {len(df_nuevos)} clientes ({size_mb:.2f} MB)") cols_req = {'nro_suministro', 'consumos', 'latitud', 'longitud'} faltantes = cols_req - set(df_nuevos.columns) if faltantes: st.error(f"Faltan columnas: {', '.join(sorted(faltantes))}") else: st.subheader("Vista previa") st.dataframe(df_nuevos.head(5), use_container_width=True) st.markdown("---") st.header("3. Ejecutar Prediccion") if st.button("Predecir Todos", type="primary", use_container_width=True, key="btn_lote_nuevos"): with st.spinner(f"Procesando {len(df_nuevos)} clientes nuevos..."): df_res_nuevos = predecir_lote_nuevos(pipelines, df_nuevos) st.session_state.resultado_lote_nuevos = df_res_nuevos st.session_state.df_nuevos_original = df_nuevos if 'resultado_lote_nuevos' in st.session_state: st.markdown("---") st.header("4. Resultados") render_results_lote(st.session_state.resultado_lote_nuevos) st.markdown("---") st.subheader("Ver detalle de un cliente nuevo") df_ok_n = st.session_state.resultado_lote_nuevos if 'estado' in df_ok_n.columns: df_ok_n = df_ok_n[df_ok_n['estado'] == 'Encontrado'] if df_ok_n.empty: st.info("No hay clientes procesados para mostrar detalle.") elif 'df_nuevos_original' in st.session_state: nro_sel_n = st.selectbox( "Seleccionar cliente:", options=df_ok_n['nro_suministro'].tolist(), key="nuevo_lote_sel_nro", ) if st.button("Ver detalle completo", key="nuevo_lote_btn_detalle"): df_orig = st.session_state.df_nuevos_original fila_orig = df_orig[df_orig['nro_suministro'] == nro_sel_n] if not fila_orig.empty: r = fila_orig.iloc[0] with st.spinner("Cargando detalle..."): res_n, datos_n, err_n = predecir_cliente_nuevo( pipelines, nro_sel_n, str(r['consumos']), float(r['latitud']), float(r['longitud']), ) if err_n: st.error(err_n) else: st.session_state.nuevo_detalle_resultado = res_n st.session_state.nuevo_detalle_datos = datos_n if 'nuevo_detalle_resultado' in st.session_state and 'nuevo_detalle_datos' in st.session_state: fi_if, fi_lof = obtener_feature_importance(pipelines) render_results( st.session_state.nuevo_detalle_resultado, st.session_state.nuevo_detalle_datos, fi_if=fi_if, fi_lof=fi_lof, ) except Exception as e: st.error(f"Error al leer el archivo: {e}") render_info_expander()