""" Pure LLM-based transformation engine. Implements simplified decision logic: template-based for known ERP+Entity, pure LLM for unknown. """ 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 .llm_handler_pure import create_pure_llm_handler from .models import EntityType, TransformationRequest, TransformationResult, TransformationMode logger = logging.getLogger(__name__) class PureTransformationEngine: """Pure LLM-based transformation engine with simplified decision logic.""" def __init__(self, template_path: Optional[Path] = None, memory_limit: str = "1GB"): """Initialize pure transformation engine. Args: template_path: Path to template.json file memory_limit: Memory limit for data processing """ self.data_processor = DataProcessor() self.template_loader = TemplateLoader(template_path) # Initialize Pure LLM handler self.pure_llm_handler = create_pure_llm_handler() def transform(self, request: TransformationRequest) -> TransformationResult: """Transform data using pure LLM approach. 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: Simplified decision logic if not request.auto_select_erp and not request.auto_select_entity: # CASE 1: ERP and Entity Known - Direct template mapping logger.info("Using template-based transformation (ERP and Entity known)") return self._template_based_transform(input_df, request.erp, request.entity) else: # CASE 2: ERP or Entity Unknown - Pure LLM mapping logger.info("Using pure LLM transformation (ERP or Entity unknown)") return self._pure_llm_transform(input_df, request) except Exception as e: logger.error(f"Pure transformation failed: {e}") return TransformationResult( success=False, message=f"Pure 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 (same as original logic). 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 _pure_llm_transform(self, input_df: pl.DataFrame, request: TransformationRequest) -> TransformationResult: """Perform pure LLM-based transformation. Args: input_df: Input DataFrame request: Transformation request Returns: Transformation result """ logger.info("Pure LLM transformation") try: columns = list(input_df.columns) # Determine target entity - if not specified, let LLM detect it if request.entity: target_entity = request.entity logger.info(f"Using specified entity: {target_entity}") else: # Let LLM detect the entity type based on column names target_entity = self._detect_entity_with_llm(columns) logger.info(f"LLM detected entity: {target_entity}") # Get CDF schema for target entity cdf_schema = self.template_loader.get_cdf_schema(target_entity) if not cdf_schema: return TransformationResult( success=False, message=f"No CDF schema found for entity: {target_entity}" ) # Use Pure LLM to infer mapping llm_mapping = self.pure_llm_handler.infer_mapping_pure(columns, cdf_schema, target_entity) if not llm_mapping: return TransformationResult( success=False, message="Pure LLM mapping failed after all retry attempts" ) # Apply LLM-generated mapping output_df = self._apply_column_mapping(input_df, llm_mapping, target_entity) # Calculate confidence based on mapping coverage mapping_coverage = len(llm_mapping) / len(cdf_schema) if cdf_schema else 0 confidence_score = min(0.9, 0.6 + (mapping_coverage * 0.3)) # 0.6-0.9 range return TransformationResult( success=True, data=output_df, detected_erp="Unknown (Pure LLM)", detected_entity=target_entity, transformation_mode=TransformationMode.AI_ASSISTED, confidence_score=confidence_score, message=f"Successfully transformed using Pure LLM mapping ({len(llm_mapping)} fields mapped)", column_mappings=llm_mapping ) except Exception as e: logger.error(f"Pure LLM transformation failed: {e}") return TransformationResult( success=False, message=f"Pure LLM transformation error: {str(e)}" ) def _detect_entity_with_llm(self, columns: List[str]) -> str: """Use LLM to detect the most likely entity type based on column names. Args: columns: List of column names from the data Returns: Detected entity type """ try: # Get available entity types available_entities = [e.value for e in EntityType] # Use LLM to detect entity type detected_entity = self.pure_llm_handler.detect_entity_type(columns, available_entities) if detected_entity and detected_entity in available_entities: return detected_entity else: # Fallback to sales_orders if detection fails logger.warning(f"LLM entity detection failed or returned invalid entity: {detected_entity}. Using fallback.") return "sales_orders" except Exception as e: logger.error(f"Entity detection failed: {e}") # Fallback to sales_orders if detection fails return "sales_orders" 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 and successfully mapped columns expected_columns = self.template_loader.get_cdf_schema(entity) mapped_columns = list(mapping.values()) # Columns that were successfully mapped # Step 3: Determine final column set - prioritize mapped columns, then add missing CDF columns final_columns = [] # Add all successfully mapped columns first (preserve LLM mapping results) for col in mapped_columns: if col in output_df.columns: final_columns.append(col) # Add any missing essential CDF columns with null values for col in expected_columns: if col not in final_columns: if col not in output_df.columns: output_df = output_df.with_columns(pl.lit(None).alias(col)) final_columns.append(col) # Step 4: Select columns in logical order (mapped first, then missing CDF columns) output_df = output_df.select(final_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) # For pure LLM engine, we don't do ERP detection # Just provide basic analysis return { "column_info": column_info, "erp_entity_suggestions": [ { "entity": "sales_orders", "erp": "Unknown (will use Pure LLM)", "confidence": 0.8, "above_threshold": True } ], "available_entities": [e.value for e in EntityType], "available_erps": ["Unknown (Pure LLM)"] + self.template_loader.get_erp_names(), "note": "Pure LLM engine will analyze your data using AI without ERP detection" } 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()