Spaces:
Runtime error
Runtime error
File size: 22,007 Bytes
68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 68e9069 95441a2 | 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 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | import streamlit as st
import pandas as pd
import numpy as np
import os
import sys
import re
from utils.common import get_safe_global_df
# Al inicio del archivo, después de los imports
from metrics_dashboard import MetricsDashboard
# Crear instancia global
metrics_dashboard = MetricsDashboard()
# =============================================================================
# CONFIGURACIÓN DE PÁGINA - DEBE IR AQUÍ AL INICIO
# =============================================================================
st.set_page_config(
page_title="DataSuite Pro",
page_icon="☣️",
layout="wide",
initial_sidebar_state="expanded"
)
from modules import (
data_converter,
advanced_analyzer,
api_generator,
db_generator,
full_export,
configuration
)
def fix_arrow_serialization(df):
"""
SOLUCIÓN ESPECÍFICA para errores de serialización Arrow
Solo convierte la columna problemática "Tipo de Dato"
"""
if df is None or df.empty:
return df
df_fixed = df.copy()
# ✅ SOLUCIÓN ESPECÍFICA: Solo convertir la columna "Tipo de Dato" si existe
if "Tipo de Dato" in df_fixed.columns:
try:
# Convertir SOLO esta columna a string
df_fixed["Tipo de Dato"] = df_fixed["Tipo de Dato"].astype(str)
except Exception as e:
# Si falla, usar conversión más segura
df_fixed["Tipo de Dato"] = df_fixed["Tipo de Dato"].apply(
lambda x: str(x) if x is not None else ""
)
# ✅ NO TOCAR LAS OTRAS COLUMNAS - mantener sus tipos originales
return df_fixed
def infer_entity_name(filename):
"""Inferir el nombre de la entidad principal desde el nombre del archivo"""
# Remover extensión del archivo
name_without_ext = filename.rsplit('.', 1)[0]
# Remover palabras comunes que podrían estar en el nombre del archivo
common_suffixes = ['_data', '_dataset', '_file', '_list', '_table', 'data_', 'dataset_']
entity_name = name_without_ext
for suffix in common_suffixes:
if entity_name.endswith(suffix):
entity_name = entity_name[:-len(suffix)]
elif entity_name.startswith(suffix):
entity_name = entity_name[len(suffix):]
# Convertir a singular si es plural común
plural_to_singular = {
'users': 'user',
'products': 'product',
'customers': 'customer',
'orders': 'order',
'items': 'item',
'categories': 'category',
'employees': 'employee',
'products': 'product',
'services': 'service',
'usuarios': 'usuario',
'productos': 'producto',
'pedidos': 'pedido',
'clientes': 'cliente',
'categorias': 'categoria'
}
entity_name = plural_to_singular.get(entity_name.lower(), entity_name)
# Limpiar caracteres especiales y convertir a snake_case
entity_name = re.sub(r'[^a-zA-Z0-9_]', '_', entity_name)
entity_name = re.sub(r'_+', '_', entity_name).strip('_')
# Si después de la limpieza está vacío, usar un nombre por defecto
if not entity_name:
entity_name = 'main_entity'
return entity_name.lower()
def apply_dark_theme():
"""Aplica tema oscuro moderno con CSS personalizado"""
st.markdown("""
<style>
.main {
background-color: #0E1117;
color: #FAFAFA;
}
.sidebar .sidebar-content {
background-color: #262730;
background-image: linear-gradient(135deg, #262730 0%, #1a1c24 100%);
}
.stRadio > div {
background-color: #262730;
padding: 10px;
border-radius: 10px;
border-left: 4px solid #FF4B4B;
}
.stRadio label {
color: #FAFAFA !important;
font-weight: 500;
}
.stButton button {
background-color: #FF4B4B;
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
font-weight: 600;
transition: all 0.3s ease;
}
.stButton button:hover {
background-color: #FF6B6B;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(255, 75, 75, 0.3);
}
.stHeader {
color: #FF4B4B !important;
border-bottom: 2px solid #FF4B4B;
padding-bottom: 10px;
}
</style>
""", unsafe_allow_html=True)
# ===========================================================
# FUNCIÓN AUXILIAR: CONVERSIÓN SEGURA DE DATOS PARA STREAMLIT
# ===========================================================
def safe_convert_dtypes_for_display(df):
"""
Convierte columnas a tipos seguros para evitar errores Arrow
y mostrar correctamente en Streamlit.
"""
import pandas as pd
if df is None or df.empty:
return df
df_fixed = df.copy()
for col in df_fixed.columns:
try:
# Si tiene tipo 'Int64' (de pandas), convertir a float64
if hasattr(df_fixed[col].dtype, "name") and df_fixed[col].dtype.name == "Int64":
df_fixed[col] = df_fixed[col].astype("float64")
else:
# Convertir valores no numéricos a string
df_fixed[col] = df_fixed[col].apply(
lambda x: str(x) if not pd.isna(x) else ""
)
except Exception:
df_fixed[col] = df_fixed[col].apply(lambda x: str(x) if not pd.isna(x) else "")
return df_fixed
def safe_display_dataframe(df, key_suffix=""):
"""
Muestra DataFrame de forma segura en Streamlit
(sin expanders anidados)
"""
if df is None or df.empty:
st.info("📭 No hay datos para mostrar")
return
try:
# ✅ Primero corregir problemas de Arrow
df_fixed = fix_arrow_serialization(df)
# ✅ Luego conversión de tipos para Streamlit
df_safe_display = safe_convert_dtypes_for_display(df_fixed)
# ✅ Mostrar sin usar expander (el expander está en main)
st.dataframe(df_safe_display, use_container_width=True)
except Exception as e:
st.error(f"❌ Error mostrando datos: {str(e)[:100]}")
# Fallback minimalista (sin expander interno)
st.write(f"**Filas:** {len(df)}, **Columnas:** {len(df.columns)}")
st.write("**Primeras filas:**")
st.write(df.head(3))
def fix_dataframe_arrow_issues(df):
"""
Función ESPECÍFICA para corregir problemas de serialización Arrow
que causan el error: "Could not convert dtype('int64') with type numpy.dtypes.Int64DType"
"""
if df is None or df.empty:
return df
df_fixed = df.copy()
for col in df_fixed.columns:
try:
# ✅ CORRECCIÓN CRÍTICA: Manejar específicamente Int64 de pandas
if hasattr(df_fixed[col].dtype, 'name'):
if df_fixed[col].dtype.name == 'Int64':
# Convertir a float64 que es compatible con Arrow
df_fixed[col] = df_fixed[col].astype('float64')
elif df_fixed[col].dtype.name == 'string':
# Asegurar que los strings sean compatibles
df_fixed[col] = df_fixed[col].astype(str)
# Manejar valores nulos
if df_fixed[col].isnull().any():
df_fixed[col] = df_fixed[col].fillna('')
except Exception as e:
# En caso de error, convertir toda la columna a string
df_fixed[col] = df_fixed[col].astype(str)
return df_fixed
def auto_detect_and_convert_dtypes(df):
"""Convierte automáticamente los tipos de datos - VERSIÓN SEGURA"""
if df is None or df.empty:
return df
new_df = df.copy()
for col in new_df.columns:
try:
# ✅ SOLO convertir columnas que claramente son numéricas
# Verificar si la columna parece ser numérica
if new_df[col].dtype == 'object':
# Intentar convertir a numérico
numeric_converted = pd.to_numeric(new_df[col], errors='coerce')
numeric_count = numeric_converted.notna().sum()
# Solo convertir si >90% son numéricos Y no son fechas
if numeric_count > len(new_df) * 0.9:
# Verificar que no sean fechas (evitar el problema 8.13024e+17)
sample_vals = new_df[col].dropna().head(5)
looks_like_date = any(
any(date_indicator in str(val).lower() for date_indicator in ['/', '-', 'date', 'fecha', 'nacim'])
for val in sample_vals if pd.notna(val)
)
if not looks_like_date:
new_df[col] = numeric_converted
continue
# ✅ Conversión de fechas MÁS SEGURA
if new_df[col].dtype == 'object':
sample_vals = new_df[col].dropna().head(3)
looks_like_date = any(
any(date_indicator in str(val) for date_indicator in ['/', '-', '202', '199', '198', '197'])
for val in sample_vals if pd.notna(val) and len(str(val)) > 5
)
if looks_like_date:
try:
date_converted = pd.to_datetime(new_df[col], errors='coerce', format='mixed')
if date_converted.notna().sum() > len(new_df) * 0.5: # 50% éxito
new_df[col] = date_converted
except:
pass
except Exception as col_error:
# Si hay error en una columna, continuar con las demás
continue
return new_df
def process_uploaded_file(uploaded_file):
"""Procesa el archivo subido - VERSIÓN SIMPLIFICADA Y SEGURA"""
try:
# Procesar archivo según tipo - USAR SOLO LOS MÉTODOS BÁSICOS
if uploaded_file.name.endswith(('.csv')):
df = pd.read_csv(uploaded_file)
elif uploaded_file.name.endswith(('.xlsx', '.xls')):
df = pd.read_excel(uploaded_file)
elif uploaded_file.name.endswith('.json'):
df = pd.read_json(uploaded_file)
else:
# ✅ EVITAR IMPORTAR DESDE data_converter QUE CAUSA CONFLICTO
st.error(f"❌ Tipo de archivo {uploaded_file.name.split('.')[-1]} no soportado")
return False
if df is not None and not df.empty:
# ✅ APLICAR CORRECCIONES BÁSICAS SOLO
df_final = fix_dataframe_arrow_issues(df)
# ✅ GUARDAR EN AMBAS VARIABLES
st.session_state.global_uploaded_file = uploaded_file
st.session_state.global_df = df_final
st.session_state.global_data = df_final.to_dict('records')
st.session_state.global_filename = uploaded_file.name
st.session_state.backup_df = df_final.copy()
# ✅ ACTUALIZAR TAMBIÉN LA VARIABLE DEL CONVERSOR
st.session_state.df = df_final
st.session_state.data = df_final.to_dict('records')
return True
else:
st.error("❌ Error: El archivo está vacío o no se pudo procesar")
return False
except Exception as e:
st.error(f"❌ Error cargando archivo: {str(e)}")
return False
def should_redirect_to_converter(current_page):
"""Determina si debería redirigir al Conversor de Datos"""
modules_requiring_data = [
"📊 Conversor de Datos",
"🔍 Analizador Avanzado",
"⚡ Generador de API",
"🗃️ Generador de BD",
"📈 Dashboard Métricas",
"📦 Exportación Completa"
]
# Si el módulo actual requiere datos pero no hay datos, redirigir
if current_page in modules_requiring_data and get_safe_global_df() is None:
return True
return False
def main():
# Aplicar tema oscuro
apply_dark_theme()
# =============================================================================
# INICIALIZACIÓN DE ESTADO GLOBAL - PERSISTENCIA DE DATOS
# =============================================================================
session_defaults = {
# Estado de navegación
'current_page': "📊 Conversor de Datos",
# Datos globales (compartidos entre todos los módulos)
'global_uploaded_file': None,
'global_df': None,
'global_data': None,
'global_filename': None,
# Estados específicos de módulos
'api_generated': False,
'db_generated': False,
'quality_changes': [],
'backup_df': None,
'sql_tables': [],
'current_sql_table': None,
'sql_content': None,
'conversion_output': None,
'conversion_filename': None,
'conversion_mime': None,
'conversion_type': None,
'json_output': None,
'json_filename': None,
'json_format': 'records',
'json_minify': False,
'json_force_ascii': True
}
# Inicializar session_state
for key, value in session_defaults.items():
if key not in st.session_state:
st.session_state[key] = value
# =============================================================================
# SIDEBAR - NAVEGACIÓN PRINCIPAL Y CARGA GLOBAL DE DATOS
# =============================================================================
with st.sidebar:
st.markdown("""
<div style='text-align: center; padding: 20px 0;'>
<h1 style='color: #FF4B4B; margin-bottom: 0;'>☣️ DataSuite Pro</h1>
<p style='color: #888; font-size: 0.9em;'>Plataforma Avanzada de Procesamiento de Datos</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# =========================================================================
# CARGA GLOBAL DE ARCHIVOS (SOLO UNA VEZ)
# =========================================================================
st.subheader("📁 Carga Global de Datos")
# Solo mostrar el uploader si no hay datos cargados
if st.session_state.global_df is None:
uploaded_file = st.file_uploader(
"Sube tu archivo de datos (se compartirá en todos los módulos)",
type=['csv', 'xlsx', 'xls', 'json', 'db', 'sqlite', 'sql'],
key="global_file_uploader"
)
if uploaded_file is not None:
if process_uploaded_file(uploaded_file):
st.success(f"✅ {uploaded_file.name} cargado globalmente!")
# ✅ REDIRIGIR AUTOMÁTICAMENTE A CONVERSOR DE DATOS
st.session_state.current_page = "📊 Conversor de Datos"
st.rerun()
else:
# Mostrar información del archivo cargado
st.success("✅ Archivo cargado")
st.info(f"**Archivo:** {st.session_state.global_filename}")
st.info(f"**Filas:** {len(get_safe_global_df())}")
st.info(f"**Columnas:** {len(get_safe_global_df().columns)}")
# ✅ PERMITIR CAMBIAR DE ARCHIVO Y REDIRIGIR
new_uploaded_file = st.file_uploader(
"¿Quieres cambiar de archivo?",
type=['csv', 'xlsx', 'xls', 'json', 'db', 'sqlite', 'sql'],
key="global_file_uploader_replace"
)
if new_uploaded_file is not None:
if process_uploaded_file(new_uploaded_file):
st.success(f"✅ {new_uploaded_file.name} cargado globalmente!")
# ✅ REDIRIGIR A CONVERSOR DE DATOS
st.session_state.current_page = "📊 Conversor de Datos"
st.rerun()
# Mostrar vista previa segura del DataFrame
with st.expander("📊 Vista previa de datos"):
safe_display_dataframe(get_safe_global_df().head(10), "preview")
# Botón para eliminar datos cargados
if st.button("🗑️ Eliminar Datos Cargados", type="secondary"):
# Limpiar todos los estados relacionados con datos
keys_to_clear = [
'global_uploaded_file', 'global_df', 'global_data', 'global_filename',
'backup_df', 'sql_tables', 'current_sql_table', 'sql_content',
'conversion_output', 'conversion_filename', 'conversion_mime',
'conversion_type', 'json_output', 'json_filename'
]
for key in keys_to_clear:
if key in st.session_state:
st.session_state[key] = None
st.rerun()
st.markdown("---")
# =========================================================================
# NAVEGACIÓN PRINCIPAL - ACTUALIZAR CON NUEVO MÓDULO
# =========================================================================
# ✅ SOLUCIÓN: Usar el índice para sincronizar el radio button
navigation_options = [
"📊 Conversor de Datos",
"🔍 Analizador Avanzado",
"⚡ Generador de API",
"🗃️ Generador de BD",
"📦 Exportación Completa",
"📈 Dashboard Métricas",
"🛠️ Configuración"
]
# Encontrar el índice de la página actual
current_index = navigation_options.index(st.session_state.current_page)
page = st.radio(
"**NAVEGACIÓN PRINCIPAL**",
navigation_options,
index=current_index, # ✅ FORZAR LA SELECCIÓN VISUAL
key="main_nav"
)
# Solo actualizar si el usuario cambió manualmente la selección
if page != st.session_state.current_page:
st.session_state.current_page = page
st.rerun()
st.markdown("---")
# =========================================================================
# PANEL DE ESTADO DEL SISTEMA
# =========================================================================
st.markdown("**📊 ESTADO DEL SISTEMA**")
if get_safe_global_df() is not None:
st.success("✅ Datos cargados")
numeric_cols = get_safe_global_df().select_dtypes(include=[np.number]).columns.tolist()
date_cols = get_safe_global_df().select_dtypes(include=['datetime64']).columns.tolist()
st.info(f"📈 {len(numeric_cols)} col. numéricas")
st.info(f"📅 {len(date_cols)} col. fecha")
else:
st.warning("📤 Esperando archivo...")
if st.session_state.api_generated:
st.success("⚡ API Generada")
if st.session_state.db_generated:
st.success("🗃️ BD Generada")
# =============================================================================
# ÁREA PRINCIPAL - CONTENIDO DINÁMICO
# =============================================================================
# ✅ VERIFICAR SI DEBE REDIRIGIR AL CONVERSOR DE DATOS
if should_redirect_to_converter(st.session_state.current_page):
st.warning("⚠️ No hay datos cargados. Redirigiendo al Conversor de Datos...")
st.session_state.current_page = "📊 Conversor de Datos"
st.rerun()
st.markdown(f"# {st.session_state.current_page}")
st.markdown("---")
# Verificar si hay datos cargados para módulos que los requieren
required_data_modules = [
"📊 Conversor de Datos",
"🔍 Analizador Avanzado",
"⚡ Generador de API",
"🗃️ Generador de BD",
"📈 Dashboard Métricas", # 👈 AGREGADO AQUÍ TAMBIÉN
"📦 Exportación Completa"
]
if st.session_state.current_page in required_data_modules and get_safe_global_df() is None:
st.warning("⚠️ No hay datos cargados. Por favor, sube un archivo en la barra lateral.")
st.info("💡 Los datos que cargues estarán disponibles en todos los módulos del sistema.")
return
# Navegación modular mejorada
try:
if st.session_state.current_page == "📊 Conversor de Datos":
try:
data_converter.show()
except Exception as e:
import traceback
st.error("❌ Error en Conversor de Datos:")
st.code(traceback.format_exc())
elif st.session_state.current_page == "🔍 Analizador Avanzado":
advanced_analyzer.show()
elif st.session_state.current_page == "⚡ Generador de API":
try:
api_generator.show()
except Exception as e:
import traceback
st.error("❌ Error generador api:")
st.code(traceback.format_exc())
elif st.session_state.current_page == "🗃️ Generador de BD":
db_generator.show()
elif st.session_state.current_page == "📦 Exportación Completa":
full_export.show()
elif st.session_state.current_page == "📈 Dashboard Métricas": # 👈 NUEVO MÓDULO
metrics_dashboard.show()
elif st.session_state.current_page == "🛠️ Configuración":
configuration.show()
except Exception as e:
st.error(f"❌ Error cargando el módulo: {str(e)}")
st.info("🔧 Algunos módulos pueden estar en desarrollo")
if __name__ == "__main__":
main() |