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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# --- INSTALACIÓN DE DEPENDENCIAS ADICIONALES ---
import os
import sys
import subprocess

os.system("pip install --upgrade gradio")

import gradio as gr
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from gradio_client import Client, handle_file
import tempfile
import os
import asyncio
import json
from datetime import datetime
import logging

# Configurar logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class BiotechAnalysisAgent:
    def __init__(self):
        self.biotech_client = Client("C2MV/BiotechU4")
        self.analysis_client = Client("C2MV/Project-HF-2025")
        self.results_cache = {}
        
    async def process_biotech_data(self, file_path, models, component, use_de, maxfev, exp_names, theme):
        """Procesa los datos biotecnológicos usando el primer endpoint"""
        try:
            logger.info(f"Procesando archivo: {file_path}")
            
            result = self.biotech_client.predict(
                file=handle_file(file_path),
                models=models,
                component=component,
                use_de=use_de,
                maxfev=maxfev,
                exp_names=exp_names,
                theme=theme,
                api_name="/run_analysis_wrapper"
            )
            
            # Extraer resultados
            plot_data, table_data, status = result
            
            # Guardar en caché
            self.results_cache['biotech_results'] = {
                'plot': plot_data,
                'table': table_data,
                'status': status,
                'timestamp': datetime.now()
            }
            
            return plot_data, table_data, status
            
        except Exception as e:
            logger.error(f"Error en análisis biotecnológico: {str(e)}")
            return None, None, f"Error: {str(e)}"
    
    async def generate_csv_from_results(self, table_data):
        """Convierte los resultados de la tabla en un archivo CSV temporal"""
        try:
            if not table_data or 'data' not in table_data:
                return None, "No hay datos para convertir"
            
            # Crear DataFrame
            df = pd.DataFrame(
                data=table_data['data'],
                columns=table_data.get('headers', [])
            )
            
            # Guardar como CSV temporal
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.csv', mode='w')
            df.to_csv(temp_file.name, index=False)
            temp_file.close()
            
            return temp_file.name, "CSV generado exitosamente"
            
        except Exception as e:
            logger.error(f"Error generando CSV: {str(e)}")
            return None, f"Error generando CSV: {str(e)}"
    
    async def generate_analysis_report(self, csv_file_path, model, detail, language, additional_specs):
        """Genera el reporte de análisis usando el segundo endpoint"""
        try:
            if not csv_file_path or not os.path.exists(csv_file_path):
                return "Error: No se encontró el archivo CSV", ""
            
            logger.info(f"Generando reporte con archivo: {csv_file_path}")
            
            result = self.analysis_client.predict(
                files=[handle_file(csv_file_path)],
                model=model,
                detail=detail,
                language=language,
                additional_specs=additional_specs,
                api_name="/process_and_store"
            )
            
            analysis_markdown, implementation_code = result
            
            # Limpiar archivo temporal
            try:
                os.unlink(csv_file_path)
            except:
                pass
            
            return analysis_markdown, implementation_code
            
        except Exception as e:
            logger.error(f"Error generando reporte: {str(e)}")
            return f"Error generando reporte: {str(e)}", ""
    
    async def export_report(self, format_type, language):
        """Exporta el reporte en el formato especificado"""
        try:
            result = self.analysis_client.predict(
                format=format_type,
                language=language,
                api_name="/handle_export"
            )
            
            status, file_path = result
            return status, file_path
            
        except Exception as e:
            logger.error(f"Error exportando: {str(e)}")
            return f"Error exportando: {str(e)}", None

# Inicializar el agente
agent = BiotechAnalysisAgent()

def create_sample_plot():
    """Crea un gráfico de ejemplo"""
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Ejemplo'))
    fig.update_layout(
        title="Gráfico de Ejemplo - Carga tus datos para ver resultados reales",
        xaxis_title="Tiempo",
        yaxis_title="Valor",
        template="plotly_white"
    )
    return fig

