Spaces:
Sleeping
Sleeping
Update src/app.py
Browse files- src/app.py +100 -39
src/app.py
CHANGED
@@ -7,11 +7,12 @@ from sklearn.preprocessing import PolynomialFeatures
|
|
7 |
from sklearn.neighbors import KNeighborsRegressor
|
8 |
from sklearn.metrics import r2_score, mean_squared_error
|
9 |
import numpy as np
|
|
|
10 |
|
11 |
# Configuración inicial
|
12 |
st.set_page_config(page_title="📊 Dashboard Avanzado", layout="wide")
|
13 |
st.title("🧠 Dashboard Dinámico con Análisis Avanzado")
|
14 |
-
st.markdown("Carga un CSV y explora visualizaciones + modelos de ML
|
15 |
|
16 |
# Subida de archivo
|
17 |
uploaded_file = st.file_uploader("📁 Cargar archivo CSV", type=["csv"])
|
@@ -19,7 +20,12 @@ if uploaded_file:
|
|
19 |
df = pd.read_csv(uploaded_file)
|
20 |
|
21 |
# Tabs para organización
|
22 |
-
tabs = st.tabs([
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
# Pestaña 1: Datos
|
25 |
with tabs[0]:
|
@@ -64,7 +70,7 @@ if uploaded_file:
|
|
64 |
try:
|
65 |
fig = None
|
66 |
if plot_type == "Scatter":
|
67 |
-
fig = px.scatter(df, x=x_col, y=y_col
|
68 |
elif plot_type == "Line":
|
69 |
fig = px.line(df, x=x_col, y=y_col)
|
70 |
elif plot_type == "Bar":
|
@@ -92,41 +98,96 @@ if uploaded_file:
|
|
92 |
)
|
93 |
|
94 |
# Selección de variables
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
else:
|
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 |
-
fig.add_trace(go.Scatter(x=y, y=y_pred, mode='markers', name='Predicción'))
|
130 |
-
fig.add_trace(go.Scatter(x=[y.min(), y.max()], y=[y.min(), y.max()], mode='lines', name='Ideal'))
|
131 |
-
fig.update_layout(title="Predicción vs Valores Reales", xaxis_title="Real", yaxis_title="Predicho")
|
132 |
-
st.plotly_chart(fig)
|
|
|
7 |
from sklearn.neighbors import KNeighborsRegressor
|
8 |
from sklearn.metrics import r2_score, mean_squared_error
|
9 |
import numpy as np
|
10 |
+
import requests
|
11 |
|
12 |
# Configuración inicial
|
13 |
st.set_page_config(page_title="📊 Dashboard Avanzado", layout="wide")
|
14 |
st.title("🧠 Dashboard Dinámico con Análisis Avanzado")
|
15 |
+
st.markdown("Carga un CSV y explora visualizaciones + modelos de ML + IA generativa.")
|
16 |
|
17 |
# Subida de archivo
|
18 |
uploaded_file = st.file_uploader("📁 Cargar archivo CSV", type=["csv"])
|
|
|
20 |
df = pd.read_csv(uploaded_file)
|
21 |
|
22 |
# Tabs para organización
|
23 |
+
tabs = st.tabs([
|
24 |
+
"🔍 Datos",
|
25 |
+
"📊 Visualizaciones",
|
26 |
+
"🤖 Machine Learning",
|
27 |
+
"🧠 Análisis con IA Generativa"
|
28 |
+
])
|
29 |
|
30 |
# Pestaña 1: Datos
|
31 |
with tabs[0]:
|
|
|
70 |
try:
|
71 |
fig = None
|
72 |
if plot_type == "Scatter":
|
73 |
+
fig = px.scatter(df, x=x_col, y=y_col) # Sin trendline para evitar dependencia statsmodels
|
74 |
elif plot_type == "Line":
|
75 |
fig = px.line(df, x=x_col, y=y_col)
|
76 |
elif plot_type == "Bar":
|
|
|
98 |
)
|
99 |
|
100 |
# Selección de variables
|
101 |
+
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
|
102 |
+
if len(numeric_cols) < 2:
|
103 |
+
st.warning("Necesitas al menos dos columnas numéricas para entrenar un modelo.")
|
104 |
+
else:
|
105 |
+
target = st.selectbox("Variable objetivo (Y)", numeric_cols)
|
106 |
+
features = st.multiselect("Variables independientes (X)", numeric_cols, default=numeric_cols[:1])
|
107 |
+
|
108 |
+
if st.button("Entrenar Modelo"):
|
109 |
+
if len(features) == 0 or target is None:
|
110 |
+
st.error("Selecciona al menos una variable independiente y una dependiente.")
|
111 |
+
else:
|
112 |
+
X = df[features]
|
113 |
+
y = df[target]
|
114 |
+
|
115 |
+
# Entrenamiento según modelo
|
116 |
+
model = None
|
117 |
+
if model_type == "Linear Regression":
|
118 |
+
model = LinearRegression()
|
119 |
+
elif model_type == "Polynomial Regression":
|
120 |
+
poly = PolynomialFeatures(degree=2)
|
121 |
+
X = poly.fit_transform(X)
|
122 |
+
model = LinearRegression()
|
123 |
+
elif model_type == "K-Nearest Neighbors":
|
124 |
+
model = KNeighborsRegressor(n_neighbors=5)
|
125 |
+
|
126 |
+
model.fit(X, y)
|
127 |
+
y_pred = model.predict(X)
|
128 |
+
|
129 |
+
# Métricas
|
130 |
+
r2 = r2_score(y, y_pred)
|
131 |
+
mse = mean_squared_error(y, y_pred)
|
132 |
+
|
133 |
+
# Resultados
|
134 |
+
st.write(f"**R² Score:** {r2:.2f}")
|
135 |
+
st.write(f"**Mean Squared Error:** {mse:.2f}")
|
136 |
+
|
137 |
+
# Gráfico de predicción vs real
|
138 |
+
fig = go.Figure()
|
139 |
+
fig.add_trace(go.Scatter(x=y, y=y_pred, mode='markers', name='Predicción'))
|
140 |
+
fig.add_trace(go.Scatter(x=[y.min(), y.max()], y=[y.min(), y.max()], mode='lines', name='Ideal'))
|
141 |
+
fig.update_layout(title="Predicción vs Valores Reales", xaxis_title="Real", yaxis_title="Predicho")
|
142 |
+
st.plotly_chart(fig)
|
143 |
+
|
144 |
+
# Pestaña 4: IA Generativa
|
145 |
+
with tabs[3]:
|
146 |
+
st.subheader("💬 Usar IA Generativa (Gemini API)")
|
147 |
+
st.markdown("Introduce tu clave de API de Gemini y haz preguntas sobre los datos.")
|
148 |
+
|
149 |
+
# Campo para la API Key
|
150 |
+
gemini_api_key = st.text_input("Gemini API Key", type="password")
|
151 |
+
|
152 |
+
# Campo para la pregunta
|
153 |
+
user_query = st.text_area(
|
154 |
+
"Haz una pregunta sobre los datos",
|
155 |
+
"¿Cuál es el promedio de la columna X? ¿Hay alguna correlación entre X e Y?"
|
156 |
+
)
|
157 |
+
|
158 |
+
if st.button("Enviar a Gemini"):
|
159 |
+
if not gemini_api_key:
|
160 |
+
st.error("Por favor, introduce una API Key válida.")
|
161 |
else:
|
162 |
+
try:
|
163 |
+
# Datos del dataset como contexto
|
164 |
+
context = f"""
|
165 |
+
Estos son los primeros 5 registros del dataset cargado:
|
166 |
+
{df.head().to_string()}
|
167 |
+
|
168 |
+
Pregunta del usuario: {user_query}
|
169 |
+
"""
|
170 |
+
|
171 |
+
# Llamada a la API de Gemini
|
172 |
+
url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" + gemini_api_key
|
173 |
+
|
174 |
+
payload = {
|
175 |
+
"contents": [{"parts": [{"text": context}]}]
|
176 |
+
}
|
177 |
+
|
178 |
+
headers = {
|
179 |
+
"Content-Type": "application/json"
|
180 |
+
}
|
181 |
+
|
182 |
+
response = requests.post(url, json=payload, headers=headers)
|
183 |
+
|
184 |
+
if response.status_code == 200:
|
185 |
+
result = response.json()
|
186 |
+
ai_response = result["candidates"][0]["content"]["parts"][0]["text"]
|
187 |
+
st.markdown("### 🤖 Respuesta de Gemini:")
|
188 |
+
st.markdown(ai_response)
|
189 |
+
else:
|
190 |
+
st.error(f"Error en la API: {response.status_code} - {response.text}")
|
191 |
|
192 |
+
except Exception as e:
|
193 |
+
st.error(f"Error al conectar con Gemini: {e}")
|
|
|
|
|
|
|
|