cleanflowai / mapper /transformation_engine.py
KiranParthiban's picture
feat: enhance entity type detection and mapping logic
5a56d29
Raw History Blame Contribute Delete
26.5 kB
"""
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()