# CleanFlow AI - Complete Developer Information ## Overview CleanFlow AI is a high-performance ERP to CDF (Common Data Frame) transformation system that converts data from various ERP systems into a standardized format using Polars and DuckDB for optimal performance. ## Core Architecture & Functions ### 1. Main Application (app.py) FastAPI-based REST API server with the following endpoints: **Health & Information:** - GET /health - Health check endpoint - GET /entities - List supported entity types (5 types) - GET /erps - List supported ERP systems (11 systems) - GET /formats - List supported file formats **Core Transformation:** - POST /transform - Transform JSON data to CDF format - POST /transform/file - Transform uploaded files - POST /transform/file/download - Transform and download results **Analysis & Validation:** - POST /analyze - Analyze data structure and suggest ERP/entity combinations - POST /validate - Validate file format and structure **Template Information:** - GET /template/erp/{erp}/entity/{entity} - Get specific mapping - GET /template/entity/{entity}/schema - Get CDF schema ### 2. Transformation Engine (mapper/transformation_engine.py) Main orchestrator class with key functions: - transform() - Main transformation function with auto-detection - _load_data() - Load data from various sources (files, bytes, paths) - _template_based_transform() - Direct template mapping when ERP/entity known - _auto_detect_and_transform() - Auto-detect ERP/entity and transform - _detect_erp_and_entity() - Detect ERP system and entity type - _ai_assisted_transform() - AI-powered mapping when templates fail - _apply_column_mapping() - Apply column transformations - _apply_data_types() - Apply proper data types and formatting - analyze_data() - Analyze input data and provide insights ### 3. Data Processor (mapper/data_processor.py) High-performance data processing using Polars and DuckDB: - detect_file_format() - Auto-detect file format from extension - load_file() - Load files into Polars DataFrame - _load_csv(), _load_excel(), _load_json(), _load_sql() - Format-specific loaders - load_from_bytes() - Load data from byte streams - normalize_column_names() - Normalize column names for processing - get_column_info() - Get detailed DataFrame column information - export_dataframe() - Export DataFrame to various formats - to_dict() - Convert DataFrame to dictionary format ### 4. Template Loader (mapper/template_loader.py) Manages ERP to CDF mapping templates: - load_template() - Load mapping template from JSON file - get_erp_names() - Get list of available ERP systems - get_entity_mapping() - Get column mapping for specific ERP/entity - get_cdf_schema() - Get CDF column schema for entity - get_all_erp_columns() - Get all columns for an entity across ERPs - _validate_template() - Validate template structure ### 5. ERP Resolver (mapper/erp_resolver.py) Auto-detection of ERP systems using similarity matching: - detect_erp() - Detect ERP system from column names - get_similarity_scores() - Get similarity scores for all ERPs - _calculate_similarity_scores() - Calculate Jaccard similarity scores - _jaccard_similarity() - Calculate Jaccard similarity coefficient - get_matching_columns() - Get detailed column matching information - suggest_best_matches() - Suggest best ERP matches with details ### 6. LLM Handler (mapper/llm_handler.py) AI-assisted mapping using LangChain and Groq Cloud: - infer_mapping() - Infer column mapping using LLM - _heuristic_mapping() - Fallback heuristic mapping - _calculate_similarity() - Calculate string similarity - _get_entity_guidance() - Get entity-specific mapping guidance - _validate_mapping() - Validate generated mappings - create_llm_handler() - Factory function for LLM handler ### 7. Models (mapper/models.py) Data models and enums: - EntityType - Enum for supported entity types - FileFormat - Enum for supported file formats - TransformationMode - Enum for transformation modes - TransformationRequest - Request model for transformations - TransformationResult - Result model for transformations - AnalysisResult - Result model for data analysis - MappingConfidence - Confidence scoring for mappings ## Supported Systems & Entities ### 11 ERP Systems: 1. Oracle Fusion 2. SAP ERP 3. Microsoft Dynamics 4. NetSuite 5. Workday 6. Infor M3 7. Infor LN 8. Epicor Kinetic 9. QAD ERP 10. IFS Cloud 11. Sage Intacct ### 5 Entity Types: 1. Sales Orders (13 fields) - Order transactions with line items 2. Customers (16 fields) - Customer master data with full address 3. Invoices (14 fields) - Invoice documents 4. Purchase Orders (14 fields) - Purchase order documents 5. Inventory Items (12 fields) - Product catalog data ### File Formats: - CSV, Excel (.xlsx/.xls), JSON, SQL, Parquet ## How to Run the Application ### Prerequisites: ```bash # Install Python 3.11+ # Install dependencies pip install -r requirements.txt # Optional: Set up Groq API key for LLM features export GROQ_API_KEY="your-groq-api-key" ``` ### Option 1: API Server (Recommended) ```bash # Start the FastAPI server python app.py # API available at: http://localhost:8000 # Interactive docs at: http://localhost:8000/docs ``` ### Option 2: Python Package Usage ```python from mapper import TransformationEngine, TransformationRequest # Create engine engine = TransformationEngine() # Transform with auto-detection request = TransformationRequest( auto_select_erp=True, auto_select_entity=True, file_data="sample.csv" ) result = engine.transform(request) print(f"Transformed {len(result.data)} records") ``` ## Input/Output Examples ### Sample Input (NetSuite Sales Orders): ```json [ { "tranId": "SO1001", "trandate": "2025-08-04", "entity": "CUST01", "total": 1249.0, "memo": "Rush order" } ] ``` ### Output (CDF Format): ```json [ { "order_id": "SO1001", "order_date": "2025-08-04", "customer_id": "CUST01", "status": null, "currency": null, "total_amount": 1249.0, "notes": "Rush order", "item_id": null, "description": null, "quantity": null, "unit_price": null, "line_total": null, "tax_code": null } ] ``` ## API Usage Examples ### Transform JSON Data: ```bash curl -X POST "http://localhost:8000/transform" \ -H "Content-Type: application/json" \ -d '{ "auto_select_erp": true, "auto_select_entity": true, "data": [{"tranId": "SO1001", "total": 1249.0}] }' ``` ### Transform File: ```bash curl -X POST "http://localhost:8000/transform/file" \ -F "file=@sample.csv" \ -F "auto_select_erp=true" ``` ### Analyze Data Structure: ```bash curl -X POST "http://localhost:8000/analyze" \ -F "file=@sample.csv" ``` ### Download Transformed File: ```bash curl -X POST "http://localhost:8000/transform/file/download" \ -F "file=@sample.csv" \ -F "output_format=csv" \ -o transformed_data.csv ``` ## CDF Schema Details ### Sales Orders (13 fields): - order_id, order_date, customer_id, status, currency - total_amount, notes, item_id, description, quantity - unit_price, line_total, tax_code ### Customers (16 fields): **Core**: customer_id, customer_name, contact_email, phone_number, alt_phone **Business**: is_company, status, currency, created_date, last_modified **Address**: address_type, address_line1, city, state, postal_code, country ### Invoices (14 fields): - invoice_id, invoice_date, customer_id, status, currency - total_amount, due_date, notes, item_id, description - quantity, unit_price, line_total, tax_code ### Purchase Orders (14 fields): - po_id, po_date, vendor_id, status, currency - total_amount, expected_receipt_date, notes, item_id, description - quantity, unit_price, line_total, tax_code ### Inventory Items (12 fields): - item_id, item_name, description, purchase_description, sales_description - base_price, cost_price, unit_type, is_active, quantity_on_hand - reorder_point, preferred_vendor_id ## Key Features ### High Performance: - Polars for lightning-fast DataFrame operations - DuckDB for optimized SQL query execution - Memory-efficient streaming for large files - Processing times: <100ms (small), <500ms (medium), <2s (large files) ### Intelligent Processing: - Auto-detection of ERP systems using Jaccard similarity - AI-assisted mapping with LangChain + Groq LLM - Template-based mapping for known systems - Fallback heuristic mapping ### Data Consistency: - ISO date formats (yyyy-MM-dd) - DECIMAL(18,2) precision for currency - Proper boolean and text field handling - UTF-8 encoding with escaping ## Dependencies (requirements.txt) ### Core Dependencies: - pandas>=2.0.0 - polars>=0.20.0 - duckdb>=0.10.0 - pydantic>=2.0.0 - fastapi>=0.100.0 - uvicorn[standard]>=0.20.0 ### LLM Integration (optional): - groq>=0.4.0 - langchain>=0.1.0 - langchain-groq>=0.1.0 ### Additional Utilities: - python-multipart (FastAPI file uploads) - python-dotenv (Environment variables) ### Development Dependencies (optional): - pytest>=7.0.0 - pytest-asyncio - httpx (Testing FastAPI endpoints) - black (Code formatting) - isort (Import sorting) - mypy (Type checking) ## Template Structure (template.json) The template.json file contains 883+ field mappings across 11 ERP systems: ```json { "NetSuite": { "sales_orders": { "tranId": "order_id", "trandate": "order_date", "entity": "customer_id", "total": "total_amount" } }, "CDF_META": { "sales_orders": [ "order_id", "order_date", "customer_id", "status", "currency", "total_amount", "notes", "item_id", "description", "quantity", "unit_price", "line_total", "tax_code" ] } } ``` ## Environment Variables ```bash # Optional: Groq API key for LLM fallback GROQ_API_KEY=your-groq-api-key # Optional: Custom template file path TEMPLATE_PATH=./custom-template.json ``` ## Testing ### System Validation: ```bash # Test core components python -c " from mapper import TransformationEngine, DataProcessor, FileFormat engine = TransformationEngine(use_mock_llm=True) processor = DataProcessor() print('✅ All components operational') " # Test API python -c " from app import app, transformation_engine print(f'✅ API ready: {app.title} v{app.version}') " ``` ### API Testing: ```bash # Start server python app.py # Test endpoints curl http://localhost:8000/health curl http://localhost:8000/entities curl http://localhost:8000/erps ``` ## Error Handling ### HTTP Status Codes: - 200: Success - 400: Bad Request (invalid input, unsupported format) - 404: Not Found (template mapping not found) - 422: Validation Error (invalid request body) - 500: Internal Server Error ### Common Errors: - Unsupported file format - Missing template mappings - Invalid request parameters - File processing failures ## Performance Benchmarks - Small files (< 1MB): < 100ms processing time - Medium files (1-10MB): < 500ms processing time - Large files (10-100MB): < 2s processing time ## Deployment ### Docker: ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "app.py"] ``` ### Production Considerations: - Use production ASGI server (Gunicorn + Uvicorn) - Configure logging and monitoring - Implement authentication and rate limiting - Set up health checks and metrics ## Project Structure ``` cleanflowai/ ├── app.py # Main FastAPI application ├── template.json # ERP mapping templates (883+ mappings) ├── requirements.txt # Dependencies ├── devinfo.txt # This file ├── docs/ # Documentation │ ├── API_DOCUMENTATION.md # Complete API docs │ └── PROJECT_STRUCTURE.md # Architecture details └── mapper/ # Core transformation package ├── __init__.py # Package exports ├── transformation_engine.py # Main orchestrator (Polars/DuckDB) ├── data_processor.py # High-performance data processing ├── template_loader.py # Template management ├── erp_resolver.py # ERP auto-detection ├── llm_handler.py # AI integration └── models.py # Pydantic models & CDF schemas ``` ## Data Flow ``` Input Data → DataProcessor (Polars/DuckDB) → ERP Detection → Template Mapping → Transformation → CDF Output ``` ## Version Information - API Version: 2.0.0 - Engine: Polars + DuckDB - Python: 3.11+ - Last Updated: August 5, 2025 The system provides enterprise-grade ERP data integration with 883+ field mappings across 11 ERP systems, making it suitable for large-scale data transformation and standardization projects.