async def process_complete_analysis(
    file, models, component, use_de, maxfev, exp_names, 
    claude_model, detail_level, language, additional_specs, theme
):
    """Función principal que ejecuta todo el pipeline"""
    
    if file is None:
        return (
            create_sample_plot(),
            pd.DataFrame({"Status": ["Por favor, carga un archivo para comenzar"]}),
            "⚠️ Esperando archivo...",
            "📄 Carga un archivo Excel (.xlsx) para generar el análisis completo",
            "",
            None
        )
    
    try:
        # Paso 1: Análisis biotecnológico
        yield (
            create_sample_plot(),
            pd.DataFrame({"Status": ["Procesando análisis biotecnológico..."]}),
            "🔄 Paso 1/3: Analizando datos biotecnológicos...",
            "Procesando archivo con modelos seleccionados...",
            "",
            None
        )
        
        plot_data, table_data, status = await agent.process_biotech_data(
            file.name, models, component, use_de, maxfev, exp_names, theme
        )
        
        if table_data is None:
            yield (
                create_sample_plot(),
                pd.DataFrame({"Error": [status]}),
                f"❌ Error en análisis: {status}",
                "Error en el procesamiento de datos",
                "",
                None
            )
            return
        
        # Convertir datos de tabla para mostrar
        if table_data and 'data' in table_data:
            results_df = pd.DataFrame(
                data=table_data['data'],
                columns=table_data.get('headers', [])
            )
        else:
            results_df = pd.DataFrame({"Status": ["Datos procesados pero tabla vacía"]})
        
        # Paso 2: Generar CSV
        yield (
            create_sample_plot(),
            results_df,
            "🔄 Paso 2/3: Generando archivo CSV temporal...",
            "Convirtiendo resultados para análisis con IA...",
            "",
            None
        )
        
        csv_path, csv_status = await agent.generate_csv_from_results(table_data)
        
        if csv_path is None:
            yield (
                create_sample_plot(),
                results_df,
                f"❌ Error generando CSV: {csv_status}",
                "Error en la conversión de datos",
                "",
                None
            )
            return
        
        # Paso 3: Análisis con IA
        yield (
            create_sample_plot(),
            results_df,
            "🔄 Paso 3/3: Generando análisis con IA (Claude)...",
            "Analizando resultados y generando reporte inteligente...",
            "",
            None
        )
        
        analysis_report, implementation_code = await agent.generate_analysis_report(
            csv_path, claude_model, detail_level, language, additional_specs
        )
        
        # Paso 4: Exportar reporte
        export_status, export_file = await agent.export_report("PDF", language)
        
        # Resultado final
        yield (
            create_sample_plot(),
            results_df,
            "✅ Análisis completado exitosamente",
            analysis_report,
            implementation_code,
            export_file
        )
        
    except Exception as e:
        logger.error(f"Error en análisis completo: {str(e)}")
        yield (
            create_sample_plot(),
            pd.DataFrame({"Error": [str(e)]}),
            f"❌ Error general: {str(e)}",
            "Error en el procesamiento completo",
            "",
            None
        )

