Spaces:
Sleeping
Sleeping
| # -*- coding: utf-8 -*- | |
| """Untitled0.ipynb | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1lA4vvx9sbWFfjQHAmGs8ADgwhNOypfsM | |
| """ | |
| import pandas as pd | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| import io | |
| import base64 | |
| from datetime import datetime | |
| from sklearn.ensemble import RandomForestRegressor | |
| from sklearn.metrics import r2_score, mean_squared_error | |
| import tempfile | |
| print("🚀 Iniciando GeoPredict en Hugging Face...") | |
| # ============================================================================== | |
| # BLOQUE 1: ENTRENAMIENTO DEL MODELO (se ejecuta al iniciar) | |
| # ============================================================================== | |
| print("📂 Cargando y entrenando modelos...") | |
| # Cargar datos | |
| df = pd.read_excel('base_datos.xlsx') | |
| # Limpieza robusta | |
| df['N60'] = pd.to_numeric(df['N60'], errors='coerce') | |
| df['φ_grados'] = pd.to_numeric(df['φ_grados'], errors='coerce') | |
| df['Densidad_relativa'] = df['Densidad_relativa'].astype(str).str.replace(r'[-%]', '', regex=True) | |
| df['Densidad_relativa'] = pd.to_numeric(df['Densidad_relativa'], errors='coerce') | |
| df['Cu/Su (KPa)'] = pd.to_numeric(df['Cu/Su (KPa)'], errors='coerce') | |
| df = df.dropna(subset=['MATERIAL', 'N60'], how='all') | |
| # Configuración de modelos | |
| config = [ | |
| ('ARENA', 'φ_grados', 'Ángulo de fricción (φ)', 'grados'), | |
| ('GRAVA', 'φ_grados', 'Ángulo de fricción (φ)', 'grados'), | |
| ('ARCILLA', 'Cu/Su (KPa)', 'Resistencia no drenada (Cu/Su)', 'kPa'), | |
| ('ARENA', 'Densidad_relativa', 'Densidad relativa (Dr)', 'decimal'), | |
| ('GRAVA', 'Densidad_relativa', 'Densidad relativa (Dr)', 'decimal') | |
| ] | |
| modelos_rf = {} | |
| for material, col_y, nombre_prop, unidad in config: | |
| print(f"🧠 Entrenando: {material} → {nombre_prop}") | |
| df_mat = df[df['MATERIAL'] == material].copy() | |
| X = df_mat[['N60']] | |
| y = df_mat[col_y] | |
| mask = y.notnull() | |
| X, y = X[mask], y[mask] | |
| if len(X) < 5: | |
| print(f" ⚠️ Pocos datos. Saltando...") | |
| continue | |
| # Entrenar Random Forest | |
| model = RandomForestRegressor(n_estimators=100, random_state=42) | |
| model.fit(X, y) | |
| # Evaluar | |
| y_pred = model.predict(X) | |
| r2 = r2_score(y, y_pred) | |
| rmse = np.sqrt(mean_squared_error(y, y_pred)) | |
| # Guardar modelo | |
| clave = f"{material}_{col_y}" | |
| modelos_rf[clave] = { | |
| 'modelo': model, | |
| 'R2': r2, | |
| 'RMSE': rmse, | |
| 'unidad': unidad, | |
| 'propiedad': nombre_prop, | |
| 'X_train': X.values.flatten(), | |
| 'y_train': y.values.flatten() | |
| } | |
| print("✅ Modelos entrenados correctamente") | |
| # ============================================================================== | |
| # BLOQUE 2: CONFIGURACIÓN Y FUNCIONES PARA GRADIO | |
| # ============================================================================== | |
| # Configuración profesional de matplotlib | |
| plt.rcParams['font.size'] = 12 | |
| plt.rcParams['axes.grid'] = True | |
| plt.rcParams['grid.alpha'] = 0.3 | |
| # RANGOS por material | |
| RANGOS_MATERIAL = { | |
| 'ARENA': {'min': 1, 'max': 60, 'defecto': 25, 'rango_real': "1-60"}, | |
| 'GRAVA': {'min': 5, 'max': 100, 'defecto': 40, 'rango_real': "5-100"}, | |
| 'ARCILLA': {'min': 5, 'max': 30, 'defecto': 15, 'rango_real': "5-30"} | |
| } | |
| def predecir_propiedades_completo(material, n60, nombre_ing, ubicacion, proyecto): | |
| """Función completa para predicciones profesionales""" | |
| try: | |
| # Validar rango | |
| rango = RANGOS_MATERIAL[material] | |
| if n60 < rango['min'] or n60 > rango['max']: | |
| raise ValueError(f"N60 = {n60} fuera del rango válido para {material} ({rango['min']}-{rango['max']})") | |
| predicciones = {} | |
| graficas_base64 = [] | |
| detalles_modelo = [] | |
| if material in ['ARENA', 'GRAVA']: | |
| # Predicción para φ | |
| clave_phi = f"{material}_φ_grados" | |
| if clave_phi in modelos_rf: | |
| info = modelos_rf[clave_phi] | |
| phi_pred = info['modelo'].predict([[n60]])[0] | |
| predicciones['Ángulo de Fricción (φ)'] = { | |
| 'valor': f"{phi_pred:.1f}°", | |
| 'valor_num': phi_pred, | |
| 'r2': info['R2'], | |
| 'rmse': info['RMSE'] | |
| } | |
| # Gráfica para φ | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| sample_size = min(50, len(info['X_train'])) | |
| sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False) | |
| X_sample = info['X_train'][sample_indices] | |
| y_sample = info['y_train'][sample_indices] | |
| ax.scatter(X_sample, y_sample, alpha=0.7, color='steelblue', s=60, | |
| label='Datos de Campo', edgecolors='white', linewidth=0.5) | |
| N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1) | |
| y_plot = info['modelo'].predict(N60_plot) | |
| ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest') | |
| ax.scatter([n60], [phi_pred], color='red', s=150, zorder=5, | |
| marker='*', label=f'Predicción: {phi_pred:.1f}°') | |
| ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5) | |
| ax.axhline(y=phi_pred, color='red', linestyle='--', alpha=0.5) | |
| ax.set_title(f'{material}: Ángulo de Fricción (φ)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.2f}', | |
| fontsize=14, fontweight='bold') | |
| ax.set_xlabel('N60 (SPT)', fontsize=12) | |
| ax.set_ylabel('φ (grados)', fontsize=12) | |
| ax.legend() | |
| ax.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') | |
| buf.seek(0) | |
| graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8')) | |
| plt.close() | |
| # Predicción para Dr | |
| clave_dr = f"{material}_Densidad_relativa" | |
| if clave_dr in modelos_rf: | |
| info = modelos_rf[clave_dr] | |
| dr_pred = info['modelo'].predict([[n60]])[0] * 100 | |
| predicciones['Densidad Relativa (Dr)'] = { | |
| 'valor': f"{dr_pred:.1f}%", | |
| 'valor_num': dr_pred, | |
| 'r2': info['R2'], | |
| 'rmse': info['RMSE'] | |
| } | |
| # Gráfica para Dr | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| sample_size = min(50, len(info['X_train'])) | |
| sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False) | |
| X_sample = info['X_train'][sample_indices] | |
| y_sample = info['y_train'][sample_indices] * 100 | |
| ax.scatter(X_sample, y_sample, alpha=0.7, color='green', s=60, | |
| label='Datos de Campo', edgecolors='white', linewidth=0.5) | |
| N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1) | |
| y_plot = info['modelo'].predict(N60_plot) * 100 | |
| ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest') | |
| ax.scatter([n60], [dr_pred], color='red', s=150, zorder=5, | |
| marker='*', label=f'Predicción: {dr_pred:.1f}%') | |
| ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5) | |
| ax.axhline(y=dr_pred, color='red', linestyle='--', alpha=0.5) | |
| ax.set_title(f'{material}: Densidad Relativa (Dr)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.3f}', | |
| fontsize=14, fontweight='bold') | |
| ax.set_xlabel('N60 (SPT)', fontsize=12) | |
| ax.set_ylabel('Dr (%)', fontsize=12) | |
| ax.legend() | |
| ax.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') | |
| buf.seek(0) | |
| graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8')) | |
| plt.close() | |
| elif material == 'ARCILLA': | |
| clave_cu = "ARCILLA_Cu/Su (KPa)" | |
| if clave_cu in modelos_rf: | |
| info = modelos_rf[clave_cu] | |
| cu_pred = info['modelo'].predict([[n60]])[0] | |
| predicciones['Resistencia No Drenada (Cu)'] = { | |
| 'valor': f"{cu_pred:.1f} kPa", | |
| 'valor_num': cu_pred, | |
| 'r2': info['R2'], | |
| 'rmse': info['RMSE'] | |
| } | |
| # Gráfica para Cu | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| sample_size = min(50, len(info['X_train'])) | |
| sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False) | |
| X_sample = info['X_train'][sample_indices] | |
| y_sample = info['y_train'][sample_indices] | |
| ax.scatter(X_sample, y_sample, alpha=0.7, color='coral', s=60, | |
| label='Datos de Campo', edgecolors='white', linewidth=0.5) | |
| N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1) | |
| y_plot = info['modelo'].predict(N60_plot) | |
| ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest') | |
| ax.scatter([n60], [cu_pred], color='red', s=150, zorder=5, | |
| marker='*', label=f'Predicción: {cu_pred:.1f} kPa') | |
| ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5) | |
| ax.axhline(y=cu_pred, color='red', linestyle='--', alpha=0.5) | |
| ax.set_title(f'Arcilla: Resistencia No Drenada (Cu)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.2f}', | |
| fontsize=14, fontweight='bold') | |
| ax.set_xlabel('N60 (SPT)', fontsize=12) | |
| ax.set_ylabel('Cu (kPa)', fontsize=12) | |
| ax.legend() | |
| ax.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') | |
| buf.seek(0) | |
| graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8')) | |
| plt.close() | |
| # Generar reporte HTML | |
| reporte_html = generar_reporte_completo(predicciones, graficas_base64, material, n60, nombre_ing, ubicacion, proyecto) | |
| # HTML para mostrar en la interfaz | |
| resultados_html = f""" | |
| <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;"> | |
| <h2 style="margin: 0; text-align: center;">🏗️ GeoPredict SPTro - Resultados</h2> | |
| <p style="text-align: center; margin: 5px 0 0 0; opacity: 0.9;"> | |
| {material} | N60 = {n60} | {datetime.now().strftime('%d/%m/%Y %H:%M')} | |
| </p> | |
| </div> | |
| <div style="background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px; | |
| border: 1px solid #ffeaa7; margin: 15px 0;"> | |
| <strong>📏 Rango del modelo:</strong> N60 = {rango['min']}-{rango['max']} | |
| </div> | |
| <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 15px 0;"> | |
| <h3 style="color: #2c3e50; margin-top: 0;">📊 Predicciones</h3> | |
| <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;"> | |
| """ | |
| for prop, data in predicciones.items(): | |
| resultados_html += f""" | |
| <div style="background: white; padding: 15px; border-radius: 8px; | |
| border-left: 4px solid #667eea; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"> | |
| <div style="font-weight: bold; color: #2c3e50; margin-bottom: 5px;">{prop}</div> | |
| <div style="font-size: 1.4em; font-weight: bold; color: #667eea;">{data['valor']}</div> | |
| <div style="font-size: 0.9em; color: #666; margin-top: 5px;">R² = {data['r2']:.3f}</div> | |
| </div> | |
| """ | |
| resultados_html += """ | |
| </div> | |
| </div> | |
| """ | |
| # Gráficas HTML | |
| graficas_html = "<div style='margin-top: 20px;'>" | |
| for img_base64 in graficas_base64: | |
| graficas_html += f""" | |
| <div style="background: white; padding: 15px; border-radius: 8px; margin: 15px 0; | |
| box-shadow: 0 2px 8px rgba(0,0,0,0.1);"> | |
| <img src="data:image/png;base64,{img_base64}" | |
| style="max-width: 100%; height: auto; border-radius: 5px;"> | |
| </div> | |
| """ | |
| graficas_html += "</div>" | |
| return resultados_html, graficas_html, reporte_html | |
| except Exception as e: | |
| error_html = f""" | |
| <div style="background: #f8d7da; color: #721c24; padding: 20px; border-radius: 8px; | |
| border: 1px solid #f5c6cb; margin: 20px 0;"> | |
| <h3 style="margin: 0 0 10px 0;">❌ Error en la predicción</h3> | |
| <p style="margin: 0;">{str(e)}</p> | |
| </div> | |
| """ | |
| return error_html, "", "" | |
| def generar_reporte_completo(predicciones, graficas_base64, material, n60, nombre_ing, ubicacion, proyecto): | |
| """Genera reporte HTML completo""" | |
| html_content = f"""<!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>Reporte Geotécnico - GeoPredict Pro</title> | |
| <style> | |
| body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }} | |
| .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; text-align: center; margin-bottom: 30px; }} | |
| .prediction-card {{ background: #667eea; color: white; padding: 20px; border-radius: 10px; text-align: center; margin: 10px; }} | |
| .section {{ background: white; padding: 20px; margin: 20px 0; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }} | |
| .graph-container {{ text-align: center; margin: 20px 0; }} | |
| .graph-container img {{ max-width: 100%; height: auto; }} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="header"> | |
| <h1>🏗️ GeoPredict SPTro - Reporte Geotécnico</h1> | |
| <p>{material} | N60 = {n60} | {datetime.now().strftime('%d/%m/%Y %H:%M')}</p> | |
| </div> | |
| <div class="section"> | |
| <h2>📋 Información del Proyecto</h2> | |
| <p><strong>Proyecto:</strong> {proyecto}</p> | |
| <p><strong>Ubicación:</strong> {ubicacion}</p> | |
| <p><strong>Ingeniero:</strong> {nombre_ing}</p> | |
| <p><strong>Material:</strong> {material}</p> | |
| <p><strong>N60 (SPT):</strong> {n60}</p> | |
| <p><strong>Fecha:</strong> {datetime.now().strftime('%d/%m/%Y %H:%M')}</p> | |
| </div> | |
| <div class="section"> | |
| <h2>📊 Resultados de Predicción</h2> | |
| <div style="display: flex; flex-wrap: wrap;"> | |
| """ | |
| for prop, data in predicciones.items(): | |
| html_content += f""" | |
| <div class="prediction-card"> | |
| <h3>{prop}</h3> | |
| <div style="font-size: 2em; font-weight: bold;">{data['valor']}</div> | |
| <div>R² = {data['r2']:.3f}</div> | |
| </div> | |
| """ | |
| html_content += """ | |
| </div> | |
| </div> | |
| """ | |
| if graficas_base64: | |
| html_content += """ | |
| <div class="section"> | |
| <h2>📊 Gráficas de Análisis</h2> | |
| """ | |
| for img_base64 in graficas_base64: | |
| html_content += f""" | |
| <div class="graph-container"> | |
| <img src="data:image/png;base64,{img_base64}" alt="Gráfica de análisis"> | |
| </div> | |
| """ | |
| html_content += """ | |
| </div> | |
| """ | |
| html_content += f""" | |
| <div class="section" style="text-align: center; background: #f8f9fa;"> | |
| <p><strong>GeoPredict Pro</strong> - Sistema de Predicción Geotécnica con IA</p> | |
| <p>Reporte generado automáticamente el {datetime.now().strftime('%d/%m/%Y')}</p> | |
| </div> | |
| </body> | |
| </html>""" | |
| return html_content | |
| # ============================================================================== | |
| # BLOQUE 3: INTERFAZ GRADIO | |
| # ============================================================================== | |
| with gr.Blocks(theme=gr.themes.Soft(), title="GeoPredict SPTpro") as demo: | |
| gr.Markdown(""" | |
| # 🏗️ GeoPredict SPTpro | |
| ### Sistema Profesional de Predicción Geotécnica con IA | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### ⚙️ Parámetros de Entrada") | |
| material = gr.Dropdown( | |
| ["ARENA", "GRAVA", "ARCILLA"], | |
| label="🎯 Material del Suelo", | |
| value="ARENA", | |
| info="Seleccione el tipo de material" | |
| ) | |
| n60 = gr.Slider( | |
| 1, 100, value=25, step=1, | |
| label="🔢 Valor N60 (SPT)", | |
| info="Rango completo: 1-100" | |
| ) | |
| nombre_ing = gr.Textbox( | |
| label="👤 Ingeniero Responsable", | |
| value="Ing. Geotécnico", | |
| placeholder="Ingrese su nombre" | |
| ) | |
| ubicacion = gr.Textbox( | |
| label="📍 Ubicación del Proyecto", | |
| value="Sitio de Estudio", | |
| placeholder="Ubicación del proyecto" | |
| ) | |
| proyecto = gr.Textbox( | |
| label="🏢 Nombre del Proyecto", | |
| value="Proyecto de Infraestructura", | |
| placeholder="Nombre oficial del proyecto" | |
| ) | |
| btn_predict = gr.Button( | |
| "🚀 Ejecutar Predicción", | |
| size="lg", | |
| variant="primary" | |
| ) | |
| with gr.Column(scale=2): | |
| gr.Markdown("### 📊 Resultados del Análisis") | |
| resultados = gr.HTML(label="Predicciones") | |
| graficas = gr.HTML(label="Gráficas del Modelo") | |
| gr.Markdown("### 💾 Descargar Reporte") | |
| descarga_html = gr.HTML(""" | |
| <div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; | |
| border: 1px solid #c3e6cb; text-align: center;"> | |
| <p style="margin: 0;">📄 Ejecuta una predicción para generar el reporte</p> | |
| </div> | |
| """) | |
| descarga_btn = gr.Button( | |
| "📥 Descargar Reporte HTML", | |
| size="lg", | |
| variant="secondary", | |
| visible=False | |
| ) | |
| archivo_descarga = gr.File( | |
| label="Reporte Geotécnico", | |
| visible=False | |
| ) | |
| # Ejemplos | |
| gr.Markdown("### 🚀 Ejemplos Rápidos") | |
| with gr.Row(): | |
| gr.Examples( | |
| examples=[ | |
| ["ARENA", 25, "Ing. Ejemplo", "Ciudad Ejemplo", "Edificio Corporativo"], | |
| ["GRAVA", 60, "Ing. Ejemplo", "Zona Industrial", "Planta de Producción"], | |
| ["ARCILLA", 15, "Ing. Ejemplo", "Área Residencial", "Conjunto Habitacional"] | |
| ], | |
| inputs=[material, n60, nombre_ing, ubicacion, proyecto] | |
| ) | |
| # Variable para almacenar el reporte actual | |
| reporte_actual = gr.State("") | |
| # Función principal | |
| def procesar_prediccion(material, n60, nombre_ing, ubicacion, proyecto): | |
| resultados_html, graficas_html, reporte_html = predecir_propiedades_completo( | |
| material, n60, nombre_ing, ubicacion, proyecto | |
| ) | |
| mostrar_descarga = reporte_html != "" | |
| return resultados_html, graficas_html, gr.Button(visible=mostrar_descarga), reporte_html | |
| # Función para descargar | |
| def generar_descarga(reporte_html): | |
| if reporte_html: | |
| filename = "reporte_geotecnico.html" | |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.html', mode='w', encoding='utf-8') | |
| temp_file.write(reporte_html) | |
| temp_file.close() | |
| return gr.File(value=temp_file.name, label=filename, visible=True) | |
| return gr.File(visible=False) | |
| # Conectar botones | |
| btn_predict.click( | |
| fn=procesar_prediccion, | |
| inputs=[material, n60, nombre_ing, ubicacion, proyecto], | |
| outputs=[resultados, graficas, descarga_btn, reporte_actual] | |
| ) | |
| descarga_btn.click( | |
| fn=generar_descarga, | |
| inputs=[reporte_actual], | |
| outputs=[archivo_descarga] | |
| ) | |
| # ============================================================================== | |
| # EJECUCIÓN PRINCIPAL | |
| # ============================================================================== | |
| if __name__ == "__main__": | |
| demo.launch( | |
| debug=False, | |
| show_error=True, | |
| server_name="0.0.0.0", # ← AÑADE ESTO | |
| server_port=7860 # ← AÑADE ESTO | |
| ) |