Spaces:
Sleeping
Sleeping
Download app.py from Daniel1812/Biometa: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/spaces/Daniel1812/Biometa/resolve/main/app.py
- Command line
-
hf download hf://spaces/Daniel1812/Biometa/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Daniel1812/Biometa/resolve/main/app.py
22.3 kB
| # app.py - PARTE 1 | |
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import sqlite3 | |
| import os | |
| from datetime import datetime | |
| import matplotlib.pyplot as plt | |
| from io import BytesIO | |
| import hashlib | |
| import smtplib | |
| from email.mime.text import MIMEText | |
| # ---------------- CONFIG ---------------- | |
| DB_PATH = "data/filtros.db" | |
| REPORTS_DIR = "data/reports" | |
| BACKUP_DIR = "data/backups" | |
| os.makedirs("data", exist_ok=True) | |
| os.makedirs(REPORTS_DIR, exist_ok=True) | |
| os.makedirs(BACKUP_DIR, exist_ok=True) | |
| CAPACIDAD_CARBON_G = 1.8 * 1000 * 1000 # gramos de carbón por filtro | |
| CAPACIDAD_ADSORB_G_PER_G = 0.35 # antes 0.15, ahora 0.35 g H2S/g carbón | |
| CAPACIDAD_POR_FILTRO_G = CAPACIDAD_CARBON_G * CAPACIDAD_ADSORB_G_PER_G | |
| UMBRAL_PPM = 10.0 | |
| # Optional SMTP config for email alerts: | |
| SMTP_HOST = os.environ.get("SMTP_HOST", "") | |
| SMTP_PORT = int(os.environ.get("SMTP_PORT", "587") or 587) | |
| SMTP_USER = os.environ.get("SMTP_USER", "") | |
| SMTP_PASS = os.environ.get("SMTP_PASS", "") | |
| ALERT_TO = os.environ.get("ALERT_TO", "") | |
| # ---------------- DB UTIL ---------------- | |
| def get_conn(): | |
| conn = sqlite3.connect(DB_PATH, check_same_thread=False) | |
| return conn | |
| def hash_pwd(pwd: str): | |
| return hashlib.sha256(pwd.encode()).hexdigest() | |
| def init_db(): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| cur.execute(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| username TEXT UNIQUE, | |
| fullname TEXT, | |
| password TEXT | |
| )""") | |
| cur.execute(""" | |
| CREATE TABLE IF NOT EXISTS records ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| filter_id INTEGER, | |
| timestamp TEXT, | |
| date TEXT, | |
| caudal REAL, | |
| h2s_in REAL, | |
| h2s_out REAL, | |
| user_id INTEGER | |
| )""") | |
| cur.execute(""" | |
| CREATE TABLE IF NOT EXISTS backups ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| timestamp TEXT, | |
| description TEXT, | |
| payload TEXT | |
| )""") | |
| conn.commit() | |
| # ensure admin exists | |
| cur.execute("SELECT COUNT(*) FROM users WHERE username='admin'") | |
| if cur.fetchone()[0] == 0: | |
| cur.execute("INSERT INTO users (username, fullname, password) VALUES (?,?,?)", | |
| ("admin", "Administrador", hash_pwd("admin"))) | |
| conn.commit() | |
| conn.close() | |
| init_db() | |
| # ---------------- USER FUNCTIONS ---------------- | |
| def add_user(username, fullname, password): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| try: | |
| cur.execute("INSERT INTO users (username, fullname, password) VALUES (?, ?, ?)", | |
| (username, fullname, hash_pwd(password))) | |
| conn.commit() | |
| return True, "Usuario creado" | |
| except Exception as e: | |
| return False, str(e) | |
| finally: | |
| conn.close() | |
| def reset_password(username, new_password): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| cur.execute("UPDATE users SET password=? WHERE username=?", | |
| (hash_pwd(new_password), username)) | |
| conn.commit() | |
| conn.close() | |
| return True | |
| def delete_user(username): | |
| if username == "admin": | |
| return False, "No se puede eliminar el admin" | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| try: | |
| cur.execute("DELETE FROM users WHERE username=?", (username,)) | |
| conn.commit() | |
| return True, f"Usuario {username} eliminado" | |
| except Exception as e: | |
| return False, str(e) | |
| finally: | |
| conn.close() | |
| def authenticate(username, password): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| cur.execute("SELECT id, username, fullname, password FROM users WHERE username=?", (username,)) | |
| row = cur.fetchone() | |
| conn.close() | |
| if not row: | |
| return None | |
| if hash_pwd(password) == row[3]: | |
| return {"id": row[0], "username": row[1], "fullname": row[2]} | |
| return None | |
| def list_users(): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| cur.execute("SELECT username, fullname FROM users ORDER BY username") | |
| rows = cur.fetchall() | |
| conn.close() | |
| return rows | |
| # ---------------- HELPERS (cálculos) ---------------- | |
| def ppm_to_g_m3(ppm): | |
| return ppm * 0.00152 | |
| def calc_load_captured_g(h2s_in_ppm, h2s_out_ppm, caudal_m3h): | |
| removed_ppm = max(h2s_in_ppm - h2s_out_ppm, 0) | |
| removed_g_m3 = ppm_to_g_m3(removed_ppm) | |
| return removed_g_m3 * caudal_m3h | |
| # ---------------- EMAIL ALERT (opcional) ---------------- | |
| def send_email_alert(subject, body): | |
| if not (SMTP_HOST and SMTP_USER and SMTP_PASS and ALERT_TO): | |
| return False, "SMTP no configurado" | |
| try: | |
| msg = MIMEText(body) | |
| msg["Subject"] = subject | |
| msg["From"] = SMTP_USER | |
| msg["To"] = ALERT_TO | |
| s = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=10) | |
| s.starttls() | |
| s.login(SMTP_USER, SMTP_PASS) | |
| s.sendmail(SMTP_USER, [ALERT_TO], msg.as_string()) | |
| s.quit() | |
| return True, "Enviado" | |
| except Exception as e: | |
| return False, str(e) | |
| # ---------------- UI: Auth ---------------- | |
| st.set_page_config(page_title="Filtros EPM", layout="wide") | |
| if "logged" not in st.session_state: | |
| st.session_state.logged = False | |
| if "user" not in st.session_state: | |
| st.session_state.user = None | |
| def login_panel(): | |
| st.header("Acceso - Filtros EPM") | |
| col1, col2 = st.columns([2,1]) | |
| with col1: | |
| st.subheader("Iniciar sesión") | |
| username = st.text_input("Usuario", key="login_user") | |
| password = st.text_input("Contraseña", type="password", key="login_pass") | |
| if st.button("Entrar"): | |
| user = authenticate(username, password) | |
| if user: | |
| st.session_state.logged = True | |
| st.session_state.user = user | |
| st.success(f"Bienvenido, {user['fullname'] or user['username']}") | |
| st.experimental_rerun() | |
| else: | |
| st.error("Usuario o contraseña incorrectos") | |
| # ---------------- UI: Admin ---------------- | |
| def admin_panel_ui(): | |
| st.sidebar.subheader("Admin - Gestión de usuarios") | |
| st.sidebar.write("Usuario conectado: *admin*") | |
| st.sidebar.markdown("---") | |
| st.sidebar.markdown("### ➕ Crear usuario") | |
| new_user = st.sidebar.text_input("Usuario nuevo", key="admin_new_user") | |
| new_full = st.sidebar.text_input("Nombre completo", key="admin_new_full") | |
| new_pass = st.sidebar.text_input("Contraseña", type="password", key="admin_new_pass") | |
| if st.sidebar.button("Crear usuario", key="admin_create_btn"): | |
| ok, msg = add_user(new_user, new_full, new_pass) | |
| if ok: | |
| st.sidebar.success(msg) | |
| else: | |
| st.sidebar.error(f"Error: {msg}") | |
| st.sidebar.markdown("---") | |
| st.sidebar.markdown("### 🔑 Resetear contraseña") | |
| rp_user = st.sidebar.selectbox("Seleccionar usuario", [u[0] for u in list_users()], key="rp_select") | |
| rp_new = st.sidebar.text_input("Nueva contraseña", type="password", key="rp_new_pass") | |
| if st.sidebar.button("Resetear contraseña", key="admin_reset_btn"): | |
| if reset_password(rp_user, rp_new): | |
| st.sidebar.success(f"Contraseña de {rp_user} actualizada") | |
| else: | |
| st.sidebar.error("Error al resetear") | |
| st.sidebar.markdown("---") | |
| st.sidebar.markdown("### 🗑️ Eliminar usuario") | |
| del_user = st.sidebar.selectbox("Usuario a eliminar", [u[0] for u in list_users() if u[0] != "admin"], index=0, key="del_select") | |
| if st.sidebar.button("Eliminar usuario", key="admin_del_btn"): | |
| ok, msg = delete_user(del_user) | |
| if ok: | |
| st.sidebar.success(msg) | |
| else: | |
| st.sidebar.error(msg) | |
| # app.py - PARTE 2 | |
| # ---------------- UI: Main (tus funcionalidades originales) ---------------- | |
| def sidebar_menu(): | |
| st.sidebar.title("Menú") | |
| st.sidebar.write(f"Usuario: {st.session_state.user['username']}") | |
| page = st.sidebar.radio("Navegar", ["Dashboard", "Ingresar datos", "Resetear filtros", "Reportes", "Simulación", "Historial / Backups", "Salir"]) | |
| return page | |
| # ---- Dashboard, plots y cálculo de saturación ---- | |
| def dashboard(): | |
| st.title("Dashboard - Estado de filtros") | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| filtros = [] | |
| for fid in range(1,5): | |
| cur.execute("SELECT caudal, h2s_in, h2s_out, timestamp FROM records WHERE filter_id=? ORDER BY id ASC", (fid,)) | |
| rows = cur.fetchall() | |
| acumulado = 0.0 | |
| last_h2s_out = 0.0 | |
| times = [] | |
| acumul_over_time = [] | |
| saturado_flag = False # nuevo flag | |
| if rows: | |
| for r in rows: | |
| acumulado += calc_load_captured_g(r[1], r[2], r[0]) | |
| times.append(pd.to_datetime(r[3])) | |
| acumul_over_time.append(acumulado) | |
| # Si en cualquier registro se saturó, marcarlo | |
| if r[2] >= UMBRAL_PPM or acumulado >= CAPACIDAD_POR_FILTRO_G: | |
| saturado_flag = True | |
| last_h2s_out = rows[-1][2] | |
| percent_used = round((acumulado / CAPACIDAD_POR_FILTRO_G) * 100, 1) if CAPACIDAD_POR_FILTRO_G>0 else 0 | |
| days_left = "∞" | |
| prediction_days = None | |
| if rows: | |
| last = rows[-1] | |
| carga_hora = calc_load_captured_g(last[1], last[2], last[0]) | |
| if carga_hora>0: | |
| hours_left = (CAPACIDAD_POR_FILTRO_G - acumulado) / carga_hora | |
| days_left = round(max(hours_left/24, 0),1) | |
| # Determinar estado del filtro | |
| status = "OK" | |
| if saturado_flag: | |
| status = "Saturado" | |
| elif percent_used >= 90: | |
| status = "Alerta" | |
| filtros.append({ | |
| "id":fid, | |
| "percent_used":percent_used, | |
| "days_left":days_left, | |
| "status":status, | |
| "prediction_days":prediction_days, | |
| "last_h2s_out": last_h2s_out, | |
| "acumulado":acumulado | |
| }) | |
| conn.close() | |
| # Mostrar métricas | |
| cols = st.columns(4) | |
| icons = {"OK":"🟢", "Alerta":"🟡", "Saturado":"🔴"} | |
| for i, f in enumerate(filtros): | |
| with cols[i]: | |
| st.metric( | |
| label=f"Filtro {f['id']} {icons.get(f['status'],'')}", | |
| value=f"{f['percent_used']}% usado", | |
| delta=f"{f['days_left']} días restantes" | |
| ) | |
| if f['status']=="OK": | |
| st.success("OK") | |
| elif f['status']=="Alerta": | |
| st.warning("Alerta: cerca de 90%") | |
| else: # Saturado | |
| st.error("🔴 Saturado (>10 ppm o capacidad máxima alcanzada)") | |
| # Curvas de saturación | |
| st.subheader("Curvas de saturación") | |
| fig = make_overall_plot_bars(filtros) | |
| st.pyplot(fig) | |
| def make_overall_plot_bars(filtros): | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| fig, ax = plt.subplots(figsize=(8,4)) | |
| filtro_ids = [1,2,3,4] | |
| acumulados = [] | |
| statuses = [] | |
| for fid in filtro_ids: | |
| cur.execute("SELECT caudal, h2s_in, h2s_out FROM records WHERE filter_id=? ORDER BY id ASC", (fid,)) | |
| rows = cur.fetchall() | |
| total = 0.0 | |
| saturado_flag = False | |
| for r in rows: | |
| total += calc_load_captured_g(r[1], r[2], r[0]) | |
| if r[2] >= UMBRAL_PPM or total >= CAPACIDAD_POR_FILTRO_G: | |
| saturado_flag = True | |
| acumulados.append(total/1000.0) # kg | |
| statuses.append("Saturado" if saturado_flag else "OK") | |
| # Colores según estado | |
| colors = [] | |
| for s in statuses: | |
| if s == "Saturado": | |
| colors.append("red") | |
| else: | |
| colors.append("green") | |
| bars = ax.bar([f"Filtro {i}" for i in filtro_ids], acumulados, color=colors) | |
| for bar, val in zip(bars, acumulados): | |
| ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(), f"{val:.2f} kg", ha='center', va='bottom') | |
| ax.axhline(CAPACIDAD_POR_FILTRO_G/1000.0, color='r', linestyle='--', | |
| label=f'Capacidad filtro: {CAPACIDAD_POR_FILTRO_G/1000:.0f} kg') | |
| ax.set_ylabel('H2S acumulado (kg)') | |
| ax.set_title('Acumulado de H2S por filtro') | |
| ax.legend() | |
| ax.grid(True) | |
| conn.close() | |
| return fig | |
| # ---- Ingreso de datos ---- | |
| def ingresar_datos_page(): | |
| st.header("Ingresar datos de operación") | |
| with st.form("ingresar"): | |
| filtros_text = st.text_input("Filtros operando (ej: '1 3')") | |
| h2s_in = st.number_input("H2S entrada (ppm)", min_value=0.0, value=200.0) | |
| h2s_out = st.number_input("H2S salida (ppm)", min_value=0.0, value=1.0) | |
| caudal = st.number_input("Caudal total (Nm3/h)", min_value=0.0, value=600.0) | |
| submitted = st.form_submit_button("Guardar") | |
| if submitted: | |
| try: | |
| filtros = [int(x) for x in filtros_text.split()] | |
| except Exception: | |
| st.error("Formato de filtros inválido. Ej: '1 3' ") | |
| return | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| for f in filtros: | |
| cur.execute("INSERT INTO records (filter_id, timestamp, date, caudal, h2s_in, h2s_out, user_id) VALUES (?,?,?,?,?,?,?)", | |
| (f, datetime.utcnow().isoformat(), str(datetime.utcnow().date()), caudal/len(filtros), h2s_in, h2s_out, st.session_state.user['id'])) | |
| conn.commit() | |
| conn.close() | |
| st.success("Datos guardados y memorizados por filtro.") | |
| # ---- Reset de filtros (backup antes) ---- | |
| # ---- Reset de filtros (backup antes) ---- | |
| def reset_page(): | |
| st.header("Resetear filtro(s) - respaldo antes de borrar") | |
| with st.form("reset"): | |
| filtros_text = st.text_input("Filtros a resetear (ej: '2 3')") | |
| confirm = st.checkbox("Confirmo generar backup y resetear estos filtros") | |
| submitted = st.form_submit_button("Resetear") | |
| if submitted: | |
| if not confirm: | |
| st.error("Marca la casilla de confirmación para proceder.") | |
| return | |
| try: | |
| filtros = [int(x) for x in filtros_text.split()] | |
| except Exception: | |
| st.error("Formato de filtros inválido. Ej: '2 3'") | |
| return | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| combined = {} | |
| for f in filtros: | |
| cur.execute("SELECT timestamp, date, caudal, h2s_in, h2s_out, user_id FROM records WHERE filter_id=? ORDER BY id ASC", (f,)) | |
| rows = cur.fetchall() | |
| combined[f] = [{"timestamp":r[0], "date":r[1], "caudal":r[2], "h2s_in":r[3], "h2s_out":r[4], "user_id":r[5]} for r in rows] | |
| # Crear DataFrame para Excel | |
| data_rows = [] | |
| for fid, rows in combined.items(): | |
| for r in rows: | |
| data_rows.append([fid, r['timestamp'], r['date'], r['caudal'], r['h2s_in'], r['h2s_out'], r['user_id']]) | |
| df_backup = pd.DataFrame(data_rows, columns=["filter_id","timestamp","date","caudal","h2s_in","h2s_out","user_id"]) | |
| # Guardar a Excel en memoria | |
| from io import BytesIO | |
| excel_buffer = BytesIO() | |
| with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer: | |
| df_backup.to_excel(writer, index=False, sheet_name="backup") | |
| excel_buffer.seek(0) | |
| # Guardar registro en la DB | |
| cur.execute("INSERT INTO backups (timestamp, description, payload) VALUES (?,?,?)", | |
| (datetime.utcnow().isoformat(), f"Reset filtros {filtros} por {st.session_state.user['username']}", str(combined))) | |
| # Borrar datos de los filtros seleccionados | |
| for f in filtros: | |
| cur.execute("DELETE FROM records WHERE filter_id=?", (f,)) | |
| conn.commit() | |
| conn.close() | |
| st.success(f"Backup generado para filtros {filtros} (Excel)") | |
| st.download_button( | |
| "Descargar backup (Excel)", | |
| data=excel_buffer, | |
| file_name=f"reset_backup_{''.join(map(str,filtros))}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx" | |
| ) | |
| # ---- Reportes y descargas ---- | |
| # ---- Reportes y descargas ---- | |
| def reportes_page(): | |
| st.header("Reportes y descargas") | |
| st.subheader("Descargar estado actual (todos los filtros)") | |
| if st.button("Generar Excel estado actual"): | |
| conn = get_conn() | |
| df = pd.read_sql_query("SELECT * FROM records ORDER BY filter_id, id", conn) | |
| conn.close() | |
| excel_buffer = BytesIO() | |
| with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer: | |
| df.to_excel(writer, index=False, sheet_name="estado_actual") | |
| excel_buffer.seek(0) | |
| st.download_button( | |
| "Descargar Excel", | |
| data=excel_buffer, | |
| file_name=f"estado_actual_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx" | |
| ) | |
| st.subheader("Descargar gráficos (PNG)") | |
| fig = make_overall_plot_bars([{"id":i} for i in range(1,5)]) | |
| buf = BytesIO() | |
| fig.savefig(buf, format="png", bbox_inches="tight") | |
| buf.seek(0) | |
| st.download_button("Descargar gráfica PNG", data=buf, file_name=f"curva_saturacion_{datetime.utcnow().strftime('%Y%m%d')}.png") | |
| # ---- Simulación ---- | |
| # ---- Simulación ---- | |
| # ---- Simulación corregida ---- | |
| # ---- Simulación ---- | |
| def simulacion_page(): | |
| st.header("Simulación de escenario (desde cero)") | |
| with st.form("sim"): | |
| filtros_text = st.text_input("Filtros a simular (ej: '1 2')", value="1") | |
| h2s_in = st.number_input("H2S entrada (ppm)", min_value=0.0, value=200.0) | |
| h2s_out = st.number_input("H2S salida (ppm)", min_value=0.0, value=1.0) | |
| caudal = st.number_input("Caudal total (Nm3/h)", min_value=0.0, value=600.0) | |
| carbon_kg = st.number_input("Cantidad de carbón cargado por filtro (kg)", min_value=0.0, value=1800.0) | |
| submit = st.form_submit_button("Simular") | |
| if submit: | |
| try: | |
| filtros = [int(x) for x in filtros_text.split()] | |
| except Exception: | |
| st.error("Formato de filtros inválido.") | |
| return | |
| # Nuevo factor de absorción | |
| CAPACIDAD_ADSORB_G_PER_G = 0.35 | |
| results = [] | |
| for f in filtros: | |
| # Convertir carbón cargado a gramos y calcular capacidad total de H2S | |
| carbon_g = carbon_kg * 1000 | |
| capacidad_h2s_g = carbon_g * CAPACIDAD_ADSORB_G_PER_G | |
| # Cálculo carga capturada por hora | |
| carga_hora_g = calc_load_captured_g(h2s_in, h2s_out, caudal / len(filtros)) | |
| carga_hora_kg = carga_hora_g / 1000.0 | |
| # Días y horas hasta saturación | |
| if carga_hora_kg > 0: | |
| hours_left = capacidad_h2s_g / carga_hora_g | |
| days_left = hours_left / 24 | |
| else: | |
| hours_left = np.inf | |
| days_left = np.inf | |
| results.append({ | |
| "Filtro": f, | |
| "Carga total tratada (kg)": round(capacidad_h2s_g / 1000.0, 2), | |
| "Carga capturada por hora (kg/h)": round(carga_hora_kg, 2), | |
| "Días hasta saturación": round(days_left, 2), | |
| "Horas hasta saturación": round(hours_left, 2) | |
| }) | |
| # Mostrar resultados en texto | |
| for r in results: | |
| st.subheader(f"Filtro {r['Filtro']}") | |
| st.write(f"Carga total tratada: {r['Carga total tratada (kg)']} kg") | |
| st.write(f"Carga capturada por hora: {r['Carga capturada por hora (kg/h)']} kg/h") | |
| st.write(f"Días hasta saturación: {r['Días hasta saturación']} días ({r['Horas hasta saturación']} horas)") | |
| # Generar Excel descargable | |
| df = pd.DataFrame(results) | |
| output = BytesIO() | |
| with pd.ExcelWriter(output, engine="xlsxwriter") as writer: | |
| df.to_excel(writer, index=False, sheet_name="Simulación") | |
| output.seek(0) | |
| st.download_button("Descargar resultados en Excel", data=output, | |
| file_name=f"simulacion_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx") | |
| # ---- Historial / Backups ---- | |
| def historial_page(): | |
| st.header("Historial general (backups)") | |
| conn = get_conn() | |
| cur = conn.cursor() | |
| cur.execute("SELECT id, timestamp, description, payload FROM backups ORDER BY id DESC LIMIT 50") | |
| rows = cur.fetchall() | |
| conn.close() | |
| for r in rows: | |
| st.write(r[0], r[1], r[2]) | |
| if st.button(f"Descargar backup {r[0]}", key=f"bk{r[0]}"): | |
| # Convertir payload (string de lista/dict) a DataFrame | |
| import ast | |
| try: | |
| payload_data = ast.literal_eval(r[3]) | |
| records_list = [] | |
| for fid, recs in payload_data.items(): | |
| for rec in recs: | |
| records_list.append({ | |
| "filter_id": fid, | |
| "timestamp": rec["timestamp"], | |
| "date": rec["date"], | |
| "caudal": rec["caudal"], | |
| "h2s_in": rec["h2s_in"], | |
| "h2s_out": rec["h2s_out"], | |
| "user_id": rec["user_id"] | |
| }) | |
| df = pd.DataFrame(records_list) | |
| except Exception: | |
| st.error("Error al convertir el backup a DataFrame") | |
| continue | |
| # Crear buffer Excel | |
| excel_buffer = BytesIO() | |
| with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer: | |
| df.to_excel(writer, index=False, sheet_name=f"backup_{r[0]}") | |
| excel_buffer.seek(0) | |
| st.download_button( | |
| f"Descargar backup {r[0]} en Excel", | |
| data=excel_buffer, | |
| file_name=f"backup_{r[0]}.xlsx" | |
| ) | |
| # ---------------- App layout control ---------------- | |
| if not st.session_state.logged: | |
| login_panel() | |
| else: | |
| page = sidebar_menu() | |
| if st.session_state.user and st.session_state.user.get('username') == 'admin': | |
| admin_panel_ui() | |
| if page == "Dashboard": | |
| dashboard() | |
| elif page == "Ingresar datos": | |
| ingresar_datos_page() | |
| elif page == "Resetear filtros": | |
| reset_page() | |
| elif page == "Reportes": | |
| reportes_page() | |
| elif page == "Simulación": | |
| simulacion_page() | |
| elif page == "Historial / Backups": | |
| historial_page() | |
| elif page == "Salir": | |
| st.session_state.logged = False | |
| st.session_state.user = None | |
| st.experimental_rerun() | |