# Crear la interfaz
def create_interface():
    with gr.Blocks(
        theme=gr.themes.Soft(
            primary_hue="blue",
            secondary_hue="cyan",
            neutral_hue="slate"
        ),
        title="🧬 BioTech Analysis Suite - Análisis Inteligente de Datos Biotecnológicos",
        css="""
        .main-header {
            text-align: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 10px;
            margin-bottom: 2rem;
        }
        .step-indicator {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        .results-container {
            background: #ffffff;
            border-radius: 10px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        """
    ) as interface:
        
        gr.HTML("""
            <div class="main-header">
                <h1>🧬 BioTech Analysis Suite</h1>
                <p>Análisis Inteligente de Datos Biotecnológicos con IA</p>
                <p>Carga tu archivo Excel → Análisis automático → Reporte con Claude AI</p>
            </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("## 📁 Configuración de Análisis")
                
                file_input = gr.File(
                    label="📁 Sube tu archivo Excel (.xlsx)",
                    file_types=[".xlsx", ".xls"],
                    type="filepath"
                )
                
                with gr.Accordion("⚙️ Configuración del Modelo", open=True):
                    models = gr.CheckboxGroup(
                        choices=["logistic", "gompertz", "moser", "baranyi", "monod", "contois", "andrews", "tessier", "richards", "stannard", "huang"],
                        value=["logistic", "gompertz", "moser", "baranyi"],
                        label="📊 Modelos a Probar"
                    )
                    
                    component = gr.Dropdown(
                        choices=["all", "biomass", "substrate", "product"],
                        value="all",
                        label="📈 Componente a visualizar"
                    )
                    
                with gr.Accordion("🔧 Configuración Avanzada", open=False):
                    use_de = gr.Checkbox(
                        label="Usar Evolución Diferencial",
                        value=False
                    )
                    
                    maxfev = gr.Number(
                        label="Iteraciones máximas",
                        value=50000,
                        precision=0
                    )
                    
                    exp_names = gr.Textbox(
                        label="🏷️ Nombres de Experimentos",
                        value="Experimento_BioTech"
                    )
                
                with gr.Accordion("🤖 Configuración de IA", open=True):
                    claude_model = gr.Dropdown(
                        choices=[
                            "claude-3-5-sonnet-20241022",
                            "claude-3-5-haiku-20241022", 
                            "claude-3-7-sonnet-20250219"
                        ],
                        value="claude-3-5-sonnet-20241022",
                        label="🤖 Modelo Claude"
                    )
                    
                    detail_level = gr.Radio(
                        choices=["detailed", "summarized"],
                        value="detailed",
                        label="📋 Nivel de detalle del análisis"
                    )
                    
                    language = gr.Dropdown(
                        choices=["es", "en", "fr", "de", "pt"],
                        value="es",
                        label="🌐 Idioma del reporte"
                    )
                    
                    additional_specs = gr.Textbox(
                        label="📝 Especificaciones adicionales",
                        placeholder="Ej: Enfócate en la eficiencia de crecimiento y optimización de parámetros...",
                        lines=3
                    )
                
                theme = gr.Checkbox(
                    label="🌙 Modo Oscuro",
                    value=False
                )
                
                process_btn = gr.Button(
                    "🚀 Iniciar Análisis Completo",
                    variant="primary",
                    size="lg"
                )
            
            with gr.Column(scale=2):
                gr.Markdown("## 📊 Resultados del Análisis")
                
                status_box = gr.Textbox(
                    label="📋 Estado del Proceso",
                    value="⚠️ Esperando archivo...",
                    interactive=False
                )
                
                with gr.Tabs():
                    with gr.TabItem("📈 Visualización"):
                        plot_output = gr.Plot(
                            label="Gráfico de Resultados",
                            value=create_sample_plot()
                        )
                    
                    with gr.TabItem("📊 Datos"):
                        table_output = gr.Dataframe(
                            label="Tabla de Resultados",
                            value=pd.DataFrame({"Status": ["Carga un archivo para ver resultados"]})
                        )
                    
                    with gr.TabItem("🤖 Análisis IA"):
                        analysis_output = gr.Markdown(
                            label="Reporte de Análisis",
                            value="📄 El análisis con IA aparecerá aquí una vez procesados los datos..."
                        )
                    
                    with gr.TabItem("💻 Código"):
                        code_output = gr.Code(
                            label="Código de Implementación",
                            language="python",
                            value="# El código generado aparecerá aquí..."
                        )
                
                download_file = gr.File(
                    label="📥 Descargar Reporte PDF",
                    visible=True
                )
        
        # Conectar la función principal
        process_btn.click(
            fn=process_complete_analysis,
            inputs=[
                file_input, models, component, use_de, maxfev, exp_names,
                claude_model, detail_level, language, additional_specs, theme
            ],
            outputs=[
                plot_output, table_output, status_box,
                analysis_output, code_output, download_file
            ]
        )
        
        gr.Markdown("""
            ---
            ### 📋 Instrucciones de Uso:
            1. **Carga tu archivo**: Sube un archivo Excel (.xlsx) con tus datos biotecnológicos
            2. **Configura modelos**: Selecciona los modelos de crecimiento a probar
            3. **Configura IA**: Elige el modelo Claude y nivel de detalle para el análisis
            4. **Ejecuta**: Haz clic en "Iniciar Análisis Completo"
            5. **Revisa resultados**: Explora las pestañas de visualización, datos, análisis IA y código
            6. **Descarga**: Obtén tu reporte PDF completo
            
            ### 🔬 Modelos Disponibles:
            - **Logistic, Gompertz, Moser, Baranyi**: Modelos clásicos de crecimiento
            - **Monod, Contois, Andrews**: Modelos de cinética enzimática
            - **Tessier, Richards, Stannard, Huang**: Modelos especializados
            
            ### 🤖 Análisis con IA:
            - Interpretación automática de resultados
            - Recomendaciones de optimización
            - Código de implementación generado
            - Reportes en múltiples idiomas
        """)
    
    return interface

# Lanzar la aplicación
if __name__ == "__main__":
    interface = create_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True
    )