Spaces:
Runtime error
Runtime error
Download engines/data_engine.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 7.11 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/engines/data_engine.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/engines/data_engine.py
-
curl -L -o data_engine.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/engines/data_engine.py
7.11 kB
| # engines/data_engine.py | |
| import pandas as pd | |
| import json | |
| import logging | |
| from pathlib import Path | |
| from typing import Dict, Any, List, Optional | |
| from dataclasses import dataclass | |
| from config.settings import config | |
| logger = logging.getLogger(__name__) | |
| class DataProfile: | |
| """Perfil completo de los datos analizados""" | |
| total_rows: int | |
| total_columns: int | |
| column_stats: Dict[str, Dict[str, Any]] | |
| data_types: Dict[str, str] | |
| missing_values: Dict[str, int] | |
| memory_usage: str | |
| quality_score: float | |
| class DataEngine: | |
| """Motor principal de análisis y procesamiento de datos""" | |
| def __init__(self): | |
| self.current_data = None | |
| self.data_profile = None | |
| def load_data(self, file_path: str, file_type: str = 'auto', **kwargs) -> bool: | |
| """ | |
| Carga datos desde un archivo | |
| Args: | |
| file_path: Ruta del archivo | |
| file_type: Tipo de archivo (auto, csv, json, excel, txt) | |
| **kwargs: Opciones específicas del formato | |
| Returns: | |
| True si la carga fue exitosa | |
| """ | |
| try: | |
| file_path = Path(file_path) | |
| if not file_path.exists(): | |
| logger.error(f"Archivo no encontrado: {file_path}") | |
| return False | |
| # Determinar tipo de archivo automáticamente | |
| if file_type == 'auto': | |
| file_type = file_path.suffix.lower().replace('.', '') | |
| # Cargar según el tipo | |
| if file_type in ['csv', 'txt']: | |
| self.current_data = pd.read_csv(file_path, **kwargs) | |
| elif file_type in ['xlsx', 'xls']: | |
| self.current_data = pd.read_excel(file_path, **kwargs) | |
| elif file_type == 'json': | |
| self.current_data = pd.read_json(file_path, **kwargs) | |
| else: | |
| logger.error(f"Tipo de archivo no soportado: {file_type}") | |
| return False | |
| logger.info(f"✅ Datos cargados: {len(self.current_data)} filas, {len(self.current_data.columns)} columnas") | |
| # Generar perfil automáticamente | |
| self.data_profile = self.generate_profile() | |
| return True | |
| except Exception as e: | |
| logger.error(f"❌ Error cargando datos: {e}") | |
| return False | |
| def generate_profile(self) -> DataProfile: | |
| """Genera un perfil completo de los datos""" | |
| if self.current_data is None: | |
| raise ValueError("No hay datos cargados") | |
| df = self.current_data | |
| profile = DataProfile( | |
| total_rows=len(df), | |
| total_columns=len(df.columns), | |
| column_stats={}, | |
| data_types={}, | |
| missing_values={}, | |
| memory_usage=f"{df.memory_usage(deep=True).sum() / 1024 / 1024:.2f} MB", | |
| quality_score=0.0 | |
| ) | |
| # Estadísticas por columna | |
| for column in df.columns: | |
| profile.column_stats[column] = { | |
| 'type': str(df[column].dtype), | |
| 'missing': df[column].isnull().sum(), | |
| 'unique': df[column].nunique(), | |
| 'mean': df[column].mean() if pd.api.types.is_numeric_dtype(df[column]) else None, | |
| 'std': df[column].std() if pd.api.types.is_numeric_dtype(df[column]) else None, | |
| 'min': df[column].min() if pd.api.types.is_numeric_dtype(df[column]) else None, | |
| 'max': df[column].max() if pd.api.types.is_numeric_dtype(df[column]) else None | |
| } | |
| profile.data_types[column] = str(df[column].dtype) | |
| profile.missing_values[column] = df[column].isnull().sum() | |
| # Calcular score de calidad | |
| profile.quality_score = self._calculate_quality_score(profile) | |
| return profile | |
| def _calculate_quality_score(self, profile: DataProfile) -> float: | |
| """Calcula un score de calidad de los datos (0-100)""" | |
| total_cells = profile.total_rows * profile.total_columns | |
| if total_cells == 0: | |
| return 0.0 | |
| missing_cells = sum(profile.missing_values.values()) | |
| completeness = 1 - (missing_cells / total_cells) | |
| # Score basado en completitud (podemos añadir más factores) | |
| return round(completeness * 100, 2) | |
| def get_preview(self, n_rows: int = 10) -> Dict[str, Any]: | |
| """Obtiene una vista previa de los datos""" | |
| if self.current_data is None: | |
| return {"error": "No hay datos cargados"} | |
| df = self.current_data.head(n_rows) | |
| return { | |
| "headers": df.columns.tolist(), | |
| "data": df.fillna('').to_dict('records'), | |
| "total_rows": len(self.current_data), | |
| "total_columns": len(self.current_data.columns) | |
| } | |
| def clean_data(self, strategies: Dict[str, str] = None) -> None: | |
| """Limpia los datos según estrategias especificadas""" | |
| if self.current_data is None: | |
| return | |
| if strategies is None: | |
| strategies = { | |
| 'remove_duplicates': 'true', | |
| 'fill_missing': 'mean', # o 'median', 'mode', 'drop' | |
| 'standardize_names': 'true' | |
| } | |
| # Implementar estrategias de limpieza | |
| if strategies.get('remove_duplicates') == 'true': | |
| self.current_data = self.current_data.drop_duplicates() | |
| if strategies.get('standardize_names') == 'true': | |
| self.current_data.columns = [col.strip().lower().replace(' ', '_') | |
| for col in self.current_data.columns] | |
| # Regenerar perfil después de la limpieza | |
| self.data_profile = self.generate_profile() | |
| def detect_schema(self) -> Dict[str, Any]: | |
| """Detecta el esquema y relaciones en los datos""" | |
| if self.current_data is None: | |
| return {} | |
| df = self.current_data | |
| # Análisis básico de esquema | |
| schema = { | |
| "tables_detected": [], | |
| "potential_primary_keys": [], | |
| "relationships": [], | |
| "business_entities": [] | |
| } | |
| # Detectar posibles tablas/entidades | |
| for column in df.columns: | |
| col_lower = column.lower() | |
| if any(keyword in col_lower for keyword in ['id', 'code', 'key']): | |
| schema["potential_primary_keys"].append(column) | |
| # Detectar entidades comunes | |
| if any(entity in col_lower for entity in ['name', 'title', 'description']): | |
| schema["business_entities"].append({ | |
| "entity": column.replace('_name', '').replace('_title', ''), | |
| "identifier_column": column | |
| }) | |
| return schema | |
| # Función de conveniencia | |
| def create_data_engine() -> DataEngine: | |
| """Crea una instancia del motor de datos""" | |
| return DataEngine() |