Spaces:
Sleeping
Sleeping
import hashlib | |
import yaml | |
import streamlit as st | |
from st_aggrid import AgGrid, GridOptionsBuilder | |
import os | |
import pandas as pd | |
from yaml.loader import SafeLoader | |
import streamlit_authenticator as stauth | |
st.set_page_config(layout="wide") | |
with open('config.yaml') as file: | |
config = yaml.load(file, Loader=SafeLoader) | |
def authenticate_user(username, password): | |
return username == "admin" and password == "bases" | |
def login_form(): | |
st.title("Iniciar Sesi贸n") | |
username = st.text_input("Usuario", value="admin") | |
password = st.text_input("Contrase帽a", value="bases", type="password") | |
if st.button("Iniciar Sesi贸n"): | |
if authenticate_user(username, password): | |
st.success("Autenticaci贸n exitosa.") | |
st.session_state['authenticated'] = True | |
else: | |
st.error("Credenciales incorrectas. Intenta de nuevo.") | |
class AuthenticateSHA1(stauth.Authenticate): | |
def __init__(self, credentials, cookie_name, cookie_key, cookie_expiry_days, preauthorized=None): | |
super().__init__(credentials, cookie_name, cookie_key, cookie_expiry_days, preauthorized) | |
def _check_password(self, stored_password, provided_password): | |
provided_password_hashed = hashlib.sha1(provided_password.encode()).hexdigest() | |
return stored_password == provided_password_hashed | |
authenticator = AuthenticateSHA1( | |
config['credentials'], | |
config['cookie']['name'], | |
config['cookie']['key'], | |
config['cookie']['expiry_days'], | |
config.get('preauthorized') | |
) | |
def listar_archivos_excel(): | |
return [f for f in os.listdir() if f.endswith(('.xls', '.xlsx', '.csv'))] | |
def leer_archivo(file_path): | |
try: | |
if file_path.endswith("csv"): | |
return pd.read_csv(file_path) | |
elif file_path.endswith(("xlsx", "xls")): | |
return pd.read_excel(file_path) | |
else: | |
st.error("Formato no soportado. Usa archivos CSV o Excel.") | |
return None | |
except Exception as e: | |
st.error(f"Error al leer el archivo: {e}") | |
return None | |
def mostrar_tabla_interactiva(datos): | |
try: | |
gb = GridOptionsBuilder.from_dataframe(datos) | |
gb.configure_default_column(groupable=True, value=True, enableRowGroup=True, editable=False) | |
gb.configure_pagination(paginationAutoPageSize=True) | |
gb.configure_grid_options(domLayout='normal', onGridReady="params.api.sizeColumnsToFit()") | |
grid_options = gb.build() | |
AgGrid( | |
datos, | |
gridOptions=grid_options, | |
height=900, | |
theme='streamlit', | |
enable_enterprise_modules=True, | |
allow_unsafe_jscode=True, | |
) | |
except Exception as e: | |
st.error(f"Error al mostrar la tabla: {e}") | |
def buscar_en_archivo(datos, terminos): | |
try: | |
terminos_busqueda = terminos.split() | |
coincidencias = datos.apply( | |
lambda fila: all( | |
fila.astype(str).str.contains(t, case=False).any() for t in terminos_busqueda | |
), axis=1 | |
) | |
return datos[coincidencias] | |
except Exception as e: | |
st.error(f"Error en la b煤squeda: {e}") | |
return pd.DataFrame() | |
def main(): | |
try: | |
if "authenticated" not in st.session_state: | |
st.session_state['authenticated'] = False | |
if not st.session_state['authenticated']: | |
login_form() | |
else: | |
archivos_excel = listar_archivos_excel() | |
archivo_seleccionado = st.sidebar.selectbox("Selecciona un archivo", archivos_excel) | |
termino_busqueda = st.sidebar.text_input("Buscar en el archivo", "") | |
if st.sidebar.button("Buscar"): | |
if archivo_seleccionado: | |
datos = leer_archivo(archivo_seleccionado) | |
if datos is not None: | |
resultados = buscar_en_archivo(datos, termino_busqueda) | |
st.write("### Resultados de la b煤squeda") | |
if not resultados.empty: | |
mostrar_tabla_interactiva(resultados) | |
else: | |
st.write("No se encontraron coincidencias.") | |
else: | |
st.warning("Selecciona un archivo primero.") | |
if archivo_seleccionado: | |
datos = leer_archivo(archivo_seleccionado) | |
if datos is not None: | |
mostrar_tabla_interactiva(datos) | |
except Exception as e: | |
st.error(f"Ocurri贸 un error: {e}") | |
if __name__ == "__main__": | |
main() |