Spaces:
Runtime error
Runtime error
Commit ·
0f0b6c8
1
Parent(s): 3d8755c
UI fix
Browse files
app.py
CHANGED
|
@@ -7,9 +7,9 @@ import logging
|
|
| 7 |
import tempfile
|
| 8 |
import os
|
| 9 |
from pathlib import Path
|
| 10 |
-
from typing import Dict, Any, Optional, List
|
| 11 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, BackgroundTasks
|
| 12 |
-
from fastapi.responses import JSONResponse, FileResponse
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from pydantic import BaseModel, Field
|
| 15 |
import uvicorn
|
|
@@ -19,8 +19,8 @@ from dotenv import load_dotenv
|
|
| 19 |
load_dotenv()
|
| 20 |
|
| 21 |
from mapper.transformation_engine import (
|
| 22 |
-
TransformationEngine,
|
| 23 |
-
TransformationRequest,
|
| 24 |
TransformationMode
|
| 25 |
)
|
| 26 |
from mapper.data_processor import FileFormat
|
|
@@ -30,15 +30,25 @@ from mapper.models import EntityType
|
|
| 30 |
logging.basicConfig(level=logging.INFO)
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
| 33 |
-
# Initialize FastAPI app
|
| 34 |
app = FastAPI(
|
| 35 |
title="ERP to CDF Transformation API v2.0",
|
| 36 |
description="High-performance ERP data transformation using Polars and DuckDB",
|
| 37 |
version="2.0.0",
|
| 38 |
docs_url="/docs",
|
| 39 |
-
redoc_url="/redoc"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
)
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
# Add CORS middleware
|
| 43 |
app.add_middleware(
|
| 44 |
CORSMiddleware,
|
|
@@ -51,8 +61,10 @@ app.add_middleware(
|
|
| 51 |
# Initialize transformation engine
|
| 52 |
transformation_engine = TransformationEngine()
|
| 53 |
|
| 54 |
-
|
| 55 |
# Pydantic models for API
|
|
|
|
|
|
|
| 56 |
class TransformationRequestModel(BaseModel):
|
| 57 |
"""API model for transformation requests."""
|
| 58 |
auto_select_erp: bool = Field(True, description="Auto-detect ERP system")
|
|
@@ -85,14 +97,16 @@ class AnalysisResponseModel(BaseModel):
|
|
| 85 |
processing_time_ms: Optional[float] = None
|
| 86 |
|
| 87 |
|
| 88 |
-
#
|
|
|
|
|
|
|
|
|
|
| 89 |
@app.get("/health", tags=["Health"])
|
| 90 |
async def health_check():
|
| 91 |
"""Health check endpoint."""
|
| 92 |
return {"status": "healthy", "version": "2.0.0", "engine": "Polars + DuckDB"}
|
| 93 |
|
| 94 |
|
| 95 |
-
# Information endpoints
|
| 96 |
@app.get("/entities", response_model=List[str], tags=["Information"])
|
| 97 |
async def get_entities():
|
| 98 |
"""Get list of supported entity types."""
|
|
@@ -111,26 +125,29 @@ async def get_supported_formats():
|
|
| 111 |
return [format.value for format in FileFormat]
|
| 112 |
|
| 113 |
|
|
|
|
| 114 |
# Core transformation endpoints
|
|
|
|
|
|
|
| 115 |
@app.post("/transform", response_model=TransformationResponseModel, tags=["Transformation"])
|
| 116 |
async def transform_data(request: TransformationRequestModel):
|
| 117 |
"""Transform JSON data to CDF format.
|
| 118 |
-
|
| 119 |
This endpoint accepts JSON data directly and transforms it according to the request parameters.
|
| 120 |
"""
|
| 121 |
import time
|
| 122 |
start_time = time.time()
|
| 123 |
-
|
| 124 |
try:
|
| 125 |
if not request.data:
|
| 126 |
raise HTTPException(status_code=400, detail="No data provided")
|
| 127 |
-
|
| 128 |
# Create temporary JSON file
|
| 129 |
import json
|
| 130 |
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as temp_file:
|
| 131 |
json.dump(request.data, temp_file)
|
| 132 |
temp_path = temp_file.name
|
| 133 |
-
|
| 134 |
try:
|
| 135 |
# Create transformation request
|
| 136 |
transform_request = TransformationRequest(
|
|
@@ -141,17 +158,17 @@ async def transform_data(request: TransformationRequestModel):
|
|
| 141 |
file_data=temp_path,
|
| 142 |
file_format=FileFormat.JSON
|
| 143 |
)
|
| 144 |
-
|
| 145 |
# Perform transformation
|
| 146 |
result = transformation_engine.transform(transform_request)
|
| 147 |
-
|
| 148 |
# Convert result to API response
|
| 149 |
response_data = None
|
| 150 |
if result.success and result.data is not None:
|
| 151 |
response_data = transformation_engine.data_processor.to_dict(result.data)
|
| 152 |
-
|
| 153 |
processing_time = (time.time() - start_time) * 1000
|
| 154 |
-
|
| 155 |
return TransformationResponseModel(
|
| 156 |
success=result.success,
|
| 157 |
data=response_data,
|
|
@@ -164,14 +181,14 @@ async def transform_data(request: TransformationRequestModel):
|
|
| 164 |
row_count=len(response_data) if response_data else 0,
|
| 165 |
processing_time_ms=processing_time
|
| 166 |
)
|
| 167 |
-
|
| 168 |
finally:
|
| 169 |
# Clean up temporary file
|
| 170 |
try:
|
| 171 |
os.unlink(temp_path)
|
| 172 |
except OSError:
|
| 173 |
pass
|
| 174 |
-
|
| 175 |
except Exception as e:
|
| 176 |
logger.error(f"Transform data failed: {e}")
|
| 177 |
raise HTTPException(status_code=500, detail=f"Transformation failed: {str(e)}")
|
|
@@ -187,17 +204,17 @@ async def transform_file(
|
|
| 187 |
output_format: str = Form("json", description="Output format (json, csv, parquet)")
|
| 188 |
):
|
| 189 |
"""Transform uploaded file to CDF format.
|
| 190 |
-
|
| 191 |
This endpoint accepts file uploads and transforms them according to the request parameters.
|
| 192 |
Supports CSV, Excel, JSON, and SQL files.
|
| 193 |
"""
|
| 194 |
import time
|
| 195 |
start_time = time.time()
|
| 196 |
-
|
| 197 |
try:
|
| 198 |
# Read file content
|
| 199 |
file_content = await file.read()
|
| 200 |
-
|
| 201 |
# Detect file format
|
| 202 |
file_extension = Path(file.filename).suffix.lower()
|
| 203 |
format_mapping = {
|
|
@@ -207,12 +224,12 @@ async def transform_file(
|
|
| 207 |
'.json': FileFormat.JSON,
|
| 208 |
'.sql': FileFormat.SQL
|
| 209 |
}
|
| 210 |
-
|
| 211 |
if file_extension not in format_mapping:
|
| 212 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 213 |
-
|
| 214 |
file_format = format_mapping[file_extension]
|
| 215 |
-
|
| 216 |
# Create transformation request
|
| 217 |
transform_request = TransformationRequest(
|
| 218 |
auto_select_erp=auto_select_erp,
|
|
@@ -222,17 +239,17 @@ async def transform_file(
|
|
| 222 |
file_data=file_content,
|
| 223 |
file_format=file_format
|
| 224 |
)
|
| 225 |
-
|
| 226 |
# Perform transformation
|
| 227 |
result = transformation_engine.transform(transform_request)
|
| 228 |
-
|
| 229 |
# Convert result to API response
|
| 230 |
response_data = None
|
| 231 |
if result.success and result.data is not None:
|
| 232 |
response_data = transformation_engine.data_processor.to_dict(result.data)
|
| 233 |
-
|
| 234 |
processing_time = (time.time() - start_time) * 1000
|
| 235 |
-
|
| 236 |
return TransformationResponseModel(
|
| 237 |
success=result.success,
|
| 238 |
data=response_data,
|
|
@@ -245,7 +262,7 @@ async def transform_file(
|
|
| 245 |
row_count=len(response_data) if response_data else 0,
|
| 246 |
processing_time_ms=processing_time
|
| 247 |
)
|
| 248 |
-
|
| 249 |
except Exception as e:
|
| 250 |
logger.error(f"Transform file failed: {e}")
|
| 251 |
raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")
|
|
@@ -262,13 +279,13 @@ async def transform_file_download(
|
|
| 262 |
output_format: str = Form("csv", description="Output format (csv, json, parquet)")
|
| 263 |
):
|
| 264 |
"""Transform uploaded file and return as downloadable file.
|
| 265 |
-
|
| 266 |
This endpoint transforms the file and returns the result as a downloadable file.
|
| 267 |
"""
|
| 268 |
try:
|
| 269 |
# Read file content
|
| 270 |
file_content = await file.read()
|
| 271 |
-
|
| 272 |
# Detect file format
|
| 273 |
file_extension = Path(file.filename).suffix.lower()
|
| 274 |
format_mapping = {
|
|
@@ -279,12 +296,12 @@ async def transform_file_download(
|
|
| 279 |
'.sql': FileFormat.SQL,
|
| 280 |
'.parquet': FileFormat.PARQUET
|
| 281 |
}
|
| 282 |
-
|
| 283 |
if file_extension not in format_mapping:
|
| 284 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 285 |
-
|
| 286 |
file_format = format_mapping[file_extension]
|
| 287 |
-
|
| 288 |
# Create transformation request
|
| 289 |
transform_request = TransformationRequest(
|
| 290 |
auto_select_erp=auto_select_erp,
|
|
@@ -294,52 +311,56 @@ async def transform_file_download(
|
|
| 294 |
file_data=file_content,
|
| 295 |
file_format=file_format
|
| 296 |
)
|
| 297 |
-
|
| 298 |
# Perform transformation
|
| 299 |
result = transformation_engine.transform(transform_request)
|
| 300 |
-
|
| 301 |
if not result.success:
|
| 302 |
raise HTTPException(status_code=400, detail=result.message)
|
| 303 |
-
|
| 304 |
# Create output file
|
| 305 |
output_format_enum = FileFormat(output_format.lower())
|
| 306 |
output_filename = f"transformed_{Path(file.filename).stem}_cdf.{output_format}"
|
| 307 |
-
|
| 308 |
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file:
|
| 309 |
temp_path = temp_file.name
|
| 310 |
-
|
| 311 |
# Export transformed data
|
| 312 |
transformation_engine.data_processor.export_dataframe(
|
| 313 |
result.data, temp_path, output_format_enum
|
| 314 |
)
|
| 315 |
-
|
| 316 |
# Schedule cleanup
|
| 317 |
background_tasks.add_task(cleanup_temp_file, temp_path)
|
| 318 |
-
|
| 319 |
return FileResponse(
|
| 320 |
path=temp_path,
|
| 321 |
filename=output_filename,
|
| 322 |
media_type="application/octet-stream"
|
| 323 |
)
|
| 324 |
-
|
| 325 |
except Exception as e:
|
| 326 |
logger.error(f"Transform file download failed: {e}")
|
| 327 |
raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")
|
| 328 |
|
| 329 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
@app.post("/analyze", response_model=AnalysisResponseModel, tags=["Analysis"])
|
| 331 |
async def analyze_data(file: UploadFile = File(..., description="File to analyze")):
|
| 332 |
"""Analyze uploaded file and provide insights.
|
| 333 |
-
|
| 334 |
This endpoint analyzes the file structure and suggests possible ERP/entity combinations.
|
| 335 |
"""
|
| 336 |
import time
|
| 337 |
start_time = time.time()
|
| 338 |
-
|
| 339 |
try:
|
| 340 |
# Read file content
|
| 341 |
file_content = await file.read()
|
| 342 |
-
|
| 343 |
# Detect file format
|
| 344 |
file_extension = Path(file.filename).suffix.lower()
|
| 345 |
format_mapping = {
|
|
@@ -350,23 +371,23 @@ async def analyze_data(file: UploadFile = File(..., description="File to analyze
|
|
| 350 |
'.sql': FileFormat.SQL,
|
| 351 |
'.parquet': FileFormat.PARQUET
|
| 352 |
}
|
| 353 |
-
|
| 354 |
if file_extension not in format_mapping:
|
| 355 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 356 |
-
|
| 357 |
file_format = format_mapping[file_extension]
|
| 358 |
-
|
| 359 |
# Analyze data
|
| 360 |
analysis_result = transformation_engine.analyze_data(file_content, file_format)
|
| 361 |
-
|
| 362 |
if "error" in analysis_result:
|
| 363 |
raise HTTPException(status_code=400, detail=analysis_result["error"])
|
| 364 |
-
|
| 365 |
processing_time = (time.time() - start_time) * 1000
|
| 366 |
analysis_result["processing_time_ms"] = processing_time
|
| 367 |
-
|
| 368 |
return AnalysisResponseModel(**analysis_result)
|
| 369 |
-
|
| 370 |
except Exception as e:
|
| 371 |
logger.error(f"Analyze data failed: {e}")
|
| 372 |
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
|
|
@@ -375,13 +396,13 @@ async def analyze_data(file: UploadFile = File(..., description="File to analyze
|
|
| 375 |
@app.post("/validate", tags=["Validation"])
|
| 376 |
async def validate_data(file: UploadFile = File(..., description="File to validate")):
|
| 377 |
"""Validate file structure and content.
|
| 378 |
-
|
| 379 |
This endpoint validates the file can be loaded and provides basic statistics.
|
| 380 |
"""
|
| 381 |
try:
|
| 382 |
# Read file content
|
| 383 |
file_content = await file.read()
|
| 384 |
-
|
| 385 |
# Detect file format
|
| 386 |
file_extension = Path(file.filename).suffix.lower()
|
| 387 |
format_mapping = {
|
|
@@ -392,25 +413,25 @@ async def validate_data(file: UploadFile = File(..., description="File to valida
|
|
| 392 |
'.sql': FileFormat.SQL,
|
| 393 |
'.parquet': FileFormat.PARQUET
|
| 394 |
}
|
| 395 |
-
|
| 396 |
if file_extension not in format_mapping:
|
| 397 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 398 |
-
|
| 399 |
file_format = format_mapping[file_extension]
|
| 400 |
-
|
| 401 |
# Load and validate data
|
| 402 |
df = transformation_engine.data_processor.load_from_bytes(file_content, file_format, file.filename)
|
| 403 |
-
|
| 404 |
# Get column info
|
| 405 |
column_info = transformation_engine.data_processor.get_column_info(df)
|
| 406 |
-
|
| 407 |
return {
|
| 408 |
"valid": True,
|
| 409 |
"file_format": file_format.value,
|
| 410 |
"column_info": column_info,
|
| 411 |
"message": "File is valid and can be processed"
|
| 412 |
}
|
| 413 |
-
|
| 414 |
except Exception as e:
|
| 415 |
logger.error(f"Validate data failed: {e}")
|
| 416 |
return {
|
|
@@ -420,7 +441,10 @@ async def validate_data(file: UploadFile = File(..., description="File to valida
|
|
| 420 |
}
|
| 421 |
|
| 422 |
|
| 423 |
-
#
|
|
|
|
|
|
|
|
|
|
| 424 |
@app.get("/template/erp/{erp}/entity/{entity}", tags=["Template"])
|
| 425 |
async def get_template_mapping(erp: str, entity: str):
|
| 426 |
"""Get template mapping for specific ERP and entity."""
|
|
@@ -428,14 +452,14 @@ async def get_template_mapping(erp: str, entity: str):
|
|
| 428 |
mapping = transformation_engine.template_loader.get_entity_mapping(erp, entity)
|
| 429 |
if not mapping:
|
| 430 |
raise HTTPException(status_code=404, detail=f"No mapping found for {erp} -> {entity}")
|
| 431 |
-
|
| 432 |
return {
|
| 433 |
"erp": erp,
|
| 434 |
"entity": entity,
|
| 435 |
"mapping": mapping,
|
| 436 |
"cdf_schema": transformation_engine.template_loader.get_cdf_schema(entity)
|
| 437 |
}
|
| 438 |
-
|
| 439 |
except Exception as e:
|
| 440 |
logger.error(f"Get template mapping failed: {e}")
|
| 441 |
raise HTTPException(status_code=500, detail=str(e))
|
|
@@ -451,13 +475,16 @@ async def get_entity_schema(entity: str):
|
|
| 451 |
"cdf_schema": schema,
|
| 452 |
"field_count": len(schema)
|
| 453 |
}
|
| 454 |
-
|
| 455 |
except Exception as e:
|
| 456 |
logger.error(f"Get entity schema failed: {e}")
|
| 457 |
raise HTTPException(status_code=500, detail=str(e))
|
| 458 |
|
| 459 |
|
|
|
|
| 460 |
# Background task for cleanup
|
|
|
|
|
|
|
| 461 |
def cleanup_temp_file(file_path: str):
|
| 462 |
"""Clean up temporary file."""
|
| 463 |
try:
|
|
@@ -467,7 +494,10 @@ def cleanup_temp_file(file_path: str):
|
|
| 467 |
logger.warning(f"Failed to clean up temporary file {file_path}: {e}")
|
| 468 |
|
| 469 |
|
| 470 |
-
#
|
|
|
|
|
|
|
|
|
|
| 471 |
@app.on_event("startup")
|
| 472 |
async def startup_event():
|
| 473 |
"""Startup event handler."""
|
|
@@ -485,7 +515,10 @@ async def shutdown_event():
|
|
| 485 |
logger.info("Shutdown complete.")
|
| 486 |
|
| 487 |
|
|
|
|
| 488 |
# Main entry point
|
|
|
|
|
|
|
| 489 |
if __name__ == "__main__":
|
| 490 |
uvicorn.run(
|
| 491 |
"app:app",
|
|
|
|
| 7 |
import tempfile
|
| 8 |
import os
|
| 9 |
from pathlib import Path
|
| 10 |
+
from typing import Dict, Any, Optional, List
|
| 11 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, BackgroundTasks
|
| 12 |
+
from fastapi.responses import JSONResponse, FileResponse, RedirectResponse
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from pydantic import BaseModel, Field
|
| 15 |
import uvicorn
|
|
|
|
| 19 |
load_dotenv()
|
| 20 |
|
| 21 |
from mapper.transformation_engine import (
|
| 22 |
+
TransformationEngine,
|
| 23 |
+
TransformationRequest,
|
| 24 |
TransformationMode
|
| 25 |
)
|
| 26 |
from mapper.data_processor import FileFormat
|
|
|
|
| 30 |
logging.basicConfig(level=logging.INFO)
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
| 33 |
+
# Initialize FastAPI app (Swagger UI at /docs, ReDoc at /redoc)
|
| 34 |
app = FastAPI(
|
| 35 |
title="ERP to CDF Transformation API v2.0",
|
| 36 |
description="High-performance ERP data transformation using Polars and DuckDB",
|
| 37 |
version="2.0.0",
|
| 38 |
docs_url="/docs",
|
| 39 |
+
redoc_url="/redoc",
|
| 40 |
+
swagger_ui_parameters={
|
| 41 |
+
"persistAuthorization": True, # keep auth between reloads
|
| 42 |
+
"displayRequestDuration": True, # show request timings
|
| 43 |
+
"defaultModelsExpandDepth": -1 # collapse the schemas panel
|
| 44 |
+
}
|
| 45 |
)
|
| 46 |
|
| 47 |
+
# Make Swagger UI the home page
|
| 48 |
+
@app.get("/", include_in_schema=False)
|
| 49 |
+
def home():
|
| 50 |
+
return RedirectResponse(url="/docs")
|
| 51 |
+
|
| 52 |
# Add CORS middleware
|
| 53 |
app.add_middleware(
|
| 54 |
CORSMiddleware,
|
|
|
|
| 61 |
# Initialize transformation engine
|
| 62 |
transformation_engine = TransformationEngine()
|
| 63 |
|
| 64 |
+
# ---------------------------
|
| 65 |
# Pydantic models for API
|
| 66 |
+
# ---------------------------
|
| 67 |
+
|
| 68 |
class TransformationRequestModel(BaseModel):
|
| 69 |
"""API model for transformation requests."""
|
| 70 |
auto_select_erp: bool = Field(True, description="Auto-detect ERP system")
|
|
|
|
| 97 |
processing_time_ms: Optional[float] = None
|
| 98 |
|
| 99 |
|
| 100 |
+
# ---------------------------
|
| 101 |
+
# Health / Info endpoints
|
| 102 |
+
# ---------------------------
|
| 103 |
+
|
| 104 |
@app.get("/health", tags=["Health"])
|
| 105 |
async def health_check():
|
| 106 |
"""Health check endpoint."""
|
| 107 |
return {"status": "healthy", "version": "2.0.0", "engine": "Polars + DuckDB"}
|
| 108 |
|
| 109 |
|
|
|
|
| 110 |
@app.get("/entities", response_model=List[str], tags=["Information"])
|
| 111 |
async def get_entities():
|
| 112 |
"""Get list of supported entity types."""
|
|
|
|
| 125 |
return [format.value for format in FileFormat]
|
| 126 |
|
| 127 |
|
| 128 |
+
# ---------------------------
|
| 129 |
# Core transformation endpoints
|
| 130 |
+
# ---------------------------
|
| 131 |
+
|
| 132 |
@app.post("/transform", response_model=TransformationResponseModel, tags=["Transformation"])
|
| 133 |
async def transform_data(request: TransformationRequestModel):
|
| 134 |
"""Transform JSON data to CDF format.
|
| 135 |
+
|
| 136 |
This endpoint accepts JSON data directly and transforms it according to the request parameters.
|
| 137 |
"""
|
| 138 |
import time
|
| 139 |
start_time = time.time()
|
| 140 |
+
|
| 141 |
try:
|
| 142 |
if not request.data:
|
| 143 |
raise HTTPException(status_code=400, detail="No data provided")
|
| 144 |
+
|
| 145 |
# Create temporary JSON file
|
| 146 |
import json
|
| 147 |
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as temp_file:
|
| 148 |
json.dump(request.data, temp_file)
|
| 149 |
temp_path = temp_file.name
|
| 150 |
+
|
| 151 |
try:
|
| 152 |
# Create transformation request
|
| 153 |
transform_request = TransformationRequest(
|
|
|
|
| 158 |
file_data=temp_path,
|
| 159 |
file_format=FileFormat.JSON
|
| 160 |
)
|
| 161 |
+
|
| 162 |
# Perform transformation
|
| 163 |
result = transformation_engine.transform(transform_request)
|
| 164 |
+
|
| 165 |
# Convert result to API response
|
| 166 |
response_data = None
|
| 167 |
if result.success and result.data is not None:
|
| 168 |
response_data = transformation_engine.data_processor.to_dict(result.data)
|
| 169 |
+
|
| 170 |
processing_time = (time.time() - start_time) * 1000
|
| 171 |
+
|
| 172 |
return TransformationResponseModel(
|
| 173 |
success=result.success,
|
| 174 |
data=response_data,
|
|
|
|
| 181 |
row_count=len(response_data) if response_data else 0,
|
| 182 |
processing_time_ms=processing_time
|
| 183 |
)
|
| 184 |
+
|
| 185 |
finally:
|
| 186 |
# Clean up temporary file
|
| 187 |
try:
|
| 188 |
os.unlink(temp_path)
|
| 189 |
except OSError:
|
| 190 |
pass
|
| 191 |
+
|
| 192 |
except Exception as e:
|
| 193 |
logger.error(f"Transform data failed: {e}")
|
| 194 |
raise HTTPException(status_code=500, detail=f"Transformation failed: {str(e)}")
|
|
|
|
| 204 |
output_format: str = Form("json", description="Output format (json, csv, parquet)")
|
| 205 |
):
|
| 206 |
"""Transform uploaded file to CDF format.
|
| 207 |
+
|
| 208 |
This endpoint accepts file uploads and transforms them according to the request parameters.
|
| 209 |
Supports CSV, Excel, JSON, and SQL files.
|
| 210 |
"""
|
| 211 |
import time
|
| 212 |
start_time = time.time()
|
| 213 |
+
|
| 214 |
try:
|
| 215 |
# Read file content
|
| 216 |
file_content = await file.read()
|
| 217 |
+
|
| 218 |
# Detect file format
|
| 219 |
file_extension = Path(file.filename).suffix.lower()
|
| 220 |
format_mapping = {
|
|
|
|
| 224 |
'.json': FileFormat.JSON,
|
| 225 |
'.sql': FileFormat.SQL
|
| 226 |
}
|
| 227 |
+
|
| 228 |
if file_extension not in format_mapping:
|
| 229 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 230 |
+
|
| 231 |
file_format = format_mapping[file_extension]
|
| 232 |
+
|
| 233 |
# Create transformation request
|
| 234 |
transform_request = TransformationRequest(
|
| 235 |
auto_select_erp=auto_select_erp,
|
|
|
|
| 239 |
file_data=file_content,
|
| 240 |
file_format=file_format
|
| 241 |
)
|
| 242 |
+
|
| 243 |
# Perform transformation
|
| 244 |
result = transformation_engine.transform(transform_request)
|
| 245 |
+
|
| 246 |
# Convert result to API response
|
| 247 |
response_data = None
|
| 248 |
if result.success and result.data is not None:
|
| 249 |
response_data = transformation_engine.data_processor.to_dict(result.data)
|
| 250 |
+
|
| 251 |
processing_time = (time.time() - start_time) * 1000
|
| 252 |
+
|
| 253 |
return TransformationResponseModel(
|
| 254 |
success=result.success,
|
| 255 |
data=response_data,
|
|
|
|
| 262 |
row_count=len(response_data) if response_data else 0,
|
| 263 |
processing_time_ms=processing_time
|
| 264 |
)
|
| 265 |
+
|
| 266 |
except Exception as e:
|
| 267 |
logger.error(f"Transform file failed: {e}")
|
| 268 |
raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")
|
|
|
|
| 279 |
output_format: str = Form("csv", description="Output format (csv, json, parquet)")
|
| 280 |
):
|
| 281 |
"""Transform uploaded file and return as downloadable file.
|
| 282 |
+
|
| 283 |
This endpoint transforms the file and returns the result as a downloadable file.
|
| 284 |
"""
|
| 285 |
try:
|
| 286 |
# Read file content
|
| 287 |
file_content = await file.read()
|
| 288 |
+
|
| 289 |
# Detect file format
|
| 290 |
file_extension = Path(file.filename).suffix.lower()
|
| 291 |
format_mapping = {
|
|
|
|
| 296 |
'.sql': FileFormat.SQL,
|
| 297 |
'.parquet': FileFormat.PARQUET
|
| 298 |
}
|
| 299 |
+
|
| 300 |
if file_extension not in format_mapping:
|
| 301 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 302 |
+
|
| 303 |
file_format = format_mapping[file_extension]
|
| 304 |
+
|
| 305 |
# Create transformation request
|
| 306 |
transform_request = TransformationRequest(
|
| 307 |
auto_select_erp=auto_select_erp,
|
|
|
|
| 311 |
file_data=file_content,
|
| 312 |
file_format=file_format
|
| 313 |
)
|
| 314 |
+
|
| 315 |
# Perform transformation
|
| 316 |
result = transformation_engine.transform(transform_request)
|
| 317 |
+
|
| 318 |
if not result.success:
|
| 319 |
raise HTTPException(status_code=400, detail=result.message)
|
| 320 |
+
|
| 321 |
# Create output file
|
| 322 |
output_format_enum = FileFormat(output_format.lower())
|
| 323 |
output_filename = f"transformed_{Path(file.filename).stem}_cdf.{output_format}"
|
| 324 |
+
|
| 325 |
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{output_format}") as temp_file:
|
| 326 |
temp_path = temp_file.name
|
| 327 |
+
|
| 328 |
# Export transformed data
|
| 329 |
transformation_engine.data_processor.export_dataframe(
|
| 330 |
result.data, temp_path, output_format_enum
|
| 331 |
)
|
| 332 |
+
|
| 333 |
# Schedule cleanup
|
| 334 |
background_tasks.add_task(cleanup_temp_file, temp_path)
|
| 335 |
+
|
| 336 |
return FileResponse(
|
| 337 |
path=temp_path,
|
| 338 |
filename=output_filename,
|
| 339 |
media_type="application/octet-stream"
|
| 340 |
)
|
| 341 |
+
|
| 342 |
except Exception as e:
|
| 343 |
logger.error(f"Transform file download failed: {e}")
|
| 344 |
raise HTTPException(status_code=500, detail=f"File transformation failed: {str(e)}")
|
| 345 |
|
| 346 |
|
| 347 |
+
# ---------------------------
|
| 348 |
+
# Analysis / Validation
|
| 349 |
+
# ---------------------------
|
| 350 |
+
|
| 351 |
@app.post("/analyze", response_model=AnalysisResponseModel, tags=["Analysis"])
|
| 352 |
async def analyze_data(file: UploadFile = File(..., description="File to analyze")):
|
| 353 |
"""Analyze uploaded file and provide insights.
|
| 354 |
+
|
| 355 |
This endpoint analyzes the file structure and suggests possible ERP/entity combinations.
|
| 356 |
"""
|
| 357 |
import time
|
| 358 |
start_time = time.time()
|
| 359 |
+
|
| 360 |
try:
|
| 361 |
# Read file content
|
| 362 |
file_content = await file.read()
|
| 363 |
+
|
| 364 |
# Detect file format
|
| 365 |
file_extension = Path(file.filename).suffix.lower()
|
| 366 |
format_mapping = {
|
|
|
|
| 371 |
'.sql': FileFormat.SQL,
|
| 372 |
'.parquet': FileFormat.PARQUET
|
| 373 |
}
|
| 374 |
+
|
| 375 |
if file_extension not in format_mapping:
|
| 376 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 377 |
+
|
| 378 |
file_format = format_mapping[file_extension]
|
| 379 |
+
|
| 380 |
# Analyze data
|
| 381 |
analysis_result = transformation_engine.analyze_data(file_content, file_format)
|
| 382 |
+
|
| 383 |
if "error" in analysis_result:
|
| 384 |
raise HTTPException(status_code=400, detail=analysis_result["error"])
|
| 385 |
+
|
| 386 |
processing_time = (time.time() - start_time) * 1000
|
| 387 |
analysis_result["processing_time_ms"] = processing_time
|
| 388 |
+
|
| 389 |
return AnalysisResponseModel(**analysis_result)
|
| 390 |
+
|
| 391 |
except Exception as e:
|
| 392 |
logger.error(f"Analyze data failed: {e}")
|
| 393 |
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
|
|
|
|
| 396 |
@app.post("/validate", tags=["Validation"])
|
| 397 |
async def validate_data(file: UploadFile = File(..., description="File to validate")):
|
| 398 |
"""Validate file structure and content.
|
| 399 |
+
|
| 400 |
This endpoint validates the file can be loaded and provides basic statistics.
|
| 401 |
"""
|
| 402 |
try:
|
| 403 |
# Read file content
|
| 404 |
file_content = await file.read()
|
| 405 |
+
|
| 406 |
# Detect file format
|
| 407 |
file_extension = Path(file.filename).suffix.lower()
|
| 408 |
format_mapping = {
|
|
|
|
| 413 |
'.sql': FileFormat.SQL,
|
| 414 |
'.parquet': FileFormat.PARQUET
|
| 415 |
}
|
| 416 |
+
|
| 417 |
if file_extension not in format_mapping:
|
| 418 |
raise HTTPException(status_code=400, detail=f"Unsupported file format: {file_extension}")
|
| 419 |
+
|
| 420 |
file_format = format_mapping[file_extension]
|
| 421 |
+
|
| 422 |
# Load and validate data
|
| 423 |
df = transformation_engine.data_processor.load_from_bytes(file_content, file_format, file.filename)
|
| 424 |
+
|
| 425 |
# Get column info
|
| 426 |
column_info = transformation_engine.data_processor.get_column_info(df)
|
| 427 |
+
|
| 428 |
return {
|
| 429 |
"valid": True,
|
| 430 |
"file_format": file_format.value,
|
| 431 |
"column_info": column_info,
|
| 432 |
"message": "File is valid and can be processed"
|
| 433 |
}
|
| 434 |
+
|
| 435 |
except Exception as e:
|
| 436 |
logger.error(f"Validate data failed: {e}")
|
| 437 |
return {
|
|
|
|
| 441 |
}
|
| 442 |
|
| 443 |
|
| 444 |
+
# ---------------------------
|
| 445 |
+
# Template utilities
|
| 446 |
+
# ---------------------------
|
| 447 |
+
|
| 448 |
@app.get("/template/erp/{erp}/entity/{entity}", tags=["Template"])
|
| 449 |
async def get_template_mapping(erp: str, entity: str):
|
| 450 |
"""Get template mapping for specific ERP and entity."""
|
|
|
|
| 452 |
mapping = transformation_engine.template_loader.get_entity_mapping(erp, entity)
|
| 453 |
if not mapping:
|
| 454 |
raise HTTPException(status_code=404, detail=f"No mapping found for {erp} -> {entity}")
|
| 455 |
+
|
| 456 |
return {
|
| 457 |
"erp": erp,
|
| 458 |
"entity": entity,
|
| 459 |
"mapping": mapping,
|
| 460 |
"cdf_schema": transformation_engine.template_loader.get_cdf_schema(entity)
|
| 461 |
}
|
| 462 |
+
|
| 463 |
except Exception as e:
|
| 464 |
logger.error(f"Get template mapping failed: {e}")
|
| 465 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 475 |
"cdf_schema": schema,
|
| 476 |
"field_count": len(schema)
|
| 477 |
}
|
| 478 |
+
|
| 479 |
except Exception as e:
|
| 480 |
logger.error(f"Get entity schema failed: {e}")
|
| 481 |
raise HTTPException(status_code=500, detail=str(e))
|
| 482 |
|
| 483 |
|
| 484 |
+
# ---------------------------
|
| 485 |
# Background task for cleanup
|
| 486 |
+
# ---------------------------
|
| 487 |
+
|
| 488 |
def cleanup_temp_file(file_path: str):
|
| 489 |
"""Clean up temporary file."""
|
| 490 |
try:
|
|
|
|
| 494 |
logger.warning(f"Failed to clean up temporary file {file_path}: {e}")
|
| 495 |
|
| 496 |
|
| 497 |
+
# ---------------------------
|
| 498 |
+
# Startup / Shutdown
|
| 499 |
+
# ---------------------------
|
| 500 |
+
|
| 501 |
@app.on_event("startup")
|
| 502 |
async def startup_event():
|
| 503 |
"""Startup event handler."""
|
|
|
|
| 515 |
logger.info("Shutdown complete.")
|
| 516 |
|
| 517 |
|
| 518 |
+
# ---------------------------
|
| 519 |
# Main entry point
|
| 520 |
+
# ---------------------------
|
| 521 |
+
|
| 522 |
if __name__ == "__main__":
|
| 523 |
uvicorn.run(
|
| 524 |
"app:app",
|