File size: 7,810 Bytes
f90edf8
abe96df
 
ee44c08
 
abe96df
70225aa
 
 
 
 
 
 
 
 
 
 
b1463f1
ec41c7d
b1463f1
25499d5
ec41c7d
b1463f1
abe96df
b1463f1
 
25499d5
 
 
ee44c08
b1463f1
ee44c08
 
b1463f1
ee44c08
abe96df
504884e
 
 
 
 
 
 
70225aa
504884e
 
 
70225aa
 
504884e
 
 
 
 
 
abe96df
b1463f1
ee44c08
b1463f1
 
25499d5
 
 
 
 
 
 
 
ee44c08
b1463f1
abe96df
b1463f1
ee44c08
25499d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1463f1
 
 
 
25499d5
b1463f1
25499d5
 
 
 
 
ee44c08
 
b1463f1
ee44c08
abe96df
b1463f1
ee44c08
 
b1463f1
 
 
 
 
 
 
25499d5
 
b1463f1
 
 
ee44c08
 
abe96df
b1463f1
 
 
 
25499d5
 
 
 
b1463f1
 
 
 
 
 
 
 
 
25499d5
 
b1463f1
abe96df
 
ee44c08
b1463f1
 
504884e
 
 
b1463f1
 
 
ec41c7d
b1463f1
 
 
 
 
 
504884e
ec41c7d
b1463f1
 
 
 
 
504884e
 
ec41c7d
504884e
 
b12620a
504884e
 
 
 
 
 
 
 
b12620a
504884e
 
 
 
e015459
 
 
b12620a
 
 
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
import os
import streamlit as st
import pandas as pd
import math
import matplotlib.pyplot as plt

st.markdown(
    """
    <style>
    .csv_download_button {
        display: none;
    }
    </style>
    """,
    unsafe_allow_html=True
)

directorio = os.getcwd()

def listar_archivos_excel(directorio):
    return [f for f in os.listdir(directorio) 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.dataframe(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()
        st.markdown(df_html, unsafe_allow_html=True)
        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 realizar_calculos(datos):
    try:
        st.write("### C谩lculos")
        for columna in datos.columns:
            if pd.api.types.is_numeric_dtype(datos[columna]):
                suma_columna = datos[columna].sum()
                media_columna = datos[columna].mean()
                mediana_columna = datos[columna].median()
                st.write(f"C谩lculos para la columna: {columna}")
                st.write(f"Suma: {suma_columna}")
                st.write(f"Media: {media_columna}")
                st.write(f"Mediana: {mediana_columna}")
    except Exception as e:
        st.error(f"Error al realizar c谩lculos: {e}")

def realizar_operacion_matematica(df, columnas_seleccionadas, operacion):
    try:
        if not columnas_seleccionadas:
            st.error("No se han seleccionado columnas.")
            return df
        
        operaciones = {
            "sqrt": math.sqrt,
            "log": math.log,
            "exp": math.exp,
            "sin": math.sin,
            "cos": math.cos,
            "tan": math.tan
        }
        
        if operacion in operaciones:
            resultado = df[columnas_seleccionadas].applymap(operaciones[operacion])
        elif operacion == "multiply":
            resultado = df[columnas_seleccionadas].prod(axis=1)
        elif operacion == "add":
            resultado = df[columnas_seleccionadas].sum(axis=1)
        elif operacion == "subtract" and len(columnas_seleccionadas) == 2:
            resultado = df[columnas_seleccionadas[0]] - df[columnas_seleccionadas[1]]
        else:
            st.error("Operaci贸n no soportada o selecci贸n de columnas incorrecta.")
            return df

        df[f"{operacion}_resultado"] = resultado
        return df
    except Exception as e:
        st.error(f"Error al realizar la operaci贸n matem谩tica: {e}")
        return df

def graficar_datos(datos, tipo_grafico, variables_x, variables_y):
    try:
        plt.figure(figsize=(8, 6))
        for x_var in variables_x:
            for y_var in variables_y:
                if tipo_grafico == "Dispersi贸n":
                    plt.scatter(datos[x_var], datos[y_var], label=f"{x_var} vs {y_var}")
                elif tipo_grafico == "L铆nea":
                    plt.plot(datos[x_var], datos[y_var], label=f"{x_var} vs {y_var}")
                elif tipo_grafico == "Barras":
                    plt.bar(range(len(datos)), datos[y_var], label=y_var)
        
        plt.xlabel("Valores de X")
        plt.ylabel("Valores de Y")
        plt.title(f"Gr谩fico de {tipo_grafico}")
        plt.legend()
        st.pyplot()
    except Exception as e:
        st.error(f"Error al graficar los datos: {e}")

def buscar_en_archivos(archivos, termino):
    resultados = {}
    num_archivos = len(archivos)
    progreso = st.progress(0)
    
    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: fila.astype(str).str.contains(termino, case=False).any(), 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:
        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(directorio)
        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}")
                st.dataframe(resultados.applymap(lambda x: f"{x:.0f}" if isinstance(x, (int, float)) else x))
        
        if archivo_seleccionado:
            ruta_archivo = os.path.join(directorio, archivo_seleccionado)
            with open(ruta_archivo, "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=10000, value=10)
                    mostrar_datos(datos, num_filas, st.session_state.pagina)
                    
                    if st.sidebar.checkbox("Mostrar opciones adicionales"):
                        realizar_calculos(datos)

                        st.write("### Visualizador de Gr谩ficos")
                        st.write("Selecciona variables para la visualizaci贸n:")
                        tipo_grafico = st.selectbox("Tipo de Gr谩fico", options=["Dispersi贸n", "L铆nea", "Barras"])
                        variables_x = st.multiselect("Variables X", options=datos.columns)
                        variables_y = st.multiselect("Variables Y", options=datos.columns)
                        
                        columnas_seleccionadas = st.multiselect("Selecciona columnas:", options=datos.columns)
                        operacion = st.selectbox("Selecciona una operaci贸n:", ["sqrt", "log", "exp", "sin", "cos", "tan", "multiply", "add", "subtract"])

                        if st.button("Calcular"):
                            datos = realizar_operacion_matematica(datos, columnas_seleccionadas, operacion)
                            st.write(datos.applymap(lambda x: f"{x:.0f}" if isinstance(x, (int, float)) else x))
                        if st.button("Graficar"):
                            graficar_datos(datos, tipo_grafico, variables_x, variables_y)
    except Exception as e:
        st.error(f"Ocurri贸 un error: {e}")

if __name__ == "__main__":
    main()