Spaces:
Runtime error
Runtime error
Download backend/api_generator/api_factory.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/backend/api_generator/api_factory.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/backend/api_generator/api_factory.py
-
curl -L -o api_factory.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/backend/api_generator/api_factory.py
17.2 kB
| # backend/api_generator/api_factory.py - VERSIÓN CORREGIDA | |
| import json | |
| import logging | |
| from pathlib import Path | |
| from typing import Dict, Any, List, Optional | |
| from dataclasses import dataclass | |
| from jinja2 import Environment, FileSystemLoader | |
| from config.settings import config | |
| import pandas as pd | |
| logger = logging.getLogger(__name__) | |
| class APIEndpoint: | |
| """Define un endpoint de API""" | |
| path: str | |
| method: str | |
| operation: str # create, read, update, delete, list | |
| description: str | |
| parameters: List[Dict[str, Any]] | |
| class APIConfig: | |
| """Configuración para la generación de API""" | |
| framework: str # fastapi, flask, django | |
| project_name: str | |
| version: str | |
| authentication: bool | |
| pagination: bool | |
| documentation: bool | |
| database: str # sqlite, mysql, postgresql | |
| class APIFactory: | |
| """Factory para generar APIs completas desde datos""" | |
| def __init__(self): | |
| # Configurar Jinja2 para plantillas | |
| template_path = config.TEMPLATES_DIR / "api_templates" | |
| self.env = Environment( | |
| loader=FileSystemLoader(template_path), | |
| trim_blocks=True, | |
| lstrip_blocks=True | |
| ) | |
| def generate_fastapi(self, data_profile: Any, api_config: APIConfig, | |
| output_dir: Path) -> Dict[str, Any]: | |
| """Genera una API completa con FastAPI - VERSIÓN CORREGIDA""" | |
| try: | |
| # Crear estructura de directorios | |
| self._create_api_structure(output_dir, api_config.framework) | |
| # OBTENER INFORMACIÓN REAL DE LAS COLUMNAS - CLAVE AQUÍ | |
| columns_info = self._get_columns_info(data_profile) | |
| # Analizar datos para generar endpoints | |
| endpoints = self._analyze_data_for_endpoints(data_profile) | |
| # Generar archivos principales CON DATOS REALES | |
| generated_files = self._generate_fastapi_files( | |
| endpoints, api_config, output_dir, columns_info, data_profile | |
| ) | |
| logger.info(f"✅ API FastAPI generada en: {output_dir}") | |
| return { | |
| "success": True, | |
| "output_dir": str(output_dir), | |
| "generated_files": generated_files, | |
| "endpoints": [e.path for e in endpoints], | |
| "columns_generated": len(columns_info) | |
| } | |
| except Exception as e: | |
| logger.error(f"❌ Error generando API FastAPI: {e}") | |
| return {"success": False, "error": str(e)} | |
| def _get_columns_info(self, data_profile: Any) -> Dict[str, Dict[str, Any]]: | |
| """Extrae información REAL de las columnas del DataFrame - FUNCIÓN CLAVE""" | |
| columns_info = {} | |
| try: | |
| # Si data_profile tiene el DataFrame directamente | |
| if hasattr(data_profile, 'current_data') and data_profile.current_data is not None: | |
| df = data_profile.current_data | |
| # Si data_profile es el DataFrame mismo | |
| elif hasattr(data_profile, 'columns') and hasattr(data_profile, 'dtypes'): | |
| df = data_profile | |
| else: | |
| # Intentar obtener datos de otras formas | |
| logger.warning("No se pudo obtener DataFrame directamente, usando información básica") | |
| if hasattr(data_profile, 'column_stats'): | |
| for col_name, col_stats in data_profile.column_stats.items(): | |
| columns_info[col_name] = { | |
| 'type': col_stats.get('type', 'object'), | |
| 'sql_type': self._map_pandas_to_sql(col_stats.get('type', 'object')), | |
| 'python_type': self._map_pandas_to_python(col_stats.get('type', 'object')), | |
| 'nullable': col_stats.get('missing', 0) > 0 | |
| } | |
| return columns_info | |
| else: | |
| # Datos por defecto como fallback | |
| return { | |
| 'id': {'type': 'int64', 'sql_type': 'INTEGER', 'python_type': 'int', 'nullable': False}, | |
| 'nombre': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True}, | |
| 'descripcion': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True} | |
| } | |
| # Extraer información REAL de cada columna del DataFrame | |
| for col_name in df.columns: | |
| col_dtype = str(df[col_name].dtype) | |
| columns_info[col_name] = { | |
| 'type': col_dtype, | |
| 'sql_type': self._map_pandas_to_sql(col_dtype), | |
| 'python_type': self._map_pandas_to_python(col_dtype), | |
| 'nullable': df[col_name].isnull().any(), | |
| 'unique_count': df[col_name].nunique(), | |
| 'sample_value': self._get_sample_value(df[col_name]) | |
| } | |
| logger.info(f"📊 Extraída información de {len(columns_info)} columnas") | |
| return columns_info | |
| except Exception as e: | |
| logger.error(f"❌ Error extrayendo información de columnas: {e}") | |
| # Datos de fallback para evitar errores | |
| return { | |
| 'id': {'type': 'int64', 'sql_type': 'INTEGER', 'python_type': 'int', 'nullable': False}, | |
| 'nombre': {'type': 'object', 'sql_type': 'TEXT', 'python_type': 'str', 'nullable': True} | |
| } | |
| def _get_sample_value(self, series): | |
| """Obtiene un valor de muestra no nulo de la serie""" | |
| try: | |
| # Buscar el primer valor no nulo | |
| non_null_values = series.dropna() | |
| if len(non_null_values) > 0: | |
| sample = non_null_values.iloc[0] | |
| # Truncar si es muy largo | |
| if isinstance(sample, str) and len(sample) > 50: | |
| return sample[:50] + "..." | |
| return sample | |
| return None | |
| except: | |
| return None | |
| def _map_pandas_to_sql(self, pandas_type: str) -> str: | |
| """Mapea tipos de pandas a tipos SQL - CORREGIDO""" | |
| type_mapping = { | |
| 'int64': 'INTEGER', | |
| 'int32': 'INTEGER', | |
| 'float64': 'REAL', | |
| 'float32': 'REAL', | |
| 'object': 'TEXT', | |
| 'bool': 'BOOLEAN', | |
| 'boolean': 'BOOLEAN', | |
| 'datetime64[ns]': 'TIMESTAMP', | |
| 'datetime64[ms]': 'TIMESTAMP', | |
| 'category': 'TEXT' | |
| } | |
| return type_mapping.get(pandas_type, 'TEXT') | |
| def _map_pandas_to_python(self, pandas_type: str) -> str: | |
| """Mapea tipos de pandas a tipos de Python/FastAPI - CORREGIDO""" | |
| type_mapping = { | |
| 'int64': 'int', | |
| 'int32': 'int', | |
| 'float64': 'float', | |
| 'float32': 'float', | |
| 'object': 'str', | |
| 'bool': 'bool', | |
| 'boolean': 'bool', | |
| 'datetime64[ns]': 'datetime', | |
| 'datetime64[ms]': 'datetime', | |
| 'category': 'str' | |
| } | |
| return type_mapping.get(pandas_type, 'str') | |
| def _create_api_structure(self, output_dir: Path, framework: str): | |
| """Crea la estructura de directorios de la API""" | |
| directories = [ | |
| output_dir / "app", | |
| output_dir / "app" / "api", | |
| output_dir / "tests", | |
| ] | |
| for directory in directories: | |
| directory.mkdir(parents=True, exist_ok=True) | |
| def _analyze_data_for_endpoints(self, data_profile: Any) -> List[APIEndpoint]: | |
| """Analiza los datos para generar endpoints automáticamente""" | |
| endpoints = [] | |
| # Detectar entidades principales basadas en nombres de columnas | |
| entities = self._detect_entities(data_profile) | |
| for entity in entities: | |
| entity_name = entity["name"] | |
| entity_columns = entity["columns"] | |
| # Endpoint para listar todos los registros | |
| endpoints.append(APIEndpoint( | |
| path=f"/api/{entity_name}/", | |
| method="GET", | |
| operation="list", | |
| description=f"Listar todos los {entity_name}", | |
| parameters=[ | |
| {"name": "skip", "type": "int", "default": 0, "description": "Número de registros a saltar"}, | |
| {"name": "limit", "type": "int", "default": 100, "description": "Número máximo de registros a retornar"} | |
| ] | |
| )) | |
| # Endpoint para obtener un registro por ID | |
| endpoints.append(APIEndpoint( | |
| path=f"/api/{entity_name}/{{item_id}}", | |
| method="GET", | |
| operation="read", | |
| description=f"Obtener un {entity_name} por ID", | |
| parameters=[ | |
| {"name": "item_id", "type": "int", "description": "ID del registro"} | |
| ] | |
| )) | |
| # Endpoint para crear nuevo registro | |
| endpoints.append(APIEndpoint( | |
| path=f"/api/{entity_name}/", | |
| method="POST", | |
| operation="create", | |
| description=f"Crear un nuevo {entity_name}", | |
| parameters=entity_columns | |
| )) | |
| # Endpoint para actualizar registro | |
| endpoints.append(APIEndpoint( | |
| path=f"/api/{entity_name}/{{item_id}}", | |
| method="PUT", | |
| operation="update", | |
| description=f"Actualizar un {entity_name} existente", | |
| parameters=entity_columns | |
| )) | |
| # Endpoint para eliminar registro | |
| endpoints.append(APIEndpoint( | |
| path=f"/api/{entity_name}/{{item_id}}", | |
| method="DELETE", | |
| operation="delete", | |
| description=f"Eliminar un {entity_name}", | |
| parameters=[ | |
| {"name": "item_id", "type": "int", "description": "ID del registro a eliminar"} | |
| ] | |
| )) | |
| return endpoints | |
| def _detect_entities(self, data_profile: Any) -> List[Dict[str, Any]]: | |
| """Detecta entidades automáticamente basado en el perfil de datos""" | |
| entities = [] | |
| # Obtener información de columnas REAL | |
| columns_info = self._get_columns_info(data_profile) | |
| if columns_info: | |
| columns = [] | |
| for col_name, col_info in columns_info.items(): | |
| column_def = { | |
| "name": col_name, | |
| "type": col_info['python_type'], | |
| "required": not col_info['nullable'], | |
| "description": f"Campo {col_name} - Tipo: {col_info['type']}", | |
| "sql_type": col_info['sql_type'] | |
| } | |
| columns.append(column_def) | |
| # Detectar primary key | |
| primary_key = self._detect_primary_key(data_profile) | |
| entities.append({ | |
| "name": "items", # Nombre por defecto | |
| "columns": columns, | |
| "primary_key": primary_key, | |
| "total_columns": len(columns) | |
| }) | |
| return entities | |
| def _detect_primary_key(self, data_profile: Any) -> str: | |
| """Detecta la columna que probablemente sea la primary key - MEJORADO""" | |
| try: | |
| if hasattr(data_profile, 'current_data') and data_profile.current_data is not None: | |
| df = data_profile.current_data | |
| elif hasattr(data_profile, 'columns') and hasattr(data_profile, 'dtypes'): | |
| df = data_profile | |
| else: | |
| return "id" # Por defecto | |
| # Buscar columnas que sean buenas candidatas a PK | |
| for col_name in df.columns: | |
| col_lower = col_name.lower() | |
| # Criterios para ser primary key | |
| is_id_like = any(keyword in col_lower for keyword in ['id', 'code', 'key', 'pk']) | |
| is_unique = df[col_name].nunique() == len(df) | |
| has_no_nulls = not df[col_name].isnull().any() | |
| if is_id_like and is_unique and has_no_nulls: | |
| logger.info(f"🔑 Primary key detectada: {col_name}") | |
| return col_name | |
| # Si no se encuentra, usar la primera columna única | |
| for col_name in df.columns: | |
| if df[col_name].nunique() == len(df) and not df[col_name].isnull().any(): | |
| logger.info(f"🔑 Primary key alternativa detectada: {col_name}") | |
| return col_name | |
| # Por defecto, usar 'id' | |
| return "id" | |
| except Exception as e: | |
| logger.warning(f"⚠️ Error detectando primary key: {e}") | |
| return "id" | |
| def _generate_fastapi_files(self, endpoints: List[APIEndpoint], | |
| api_config: APIConfig, output_dir: Path, | |
| columns_info: Dict, data_profile: Any) -> List[str]: | |
| """Genera los archivos específicos de FastAPI CON DATOS REALES""" | |
| generated_files = [] | |
| # Contexto para plantillas - INCLUYENDO INFORMACIÓN REAL DE COLUMNAS | |
| context = { | |
| "project_name": api_config.project_name, | |
| "version": api_config.version, | |
| "endpoints": endpoints, | |
| "authentication": api_config.authentication, | |
| "pagination": api_config.pagination, | |
| "database": api_config.database, | |
| # INFORMACIÓN REAL DE DATOS - CLAVE PARA QUE FUNCIONE | |
| "columns": columns_info, | |
| "columns_info": columns_info, # alias para compatibilidad | |
| "primary_key": self._detect_primary_key(data_profile), | |
| "total_columns": len(columns_info), | |
| "has_data": len(columns_info) > 0 | |
| } | |
| # Archivos a generar | |
| templates_to_generate = { | |
| "main.py.j2": "app/main.py", | |
| "models.py.j2": "app/models.py", | |
| "schemas.py.j2": "app/schemas.py", | |
| "database.py.j2": "app/database.py", | |
| "api_endpoints.py.j2": "app/api/api.py", | |
| "requirements.txt.j2": "requirements.txt", | |
| "Dockerfile.j2": "Dockerfile", | |
| "README.md.j2": "README.md" | |
| } | |
| for template_name, output_path in templates_to_generate.items(): | |
| try: | |
| template = self.env.get_template(template_name) | |
| content = template.render(**context) # Usar ** para expandir el contexto | |
| file_path = output_dir / output_path | |
| file_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(content) | |
| generated_files.append(str(file_path)) | |
| logger.info(f"✅ Generado: {file_path}") | |
| except Exception as e: | |
| logger.error(f"❌ Error generando {template_name}: {e}") | |
| # Crear archivo básico como fallback | |
| self._create_fallback_file(file_path, template_name) | |
| return generated_files | |
| def _create_fallback_file(self, file_path: Path, template_name: str): | |
| """Crea un archivo básico como fallback si la plantilla falla""" | |
| try: | |
| if template_name == "models.py.j2": | |
| content = """from sqlalchemy import Column, Integer, String, Text, DateTime | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from datetime import datetime | |
| Base = declarative_base() | |
| class Item(Base): | |
| __tablename__ = "items" | |
| id = Column(Integer, primary_key=True, index=True) | |
| nombre = Column(String(100)) | |
| descripcion = Column(Text) | |
| created_at = Column(DateTime, default=datetime.utcnow) | |
| """ | |
| elif template_name == "schemas.py.j2": | |
| content = """from pydantic import BaseModel | |
| from datetime import datetime | |
| from typing import Optional | |
| class ItemBase(BaseModel): | |
| nombre: str | |
| descripcion: Optional[str] = None | |
| class ItemCreate(ItemBase): | |
| pass | |
| class ItemUpdate(ItemBase): | |
| pass | |
| class Item(ItemBase): | |
| id: int | |
| created_at: datetime | |
| class Config: | |
| from_attributes = True | |
| """ | |
| else: | |
| content = f"# Fallback para {template_name}\n# Error al generar plantilla" | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(content) | |
| logger.info(f"📄 Archivo fallback creado: {file_path}") | |
| except Exception as e: | |
| logger.error(f"❌ Error creando archivo fallback: {e}") | |
| # Función de conveniencia | |
| def create_api_factory() -> APIFactory: | |
| """Crea una instancia del factory de APIs""" | |
| return APIFactory() | |