""" Enhanced FastAPI server with high-performance Polars/DuckDB transformation engine. Implements the ERP to CDF transformation logic with auto-detection capabilities. """ import logging import tempfile import os from pathlib import Path from typing import Dict, Any, Optional, List from fastapi import FastAPI, File, UploadFile, Form, HTTPException, BackgroundTasks from fastapi.responses import JSONResponse, FileResponse, RedirectResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field import uvicorn from dotenv import load_dotenv # Load environment variables load_dotenv() from mapper.transformation_engine import ( TransformationEngine, TransformationRequest, TransformationMode ) from mapper.transformation_engine_pure import PureTransformationEngine from mapper.data_processor import FileFormat from mapper.models import EntityType # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize FastAPI app (Swagger UI at /docs, ReDoc at /redoc) app = FastAPI( title="ERP to CDF Transformation API v2.0", description="High-performance ERP data transformation using Polars and DuckDB", version="2.0.0", docs_url="/docs", redoc_url="/redoc", swagger_ui_parameters={ "persistAuthorization": True, # keep auth between reloads "displayRequestDuration": True, # show request timings "defaultModelsExpandDepth": -1 # collapse the schemas panel } ) # Make Swagger UI the home page @app.get("/", include_in_schema=False) def home(): return RedirectResponse(url="/docs") # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Initialize transformation engines transformation_engine = TransformationEngine() pure_transformation_engine = PureTransformationEngine() # --------------------------- # Pydantic models for API # --------------------------- class TransformationRequestModel(BaseModel): """API model for transformation requests.""" auto_select_erp: bool = Field(True, description="Auto-detect ERP system") auto_select_entity: bool = Field(True, description="Auto-detect entity type") entity: Optional[str] = Field(None, description="Entity type (if known)") erp: Optional[str] = Field(None, description="ERP system (if known)") data: Optional[List[Dict[str, Any]]] = Field(None, description="JSON data (alternative to file)") class TransformationResponseModel(BaseModel): """API model for transformation responses.""" success: bool data: Optional[List[Dict[str, Any]]] = None detected_erp: Optional[str] = None detected_entity: Optional[str] = None transformation_mode: Optional[str] = None confidence_score: Optional[float] = None message: Optional[str] = None column_mappings: Optional[Dict[str, str]] = None row_count: Optional[int] = None processing_time_ms: Optional[float] = None class AnalysisResponseModel(BaseModel): """API model for data analysis responses.""" column_info: Dict[str, Any] erp_entity_suggestions: List[Dict[str, Any]] available_entities: List[str] available_erps: List[str] processing_time_ms: Optional[float] = None # --------------------------- # Health / Info endpoints # --------------------------- @app.get("/health", tags=["Health"]) async def health_check(): """Health check endpoint.""" return {"status": "healthy", "version": "2.0.0", "engine": "Polars + DuckDB"} @app.get("/entities", response_model=List[str], tags=["Information"]) async def get_entities(): """Get list of supported entity types.""" return [entity.value for entity in EntityType] @app.get("/erps", response_model=List[str], tags=["Information"]) async def get_erps(): """Get list of supported ERP systems.""" return transformation_engine.template_loader.get_erp_names() @app.get("/formats", response_model=List[str], tags=["Information"]) async def get_supported_formats(): """Get list of supported file formats.""" return [format.value for format in FileFormat] @app.get("/formats/processing", tags=["Information"]) async def get_format_processing_methods(): """Get processing methods for each file format (in-memory vs temp-file).""" processing_info = {} for format in FileFormat: method = transformation_engine.data_processor.get_processing_method(format) processing_info[format.value] = { "processing_method": method, "description": { "in-memory": "Fast, secure processing without temporary files", "temp-file": "Reliable processing using temporary files for complex formats" }.get(method, "Unknown processing method") } return { "formats": processing_info, "summary": { "in_memory_formats": [f.value for f in FileFormat if transformation_engine.data_processor.get_processing_method(f) == 'in-memory'], "temp_file_formats": [f.value for f in FileFormat if transformation_engine.data_processor.get_processing_method(f) == 'temp-file'] } } # --------------------------- # Core transformation endpoints (Original) # --------------------------- @app.post("/transform", response_model=TransformationResponseModel, tags=["Transformation"]) async def transform_data(request: TransformationRequestModel): """Transform JSON data to CDF format. This endpoint accepts JSON data directly and transforms it according to the request parameters. Uses completely in-memory processing for better performance and security. """ import time start_time = time.time() try: if not request.data: raise HTTPException(status_code=400, detail="No data provided") # Convert JSON data to bytes for in-memory processing (no temp files) import json json_bytes = json.dumps(request.data).encode('utf-8') # Create transformation request with bytes data transform_request = TransformationRequest( auto_select_erp=request.auto_select_erp, auto_select_entity=request.auto_select_entity, entity=request.entity, erp=request.erp, file_data=json_bytes, file_format=FileFormat.JSON ) # Perform transformation (completely in-memory for JSON) result = transformation_engine.transform(transform_request) # Convert result to API response response_data = None if result.success and result.data is not None: response_data = transformation_engine.data_processor.to_dict(result.data) processing_time = (time.time() - start_time) * 1000 return TransformationResponseModel( success=result.success, data=response_data, detected_erp=result.detected_erp, detected_entity=result.detected_entity, transformation_mode=result.transformation_mode.value if result.transformation_mode else None, confidence_score=result.confidence_score, message=result.message, column_mappings=result.column_mappings, row_count=len(response_data) if response_data else 0, processing_time_ms=processing_time ) except Exception as e: logger.error(f"Transform data failed: {e}") raise HTTPException(status_code=500, detail=f"Transformation failed: {str(e)}") @app.post("/transform/file", response_model=TransformationResponseModel, tags=["Transformation"]) async def transform_file( file: UploadFile = File(..., description="File to transform"), auto_select_erp: bool = Form(True, description="Auto-detect ERP system"), auto_select_entity: bool = Form(True, description="Auto-detect entity type"), entity: Optional[str] = Form(None, description="Entity type (if known)"), erp: Optional[str] = Form(None, description="ERP system (if known)"), output_format: str = Form("json", description="Output format (json, csv, parquet)") ): """Transform uploaded file to CDF format. This endpoint accepts file uploads and transforms them according to the request parameters. Supports CSV, Excel, JSON, and SQL files. """ import time start_time = time.time() try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Create transformation request transform_request = TransformationRequest( auto_select_erp=auto_select_erp, auto_select_entity=auto_select_entity, entity=entity, erp=erp, file_data=file_content, file_format=file_format ) # Perform transformation result = transformation_engine.transform(transform_request) # Convert result to API response response_data = None if result.success and result.data is not None: response_data = transformation_engine.data_processor.to_dict(result.data) processing_time = (time.time() - start_time) * 1000 return TransformationResponseModel( success=result.success, data=response_data, detected_erp=result.detected_erp, detected_entity=result.detected_entity, transformation_mode=result.transformation_mode.value if result.transformation_mode else None, confidence_score=result.confidence_score, message=result.message, column_mappings=result.column_mappings, row_count=len(response_data) if response_data else 0, processing_time_ms=processing_time ) except Exception as e: logger.error(f"Transform file failed: {e}") raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}") @app.post("/transform/file/download", tags=["Transformation"]) async def transform_file_download( background_tasks: BackgroundTasks, file: UploadFile = File(..., description="File to transform"), auto_select_erp: bool = Form(True, description="Auto-detect ERP system"), auto_select_entity: bool = Form(True, description="Auto-detect entity type"), entity: Optional[str] = Form(None, description="Entity type (if known)"), erp: Optional[str] = Form(None, description="ERP system (if known)"), output_format: str = Form("csv", description="Output format (csv, json, parquet)") ): """Transform uploaded file and return as downloadable file. This endpoint transforms the file and returns the result as a downloadable file. """ try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Create transformation request transform_request = TransformationRequest( auto_select_erp=auto_select_erp, auto_select_entity=auto_select_entity, entity=entity, erp=erp, file_data=file_content, file_format=file_format ) # Perform transformation result = transformation_engine.transform(transform_request) if not result.success: raise HTTPException(status_code=400, detail=result.message) # Create output file output_format_enum = FileFormat(output_format.lower()) output_filename = f"transformed_{Path(file.filename).stem}_cdf.{output_format}" with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file: temp_path = temp_file.name # Export transformed data transformation_engine.data_processor.export_dataframe( result.data, temp_path, output_format_enum ) # Schedule cleanup background_tasks.add_task(cleanup_temp_file, temp_path) return FileResponse( path=temp_path, filename=output_filename, media_type="application/octet-stream" ) except Exception as e: logger.error(f"Transform file download failed: {e}") raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}") # --------------------------- # Pure LLM transformation endpoints (NEW) # --------------------------- @app.post("/llm_pure/transform", response_model=TransformationResponseModel, tags=["Pure LLM Transformation"]) async def pure_llm_transform_data(request: TransformationRequestModel): """Transform JSON data to CDF format using Pure LLM approach. This endpoint uses only LLM-based mapping when ERP or Entity is unknown, with enhanced template context and 5 retry attempts. """ import time start_time = time.time() try: if not request.data: raise HTTPException(status_code=400, detail="No data provided") # Convert JSON data to bytes for in-memory processing import json json_bytes = json.dumps(request.data).encode('utf-8') # Create transformation request with bytes data transform_request = TransformationRequest( auto_select_erp=request.auto_select_erp, auto_select_entity=request.auto_select_entity, entity=request.entity, erp=request.erp, file_data=json_bytes, file_format=FileFormat.JSON ) # Perform Pure LLM transformation result = pure_transformation_engine.transform(transform_request) # Convert result to API response response_data = None if result.success and result.data is not None: response_data = pure_transformation_engine.data_processor.to_dict(result.data) processing_time = (time.time() - start_time) * 1000 return TransformationResponseModel( success=result.success, data=response_data, detected_erp=result.detected_erp, detected_entity=result.detected_entity, transformation_mode=result.transformation_mode.value if result.transformation_mode else None, confidence_score=result.confidence_score, message=result.message, column_mappings=result.column_mappings, row_count=len(response_data) if response_data else 0, processing_time_ms=processing_time ) except Exception as e: logger.error(f"Pure LLM transform data failed: {e}") raise HTTPException(status_code=500, detail=f"Pure LLM transformation failed: {str(e)}") @app.post("/llm_pure/transform/file", response_model=TransformationResponseModel, tags=["Pure LLM Transformation"]) async def pure_llm_transform_file( file: UploadFile = File(..., description="File to transform"), auto_select_erp: bool = Form(True, description="Auto-detect ERP system"), auto_select_entity: bool = Form(True, description="Auto-detect entity type"), entity: Optional[str] = Form(None, description="Entity type (if known)"), erp: Optional[str] = Form(None, description="ERP system (if known)"), output_format: str = Form("json", description="Output format (json, csv, parquet)") ): """Transform uploaded file to CDF format using Pure LLM approach. This endpoint uses only LLM-based mapping when ERP or Entity is unknown, with enhanced template context and 5 retry attempts. """ import time start_time = time.time() try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Create transformation request transform_request = TransformationRequest( auto_select_erp=auto_select_erp, auto_select_entity=auto_select_entity, entity=entity, erp=erp, file_data=file_content, file_format=file_format ) # Perform Pure LLM transformation result = pure_transformation_engine.transform(transform_request) # Convert result to API response response_data = None if result.success and result.data is not None: response_data = pure_transformation_engine.data_processor.to_dict(result.data) processing_time = (time.time() - start_time) * 1000 return TransformationResponseModel( success=result.success, data=response_data, detected_erp=result.detected_erp, detected_entity=result.detected_entity, transformation_mode=result.transformation_mode.value if result.transformation_mode else None, confidence_score=result.confidence_score, message=result.message, column_mappings=result.column_mappings, row_count=len(response_data) if response_data else 0, processing_time_ms=processing_time ) except Exception as e: logger.error(f"Pure LLM transform file failed: {e}") raise HTTPException(status_code=500, detail=f"Pure LLM file transformation failed: {str(e)}") @app.post("/llm_pure/transform/file/download", tags=["Pure LLM Transformation"]) async def pure_llm_transform_file_download( background_tasks: BackgroundTasks, file: UploadFile = File(..., description="File to transform"), auto_select_erp: bool = Form(True, description="Auto-detect ERP system"), auto_select_entity: bool = Form(True, description="Auto-detect entity type"), entity: Optional[str] = Form(None, description="Entity type (if known)"), erp: Optional[str] = Form(None, description="ERP system (if known)"), output_format: str = Form("csv", description="Output format (csv, json, parquet)") ): """Transform uploaded file and return as downloadable file using Pure LLM approach. This endpoint uses only LLM-based mapping when ERP or Entity is unknown, with enhanced template context and 5 retry attempts. """ try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Create transformation request transform_request = TransformationRequest( auto_select_erp=auto_select_erp, auto_select_entity=auto_select_entity, entity=entity, erp=erp, file_data=file_content, file_format=file_format ) # Perform Pure LLM transformation result = pure_transformation_engine.transform(transform_request) if not result.success: raise HTTPException(status_code=400, detail=result.message) # Create output file output_format_enum = FileFormat(output_format.lower()) output_filename = f"pure_llm_transformed_{Path(file.filename).stem}_cdf.{output_format}" with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file: temp_path = temp_file.name # Export transformed data pure_transformation_engine.data_processor.export_dataframe( result.data, temp_path, output_format_enum ) # Schedule cleanup background_tasks.add_task(cleanup_temp_file, temp_path) return FileResponse( path=temp_path, filename=output_filename, media_type="application/octet-stream" ) except Exception as e: logger.error(f"Pure LLM transform file download failed: {e}") raise HTTPException(status_code=500, detail=f"Pure LLM file transformation failed: {str(e)}") # --------------------------- # Analysis / Validation # --------------------------- @app.post("/analyze", response_model=AnalysisResponseModel, tags=["Analysis"]) async def analyze_data(file: UploadFile = File(..., description="File to analyze")): """Analyze uploaded file and provide insights. This endpoint analyzes the file structure and suggests possible ERP/entity combinations. """ import time start_time = time.time() try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Analyze data analysis_result = transformation_engine.analyze_data(file_content, file_format) if "error" in analysis_result: raise HTTPException(status_code=400, detail=analysis_result["error"]) processing_time = (time.time() - start_time) * 1000 analysis_result["processing_time_ms"] = processing_time return AnalysisResponseModel(**analysis_result) except Exception as e: logger.error(f"Analyze data failed: {e}") raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}") @app.post("/llm_pure/analyze", response_model=AnalysisResponseModel, tags=["Pure LLM Analysis"]) async def pure_llm_analyze_data(file: UploadFile = File(..., description="File to analyze")): """Analyze uploaded file using Pure LLM approach. This endpoint analyzes the file structure for Pure LLM transformation. """ import time start_time = time.time() try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Analyze data using Pure LLM engine analysis_result = pure_transformation_engine.analyze_data(file_content, file_format) if "error" in analysis_result: raise HTTPException(status_code=400, detail=analysis_result["error"]) processing_time = (time.time() - start_time) * 1000 analysis_result["processing_time_ms"] = processing_time return AnalysisResponseModel(**analysis_result) except Exception as e: logger.error(f"Pure LLM analyze data failed: {e}") raise HTTPException(status_code=500, detail=f"Pure LLM analysis failed: {str(e)}") @app.post("/validate", tags=["Validation"]) async def validate_data(file: UploadFile = File(..., description="File to validate")): """Validate file structure and content. This endpoint validates the file can be loaded and provides basic statistics. """ try: # Read file content file_content = await file.read() # Detect file format file_extension = Path(file.filename).suffix.lower() format_mapping = { '.csv': FileFormat.CSV, '.xlsx': FileFormat.EXCEL, '.xls': FileFormat.EXCEL, '.json': FileFormat.JSON, '.sql': FileFormat.SQL, '.parquet': FileFormat.PARQUET } if file_extension not in format_mapping: raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}") file_format = format_mapping[file_extension] # Load and validate data df = transformation_engine.data_processor.load_from_bytes(file_content, file_format, file.filename) # Get column info column_info = transformation_engine.data_processor.get_column_info(df) return { "valid": True, "file_format": file_format.value, "column_info": column_info, "message": "File is valid and can be processed" } except Exception as e: logger.error(f"Validate data failed: {e}") return { "valid": False, "error": str(e), "message": "File validation failed" } # --------------------------- # Template utilities # --------------------------- @app.get("/template/erp/{erp}/entity/{entity}", tags=["Template"]) async def get_template_mapping(erp: str, entity: str): """Get template mapping for specific ERP and entity.""" try: mapping = transformation_engine.template_loader.get_entity_mapping(erp, entity) if not mapping: raise HTTPException(status_code=404, detail=f"No mapping found for {erp} -> {entity}") return { "erp": erp, "entity": entity, "mapping": mapping, "cdf_schema": transformation_engine.template_loader.get_cdf_schema(entity) } except Exception as e: logger.error(f"Get template mapping failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/template/entity/{entity}/schema", tags=["Template"]) async def get_entity_schema(entity: str): """Get CDF schema for specific entity.""" try: schema = transformation_engine.template_loader.get_cdf_schema(entity) return { "entity": entity, "cdf_schema": schema, "field_count": len(schema) } except Exception as e: logger.error(f"Get entity schema failed: {e}") raise HTTPException(status_code=500, detail=str(e)) # --------------------------- # Background task for cleanup # --------------------------- def cleanup_temp_file(file_path: str): """Clean up temporary file.""" try: os.unlink(file_path) logger.info(f"Cleaned up temporary file: {file_path}") except OSError as e: logger.warning(f"Failed to clean up temporary file {file_path}: {e}") # --------------------------- # Startup / Shutdown # --------------------------- @app.on_event("startup") async def startup_event(): """Startup event handler.""" logger.info("ERP to CDF Transformation API v2.0 starting up...") logger.info(f"Supported ERP systems: {len(transformation_engine.template_loader.get_erp_names())}") logger.info(f"Supported entities: {len([e.value for e in EntityType])}") logger.info("Pure LLM transformation engine initialized") logger.info("API ready for high-performance transformations!") @app.on_event("shutdown") async def shutdown_event(): """Shutdown event handler.""" logger.info("ERP to CDF Transformation API v2.0 shutting down...") transformation_engine.close() pure_transformation_engine.close() logger.info("Shutdown complete.") # --------------------------- # Main entry point # --------------------------- if __name__ == "__main__": uvicorn.run( "app:app", host="127.0.0.1", port=8000, reload=True, log_level="info" )