Spaces:
Runtime error
Runtime error
File size: 12,834 Bytes
3d8755c | 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 | # 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.
|