Spaces:
Runtime error
Runtime error
Download cli_interface_improved.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/cli_interface_improved.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/cli_interface_improved.py
-
curl -L -o cli_interface_improved.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/cli_interface_improved.py
16.7 kB
| # 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() |