Spaces:
Sleeping
Sleeping
File size: 21,173 Bytes
69b4029 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
# -*- 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
) |