Spaces:
Runtime error
Runtime error
File size: 7,110 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 | # 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__)
@dataclass
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() |