DePol1's picture
update
95441a2 verified
Raw History Blame Contribute Delete
22 kB
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()