Spaces:
Runtime error
Runtime error
File size: 16,694 Bytes
68e9069 | 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 | # cli_interface_improved.py
import sys
from pathlib import Path
import pandas as pd
import os
sys.path.append(str(Path(__file__).parent))
from backend.converters.converter_engine import UniversalConverter
from engines.data_engine import DataEngine
from backend.api_generator.api_factory import APIFactory, APIConfig
from backend.db_generator.database_factory import DatabaseFactory, DatabaseConfig
class ImprovedCLIInterface:
"""Interfaz mejorada con estado compartido entre menús"""
def __init__(self):
self.converter = UniversalConverter()
self.data_engine = DataEngine()
self.api_factory = APIFactory()
self.db_factory = DatabaseFactory()
self.current_file_path = None
self.current_dataframe = None
self.data_loaded = False
def run(self):
"""Ejecuta la interfaz principal"""
print("🚀 DataSuite Pro - Interface Mejorada")
print("=" * 50)
print("✅ **MEJORA**: Los datos se mantienen cargados entre menús")
print("=" * 50)
while True:
self._print_main_menu()
choice = input("\nSelecciona una opción: ").strip()
if choice == "1":
self.load_data_menu()
elif choice == "2":
self.converter_menu()
elif choice == "3":
self.analyzer_menu()
elif choice == "4":
self.api_menu()
elif choice == "5":
self.database_menu()
elif choice == "6":
self.show_current_data()
elif choice == "0":
print("👋 ¡Hasta luego!")
break
else:
print("❌ Opción no válida")
def _print_main_menu(self):
"""Muestra el menú principal con estado actual"""
print(f"\n📋 MENU PRINCIPAL (Estado: {self._get_status()})")
print("-" * 50)
print("1. 📥 Cargar datos desde archivo")
print("2. 📊 Conversor de formatos")
print("3. 🔍 Analizador de datos")
print("4. ⚡ Generador de API")
print("5. 🗃️ Generador de base de datos")
print("6. 👀 Ver datos actuales")
print("0. 🚪 Salir")
if self.data_loaded:
print(f"\n💡 Datos cargados: {self.current_file_path}")
print(f" 📊 {len(self.current_dataframe)} filas × {len(self.current_dataframe.columns)} columnas")
def _get_status(self):
"""Retorna el estado actual"""
if self.data_loaded:
return "Datos Cargados ✅"
return "Sin Datos ❌"
def load_data_menu(self):
"""Menú para cargar datos"""
print("\n📥 CARGAR DATOS DESDE ARCHIVO")
print("-" * 30)
file_path = input("Ruta del archivo (CSV, JSON, Excel, TXT): ").strip()
if not Path(file_path).exists():
print("❌ Archivo no encontrado")
return
# Detectar tipo de archivo
file_ext = Path(file_path).suffix.lower()
supported_formats = ['.csv', '.json', '.xlsx', '.xls', '.txt']
if file_ext not in supported_formats:
print(f"❌ Formato no soportado: {file_ext}")
print(f" Formatos soportados: {', '.join(supported_formats)}")
return
try:
print(f"🔄 Cargando {file_ext}...")
# Cargar según el formato
if file_ext == '.csv':
df = pd.read_csv(file_path)
elif file_ext == '.json':
df = pd.read_json(file_path)
elif file_ext in ['.xlsx', '.xls']:
df = pd.read_excel(file_path)
elif file_ext == '.txt':
# Intentar como CSV con diferentes delimitadores
try:
df = pd.read_csv(file_path, sep=',')
except:
try:
df = pd.read_csv(file_path, sep=';')
except:
df = pd.read_csv(file_path, sep='\t')
# Guardar estado
self.current_file_path = file_path
self.current_dataframe = df
self.data_loaded = True
# Cargar también en el data engine para análisis avanzado
self.data_engine.load_data(file_path, 'auto')
print("✅ Datos cargados exitosamente!")
print(f" 📈 Filas: {len(df)}")
print(f" 📊 Columnas: {len(df.columns)}")
print(f" 💾 Memoria: {df.memory_usage(deep=True).sum() / 1024 / 1024:.2f} MB")
# Mostrar primeras filas
print("\n👀 Vista previa (primeras 3 filas):")
print(df.head(3).to_string(index=False))
except Exception as e:
print(f"❌ Error cargando archivo: {e}")
def show_current_data(self):
"""Muestra los datos actualmente cargados"""
if not self.data_loaded:
print("❌ No hay datos cargados. Usa la opción 1 primero.")
return
print(f"\n👀 DATOS ACTUALMENTE CARGADOS")
print("-" * 40)
print(f"📁 Archivo: {self.current_file_path}")
print(f"📈 Filas: {len(self.current_dataframe)}")
print(f"📊 Columnas: {len(self.current_dataframe.columns)}")
print("\n📋 Columnas:")
for i, col in enumerate(self.current_dataframe.columns, 1):
dtype = self.current_dataframe[col].dtype
print(f" {i}. {col} ({dtype})")
print("\n📊 Primeras 5 filas:")
print(self.current_dataframe.head().to_string(index=False))
# Estadísticas básicas
print("\n📈 Estadísticas básicas:")
print(f" Valores faltantes: {self.current_dataframe.isnull().sum().sum()}")
print(f" Filas duplicadas: {self.current_dataframe.duplicated().sum()}")
def converter_menu(self):
"""Menú del conversor"""
if not self.data_loaded:
print("❌ Primero carga datos con la opción 1")
return
print("\n📊 CONVERSOR DE FORMATOS")
print("-" * 30)
print(f"Convirtiendo: {self.current_file_path}")
print("\nFormatos de salida disponibles:")
print("1. JSON (.json) - Ideal para APIs")
print("2. CSV (.csv) - Excel/Base de datos")
print("3. Excel (.xlsx) - Microsoft Excel")
print("4. Texto (.txt) - Formato simple")
format_choice = input("Selecciona formato de salida (1-4): ").strip()
format_map = {
"1": ".json",
"2": ".csv",
"3": ".xlsx",
"4": ".txt"
}
if format_choice not in format_map:
print("❌ Opción no válida")
return
output_format = format_map[format_choice]
try:
print(f"🔄 Convirtiendo a {output_format}...")
output_path = self.converter.convert(self.current_file_path, output_format)
print(f"✅ Conversión exitosa!")
print(f"📁 Archivo generado: {output_path}")
# Mostrar tamaño
file_size = Path(output_path).stat().st_size
print(f"📏 Tamaño: {file_size} bytes ({file_size/1024:.2f} KB)")
# Opción para abrir o ver
if output_format == '.json' and file_size < 10000: # Solo si es pequeño
view = input("¿Ver contenido? (s/n): ").strip().lower()
if view == 's':
with open(output_path, 'r') as f:
content = f.read()
print("\n📄 Contenido:")
print(content[:500] + "..." if len(content) > 500 else content)
except Exception as e:
print(f"❌ Error en conversión: {e}")
def analyzer_menu(self):
"""Menú del analizador - AHORA FUNCIONA CON DATOS CARGADOS"""
if not self.data_loaded:
print("❌ Primero carga datos con la opción 1")
return
print("\n🔍 ANALIZADOR DE DATOS AVANZADO")
print("-" * 40)
print(f"Analizando: {self.current_file_path}")
try:
# Usar el data engine que ya tiene los datos cargados
profile = self.data_engine.data_profile
print("✅ Análisis completado:")
print(f"📈 Total filas: {profile.total_rows}")
print(f"📊 Total columnas: {profile.total_columns}")
print(f"💾 Uso memoria: {profile.memory_usage}")
print(f"⭐ Puntuación calidad: {profile.quality_score}%")
print("\n📋 DETALLE POR COLUMNA:")
print("-" * 50)
for col_name, stats in profile.column_stats.items():
print(f"\n📊 {col_name} ({stats['type']})")
print(f" ❓ Faltantes: {stats['missing']} ({stats['missing']/profile.total_rows*100:.1f}%)")
print(f" 🔑 Únicos: {stats['unique']} ({stats['unique']/profile.total_rows*100:.1f}%)")
if stats['mean'] is not None:
print(f" 📐 Media: {stats['mean']:.2f}")
print(f" σ Desviación: {stats['std']:.2f}")
print(f" 📉 Mínimo: {stats['min']}")
print(f" 📈 Máximo: {stats['max']}")
# Detección de patrones
print("\n🎯 DETECCIÓN DE PATRONES:")
schema = self.data_engine.detect_schema()
if schema['potential_primary_keys']:
print(f" 🔑 Posibles claves primarias: {', '.join(schema['potential_primary_keys'])}")
if schema['business_entities']:
print(" 🏢 Entidades de negocio detectadas:")
for entity in schema['business_entities']:
print(f" - {entity['entity']} ({entity['identifier_column']})")
# Recomendaciones
print("\n💡 RECOMENDACIONES:")
if profile.quality_score < 90:
print(" ⚠️ Calidad de datos baja - considerar limpieza")
if any(stats['missing'] > 0 for stats in profile.column_stats.values()):
print(" 🧹 Existen valores faltantes - considerar imputación")
if len(profile.column_stats) > 10:
print(" 🗃️ Muchas columnas - considerar normalización")
except Exception as e:
print(f"❌ Error en análisis: {e}")
def api_menu(self):
"""Menú del generador de API"""
if not self.data_loaded:
print("❌ Primero carga datos con la opción 1")
return
print("\n⚡ GENERADOR DE API REST")
print("-" * 30)
print(f"Basado en: {self.current_file_path}")
# Configuración interactiva
project_name = input("Nombre del proyecto API [MiAPI]: ").strip() or "MiAPI"
framework = input("Framework (fastapi/flask) [fastapi]: ").strip() or "fastapi"
database = input("Base de datos (sqlite/mysql/postgresql) [sqlite]: ").strip() or "sqlite"
# Características avanzadas
print("\n🎛️ Características avanzadas:")
auth = input("¿Incluir autenticación JWT? (s/n) [s]: ").strip().lower() != 'n'
docs = input("¿Incluir documentación Swagger? (s/n) [s]: ").strip().lower() != 'n'
try:
print("🔄 Generando API profesional...")
api_config = APIConfig(
framework=framework,
project_name=project_name,
version="1.0.0",
authentication=auth,
pagination=True,
documentation=docs,
database=database
)
output_dir = Path("exports/apis") / project_name
result = self.api_factory.generate_fastapi(
self.data_engine.data_profile,
api_config,
output_dir
)
if result["success"]:
print("✅ API generada exitosamente!")
print(f"📁 Directorio: {result['output_dir']}")
print("\n🔗 ENDPOINTS GENERADOS:")
endpoints = result.get("endpoints", [])
for i, endpoint in enumerate(endpoints[:5], 1): # Mostrar primeros 5
print(f" {i}. {endpoint}")
if len(endpoints) > 5:
print(f" ... y {len(endpoints) - 5} endpoints más")
print(f"\n📄 ARCHIVOS GENERADOS: {len(result['generated_files'])}")
key_files = [f for f in result['generated_files'] if any(x in f for x in ['main.py', 'requirements.txt'])]
for file_path in key_files:
print(f" 📄 {Path(file_path).name}")
print(f"\n🚀 PARA EJECUTAR:")
print(f" cd {result['output_dir']}")
print(f" pip install -r requirements.txt")
print(f" uvicorn app.main:app --reload")
print(f" 📖 Documentación: http://localhost:8000/docs")
else:
print(f"❌ Error: {result.get('error')}")
except Exception as e:
print(f"❌ Error generando API: {e}")
def database_menu(self):
"""Menú del generador de base de datos"""
if not self.data_loaded:
print("❌ Primero carga datos con la opción 1")
return
print("\n🗃️ GENERADOR DE BASE DE DATOS")
print("-" * 30)
print(f"Desde: {self.current_file_path}")
print("\n💾 Tipos de base de datos:")
print("1. SQLite (archivo .db - recomendado para empezar)")
print("2. MySQL (script SQL - para producción)")
print("3. PostgreSQL (script SQL - enterprise)")
db_choice = input("Selecciona tipo (1-3) [1]: ").strip() or "1"
db_map = {
"1": "sqlite",
"2": "mysql",
"3": "postgresql"
}
if db_choice not in db_map:
print("❌ Opción no válida, usando SQLite")
db_choice = "1"
db_type = db_map[db_choice]
db_name = input("Nombre de la base de datos [mi_basedatos]: ").strip() or "mi_basedatos"
try:
print(f"🔄 Generando base de datos {db_type}...")
db_config = DatabaseConfig(
db_type=db_type,
db_name=db_name,
normalize=True,
create_indexes=True
)
output_dir = Path("exports/databases") / db_type
result = self.db_factory.generate_database(
self.current_dataframe,
db_config,
output_dir
)
if result["success"]:
print("✅ Base de datos generada exitosamente!")
if db_type == "sqlite":
print(f"📁 Archivo SQLite: {result['db_path']}")
file_size = Path(result['db_path']).stat().st_size
print(f"📏 Tamaño: {file_size} bytes")
else:
print(f"📁 Script SQL: {result['sql_script']}")
print(f"📊 Tabla: {result['table_name']}")
print(f"📈 Filas importadas: {result['row_count']}")
# Mostrar esquema
print("\n🗂️ ESQUEMA GENERADO:")
for col in self.current_dataframe.columns:
dtype = self.current_dataframe[col].dtype
print(f" - {col} ({dtype})")
else:
print(f"❌ Error: {result.get('error')}")
except Exception as e:
print(f"❌ Error generando BD: {e}")
if __name__ == "__main__":
print("🚀 Iniciando DataSuite Pro - Interface Mejorada...")
interface = ImprovedCLIInterface()
interface.run() |