Spaces:
Runtime error
Runtime error
File size: 26,467 Bytes
f12ad36 d16f985 f12ad36 d16f985 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 5a56d29 f12ad36 | 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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | """
High-performance transformation engine using Polars and DuckDB.
Implements the ERP to CDF transformation logic with auto-detection capabilities.
"""
import logging
import polars as pl
from typing import Dict, Any, Optional, Tuple, Union, List
from pathlib import Path
from enum import Enum
from .data_processor import DataProcessor, FileFormat
from .template_loader import TemplateLoader
from .erp_resolver import ERPResolver
from .llm_handler import create_llm_handler, load_template_context
from .models import EntityType, TransformationRequest, TransformationResult, TransformationMode
logger = logging.getLogger(__name__)
class TransformationEngine:
"""High-performance transformation engine for ERP to CDF conversion."""
def __init__(self,
template_path: Optional[Path] = None,
similarity_threshold: float = 0.4,
memory_limit: str = "1GB"):
"""Initialize transformation engine.
Args:
template_path: Path to template.json file
similarity_threshold: Minimum similarity for ERP detection
memory_limit: Memory limit for data processing
"""
self.data_processor = DataProcessor()
self.template_loader = TemplateLoader(template_path)
self.erp_resolver = ERPResolver(self.template_loader, similarity_threshold)
# Initialize LLM handler
self.llm_handler = create_llm_handler()
def transform(self, request: TransformationRequest) -> TransformationResult:
"""Transform data according to request parameters.
Args:
request: Transformation request
Returns:
Transformation result
"""
try:
# Step 1: Load data
input_df = self._load_data(request)
if input_df is None:
return TransformationResult(
success=False,
message="Failed to load input data"
)
logger.info(f"Loaded data: {len(input_df)} rows, {len(input_df.columns)} columns")
# Step 2: Normalize column names
input_df = self.data_processor.normalize_column_names(input_df)
# Step 3: Determine transformation approach
if not request.auto_select_erp and not request.auto_select_entity:
# CASE 1: ERP and Entity Known - Direct template mapping
return self._template_based_transform(input_df, request.erp, request.entity)
else:
# CASE 2: ERP or Entity Unknown - Auto-detection + fallback
return self._auto_detect_and_transform(input_df, request)
except Exception as e:
logger.error(f"Transformation failed: {e}")
return TransformationResult(
success=False,
message=f"Transformation error: {str(e)}"
)
def _load_data(self, request: TransformationRequest) -> Optional[pl.DataFrame]:
"""Load data from request.
Args:
request: Transformation request
Returns:
Loaded DataFrame or None if failed
"""
if request.file_data is None:
return None
try:
if isinstance(request.file_data, (str, Path)):
# File path
return self.data_processor.load_file(request.file_data, request.file_format)
elif isinstance(request.file_data, bytes):
# File bytes
if request.file_format is None:
raise ValueError("File format required for bytes data")
return self.data_processor.load_from_bytes(
request.file_data, request.file_format
)
else:
raise ValueError(f"Unsupported file_data type: {type(request.file_data)}")
except Exception as e:
logger.error(f"Failed to load data: {e}")
return None
def _template_based_transform(self, input_df: pl.DataFrame, erp: str, entity: str) -> TransformationResult:
"""Perform template-based transformation.
Args:
input_df: Input DataFrame
erp: ERP system name
entity: Entity type
Returns:
Transformation result
"""
logger.info(f"Template-based transformation: {erp} -> {entity}")
try:
# Get mapping from template
mapping = self.template_loader.get_entity_mapping(erp, entity)
if not mapping:
return TransformationResult(
success=False,
message=f"No mapping found for {erp} -> {entity}"
)
# Apply transformation
output_df = self._apply_column_mapping(input_df, mapping, entity)
return TransformationResult(
success=True,
data=output_df,
detected_erp=erp,
detected_entity=entity,
transformation_mode=TransformationMode.TEMPLATE_BASED,
confidence_score=1.0,
message=f"Successfully transformed using template mapping",
column_mappings=mapping
)
except Exception as e:
logger.error(f"Template-based transformation failed: {e}")
return TransformationResult(
success=False,
message=f"Template transformation error: {str(e)}"
)
def _auto_detect_and_transform(self, input_df: pl.DataFrame, request: TransformationRequest) -> TransformationResult:
"""Auto-detect ERP/entity and transform.
Args:
input_df: Input DataFrame
request: Transformation request
Returns:
Transformation result
"""
logger.info("Auto-detection and transformation")
# Step 1: Try to detect ERP and entity from templates
detected_erp, detected_entity, confidence = self._detect_erp_and_entity(
input_df, request.erp, request.entity
)
if detected_erp and detected_entity and confidence > 0.6:
# High confidence template match
logger.info(f"High confidence detection: {detected_erp} -> {detected_entity} ({confidence:.2f})")
return self._template_based_transform(input_df, detected_erp, detected_entity)
# Step 2: Try AI-assisted transformation
logger.info("Attempting AI-assisted transformation")
return self._ai_assisted_transform(input_df, detected_erp, detected_entity, confidence)
def _detect_erp_and_entity(self, input_df: pl.DataFrame,
hint_erp: Optional[str] = None,
hint_entity: Optional[str] = None) -> Tuple[Optional[str], Optional[str], float]:
"""Detect ERP system and entity type from DataFrame.
Args:
input_df: Input DataFrame
hint_erp: ERP hint (if provided)
hint_entity: Entity hint (if provided)
Returns:
Tuple of (detected_erp, detected_entity, confidence_score)
"""
columns = list(input_df.columns)
best_erp = hint_erp
best_entity = hint_entity
best_confidence = 0.0
# If entity is provided, only check that entity
entities_to_check = [hint_entity] if hint_entity else [e.value for e in EntityType]
for entity in entities_to_check:
if hint_erp:
# Check specific ERP
mapping = self.template_loader.get_entity_mapping(hint_erp, entity)
if mapping:
confidence = self._calculate_mapping_confidence(columns, mapping)
if confidence > best_confidence:
best_erp = hint_erp
best_entity = entity
best_confidence = confidence
else:
# Auto-detect ERP for this entity
detected_erp = self.erp_resolver.detect_erp(columns, entity)
if detected_erp:
mapping = self.template_loader.get_entity_mapping(detected_erp, entity)
if mapping:
confidence = self._calculate_mapping_confidence(columns, mapping)
if confidence > best_confidence:
best_erp = detected_erp
best_entity = entity
best_confidence = confidence
return best_erp, best_entity, best_confidence
def _calculate_mapping_confidence(self, columns: List[str], mapping: Dict[str, str]) -> float:
"""Calculate confidence score for a mapping.
Args:
columns: DataFrame columns
mapping: Column mapping dictionary
Returns:
Confidence score (0.0 to 1.0)
"""
if not mapping:
return 0.0
# Count how many mapping keys are found in columns
found_keys = sum(1 for key in mapping.keys() if key.lower() in [col.lower() for col in columns])
total_keys = len(mapping)
return found_keys / total_keys if total_keys > 0 else 0.0
def _ai_assisted_transform(self, input_df: pl.DataFrame,
detected_erp: Optional[str],
detected_entity: Optional[str],
template_confidence: float) -> TransformationResult:
"""Perform AI-assisted transformation.
Args:
input_df: Input DataFrame
detected_erp: Detected ERP (may be None)
detected_entity: Detected entity (may be None)
template_confidence: Confidence from template matching
Returns:
Transformation result
"""
logger.info("AI-assisted transformation")
try:
# Determine target entity
target_entity = detected_entity or "sales_orders" # Default fallback
# Get CDF schema for target entity
cdf_schema = self.template_loader.get_cdf_schema(target_entity)
# Use LLM to infer mapping
columns = list(input_df.columns)
llm_mapping = self.llm_handler.infer_mapping(columns, cdf_schema, target_entity)
if not llm_mapping:
return TransformationResult(
success=False,
message="AI-assisted mapping failed"
)
# Apply AI-generated mapping
output_df = self._apply_column_mapping(input_df, llm_mapping, target_entity)
return TransformationResult(
success=True,
data=output_df,
detected_erp=detected_erp or "Unknown",
detected_entity=target_entity,
transformation_mode=TransformationMode.AI_ASSISTED,
confidence_score=max(0.3, template_confidence), # AI has lower confidence
message="Successfully transformed using AI-assisted mapping",
column_mappings=llm_mapping
)
except Exception as e:
logger.error(f"AI-assisted transformation failed: {e}")
return TransformationResult(
success=False,
message=f"AI transformation error: {str(e)}"
)
def _apply_column_mapping(self, input_df: pl.DataFrame, mapping: Dict[str, str], entity: str) -> pl.DataFrame:
"""Apply column mapping to transform DataFrame.
Args:
input_df: Input DataFrame
mapping: Column mapping dictionary
entity: Target entity type
Returns:
Transformed DataFrame
"""
# Step 1: Rename columns according to mapping
rename_dict = {}
for source_col, target_col in mapping.items():
# Find matching column (case-insensitive)
for df_col in input_df.columns:
if df_col.lower() == source_col.lower():
rename_dict[df_col] = target_col
break
output_df = input_df.rename(rename_dict)
# Step 2: Get expected CDF schema
expected_columns = self.template_loader.get_cdf_schema(entity)
# Step 3: Add missing columns with null values
for col in expected_columns:
if col not in output_df.columns:
output_df = output_df.with_columns(pl.lit(None).alias(col))
# Step 4: Select only CDF columns in correct order
output_df = output_df.select(expected_columns)
# Step 5: Apply data type conversions
output_df = self._apply_data_types(output_df, entity)
return output_df
def _apply_data_types(self, df: pl.DataFrame, entity: str, output_format: str = "json") -> pl.DataFrame:
"""Apply appropriate data types and formatting based on CDF schema and output format.
Args:
df: DataFrame to type-convert
entity: Entity type
output_format: Output format (json, csv, excel, api, database)
Returns:
DataFrame with proper data types and formatting
"""
# Define data type mappings for each entity
type_mappings = {
"sales_orders": {
"order_date": pl.Date,
"total_amount": pl.Float64,
"quantity": pl.Int64,
"unit_price": pl.Float64,
"line_total": pl.Float64
},
"customers": {
"is_company": pl.Boolean,
"created_date": pl.Datetime,
"last_modified": pl.Datetime
},
"invoices": {
"invoice_date": pl.Date,
"total_amount": pl.Float64,
"due_date": pl.Date,
"quantity": pl.Int64,
"unit_price": pl.Float64,
"line_total": pl.Float64
},
"purchase_orders": {
"po_date": pl.Date,
"total_amount": pl.Float64,
"expected_receipt_date": pl.Date,
"quantity": pl.Int64,
"unit_price": pl.Float64,
"line_total": pl.Float64
},
"inventory_items": {
"base_price": pl.Float64,
"cost_price": pl.Float64,
"is_active": pl.Boolean,
"quantity_on_hand": pl.Int64,
"reorder_point": pl.Int64
}
}
entity_types = type_mappings.get(entity, {})
# Apply type conversions with proper null handling
for column, dtype in entity_types.items():
if column in df.columns:
try:
# Handle null/empty values before type conversion
if dtype == pl.Date:
df = df.with_columns(
pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
.then(None)
.otherwise(pl.col(column).str.to_date(strict=False))
.alias(column)
)
elif dtype == pl.Datetime:
df = df.with_columns(
pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
.then(None)
.otherwise(pl.col(column).str.to_datetime(strict=False))
.alias(column)
)
elif dtype == pl.Boolean:
df = df.with_columns(
pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
.then(None)
.otherwise(pl.col(column).cast(pl.Boolean, strict=False))
.alias(column)
)
elif dtype in [pl.Int64, pl.Float64]:
df = df.with_columns(
pl.when(pl.col(column).is_null() | (pl.col(column).str.strip_chars() == ""))
.then(None)
.otherwise(pl.col(column).cast(dtype, strict=False))
.alias(column)
)
except Exception as e:
logger.warning(f"Failed to convert column {column} to {dtype}: {e}")
# Keep original column if conversion fails
continue
# Apply format-specific transformations
df = self._apply_format_consistency(df, entity, output_format)
return df
def _apply_format_consistency(self, df: pl.DataFrame, entity: str, output_format: str) -> pl.DataFrame:
"""Apply format consistency rules based on ERP-CDF-Mapping guidelines.
Args:
df: DataFrame to format
entity: Entity type
output_format: Output format (json, csv, excel, api, database)
Returns:
DataFrame with consistent formatting
"""
try:
# Date field formatting
date_columns = self._get_date_columns(entity)
for col in date_columns:
if col in df.columns:
try:
if output_format in ["csv", "excel"]:
# Human-readable format: dd-MMMM-yyyy (e.g., 04-August-2025)
df = df.with_columns(
pl.when(pl.col(col).is_null())
.then(None)
.otherwise(pl.col(col).dt.strftime("%d-%B-%Y"))
.alias(col)
)
else:
# API/Database format: ISO yyyy-MM-dd
df = df.with_columns(
pl.when(pl.col(col).is_null())
.then(None)
.otherwise(pl.col(col).dt.strftime("%Y-%m-%d"))
.alias(col)
)
except Exception as e:
logger.warning(f"Failed to format date column {col}: {e}")
# Decimal field formatting (currency, unit prices, totals)
decimal_columns = self._get_decimal_columns(entity)
for col in decimal_columns:
if col in df.columns:
try:
# Ensure two decimal places (e.g., 1249.00) - only for non-null numeric values
df = df.with_columns(
pl.when(pl.col(col).is_null() | pl.col(col).is_nan())
.then(None)
.otherwise(pl.col(col).round(2))
.alias(col)
)
except Exception as e:
logger.warning(f"Failed to format decimal column {col}: {e}")
# Boolean field formatting
boolean_columns = self._get_boolean_columns(entity)
for col in boolean_columns:
if col in df.columns:
try:
if output_format == "database":
# Database format: 1/0
df = df.with_columns(
pl.when(pl.col(col).is_null())
.then(None)
.otherwise(pl.col(col).cast(pl.Int8))
.alias(col)
)
else:
# JSON/API format: true/false
df = df.with_columns(
pl.when(pl.col(col).is_null())
.then(None)
.otherwise(pl.col(col).cast(pl.Boolean))
.alias(col)
)
except Exception as e:
logger.warning(f"Failed to format boolean column {col}: {e}")
# Text field formatting (UTF-8 encoding)
text_columns = self._get_text_columns(entity)
for col in text_columns:
if col in df.columns:
try:
# Ensure UTF-8 encoding and proper escaping
df = df.with_columns(
pl.when(pl.col(col).is_null())
.then(None)
.otherwise(pl.col(col).str.strip_chars())
.alias(col)
)
except Exception as e:
logger.warning(f"Failed to format text column {col}: {e}")
return df
except Exception as e:
logger.error(f"Format consistency failed: {e}")
return df # Return original DataFrame if formatting fails
def _get_date_columns(self, entity: str) -> List[str]:
"""Get date columns for entity."""
date_mappings = {
"sales_orders": ["order_date"],
"customers": ["created_date", "last_modified"],
"invoices": ["invoice_date", "due_date"],
"purchase_orders": ["po_date", "expected_receipt_date"],
"inventory_items": []
}
return date_mappings.get(entity, [])
def _get_decimal_columns(self, entity: str) -> List[str]:
"""Get decimal columns for entity (currency, prices, totals)."""
decimal_mappings = {
"sales_orders": ["total_amount", "unit_price", "line_total"],
"customers": [],
"invoices": ["total_amount", "unit_price", "line_total"],
"purchase_orders": ["total_amount", "unit_price", "line_total"],
"inventory_items": ["base_price", "cost_price"]
}
return decimal_mappings.get(entity, [])
def _get_boolean_columns(self, entity: str) -> List[str]:
"""Get boolean columns for entity."""
boolean_mappings = {
"sales_orders": [],
"customers": ["is_company"],
"invoices": [],
"purchase_orders": [],
"inventory_items": ["is_active"]
}
return boolean_mappings.get(entity, [])
def _get_text_columns(self, entity: str) -> List[str]:
"""Get text columns for entity."""
text_mappings = {
"sales_orders": ["customer_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
"customers": ["customer_id", "customer_name", "contact_email", "phone_number", "alt_phone", "status", "currency", "address_type", "address_line1", "city", "state", "postal_code", "country"],
"invoices": ["invoice_id", "customer_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
"purchase_orders": ["po_id", "vendor_id", "status", "currency", "notes", "item_id", "description", "tax_code"],
"inventory_items": ["item_id", "item_name", "description", "purchase_description", "sales_description", "unit_type", "preferred_vendor_id"]
}
return text_mappings.get(entity, [])
def analyze_data(self, file_data: Union[str, Path, bytes],
file_format: Optional[FileFormat] = None) -> Dict[str, Any]:
"""Analyze input data and provide insights.
Args:
file_data: File path, bytes, or data
file_format: File format (auto-detected if None)
Returns:
Analysis results
"""
try:
# Load data
request = TransformationRequest(file_data=file_data, file_format=file_format)
input_df = self._load_data(request)
if input_df is None:
return {"error": "Failed to load data"}
# Normalize columns
input_df = self.data_processor.normalize_column_names(input_df)
# Get basic info
column_info = self.data_processor.get_column_info(input_df)
# Detect possible ERP/entity combinations
columns = list(input_df.columns)
suggestions = []
for entity in EntityType:
erp_suggestions = self.erp_resolver.suggest_best_matches(columns, entity.value)
for suggestion in erp_suggestions[:3]: # Top 3 suggestions
suggestions.append({
"entity": entity.value,
"erp": suggestion["erp"],
"confidence": suggestion["confidence"],
"above_threshold": suggestion["above_threshold"]
})
# Sort by confidence
suggestions.sort(key=lambda x: x["confidence"], reverse=True)
return {
"column_info": column_info,
"erp_entity_suggestions": suggestions[:10], # Top 10 suggestions
"available_entities": [e.value for e in EntityType],
"available_erps": self.template_loader.get_erp_names()
}
except Exception as e:
logger.error(f"Data analysis failed: {e}")
return {"error": f"Analysis failed: {str(e)}"}
def close(self):
"""Close resources."""
if self.data_processor:
self.data_processor.close()
|