Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,470 +1,348 @@
|
|
1 |
-
# --- INSTALACIÓN DE DEPENDENCIAS ADICIONALES ---
|
2 |
-
import os
|
3 |
-
import sys
|
4 |
-
import subprocess
|
5 |
-
|
6 |
-
os.system("pip install --upgrade gradio")
|
7 |
-
|
8 |
import gradio as gr
|
9 |
-
import pandas as pd
|
10 |
-
import numpy as np
|
11 |
-
import plotly.graph_objects as go
|
12 |
-
import plotly.express as px
|
13 |
from gradio_client import Client, handle_file
|
|
|
|
|
14 |
import tempfile
|
15 |
import os
|
16 |
-
import asyncio
|
17 |
-
import json
|
18 |
from datetime import datetime
|
19 |
-
import logging
|
20 |
-
|
21 |
-
# Configurar logging
|
22 |
-
logging.basicConfig(level=logging.INFO)
|
23 |
-
logger = logging.getLogger(__name__)
|
24 |
-
|
25 |
-
class BiotechAnalysisAgent:
|
26 |
-
def __init__(self):
|
27 |
-
self.biotech_client = Client("C2MV/BiotechU4")
|
28 |
-
self.analysis_client = Client("C2MV/Project-HF-2025")
|
29 |
-
self.results_cache = {}
|
30 |
-
|
31 |
-
async def process_biotech_data(self, file_path, models, component, use_de, maxfev, exp_names, theme):
|
32 |
-
"""Procesa los datos biotecnológicos usando el primer endpoint"""
|
33 |
-
try:
|
34 |
-
logger.info(f"Procesando archivo: {file_path}")
|
35 |
-
|
36 |
-
result = self.biotech_client.predict(
|
37 |
-
file=handle_file(file_path),
|
38 |
-
models=models,
|
39 |
-
component=component,
|
40 |
-
use_de=use_de,
|
41 |
-
maxfev=maxfev,
|
42 |
-
exp_names=exp_names,
|
43 |
-
theme=theme,
|
44 |
-
api_name="/run_analysis_wrapper"
|
45 |
-
)
|
46 |
-
|
47 |
-
# Extraer resultados
|
48 |
-
plot_data, table_data, status = result
|
49 |
-
|
50 |
-
# Guardar en caché
|
51 |
-
self.results_cache['biotech_results'] = {
|
52 |
-
'plot': plot_data,
|
53 |
-
'table': table_data,
|
54 |
-
'status': status,
|
55 |
-
'timestamp': datetime.now()
|
56 |
-
}
|
57 |
-
|
58 |
-
return plot_data, table_data, status
|
59 |
-
|
60 |
-
except Exception as e:
|
61 |
-
logger.error(f"Error en análisis biotecnológico: {str(e)}")
|
62 |
-
return None, None, f"Error: {str(e)}"
|
63 |
-
|
64 |
-
async def generate_csv_from_results(self, table_data):
|
65 |
-
"""Convierte los resultados de la tabla en un archivo CSV temporal"""
|
66 |
-
try:
|
67 |
-
if not table_data or 'data' not in table_data:
|
68 |
-
return None, "No hay datos para convertir"
|
69 |
-
|
70 |
-
# Crear DataFrame
|
71 |
-
df = pd.DataFrame(
|
72 |
-
data=table_data['data'],
|
73 |
-
columns=table_data.get('headers', [])
|
74 |
-
)
|
75 |
-
|
76 |
-
# Guardar como CSV temporal
|
77 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.csv', mode='w')
|
78 |
-
df.to_csv(temp_file.name, index=False)
|
79 |
-
temp_file.close()
|
80 |
-
|
81 |
-
return temp_file.name, "CSV generado exitosamente"
|
82 |
-
|
83 |
-
except Exception as e:
|
84 |
-
logger.error(f"Error generando CSV: {str(e)}")
|
85 |
-
return None, f"Error generando CSV: {str(e)}"
|
86 |
-
|
87 |
-
async def generate_analysis_report(self, csv_file_path, model, detail, language, additional_specs):
|
88 |
-
"""Genera el reporte de análisis usando el segundo endpoint"""
|
89 |
-
try:
|
90 |
-
if not csv_file_path or not os.path.exists(csv_file_path):
|
91 |
-
return "Error: No se encontró el archivo CSV", ""
|
92 |
-
|
93 |
-
logger.info(f"Generando reporte con archivo: {csv_file_path}")
|
94 |
-
|
95 |
-
result = self.analysis_client.predict(
|
96 |
-
files=[handle_file(csv_file_path)],
|
97 |
-
model=model,
|
98 |
-
detail=detail,
|
99 |
-
language=language,
|
100 |
-
additional_specs=additional_specs,
|
101 |
-
api_name="/process_and_store"
|
102 |
-
)
|
103 |
-
|
104 |
-
analysis_markdown, implementation_code = result
|
105 |
-
|
106 |
-
# Limpiar archivo temporal
|
107 |
-
try:
|
108 |
-
os.unlink(csv_file_path)
|
109 |
-
except:
|
110 |
-
pass
|
111 |
-
|
112 |
-
return analysis_markdown, implementation_code
|
113 |
-
|
114 |
-
except Exception as e:
|
115 |
-
logger.error(f"Error generando reporte: {str(e)}")
|
116 |
-
return f"Error generando reporte: {str(e)}", ""
|
117 |
-
|
118 |
-
async def export_report(self, format_type, language):
|
119 |
-
"""Exporta el reporte en el formato especificado"""
|
120 |
-
try:
|
121 |
-
result = self.analysis_client.predict(
|
122 |
-
format=format_type,
|
123 |
-
language=language,
|
124 |
-
api_name="/handle_export"
|
125 |
-
)
|
126 |
-
|
127 |
-
status, file_path = result
|
128 |
-
return status, file_path
|
129 |
-
|
130 |
-
except Exception as e:
|
131 |
-
logger.error(f"Error exportando: {str(e)}")
|
132 |
-
return f"Error exportando: {str(e)}", None
|
133 |
|
134 |
-
#
|
135 |
-
|
|
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
title="Gráfico de Ejemplo - Carga tus datos para ver resultados reales",
|
146 |
-
xaxis_title="Tiempo",
|
147 |
-
yaxis_title="Valor",
|
148 |
-
template="plotly_white"
|
149 |
-
)
|
150 |
-
return fig
|
151 |
|
152 |
-
|
153 |
-
|
154 |
-
claude_model, detail_level, language, additional_specs, theme
|
155 |
-
):
|
156 |
-
"""Función principal que ejecuta todo el pipeline"""
|
157 |
-
|
158 |
-
if file is None:
|
159 |
-
return (
|
160 |
-
create_sample_plot(),
|
161 |
-
pd.DataFrame({"Status": ["Por favor, carga un archivo para comenzar"]}),
|
162 |
-
"⚠️ Esperando archivo...",
|
163 |
-
"📄 Carga un archivo Excel (.xlsx) para generar el análisis completo",
|
164 |
-
"",
|
165 |
-
None
|
166 |
-
)
|
167 |
-
|
168 |
try:
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
plot_data, table_data, status = await agent.process_biotech_data(
|
180 |
-
file.name, models, component, use_de, maxfev, exp_names, theme
|
181 |
-
)
|
182 |
-
|
183 |
-
if table_data is None:
|
184 |
-
yield (
|
185 |
-
create_sample_plot(),
|
186 |
-
pd.DataFrame({"Error": [status]}),
|
187 |
-
f"❌ Error en análisis: {status}",
|
188 |
-
"Error en el procesamiento de datos",
|
189 |
-
"",
|
190 |
-
None
|
191 |
-
)
|
192 |
-
return
|
193 |
-
|
194 |
-
# Convertir datos de tabla para mostrar
|
195 |
-
if table_data and 'data' in table_data:
|
196 |
-
results_df = pd.DataFrame(
|
197 |
-
data=table_data['data'],
|
198 |
-
columns=table_data.get('headers', [])
|
199 |
-
)
|
200 |
-
else:
|
201 |
-
results_df = pd.DataFrame({"Status": ["Datos procesados pero tabla vacía"]})
|
202 |
-
|
203 |
-
# Paso 2: Generar CSV
|
204 |
-
yield (
|
205 |
-
create_sample_plot(),
|
206 |
-
results_df,
|
207 |
-
"🔄 Paso 2/3: Generando archivo CSV temporal...",
|
208 |
-
"Convirtiendo resultados para análisis con IA...",
|
209 |
-
"",
|
210 |
-
None
|
211 |
-
)
|
212 |
-
|
213 |
-
csv_path, csv_status = await agent.generate_csv_from_results(table_data)
|
214 |
-
|
215 |
-
if csv_path is None:
|
216 |
-
yield (
|
217 |
-
create_sample_plot(),
|
218 |
-
results_df,
|
219 |
-
f"❌ Error generando CSV: {csv_status}",
|
220 |
-
"Error en la conversión de datos",
|
221 |
-
"",
|
222 |
-
None
|
223 |
-
)
|
224 |
-
return
|
225 |
-
|
226 |
-
# Paso 3: Análisis con IA
|
227 |
-
yield (
|
228 |
-
create_sample_plot(),
|
229 |
-
results_df,
|
230 |
-
"🔄 Paso 3/3: Generando análisis con IA (Claude)...",
|
231 |
-
"Analizando resultados y generando reporte inteligente...",
|
232 |
-
"",
|
233 |
-
None
|
234 |
)
|
235 |
-
|
236 |
-
|
237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
238 |
)
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
|
|
|
|
251 |
)
|
252 |
-
|
253 |
except Exception as e:
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
|
|
|
|
262 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
263 |
|
264 |
-
#
|
265 |
-
|
266 |
-
|
267 |
-
theme=gr.themes.Soft(
|
268 |
-
primary_hue="blue",
|
269 |
-
secondary_hue="cyan",
|
270 |
-
neutral_hue="slate"
|
271 |
-
),
|
272 |
-
title="🧬 BioTech Analysis Suite - Análisis Inteligente de Datos Biotecnológicos",
|
273 |
-
css="""
|
274 |
-
.main-header {
|
275 |
-
text-align: center;
|
276 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
277 |
-
color: white;
|
278 |
-
padding: 2rem;
|
279 |
-
border-radius: 10px;
|
280 |
-
margin-bottom: 2rem;
|
281 |
-
}
|
282 |
-
.step-indicator {
|
283 |
-
background: #f8f9fa;
|
284 |
-
padding: 1rem;
|
285 |
-
border-radius: 8px;
|
286 |
-
border-left: 4px solid #007bff;
|
287 |
-
}
|
288 |
-
.results-container {
|
289 |
-
background: #ffffff;
|
290 |
-
border-radius: 10px;
|
291 |
-
padding: 1.5rem;
|
292 |
-
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
293 |
-
}
|
294 |
"""
|
295 |
-
|
296 |
|
297 |
-
|
298 |
-
<div class="main-header">
|
299 |
-
<h1>🧬 BioTech Analysis Suite</h1>
|
300 |
-
<p>Análisis Inteligente de Datos Biotecnológicos con IA</p>
|
301 |
-
<p>Carga tu archivo Excel → Análisis automático → Reporte con Claude AI</p>
|
302 |
-
</div>
|
303 |
-
""")
|
304 |
|
305 |
-
|
306 |
-
|
307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
308 |
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
|
|
|
|
313 |
)
|
314 |
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
label="Usar Evolución Diferencial",
|
331 |
value=False
|
332 |
)
|
333 |
|
334 |
-
|
335 |
-
label="Iteraciones máximas",
|
336 |
value=50000,
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
exp_names = gr.Textbox(
|
341 |
-
label="🏷️ Nombres de Experimentos",
|
342 |
-
value="Experimento_BioTech"
|
343 |
-
)
|
344 |
-
|
345 |
-
with gr.Accordion("🤖 Configuración de IA", open=True):
|
346 |
-
claude_model = gr.Dropdown(
|
347 |
-
choices=[
|
348 |
-
"claude-3-5-sonnet-20241022",
|
349 |
-
"claude-3-5-haiku-20241022",
|
350 |
-
"claude-3-7-sonnet-20250219"
|
351 |
-
],
|
352 |
-
value="claude-3-5-sonnet-20241022",
|
353 |
-
label="🤖 Modelo Claude"
|
354 |
-
)
|
355 |
-
|
356 |
-
detail_level = gr.Radio(
|
357 |
-
choices=["detailed", "summarized"],
|
358 |
-
value="detailed",
|
359 |
-
label="📋 Nivel de detalle del análisis"
|
360 |
-
)
|
361 |
-
|
362 |
-
language = gr.Dropdown(
|
363 |
-
choices=["es", "en", "fr", "de", "pt"],
|
364 |
-
value="es",
|
365 |
-
label="🌐 Idioma del reporte"
|
366 |
-
)
|
367 |
-
|
368 |
-
additional_specs = gr.Textbox(
|
369 |
-
label="📝 Especificaciones adicionales",
|
370 |
-
placeholder="Ej: Enfócate en la eficiencia de crecimiento y optimización de parámetros...",
|
371 |
-
lines=3
|
372 |
)
|
|
|
|
|
|
|
373 |
|
374 |
-
|
375 |
-
|
376 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
)
|
378 |
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
)
|
384 |
-
|
385 |
-
with gr.Column(scale=2):
|
386 |
-
gr.Markdown("## 📊 Resultados del Análisis")
|
387 |
|
388 |
-
|
389 |
-
|
390 |
-
value=
|
391 |
-
|
392 |
)
|
393 |
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
)
|
400 |
-
|
401 |
-
with gr.TabItem("📊 Datos"):
|
402 |
-
table_output = gr.Dataframe(
|
403 |
-
label="Tabla de Resultados",
|
404 |
-
value=pd.DataFrame({"Status": ["Carga un archivo para ver resultados"]})
|
405 |
-
)
|
406 |
-
|
407 |
-
with gr.TabItem("🤖 Análisis IA"):
|
408 |
-
analysis_output = gr.Markdown(
|
409 |
-
label="Reporte de Análisis",
|
410 |
-
value="📄 El análisis con IA aparecerá aquí una vez procesados los datos..."
|
411 |
-
)
|
412 |
-
|
413 |
-
with gr.TabItem("💻 Código"):
|
414 |
-
code_output = gr.Code(
|
415 |
-
label="Código de Implementación",
|
416 |
-
language="python",
|
417 |
-
value="# El código generado aparecerá aquí..."
|
418 |
-
)
|
419 |
|
420 |
-
|
421 |
-
|
422 |
-
|
|
|
423 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
424 |
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
6. **Descarga**: Obtén tu reporte PDF completo
|
447 |
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
|
|
|
|
452 |
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
459 |
|
460 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
461 |
|
462 |
-
# Lanzar la aplicación
|
463 |
if __name__ == "__main__":
|
464 |
-
|
465 |
-
interface.launch(
|
466 |
-
server_name="0.0.0.0",
|
467 |
-
server_port=7860,
|
468 |
share=True,
|
469 |
-
show_error=True
|
|
|
470 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
2 |
from gradio_client import Client, handle_file
|
3 |
+
import pandas as pd
|
4 |
+
import json
|
5 |
import tempfile
|
6 |
import os
|
|
|
|
|
7 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
# Configuración de clientes
|
10 |
+
biotech_client = Client("C2MV/BiotechU4")
|
11 |
+
analysis_client = Client("C2MV/Project-HF-2025")
|
12 |
|
13 |
+
# Tema personalizado
|
14 |
+
theme = gr.themes.Soft(
|
15 |
+
primary_hue="blue",
|
16 |
+
secondary_hue="indigo",
|
17 |
+
neutral_hue="slate",
|
18 |
+
spacing_size="md",
|
19 |
+
radius_size="lg",
|
20 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
+
def process_biotech_data(file, models, component, use_de, maxfev, exp_names):
|
23 |
+
"""Procesa los datos en el primer endpoint de BiotechU4"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
try:
|
25 |
+
result = biotech_client.predict(
|
26 |
+
file=handle_file(file.name),
|
27 |
+
models=models,
|
28 |
+
component=component,
|
29 |
+
use_de=use_de,
|
30 |
+
maxfev=maxfev,
|
31 |
+
exp_names=exp_names,
|
32 |
+
theme=False,
|
33 |
+
api_name="/run_analysis_wrapper"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
)
|
35 |
+
return result
|
36 |
+
except Exception as e:
|
37 |
+
return None, None, f"Error en el análisis: {str(e)}"
|
38 |
+
|
39 |
+
def download_results_as_csv(df_data):
|
40 |
+
"""Descarga los resultados como CSV desde BiotechU4"""
|
41 |
+
try:
|
42 |
+
result = biotech_client.predict(
|
43 |
+
df=df_data,
|
44 |
+
api_name="/download_results_excel"
|
45 |
)
|
46 |
+
return result
|
47 |
+
except Exception as e:
|
48 |
+
return None
|
49 |
+
|
50 |
+
def generate_claude_report(csv_file, model, detail_level, language, additional_specs):
|
51 |
+
"""Genera el informe usando Claude"""
|
52 |
+
try:
|
53 |
+
result = analysis_client.predict(
|
54 |
+
files=[handle_file(csv_file)],
|
55 |
+
model=model,
|
56 |
+
detail=detail_level,
|
57 |
+
language=language,
|
58 |
+
additional_specs=additional_specs,
|
59 |
+
api_name="/process_and_store"
|
60 |
)
|
61 |
+
return result
|
62 |
except Exception as e:
|
63 |
+
return f"Error en el análisis: {str(e)}", ""
|
64 |
+
|
65 |
+
def export_report(format_type, language, analysis, code):
|
66 |
+
"""Exporta el informe en el formato seleccionado"""
|
67 |
+
try:
|
68 |
+
# Primero procesamos y almacenamos
|
69 |
+
result = analysis_client.predict(
|
70 |
+
format=format_type,
|
71 |
+
language=language,
|
72 |
+
api_name="/handle_export"
|
73 |
)
|
74 |
+
return result[1], result[0]
|
75 |
+
except Exception as e:
|
76 |
+
return None, f"Error al exportar: {str(e)}"
|
77 |
+
|
78 |
+
def process_complete_pipeline(
|
79 |
+
file,
|
80 |
+
models,
|
81 |
+
component,
|
82 |
+
use_de,
|
83 |
+
maxfev,
|
84 |
+
exp_names,
|
85 |
+
claude_model,
|
86 |
+
detail_level,
|
87 |
+
language,
|
88 |
+
additional_specs,
|
89 |
+
export_format
|
90 |
+
):
|
91 |
+
"""Pipeline completo de procesamiento"""
|
92 |
+
progress_updates = []
|
93 |
+
|
94 |
+
# Paso 1: Procesar con BiotechU4
|
95 |
+
progress_updates.append("🔄 Procesando datos biotecnológicos...")
|
96 |
+
plot, df_data, status = process_biotech_data(
|
97 |
+
file, models, component, use_de, maxfev, exp_names
|
98 |
+
)
|
99 |
+
|
100 |
+
if "Error" in status:
|
101 |
+
return None, None, None, status, None, None
|
102 |
+
|
103 |
+
progress_updates.append("✅ Análisis biotecnológico completado")
|
104 |
+
|
105 |
+
# Paso 2: Descargar resultados como CSV
|
106 |
+
progress_updates.append("📥 Descargando resultados...")
|
107 |
+
csv_file = download_results_as_csv(df_data)
|
108 |
+
|
109 |
+
if not csv_file:
|
110 |
+
return plot, df_data, None, "Error al descargar resultados", None, status
|
111 |
+
|
112 |
+
# Paso 3: Generar análisis con Claude
|
113 |
+
progress_updates.append(f"🤖 Generando análisis con {claude_model}...")
|
114 |
+
analysis, code = generate_claude_report(
|
115 |
+
csv_file, claude_model, detail_level, language, additional_specs
|
116 |
+
)
|
117 |
+
|
118 |
+
progress_updates.append("✅ Análisis con Claude completado")
|
119 |
+
|
120 |
+
# Paso 4: Exportar informe
|
121 |
+
progress_updates.append(f"📄 Exportando informe en formato {export_format}...")
|
122 |
+
report_file, export_status = export_report(export_format, language, analysis, code)
|
123 |
+
|
124 |
+
final_status = "\n".join(progress_updates) + f"\n\n{export_status}"
|
125 |
+
|
126 |
+
return plot, df_data, analysis, code, report_file, final_status
|
127 |
|
128 |
+
# Interfaz de Gradio
|
129 |
+
with gr.Blocks(theme=theme, title="🧬 BioTech Analysis & Report Generator") as demo:
|
130 |
+
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
"""
|
132 |
+
# 🧬 BioTech Analysis & Report Generator
|
133 |
|
134 |
+
### Pipeline completo de análisis biotecnológico con IA
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
+
Este sistema combina análisis avanzado de datos biotecnológicos con generación de informes mediante Claude 3.5.
|
137 |
+
"""
|
138 |
+
)
|
139 |
+
|
140 |
+
with gr.Row():
|
141 |
+
with gr.Column(scale=1):
|
142 |
+
gr.Markdown("## 📊 Configuración del Análisis")
|
143 |
+
|
144 |
+
# Inputs para BiotechU4
|
145 |
+
file_input = gr.File(
|
146 |
+
label="📁 Archivo de datos (CSV/Excel)",
|
147 |
+
file_types=[".csv", ".xlsx", ".xls"],
|
148 |
+
elem_classes="file-input"
|
149 |
+
)
|
150 |
+
|
151 |
+
with gr.Group():
|
152 |
+
gr.Markdown("### 🔬 Parámetros de Análisis")
|
153 |
|
154 |
+
models_input = gr.CheckboxGroup(
|
155 |
+
choices=['logistic', 'gompertz', 'moser', 'baranyi', 'monod',
|
156 |
+
'contois', 'andrews', 'tessier', 'richards', 'stannard', 'huang'],
|
157 |
+
value=['logistic', 'gompertz', 'moser', 'baranyi'],
|
158 |
+
label="📊 Modelos a probar",
|
159 |
+
elem_classes="models-input"
|
160 |
)
|
161 |
|
162 |
+
component_input = gr.Dropdown(
|
163 |
+
choices=['all', 'biomass', 'substrate', 'product'],
|
164 |
+
value='all',
|
165 |
+
label="📈 Componente a visualizar"
|
166 |
+
)
|
167 |
+
|
168 |
+
exp_names_input = gr.Textbox(
|
169 |
+
label="🏷️ Nombres de experimentos",
|
170 |
+
placeholder="Experimento 1, Experimento 2...",
|
171 |
+
value="Análisis Biotecnológico"
|
172 |
+
)
|
173 |
+
|
174 |
+
with gr.Row():
|
175 |
+
use_de_input = gr.Checkbox(
|
176 |
+
label="🧮 Usar Evolución Diferencial",
|
|
|
177 |
value=False
|
178 |
)
|
179 |
|
180 |
+
maxfev_input = gr.Number(
|
181 |
+
label="🔄 Iteraciones máximas",
|
182 |
value=50000,
|
183 |
+
minimum=1000,
|
184 |
+
maximum=100000,
|
185 |
+
step=1000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
)
|
187 |
+
|
188 |
+
with gr.Group():
|
189 |
+
gr.Markdown("### 🤖 Configuración de Claude")
|
190 |
|
191 |
+
claude_model_input = gr.Dropdown(
|
192 |
+
choices=[
|
193 |
+
'claude-3-7-sonnet-20250219',
|
194 |
+
'claude-3-5-sonnet-20241022',
|
195 |
+
'claude-3-5-haiku-20241022',
|
196 |
+
'claude-sonnet-4-20250514',
|
197 |
+
'claude-opus-4-20250514'
|
198 |
+
],
|
199 |
+
value='claude-3-7-sonnet-20250219',
|
200 |
+
label="🤖 Modelo de Claude"
|
201 |
)
|
202 |
|
203 |
+
detail_level_input = gr.Radio(
|
204 |
+
choices=['detailed', 'summarized'],
|
205 |
+
value='detailed',
|
206 |
+
label="📋 Nivel de detalle del análisis"
|
207 |
)
|
|
|
|
|
|
|
208 |
|
209 |
+
language_input = gr.Dropdown(
|
210 |
+
choices=['en', 'es', 'fr', 'de', 'pt'],
|
211 |
+
value='es',
|
212 |
+
label="🌐 Idioma del informe"
|
213 |
)
|
214 |
|
215 |
+
additional_specs_input = gr.Textbox(
|
216 |
+
label="📝 Especificaciones adicionales",
|
217 |
+
placeholder="Añade contexto o requisitos específicos para el análisis...",
|
218 |
+
lines=3
|
219 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
|
221 |
+
export_format_input = gr.Radio(
|
222 |
+
choices=['PDF', 'DOCX'],
|
223 |
+
value='PDF',
|
224 |
+
label="📄 Formato de exportación"
|
225 |
)
|
226 |
+
|
227 |
+
process_btn = gr.Button(
|
228 |
+
"🚀 Ejecutar Pipeline Completo",
|
229 |
+
variant="primary",
|
230 |
+
size="lg"
|
231 |
+
)
|
232 |
|
233 |
+
with gr.Column(scale=2):
|
234 |
+
gr.Markdown("## 📈 Resultados")
|
235 |
+
|
236 |
+
with gr.Tabs():
|
237 |
+
with gr.TabItem("📊 Visualización"):
|
238 |
+
plot_output = gr.Plot(label="Gráfico interactivo")
|
239 |
+
|
240 |
+
with gr.TabItem("📋 Tabla de Resultados"):
|
241 |
+
table_output = gr.Dataframe(
|
242 |
+
label="Resultados del ajuste",
|
243 |
+
interactive=False
|
244 |
+
)
|
245 |
+
|
246 |
+
with gr.TabItem("📝 Análisis de Claude"):
|
247 |
+
analysis_output = gr.Markdown(label="Análisis comparativo")
|
248 |
+
|
249 |
+
with gr.TabItem("💻 Código"):
|
250 |
+
code_output = gr.Code(
|
251 |
+
label="Código de implementación",
|
252 |
+
language="python"
|
253 |
+
)
|
|
|
254 |
|
255 |
+
with gr.Row():
|
256 |
+
status_output = gr.Textbox(
|
257 |
+
label="📊 Estado del proceso",
|
258 |
+
lines=6,
|
259 |
+
interactive=False
|
260 |
+
)
|
261 |
|
262 |
+
with gr.Row():
|
263 |
+
report_output = gr.File(
|
264 |
+
label="📥 Descargar informe",
|
265 |
+
interactive=False
|
266 |
+
)
|
267 |
+
|
268 |
+
# Conectar la función principal
|
269 |
+
process_btn.click(
|
270 |
+
fn=process_complete_pipeline,
|
271 |
+
inputs=[
|
272 |
+
file_input,
|
273 |
+
models_input,
|
274 |
+
component_input,
|
275 |
+
use_de_input,
|
276 |
+
maxfev_input,
|
277 |
+
exp_names_input,
|
278 |
+
claude_model_input,
|
279 |
+
detail_level_input,
|
280 |
+
language_input,
|
281 |
+
additional_specs_input,
|
282 |
+
export_format_input
|
283 |
+
],
|
284 |
+
outputs=[
|
285 |
+
plot_output,
|
286 |
+
table_output,
|
287 |
+
analysis_output,
|
288 |
+
code_output,
|
289 |
+
report_output,
|
290 |
+
status_output
|
291 |
+
]
|
292 |
+
)
|
293 |
|
294 |
+
# Ejemplos
|
295 |
+
gr.Examples(
|
296 |
+
examples=[
|
297 |
+
[
|
298 |
+
"example_data.csv",
|
299 |
+
['logistic', 'gompertz'],
|
300 |
+
'all',
|
301 |
+
False,
|
302 |
+
50000,
|
303 |
+
"Crecimiento bacteriano",
|
304 |
+
'claude-3-7-sonnet-20250219',
|
305 |
+
'detailed',
|
306 |
+
'es',
|
307 |
+
"Analizar el crecimiento bacteriano en diferentes condiciones de temperatura",
|
308 |
+
'PDF'
|
309 |
+
]
|
310 |
+
],
|
311 |
+
inputs=[
|
312 |
+
file_input,
|
313 |
+
models_input,
|
314 |
+
component_input,
|
315 |
+
use_de_input,
|
316 |
+
maxfev_input,
|
317 |
+
exp_names_input,
|
318 |
+
claude_model_input,
|
319 |
+
detail_level_input,
|
320 |
+
language_input,
|
321 |
+
additional_specs_input,
|
322 |
+
export_format_input
|
323 |
+
]
|
324 |
+
)
|
325 |
+
|
326 |
+
gr.Markdown(
|
327 |
+
"""
|
328 |
+
---
|
329 |
+
### 📚 Instrucciones de uso:
|
330 |
+
|
331 |
+
1. **Sube tu archivo de datos** en formato CSV o Excel
|
332 |
+
2. **Selecciona los modelos** que deseas probar para el ajuste
|
333 |
+
3. **Configura los parámetros** de análisis según tus necesidades
|
334 |
+
4. **Elige el modelo de Claude** para generar el informe
|
335 |
+
5. **Especifica el idioma y formato** de exportación deseado
|
336 |
+
6. **Haz clic en "Ejecutar Pipeline Completo"** y espera los resultados
|
337 |
+
|
338 |
+
El sistema procesará tus datos, realizará el ajuste de modelos, generará un análisis
|
339 |
+
detallado con IA y producirá un informe profesional descargable.
|
340 |
+
"""
|
341 |
+
)
|
342 |
|
|
|
343 |
if __name__ == "__main__":
|
344 |
+
demo.launch(
|
|
|
|
|
|
|
345 |
share=True,
|
346 |
+
show_error=True,
|
347 |
+
favicon_path="🧬"
|
348 |
)
|