leads / app.py
salomonsky's picture
Update app.py
0246754 verified
raw
history blame contribute delete
No virus
5.06 kB
import hashlib
import yaml
import streamlit as st
import streamlit_authenticator as stauth
import os
import pandas as pd
from yaml.loader import SafeLoader
with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
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):
try:
extension_archivo = file.name.split(".")[-1]
if extension_archivo == "csv":
return pd.read_csv(file)
elif extension_archivo in {"xlsx", "xls"}:
return pd.read_excel(file)
else:
st.error("Formato de archivo no soportado. Por favor, suba un archivo CSV o Excel.")
return None
except Exception as e:
st.error(f"Error al leer el archivo: {e}")
return None
def formatear_datos(datos):
return datos.applymap(lambda x: f"{x:.0f}" if isinstance(x, (int, float)) else x)
def mostrar_datos(datos, num_filas, pagina=0):
total_filas = len(datos)
datos_formateados = formatear_datos(datos)
if total_filas <= num_filas:
st.write(datos_formateados.head(num_filas))
else:
start_row = pagina * num_filas
end_row = start_row + num_filas
df_html = datos_formateados.iloc[start_row:end_row].to_html(index=False)
st.write(df_html, unsafe_allow_html=True, width=0)
if start_row > 0:
if st.button("Anterior", key="prev"):
st.session_state.pagina -= 1
if end_row < total_filas:
if st.button("Siguiente", key="next"):
st.session_state.pagina += 1
def buscar_en_archivos(archivos, termino):
resultados = {}
num_archivos = len(archivos)
progreso = st.progress(0)
terminos_busqueda = termino.split()
for i, archivo in enumerate(archivos):
try:
if archivo.endswith('.csv'):
datos = pd.read_csv(archivo)
elif archivo.endswith(('.xlsx', '.xls')):
datos = pd.read_excel(archivo)
coincidencias = datos.apply(lambda fila: all(fila.astype(str).str.contains(t, case=False).any() for t in terminos_busqueda), axis=1)
resultados[archivo] = datos[coincidencias]
except Exception as e:
st.error(f"Error al buscar en el archivo {archivo}: {e}")
progreso.progress((i + 1) / num_archivos)
return resultados
def main():
try:
name, authentication_status, username = authenticator.login(
location='main',
fields={'Form name': 'Login', 'Username': 'Username', 'Password': 'Password', 'Login': 'Login'}
)
if authentication_status:
st.title("Base de Datos XLS")
if "pagina" not in st.session_state:
st.session_state.pagina = 0
st.sidebar.title("Archivos Excel Disponibles")
archivos_excel = listar_archivos_excel()
archivo_seleccionado = st.sidebar.selectbox("Selecciona un archivo Excel", archivos_excel)
termino_busqueda = st.sidebar.text_input("Buscar en todos los archivos", "")
if st.sidebar.button("Buscar"):
resultados_busqueda = buscar_en_archivos(archivos_excel, termino_busqueda)
st.write("### Resultados de la búsqueda global")
for archivo, resultados in resultados_busqueda.items():
st.write(f"#### {archivo}")
if not resultados.empty:
st.dataframe(resultados)
else:
st.write("No se encontraron coincidencias en este archivo.")
if archivo_seleccionado:
with open(archivo_seleccionado, "rb") as file:
datos = leer_archivo(file)
if datos is not None:
num_filas = st.sidebar.slider("Número de filas a mostrar", min_value=1, max_value=100, value=10)
mostrar_datos(datos, num_filas, st.session_state.pagina)
elif authentication_status == False:
st.error('Nombre de usuario/contraseña incorrectos')
elif authentication_status == None:
st.warning('Por favor, introduce tu nombre de usuario y contraseña')
except Exception as e:
st.error(f"Ocurrió un error: {e}")
if __name__ == "__main__":
main()