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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled0.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1lA4vvx9sbWFfjQHAmGs8ADgwhNOypfsM
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import numpy as np
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import io
|
| 15 |
+
import base64
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 18 |
+
from sklearn.metrics import r2_score, mean_squared_error
|
| 19 |
+
import tempfile
|
| 20 |
+
|
| 21 |
+
print("🚀 Iniciando GeoPredict en Hugging Face...")
|
| 22 |
+
|
| 23 |
+
# ==============================================================================
|
| 24 |
+
# BLOQUE 1: ENTRENAMIENTO DEL MODELO (se ejecuta al iniciar)
|
| 25 |
+
# ==============================================================================
|
| 26 |
+
|
| 27 |
+
print("📂 Cargando y entrenando modelos...")
|
| 28 |
+
|
| 29 |
+
# Cargar datos
|
| 30 |
+
df = pd.read_excel('base_datos.xlsx')
|
| 31 |
+
|
| 32 |
+
# Limpieza robusta
|
| 33 |
+
df['N60'] = pd.to_numeric(df['N60'], errors='coerce')
|
| 34 |
+
df['φ_grados'] = pd.to_numeric(df['φ_grados'], errors='coerce')
|
| 35 |
+
df['Densidad_relativa'] = df['Densidad_relativa'].astype(str).str.replace(r'[-%]', '', regex=True)
|
| 36 |
+
df['Densidad_relativa'] = pd.to_numeric(df['Densidad_relativa'], errors='coerce')
|
| 37 |
+
df['Cu/Su (KPa)'] = pd.to_numeric(df['Cu/Su (KPa)'], errors='coerce')
|
| 38 |
+
df = df.dropna(subset=['MATERIAL', 'N60'], how='all')
|
| 39 |
+
|
| 40 |
+
# Configuración de modelos
|
| 41 |
+
config = [
|
| 42 |
+
('ARENA', 'φ_grados', 'Ángulo de fricción (φ)', 'grados'),
|
| 43 |
+
('GRAVA', 'φ_grados', 'Ángulo de fricción (φ)', 'grados'),
|
| 44 |
+
('ARCILLA', 'Cu/Su (KPa)', 'Resistencia no drenada (Cu/Su)', 'kPa'),
|
| 45 |
+
('ARENA', 'Densidad_relativa', 'Densidad relativa (Dr)', 'decimal'),
|
| 46 |
+
('GRAVA', 'Densidad_relativa', 'Densidad relativa (Dr)', 'decimal')
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
modelos_rf = {}
|
| 50 |
+
|
| 51 |
+
for material, col_y, nombre_prop, unidad in config:
|
| 52 |
+
print(f"🧠 Entrenando: {material} → {nombre_prop}")
|
| 53 |
+
df_mat = df[df['MATERIAL'] == material].copy()
|
| 54 |
+
X = df_mat[['N60']]
|
| 55 |
+
y = df_mat[col_y]
|
| 56 |
+
|
| 57 |
+
mask = y.notnull()
|
| 58 |
+
X, y = X[mask], y[mask]
|
| 59 |
+
|
| 60 |
+
if len(X) < 5:
|
| 61 |
+
print(f" ⚠️ Pocos datos. Saltando...")
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
# Entrenar Random Forest
|
| 65 |
+
model = RandomForestRegressor(n_estimators=100, random_state=42)
|
| 66 |
+
model.fit(X, y)
|
| 67 |
+
|
| 68 |
+
# Evaluar
|
| 69 |
+
y_pred = model.predict(X)
|
| 70 |
+
r2 = r2_score(y, y_pred)
|
| 71 |
+
rmse = np.sqrt(mean_squared_error(y, y_pred))
|
| 72 |
+
|
| 73 |
+
# Guardar modelo
|
| 74 |
+
clave = f"{material}_{col_y}"
|
| 75 |
+
modelos_rf[clave] = {
|
| 76 |
+
'modelo': model,
|
| 77 |
+
'R2': r2,
|
| 78 |
+
'RMSE': rmse,
|
| 79 |
+
'unidad': unidad,
|
| 80 |
+
'propiedad': nombre_prop,
|
| 81 |
+
'X_train': X.values.flatten(),
|
| 82 |
+
'y_train': y.values.flatten()
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
print("✅ Modelos entrenados correctamente")
|
| 86 |
+
|
| 87 |
+
# ==============================================================================
|
| 88 |
+
# BLOQUE 2: CONFIGURACIÓN Y FUNCIONES PARA GRADIO
|
| 89 |
+
# ==============================================================================
|
| 90 |
+
|
| 91 |
+
# Configuración profesional de matplotlib
|
| 92 |
+
plt.rcParams['font.size'] = 12
|
| 93 |
+
plt.rcParams['axes.grid'] = True
|
| 94 |
+
plt.rcParams['grid.alpha'] = 0.3
|
| 95 |
+
|
| 96 |
+
# RANGOS por material
|
| 97 |
+
RANGOS_MATERIAL = {
|
| 98 |
+
'ARENA': {'min': 1, 'max': 60, 'defecto': 25, 'rango_real': "1-60"},
|
| 99 |
+
'GRAVA': {'min': 5, 'max': 100, 'defecto': 40, 'rango_real': "5-100"},
|
| 100 |
+
'ARCILLA': {'min': 5, 'max': 30, 'defecto': 15, 'rango_real': "5-30"}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def predecir_propiedades_completo(material, n60, nombre_ing, ubicacion, proyecto):
|
| 104 |
+
"""Función completa para predicciones profesionales"""
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
# Validar rango
|
| 108 |
+
rango = RANGOS_MATERIAL[material]
|
| 109 |
+
if n60 < rango['min'] or n60 > rango['max']:
|
| 110 |
+
raise ValueError(f"N60 = {n60} fuera del rango válido para {material} ({rango['min']}-{rango['max']})")
|
| 111 |
+
|
| 112 |
+
predicciones = {}
|
| 113 |
+
graficas_base64 = []
|
| 114 |
+
detalles_modelo = []
|
| 115 |
+
|
| 116 |
+
if material in ['ARENA', 'GRAVA']:
|
| 117 |
+
# Predicción para φ
|
| 118 |
+
clave_phi = f"{material}_φ_grados"
|
| 119 |
+
if clave_phi in modelos_rf:
|
| 120 |
+
info = modelos_rf[clave_phi]
|
| 121 |
+
phi_pred = info['modelo'].predict([[n60]])[0]
|
| 122 |
+
predicciones['Ángulo de Fricción (φ)'] = {
|
| 123 |
+
'valor': f"{phi_pred:.1f}°",
|
| 124 |
+
'valor_num': phi_pred,
|
| 125 |
+
'r2': info['R2'],
|
| 126 |
+
'rmse': info['RMSE']
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
# Gráfica para φ
|
| 130 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 131 |
+
|
| 132 |
+
sample_size = min(50, len(info['X_train']))
|
| 133 |
+
sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False)
|
| 134 |
+
X_sample = info['X_train'][sample_indices]
|
| 135 |
+
y_sample = info['y_train'][sample_indices]
|
| 136 |
+
|
| 137 |
+
ax.scatter(X_sample, y_sample, alpha=0.7, color='steelblue', s=60,
|
| 138 |
+
label='Datos de Campo', edgecolors='white', linewidth=0.5)
|
| 139 |
+
|
| 140 |
+
N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1)
|
| 141 |
+
y_plot = info['modelo'].predict(N60_plot)
|
| 142 |
+
ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest')
|
| 143 |
+
|
| 144 |
+
ax.scatter([n60], [phi_pred], color='red', s=150, zorder=5,
|
| 145 |
+
marker='*', label=f'Predicción: {phi_pred:.1f}°')
|
| 146 |
+
|
| 147 |
+
ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5)
|
| 148 |
+
ax.axhline(y=phi_pred, color='red', linestyle='--', alpha=0.5)
|
| 149 |
+
|
| 150 |
+
ax.set_title(f'{material}: Ángulo de Fricción (φ)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.2f}',
|
| 151 |
+
fontsize=14, fontweight='bold')
|
| 152 |
+
ax.set_xlabel('N60 (SPT)', fontsize=12)
|
| 153 |
+
ax.set_ylabel('φ (grados)', fontsize=12)
|
| 154 |
+
ax.legend()
|
| 155 |
+
ax.grid(True, alpha=0.3)
|
| 156 |
+
|
| 157 |
+
plt.tight_layout()
|
| 158 |
+
buf = io.BytesIO()
|
| 159 |
+
plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
|
| 160 |
+
buf.seek(0)
|
| 161 |
+
graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8'))
|
| 162 |
+
plt.close()
|
| 163 |
+
|
| 164 |
+
# Predicción para Dr
|
| 165 |
+
clave_dr = f"{material}_Densidad_relativa"
|
| 166 |
+
if clave_dr in modelos_rf:
|
| 167 |
+
info = modelos_rf[clave_dr]
|
| 168 |
+
dr_pred = info['modelo'].predict([[n60]])[0] * 100
|
| 169 |
+
predicciones['Densidad Relativa (Dr)'] = {
|
| 170 |
+
'valor': f"{dr_pred:.1f}%",
|
| 171 |
+
'valor_num': dr_pred,
|
| 172 |
+
'r2': info['R2'],
|
| 173 |
+
'rmse': info['RMSE']
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
# Gráfica para Dr
|
| 177 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 178 |
+
|
| 179 |
+
sample_size = min(50, len(info['X_train']))
|
| 180 |
+
sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False)
|
| 181 |
+
X_sample = info['X_train'][sample_indices]
|
| 182 |
+
y_sample = info['y_train'][sample_indices] * 100
|
| 183 |
+
|
| 184 |
+
ax.scatter(X_sample, y_sample, alpha=0.7, color='green', s=60,
|
| 185 |
+
label='Datos de Campo', edgecolors='white', linewidth=0.5)
|
| 186 |
+
|
| 187 |
+
N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1)
|
| 188 |
+
y_plot = info['modelo'].predict(N60_plot) * 100
|
| 189 |
+
ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest')
|
| 190 |
+
|
| 191 |
+
ax.scatter([n60], [dr_pred], color='red', s=150, zorder=5,
|
| 192 |
+
marker='*', label=f'Predicción: {dr_pred:.1f}%')
|
| 193 |
+
|
| 194 |
+
ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5)
|
| 195 |
+
ax.axhline(y=dr_pred, color='red', linestyle='--', alpha=0.5)
|
| 196 |
+
|
| 197 |
+
ax.set_title(f'{material}: Densidad Relativa (Dr)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.3f}',
|
| 198 |
+
fontsize=14, fontweight='bold')
|
| 199 |
+
ax.set_xlabel('N60 (SPT)', fontsize=12)
|
| 200 |
+
ax.set_ylabel('Dr (%)', fontsize=12)
|
| 201 |
+
ax.legend()
|
| 202 |
+
ax.grid(True, alpha=0.3)
|
| 203 |
+
|
| 204 |
+
plt.tight_layout()
|
| 205 |
+
buf = io.BytesIO()
|
| 206 |
+
plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
|
| 207 |
+
buf.seek(0)
|
| 208 |
+
graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8'))
|
| 209 |
+
plt.close()
|
| 210 |
+
|
| 211 |
+
elif material == 'ARCILLA':
|
| 212 |
+
clave_cu = "ARCILLA_Cu/Su (KPa)"
|
| 213 |
+
if clave_cu in modelos_rf:
|
| 214 |
+
info = modelos_rf[clave_cu]
|
| 215 |
+
cu_pred = info['modelo'].predict([[n60]])[0]
|
| 216 |
+
predicciones['Resistencia No Drenada (Cu)'] = {
|
| 217 |
+
'valor': f"{cu_pred:.1f} kPa",
|
| 218 |
+
'valor_num': cu_pred,
|
| 219 |
+
'r2': info['R2'],
|
| 220 |
+
'rmse': info['RMSE']
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
# Gráfica para Cu
|
| 224 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 225 |
+
|
| 226 |
+
sample_size = min(50, len(info['X_train']))
|
| 227 |
+
sample_indices = np.random.choice(len(info['X_train']), size=sample_size, replace=False)
|
| 228 |
+
X_sample = info['X_train'][sample_indices]
|
| 229 |
+
y_sample = info['y_train'][sample_indices]
|
| 230 |
+
|
| 231 |
+
ax.scatter(X_sample, y_sample, alpha=0.7, color='coral', s=60,
|
| 232 |
+
label='Datos de Campo', edgecolors='white', linewidth=0.5)
|
| 233 |
+
|
| 234 |
+
N60_plot = np.linspace(info['X_train'].min(), info['X_train'].max(), 100).reshape(-1, 1)
|
| 235 |
+
y_plot = info['modelo'].predict(N60_plot)
|
| 236 |
+
ax.plot(N60_plot, y_plot, color='purple', linewidth=3, label='Modelo Random Forest')
|
| 237 |
+
|
| 238 |
+
ax.scatter([n60], [cu_pred], color='red', s=150, zorder=5,
|
| 239 |
+
marker='*', label=f'Predicción: {cu_pred:.1f} kPa')
|
| 240 |
+
|
| 241 |
+
ax.axvline(x=n60, color='red', linestyle='--', alpha=0.5)
|
| 242 |
+
ax.axhline(y=cu_pred, color='red', linestyle='--', alpha=0.5)
|
| 243 |
+
|
| 244 |
+
ax.set_title(f'Arcilla: Resistencia No Drenada (Cu)\nR² = {info["R2"]:.3f} | RMSE = {info["RMSE"]:.2f}',
|
| 245 |
+
fontsize=14, fontweight='bold')
|
| 246 |
+
ax.set_xlabel('N60 (SPT)', fontsize=12)
|
| 247 |
+
ax.set_ylabel('Cu (kPa)', fontsize=12)
|
| 248 |
+
ax.legend()
|
| 249 |
+
ax.grid(True, alpha=0.3)
|
| 250 |
+
|
| 251 |
+
plt.tight_layout()
|
| 252 |
+
buf = io.BytesIO()
|
| 253 |
+
plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
|
| 254 |
+
buf.seek(0)
|
| 255 |
+
graficas_base64.append(base64.b64encode(buf.getvalue()).decode('utf-8'))
|
| 256 |
+
plt.close()
|
| 257 |
+
|
| 258 |
+
# Generar reporte HTML
|
| 259 |
+
reporte_html = generar_reporte_completo(predicciones, graficas_base64, material, n60, nombre_ing, ubicacion, proyecto)
|
| 260 |
+
|
| 261 |
+
# HTML para mostrar en la interfaz
|
| 262 |
+
resultados_html = f"""
|
| 263 |
+
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 264 |
+
color: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
|
| 265 |
+
<h2 style="margin: 0; text-align: center;">🏗️ GeoPredict SPTro - Resultados</h2>
|
| 266 |
+
<p style="text-align: center; margin: 5px 0 0 0; opacity: 0.9;">
|
| 267 |
+
{material} | N60 = {n60} | {datetime.now().strftime('%d/%m/%Y %H:%M')}
|
| 268 |
+
</p>
|
| 269 |
+
</div>
|
| 270 |
+
|
| 271 |
+
<div style="background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px;
|
| 272 |
+
border: 1px solid #ffeaa7; margin: 15px 0;">
|
| 273 |
+
<strong>📏 Rango del modelo:</strong> N60 = {rango['min']}-{rango['max']}
|
| 274 |
+
</div>
|
| 275 |
+
|
| 276 |
+
<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 15px 0;">
|
| 277 |
+
<h3 style="color: #2c3e50; margin-top: 0;">📊 Predicciones</h3>
|
| 278 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
for prop, data in predicciones.items():
|
| 282 |
+
resultados_html += f"""
|
| 283 |
+
<div style="background: white; padding: 15px; border-radius: 8px;
|
| 284 |
+
border-left: 4px solid #667eea; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
|
| 285 |
+
<div style="font-weight: bold; color: #2c3e50; margin-bottom: 5px;">{prop}</div>
|
| 286 |
+
<div style="font-size: 1.4em; font-weight: bold; color: #667eea;">{data['valor']}</div>
|
| 287 |
+
<div style="font-size: 0.9em; color: #666; margin-top: 5px;">R² = {data['r2']:.3f}</div>
|
| 288 |
+
</div>
|
| 289 |
+
"""
|
| 290 |
+
|
| 291 |
+
resultados_html += """
|
| 292 |
+
</div>
|
| 293 |
+
</div>
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
# Gráficas HTML
|
| 297 |
+
graficas_html = "<div style='margin-top: 20px;'>"
|
| 298 |
+
for img_base64 in graficas_base64:
|
| 299 |
+
graficas_html += f"""
|
| 300 |
+
<div style="background: white; padding: 15px; border-radius: 8px; margin: 15px 0;
|
| 301 |
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
|
| 302 |
+
<img src="data:image/png;base64,{img_base64}"
|
| 303 |
+
style="max-width: 100%; height: auto; border-radius: 5px;">
|
| 304 |
+
</div>
|
| 305 |
+
"""
|
| 306 |
+
graficas_html += "</div>"
|
| 307 |
+
|
| 308 |
+
return resultados_html, graficas_html, reporte_html
|
| 309 |
+
|
| 310 |
+
except Exception as e:
|
| 311 |
+
error_html = f"""
|
| 312 |
+
<div style="background: #f8d7da; color: #721c24; padding: 20px; border-radius: 8px;
|
| 313 |
+
border: 1px solid #f5c6cb; margin: 20px 0;">
|
| 314 |
+
<h3 style="margin: 0 0 10px 0;">❌ Error en la predicción</h3>
|
| 315 |
+
<p style="margin: 0;">{str(e)}</p>
|
| 316 |
+
</div>
|
| 317 |
+
"""
|
| 318 |
+
return error_html, "", ""
|
| 319 |
+
|
| 320 |
+
def generar_reporte_completo(predicciones, graficas_base64, material, n60, nombre_ing, ubicacion, proyecto):
|
| 321 |
+
"""Genera reporte HTML completo"""
|
| 322 |
+
html_content = f"""<!DOCTYPE html>
|
| 323 |
+
<html>
|
| 324 |
+
<head>
|
| 325 |
+
<meta charset="UTF-8">
|
| 326 |
+
<title>Reporte Geotécnico - GeoPredict Pro</title>
|
| 327 |
+
<style>
|
| 328 |
+
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }}
|
| 329 |
+
.header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; text-align: center; margin-bottom: 30px; }}
|
| 330 |
+
.prediction-card {{ background: #667eea; color: white; padding: 20px; border-radius: 10px; text-align: center; margin: 10px; }}
|
| 331 |
+
.section {{ background: white; padding: 20px; margin: 20px 0; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }}
|
| 332 |
+
.graph-container {{ text-align: center; margin: 20px 0; }}
|
| 333 |
+
.graph-container img {{ max-width: 100%; height: auto; }}
|
| 334 |
+
</style>
|
| 335 |
+
</head>
|
| 336 |
+
<body>
|
| 337 |
+
<div class="header">
|
| 338 |
+
<h1>🏗️ GeoPredict SPTro - Reporte Geotécnico</h1>
|
| 339 |
+
<p>{material} | N60 = {n60} | {datetime.now().strftime('%d/%m/%Y %H:%M')}</p>
|
| 340 |
+
</div>
|
| 341 |
+
|
| 342 |
+
<div class="section">
|
| 343 |
+
<h2>📋 Información del Proyecto</h2>
|
| 344 |
+
<p><strong>Proyecto:</strong> {proyecto}</p>
|
| 345 |
+
<p><strong>Ubicación:</strong> {ubicacion}</p>
|
| 346 |
+
<p><strong>Ingeniero:</strong> {nombre_ing}</p>
|
| 347 |
+
<p><strong>Material:</strong> {material}</p>
|
| 348 |
+
<p><strong>N60 (SPT):</strong> {n60}</p>
|
| 349 |
+
<p><strong>Fecha:</strong> {datetime.now().strftime('%d/%m/%Y %H:%M')}</p>
|
| 350 |
+
</div>
|
| 351 |
+
|
| 352 |
+
<div class="section">
|
| 353 |
+
<h2>📊 Resultados de Predicción</h2>
|
| 354 |
+
<div style="display: flex; flex-wrap: wrap;">
|
| 355 |
+
"""
|
| 356 |
+
|
| 357 |
+
for prop, data in predicciones.items():
|
| 358 |
+
html_content += f"""
|
| 359 |
+
<div class="prediction-card">
|
| 360 |
+
<h3>{prop}</h3>
|
| 361 |
+
<div style="font-size: 2em; font-weight: bold;">{data['valor']}</div>
|
| 362 |
+
<div>R² = {data['r2']:.3f}</div>
|
| 363 |
+
</div>
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
html_content += """
|
| 367 |
+
</div>
|
| 368 |
+
</div>
|
| 369 |
+
"""
|
| 370 |
+
|
| 371 |
+
if graficas_base64:
|
| 372 |
+
html_content += """
|
| 373 |
+
<div class="section">
|
| 374 |
+
<h2>📊 Gráficas de Análisis</h2>
|
| 375 |
+
"""
|
| 376 |
+
for img_base64 in graficas_base64:
|
| 377 |
+
html_content += f"""
|
| 378 |
+
<div class="graph-container">
|
| 379 |
+
<img src="data:image/png;base64,{img_base64}" alt="Gráfica de análisis">
|
| 380 |
+
</div>
|
| 381 |
+
"""
|
| 382 |
+
html_content += """
|
| 383 |
+
</div>
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
html_content += f"""
|
| 387 |
+
<div class="section" style="text-align: center; background: #f8f9fa;">
|
| 388 |
+
<p><strong>GeoPredict Pro</strong> - Sistema de Predicción Geotécnica con IA</p>
|
| 389 |
+
<p>Reporte generado automáticamente el {datetime.now().strftime('%d/%m/%Y')}</p>
|
| 390 |
+
</div>
|
| 391 |
+
</body>
|
| 392 |
+
</html>"""
|
| 393 |
+
return html_content
|
| 394 |
+
|
| 395 |
+
# ==============================================================================
|
| 396 |
+
# BLOQUE 3: INTERFAZ GRADIO
|
| 397 |
+
# ==============================================================================
|
| 398 |
+
|
| 399 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="GeoPredict SPTpro") as demo:
|
| 400 |
+
|
| 401 |
+
gr.Markdown("""
|
| 402 |
+
# 🏗️ GeoPredict SPTpro
|
| 403 |
+
### Sistema Profesional de Predicción Geotécnica con IA
|
| 404 |
+
""")
|
| 405 |
+
|
| 406 |
+
with gr.Row():
|
| 407 |
+
with gr.Column(scale=1):
|
| 408 |
+
gr.Markdown("### ⚙️ Parámetros de Entrada")
|
| 409 |
+
|
| 410 |
+
material = gr.Dropdown(
|
| 411 |
+
["ARENA", "GRAVA", "ARCILLA"],
|
| 412 |
+
label="🎯 Material del Suelo",
|
| 413 |
+
value="ARENA",
|
| 414 |
+
info="Seleccione el tipo de material"
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
n60 = gr.Slider(
|
| 418 |
+
1, 100, value=25, step=1,
|
| 419 |
+
label="🔢 Valor N60 (SPT)",
|
| 420 |
+
info="Rango completo: 1-100"
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
nombre_ing = gr.Textbox(
|
| 424 |
+
label="👤 Ingeniero Responsable",
|
| 425 |
+
value="Ing. Geotécnico",
|
| 426 |
+
placeholder="Ingrese su nombre"
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
ubicacion = gr.Textbox(
|
| 430 |
+
label="📍 Ubicación del Proyecto",
|
| 431 |
+
value="Sitio de Estudio",
|
| 432 |
+
placeholder="Ubicación del proyecto"
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
proyecto = gr.Textbox(
|
| 436 |
+
label="🏢 Nombre del Proyecto",
|
| 437 |
+
value="Proyecto de Infraestructura",
|
| 438 |
+
placeholder="Nombre oficial del proyecto"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
btn_predict = gr.Button(
|
| 442 |
+
"🚀 Ejecutar Predicción",
|
| 443 |
+
size="lg",
|
| 444 |
+
variant="primary"
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
with gr.Column(scale=2):
|
| 448 |
+
gr.Markdown("### 📊 Resultados del Análisis")
|
| 449 |
+
resultados = gr.HTML(label="Predicciones")
|
| 450 |
+
graficas = gr.HTML(label="Gráficas del Modelo")
|
| 451 |
+
|
| 452 |
+
gr.Markdown("### 💾 Descargar Reporte")
|
| 453 |
+
descarga_html = gr.HTML("""
|
| 454 |
+
<div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 8px;
|
| 455 |
+
border: 1px solid #c3e6cb; text-align: center;">
|
| 456 |
+
<p style="margin: 0;">📄 Ejecuta una predicción para generar el reporte</p>
|
| 457 |
+
</div>
|
| 458 |
+
""")
|
| 459 |
+
|
| 460 |
+
descarga_btn = gr.Button(
|
| 461 |
+
"📥 Descargar Reporte HTML",
|
| 462 |
+
size="lg",
|
| 463 |
+
variant="secondary",
|
| 464 |
+
visible=False
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
archivo_descarga = gr.File(
|
| 468 |
+
label="Reporte Geotécnico",
|
| 469 |
+
visible=False
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
# Ejemplos
|
| 473 |
+
gr.Markdown("### 🚀 Ejemplos Rápidos")
|
| 474 |
+
with gr.Row():
|
| 475 |
+
gr.Examples(
|
| 476 |
+
examples=[
|
| 477 |
+
["ARENA", 25, "Ing. Ejemplo", "Ciudad Ejemplo", "Edificio Corporativo"],
|
| 478 |
+
["GRAVA", 60, "Ing. Ejemplo", "Zona Industrial", "Planta de Producción"],
|
| 479 |
+
["ARCILLA", 15, "Ing. Ejemplo", "Área Residencial", "Conjunto Habitacional"]
|
| 480 |
+
],
|
| 481 |
+
inputs=[material, n60, nombre_ing, ubicacion, proyecto]
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
# Variable para almacenar el reporte actual
|
| 485 |
+
reporte_actual = gr.State("")
|
| 486 |
+
|
| 487 |
+
# Función principal
|
| 488 |
+
def procesar_prediccion(material, n60, nombre_ing, ubicacion, proyecto):
|
| 489 |
+
resultados_html, graficas_html, reporte_html = predecir_propiedades_completo(
|
| 490 |
+
material, n60, nombre_ing, ubicacion, proyecto
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
mostrar_descarga = reporte_html != ""
|
| 494 |
+
|
| 495 |
+
return resultados_html, graficas_html, gr.Button(visible=mostrar_descarga), reporte_html
|
| 496 |
+
|
| 497 |
+
# Función para descargar
|
| 498 |
+
def generar_descarga(reporte_html):
|
| 499 |
+
if reporte_html:
|
| 500 |
+
filename = "reporte_geotecnico.html"
|
| 501 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.html', mode='w', encoding='utf-8')
|
| 502 |
+
temp_file.write(reporte_html)
|
| 503 |
+
temp_file.close()
|
| 504 |
+
return gr.File(value=temp_file.name, label=filename, visible=True)
|
| 505 |
+
return gr.File(visible=False)
|
| 506 |
+
|
| 507 |
+
# Conectar botones
|
| 508 |
+
btn_predict.click(
|
| 509 |
+
fn=procesar_prediccion,
|
| 510 |
+
inputs=[material, n60, nombre_ing, ubicacion, proyecto],
|
| 511 |
+
outputs=[resultados, graficas, descarga_btn, reporte_actual]
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
descarga_btn.click(
|
| 515 |
+
fn=generar_descarga,
|
| 516 |
+
inputs=[reporte_actual],
|
| 517 |
+
outputs=[archivo_descarga]
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
# ==============================================================================
|
| 521 |
+
# EJECUCIÓN PRINCIPAL
|
| 522 |
+
# ==============================================================================
|
| 523 |
+
|
| 524 |
+
if __name__ == "__main__":
|
| 525 |
+
demo.launch(
|
| 526 |
+
debug=False,
|
| 527 |
+
show_error=True,
|
| 528 |
+
server_name="0.0.0.0", # ← AÑADE ESTO
|
| 529 |
+
server_port=7860 # ← AÑADE ESTO
|
| 530 |
+
)
|
base_datos.xlsx
ADDED
|
Binary file (49.6 kB). View file
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas==1.5.3
|
| 2 |
+
scikit-learn==1.2.2
|
| 3 |
+
matplotlib==3.7.1
|
| 4 |
+
openpyxl==3.1.2
|
| 5 |
+
numpy==1.24.3
|
| 6 |
+
gradio==4.13.0
|