Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,230 +1,75 @@
|
|
| 1 |
-
# app.py
|
| 2 |
import sys
|
| 3 |
from pathlib import Path
|
| 4 |
import os
|
| 5 |
import subprocess
|
| 6 |
-
import
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# Set up the current directory in path
|
| 10 |
CURRENT_DIR = Path(__file__).parent
|
| 11 |
if str(CURRENT_DIR) not in sys.path:
|
| 12 |
sys.path.insert(0, str(CURRENT_DIR))
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
from io import BytesIO
|
| 25 |
-
from PIL import Image
|
| 26 |
-
|
| 27 |
-
# Create a simple plot
|
| 28 |
-
fig, ax = plt.subplots(figsize=(10, 6))
|
| 29 |
-
t = np.linspace(0, 10, 100)
|
| 30 |
-
ax.plot(t, np.exp(-t/3) * np.sin(t), label='Sample Data')
|
| 31 |
-
ax.set_xlabel('Time')
|
| 32 |
-
ax.set_ylabel('Value')
|
| 33 |
-
ax.legend()
|
| 34 |
-
ax.grid(True)
|
| 35 |
-
|
| 36 |
-
# Convert to PIL Image
|
| 37 |
-
buf = BytesIO()
|
| 38 |
-
plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
|
| 39 |
-
buf.seek(0)
|
| 40 |
-
img = Image.open(buf)
|
| 41 |
-
plt.close()
|
| 42 |
-
|
| 43 |
-
analysis_text = """
|
| 44 |
-
## An谩lisis del Modelo
|
| 45 |
-
|
| 46 |
-
Se ha procesado el modelo de bioproceso con los siguientes resultados:
|
| 47 |
-
|
| 48 |
-
- **Estado**: Procesamiento completado exitosamente
|
| 49 |
-
- **Par谩metros ajustados**: Los par谩metros se han optimizado
|
| 50 |
-
- **Calidad del ajuste**: R虏 > 0.95
|
| 51 |
-
|
| 52 |
-
### Recomendaciones:
|
| 53 |
-
1. Verificar la consistencia de los datos experimentales
|
| 54 |
-
2. Considerar validaci贸n cruzada del modelo
|
| 55 |
-
3. Evaluar la robustez de los par谩metros estimados
|
| 56 |
-
"""
|
| 57 |
-
|
| 58 |
-
return img, analysis_text
|
| 59 |
-
|
| 60 |
-
def create_interface():
|
| 61 |
-
"""
|
| 62 |
-
Create the complete user interface for bioprocess modeling.
|
| 63 |
-
"""
|
| 64 |
-
with gr.Blocks(theme='gradio/soft', title="Bioprocess Modeling") as demo:
|
| 65 |
-
gr.Markdown("# Modelado de Bioprocesos con Ecuaciones Personalizadas y An谩lisis por IA")
|
| 66 |
-
gr.Markdown(
|
| 67 |
-
"Sube un archivo Excel (columnas: 'Tiempo', 'Biomasa', 'Sustrato', 'Producto'). "
|
| 68 |
-
"Ingresa ecuaciones (usa 't' para tiempo; 'X_val' para X(t) en S/P), "
|
| 69 |
-
"par谩metros y l铆mites. El sistema ajustar谩 los modelos y un LLM analizar谩 los resultados."
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
with gr.Row():
|
| 73 |
-
with gr.Column(scale=2):
|
| 74 |
-
gr.Markdown("### 1. Carga de Datos y Configuraci贸n General del Gr谩fico")
|
| 75 |
-
file_input = gr.File(label="Subir archivo Excel (.xlsx)", file_types=[".xlsx"])
|
| 76 |
-
|
| 77 |
-
show_legend_ui = gr.Checkbox(label="Mostrar leyenda en gr谩ficos", value=True)
|
| 78 |
-
show_params_ui = gr.Checkbox(label="Mostrar par谩metros ajustados en gr谩ficos", value=True)
|
| 79 |
-
legend_position_ui = gr.Dropdown(
|
| 80 |
-
label="Posici贸n de la leyenda",
|
| 81 |
-
choices=['best', 'upper right', 'upper left', 'lower right', 'lower left', 'center left', 'center right', 'lower center', 'upper center', 'center'],
|
| 82 |
-
value='best'
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
with gr.Column(scale=1):
|
| 86 |
-
gr.Markdown("### 2. Conteo de Ecuaciones a Probar")
|
| 87 |
-
gr.Markdown("Define cu谩ntas ecuaciones diferentes probar para cada componente (1-3).")
|
| 88 |
-
biomass_eq_count_ui = gr.Number(label="Ecuaciones de Biomasa:", value=1, minimum=1, maximum=3, step=1)
|
| 89 |
-
substrate_eq_count_ui = gr.Number(label="Ecuaciones de Sustrato:", value=1, minimum=1, maximum=3, step=1)
|
| 90 |
-
product_eq_count_ui = gr.Number(label="Ecuaciones de Producto:", value=1, minimum=1, maximum=3, step=1)
|
| 91 |
-
|
| 92 |
-
# Biomass equations section
|
| 93 |
-
with gr.Accordion("3. Definici贸n de Modelos de Biomasa", open=True):
|
| 94 |
-
gr.Markdown("Ecuaci贸n (ej: `Xm*(1 - exp(-um*(t - t_lag)))`), Par谩metros (ej: `Xm, um, t_lag`), L铆mites (ej: `(0, np.inf), (0, 5), (0, 100)`).")
|
| 95 |
-
with gr.Row():
|
| 96 |
-
with gr.Column():
|
| 97 |
-
biomass_eq1_ui = gr.Textbox(label="Ecuaci贸n Biomasa 1", value="Xm * (1 - exp(-um * (t - t_lag)))", lines=2)
|
| 98 |
-
biomass_param1_ui = gr.Textbox(label="Par谩metros Biomasa 1", value="Xm, um, t_lag")
|
| 99 |
-
biomass_bound1_ui = gr.Textbox(label="L铆mites Biomasa 1", value="(0, np.inf), (0, np.inf), (0, np.inf)")
|
| 100 |
-
|
| 101 |
-
with gr.Column(visible=False) as biomass_col2_container:
|
| 102 |
-
biomass_eq2_ui = gr.Textbox(label="Ecuaci贸n Biomasa 2", value="", lines=2, placeholder="Opcional: X0 * exp(um * t)")
|
| 103 |
-
biomass_param2_ui = gr.Textbox(label="Par谩metros Biomasa 2", value="", placeholder="Opcional: X0, um")
|
| 104 |
-
biomass_bound2_ui = gr.Textbox(label="L铆mites Biomasa 2", value="", placeholder="Opcional: (0, np.inf), (0, np.inf)")
|
| 105 |
-
|
| 106 |
-
with gr.Column(visible=False) as biomass_col3_container:
|
| 107 |
-
biomass_eq3_ui = gr.Textbox(label="Ecuaci贸n Biomasa 3", lines=2, value="", placeholder="Opcional")
|
| 108 |
-
biomass_param3_ui = gr.Textbox(label="Par谩metros Biomasa 3", value="", placeholder="Opcional")
|
| 109 |
-
biomass_bound3_ui = gr.Textbox(label="L铆mites Biomasa 3", value="", placeholder="Opcional")
|
| 110 |
-
|
| 111 |
-
# Substrate equations section
|
| 112 |
-
with gr.Accordion("4. Definici贸n de Modelos de Sustrato", open=True):
|
| 113 |
-
gr.Markdown("Usa `X_val` para X(t) si es necesario. Ej: `S0 - (X_val / YXS)`.")
|
| 114 |
-
with gr.Row():
|
| 115 |
-
with gr.Column():
|
| 116 |
-
substrate_eq1_ui = gr.Textbox(label="Ecuaci贸n Sustrato 1", value="S0 - (X_val / YXS) - mS * t", lines=2)
|
| 117 |
-
substrate_param1_ui = gr.Textbox(label="Par谩metros Sustrato 1", value="S0, YXS, mS")
|
| 118 |
-
substrate_bound1_ui = gr.Textbox(label="L铆mites Sustrato 1", value="(0, np.inf), (1e-9, np.inf), (0, np.inf)")
|
| 119 |
-
|
| 120 |
-
with gr.Column(visible=False) as substrate_col2_container:
|
| 121 |
-
substrate_eq2_ui = gr.Textbox(label="Ecuaci贸n Sustrato 2", lines=2, value="", placeholder="Opcional")
|
| 122 |
-
substrate_param2_ui = gr.Textbox(label="Par谩metros Sustrato 2", value="", placeholder="Opcional")
|
| 123 |
-
substrate_bound2_ui = gr.Textbox(label="L铆mites Sustrato 2", value="", placeholder="Opcional")
|
| 124 |
-
|
| 125 |
-
with gr.Column(visible=False) as substrate_col3_container:
|
| 126 |
-
substrate_eq3_ui = gr.Textbox(label="Ecuaci贸n Sustrato 3", lines=2, value="", placeholder="Opcional")
|
| 127 |
-
substrate_param3_ui = gr.Textbox(label="Par谩metros Sustrato 3", value="", placeholder="Opcional")
|
| 128 |
-
substrate_bound3_ui = gr.Textbox(label="L铆mites Sustrato 3", value="", placeholder="Opcional")
|
| 129 |
|
| 130 |
-
# Product equations section
|
| 131 |
-
with gr.Accordion("5. Definici贸n de Modelos de Producto", open=True):
|
| 132 |
-
gr.Markdown("Usa `X_val` para X(t) si es necesario. Ej: `P0 + YPX * X_val`.")
|
| 133 |
-
with gr.Row():
|
| 134 |
-
with gr.Column():
|
| 135 |
-
product_eq1_ui = gr.Textbox(label="Ecuaci贸n Producto 1", value="P0 + YPX * X_val + mP * t", lines=2)
|
| 136 |
-
product_param1_ui = gr.Textbox(label="Par谩metros Producto 1", value="P0, YPX, mP")
|
| 137 |
-
product_bound1_ui = gr.Textbox(label="L铆mites Producto 1", value="(0, np.inf), (0, np.inf), (0, np.inf)")
|
| 138 |
-
|
| 139 |
-
with gr.Column(visible=False) as product_col2_container:
|
| 140 |
-
product_eq2_ui = gr.Textbox(label="Ecuaci贸n Producto 2", lines=2, value="", placeholder="Opcional")
|
| 141 |
-
product_param2_ui = gr.Textbox(label="Par谩metros Producto 2", value="", placeholder="Opcional")
|
| 142 |
-
product_bound2_ui = gr.Textbox(label="L铆mites Producto 2", value="", placeholder="Opcional")
|
| 143 |
-
|
| 144 |
-
with gr.Column(visible=False) as product_col3_container:
|
| 145 |
-
product_eq3_ui = gr.Textbox(label="Ecuaci贸n Producto 3", lines=2, value="", placeholder="Opcional")
|
| 146 |
-
product_param3_ui = gr.Textbox(label="Par谩metros Producto 3", value="", placeholder="Opcional")
|
| 147 |
-
product_bound3_ui = gr.Textbox(label="L铆mites Producto 3", value="", placeholder="Opcional")
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
fn=update_eq_visibility,
|
| 160 |
-
inputs=[biomass_eq_count_ui],
|
| 161 |
-
outputs=[biomass_col2_container, biomass_col3_container]
|
| 162 |
-
)
|
| 163 |
-
substrate_eq_count_ui.change(
|
| 164 |
-
fn=update_eq_visibility,
|
| 165 |
-
inputs=[substrate_eq_count_ui],
|
| 166 |
-
outputs=[substrate_col2_container, substrate_col3_container]
|
| 167 |
-
)
|
| 168 |
-
product_eq_count_ui.change(
|
| 169 |
-
fn=update_eq_visibility,
|
| 170 |
-
inputs=[product_eq_count_ui],
|
| 171 |
-
outputs=[product_col2_container, product_col3_container]
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
submit_button = gr.Button("Procesar y Analizar Modelos", variant="primary", size="lg")
|
| 175 |
-
|
| 176 |
-
gr.Markdown("## Resultados del An谩lisis y Modelado")
|
| 177 |
-
with gr.Row():
|
| 178 |
-
image_output = gr.Image(label="Gr谩fico Generado de Ajustes", height=400, show_download_button=True)
|
| 179 |
-
with gr.Column():
|
| 180 |
-
analysis_output = gr.Markdown(label="An谩lisis del Modelo por IA", value="Esperando procesamiento...")
|
| 181 |
-
|
| 182 |
-
# Collect all inputs
|
| 183 |
-
all_inputs = [
|
| 184 |
-
file_input,
|
| 185 |
-
biomass_eq1_ui, biomass_eq2_ui, biomass_eq3_ui,
|
| 186 |
-
biomass_param1_ui, biomass_param2_ui, biomass_param3_ui,
|
| 187 |
-
biomass_bound1_ui, biomass_bound2_ui, biomass_bound3_ui,
|
| 188 |
-
substrate_eq1_ui, substrate_eq2_ui, substrate_eq3_ui,
|
| 189 |
-
substrate_param1_ui, substrate_param2_ui, substrate_param3_ui,
|
| 190 |
-
substrate_bound1_ui, substrate_bound2_ui, substrate_bound3_ui,
|
| 191 |
-
product_eq1_ui, product_eq2_ui, product_eq3_ui,
|
| 192 |
-
product_param1_ui, product_param2_ui, product_param3_ui,
|
| 193 |
-
product_bound1_ui, product_bound2_ui, product_bound3_ui,
|
| 194 |
-
legend_position_ui,
|
| 195 |
-
show_legend_ui,
|
| 196 |
-
show_params_ui,
|
| 197 |
-
biomass_eq_count_ui,
|
| 198 |
-
substrate_eq_count_ui,
|
| 199 |
-
product_eq_count_ui
|
| 200 |
-
]
|
| 201 |
-
|
| 202 |
-
# Button click handler
|
| 203 |
-
submit_button.click(
|
| 204 |
-
fn=process_and_plot,
|
| 205 |
-
inputs=all_inputs,
|
| 206 |
-
outputs=[image_output, analysis_output]
|
| 207 |
-
)
|
| 208 |
|
| 209 |
-
return demo
|
| 210 |
|
| 211 |
def main():
|
| 212 |
-
"
|
| 213 |
-
|
| 214 |
-
|
| 215 |
|
| 216 |
-
print("
|
| 217 |
try:
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
share=
|
| 222 |
-
debug=True
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
demo.launch(
|
|
|
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
| 230 |
main()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
import sys
|
| 3 |
from pathlib import Path
|
| 4 |
import os
|
| 5 |
import subprocess
|
| 6 |
+
# import pkg_resources # Comentado o eliminado, ya que dio info enga帽osa
|
| 7 |
+
|
| 8 |
+
# --- CR脥TICO: L脥NEA PARA FORZAR LA VERSI脫N DE GRADIO Y GRADIO-CLIENT CORRECTA ---
|
| 9 |
+
print("INFO (app.py): Intentando forzar la instalaci贸n de Gradio 4.29.0 y su cliente compatible...")
|
| 10 |
+
GRADIO_TARGET_VERSION = "4.29.0"
|
| 11 |
+
GRADIO_CLIENT_TARGET_VERSION = "0.16.1" # Cliente para Gradio 4.29.0
|
| 12 |
+
try:
|
| 13 |
+
# Desinstalar cualquier versi贸n existente de gradio y gradio_client
|
| 14 |
+
# Redirigir stdout/stderr a DEVNULL para una salida m谩s limpia si tienen 茅xito
|
| 15 |
+
subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "-y", "gradio", "gradio-client"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 16 |
+
print(f"INFO (app.py): Intentando instalar gradio=={GRADIO_TARGET_VERSION} y gradio-client=={GRADIO_CLIENT_TARGET_VERSION}...")
|
| 17 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", f"gradio=={GRADIO_TARGET_VERSION}", f"gradio-client=={GRADIO_CLIENT_TARGET_VERSION}"])
|
| 18 |
+
print(f"INFO (app.py): Instalaci贸n forzada de Gradio {GRADIO_TARGET_VERSION} y Gradio-Client {GRADIO_CLIENT_TARGET_VERSION} solicitada.")
|
| 19 |
+
|
| 20 |
+
except subprocess.CalledProcessError as e:
|
| 21 |
+
print(f"ERROR (app.py): Fallo al forzar la instalaci贸n de Gradio: {e}")
|
| 22 |
+
print("Por favor, aseg煤rate de que no hay otras dependencias conflictivas y reintenta despu茅s de una limpieza profunda del entorno.")
|
| 23 |
+
# Considera no salir si el error es solo por "ya desinstalado"
|
| 24 |
+
# sys.exit(1)
|
| 25 |
+
# --- FIN DE L脥NEA CR脥TICA ---
|
| 26 |
|
|
|
|
| 27 |
CURRENT_DIR = Path(__file__).parent
|
| 28 |
if str(CURRENT_DIR) not in sys.path:
|
| 29 |
sys.path.insert(0, str(CURRENT_DIR))
|
| 30 |
|
| 31 |
+
try:
|
| 32 |
+
import decorators
|
| 33 |
+
# Usa tu UI.py COMPLEJA ahora si la UI simplificada funcion贸.
|
| 34 |
+
# Si la UI simplificada es la que est谩 en uso, este import es correcto.
|
| 35 |
+
from UI import create_interface
|
| 36 |
+
import interface as app_interface_module
|
| 37 |
+
except ImportError as e:
|
| 38 |
+
print(f"Error cr铆tico de importaci贸n en app.py: {e}. Aseg煤rate de que todos los archivos .py est茅n en el mismo directorio o en PYTHONPATH.")
|
| 39 |
+
print(f"sys.path actual: {sys.path}")
|
| 40 |
+
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
# La l贸gica del decorador dummy puede permanecer, es inofensiva
|
| 44 |
+
if decorators.was_real_spaces_gpu_imported():
|
| 45 |
+
print("INFO (app.py): El decorador GPU de 'spaces' parece estar disponible.")
|
| 46 |
+
print("INFO (app.py): Se definir谩 una funci贸n dummy decorada para satisfacer el chequeo de Gradio si es necesario.")
|
| 47 |
+
|
| 48 |
+
@decorators.gpu_decorator(duration=1)
|
| 49 |
+
def _app_py_dummy_gpu_function_for_gradio_startup():
|
| 50 |
+
pass
|
| 51 |
+
else:
|
| 52 |
+
print("INFO (app.py): El decorador GPU real de 'spaces' no fue importado. No se necesita funci贸n dummy para GPU.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
|
|
|
| 54 |
|
| 55 |
def main():
|
| 56 |
+
print("INFO (app.py): Creando la interfaz Gradio...")
|
| 57 |
+
# Aseg煤rate de que UI.py contiene tu interfaz completa ahora, o la simplificada si a煤n est谩s depurando.
|
| 58 |
+
demo_instance = create_interface(process_function_for_button=app_interface_module.process_and_plot)
|
| 59 |
|
| 60 |
+
print("INFO (app.py): Lanzando la interfaz Gradio localmente...")
|
| 61 |
try:
|
| 62 |
+
demo_instance.launch(debug=True)
|
| 63 |
+
except ValueError as ve:
|
| 64 |
+
if "shareable link must be created" in str(ve).lower() or "localhost is not accessible" in str(ve).lower():
|
| 65 |
+
print("ADVERTENCIA (app.py): Fall贸 el lanzamiento local directo, intentando con share=True...")
|
| 66 |
+
demo_instance.launch(share=True, debug=True)
|
| 67 |
+
else:
|
| 68 |
+
print(f"Error inesperado de ValueError durante launch(): {ve}")
|
| 69 |
+
raise ve
|
| 70 |
+
except Exception as e_launch:
|
| 71 |
+
print(f"Error inesperado durante demo.launch(): {e_launch}")
|
| 72 |
+
raise e_launch
|
| 73 |
|
| 74 |
if __name__ == "__main__":
|
| 75 |
main()
|