cleanflowai / README.md
AashishSankar's picture
fix: Update colorTo in README from cyan to indigo
e3ecac1
|
Raw History Blame Contribute Delete
12.7 kB
---
title: CleanflowAI
emoji: 🐳
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 8000
pinned: false
---
# ERP to CDF Transformation System v2.0
A high-performance Python system for converting ERP data exports into a standardized Common Data Frame (CDF) format using Polars and DuckDB.
## 🌟 Features
- ⚑ **High-Performance Processing** with Polars and DuckDB
- πŸ”„ **Template-driven mapping** with intelligent ERP auto-detection
- πŸ€– **AI-assisted mapping** for unknown ERP schemas
- πŸ“Š **Multiple file formats**: CSV, Excel, JSON, SQL, Parquet
- πŸš€ **FastAPI REST API** with comprehensive endpoints
- 🏒 **11 Enterprise ERP Systems** with 883+ field mappings
- πŸ“ **Enhanced data models** with full address support (16 fields)
- 🎯 **5 Entity Types**: Sales Orders, Customers, Invoices, Purchase Orders, Inventory Items
- πŸ”§ **Production-ready** with data format consistency and error handling
## πŸš€ Quick Start
### Installation
```bash
# Clone the repository
git clone <repository-url>
cd cleanflowai
# Install dependencies
pip install -r requirements.txt
# Install high-performance dependencies
pip install polars duckdb
# Optional: Set up OpenAI API key for LLM fallback
export OPENAI_API_KEY="your-api-key-here"
```
### Option 1: API Server (Recommended)
```bash
# Start the API server
python app.py
# API will be available at http://localhost:8000
# Interactive docs at http://localhost:8000/docs
```
### Option 2: Python Package
```python
from mapper import TransformationEngine, TransformationRequest
# Create transformation engine
engine = TransformationEngine()
# Transform data 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")
```
### Option 3: Quick Transform
```python
from mapper import quick_transform
# One-liner transformation
result = quick_transform(
file_data="sample.csv",
auto_detect=True
)
if result.success:
print(f"βœ… Converted {len(result.data)} records")
print(f"πŸ” Detected ERP: {result.detected_erp}")
```
## πŸ“Š API Endpoints
### 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
### Information
- `GET /health` - Health check
- `GET /entities` - List supported entity types
- `GET /erps` - List supported ERP systems
- `GET /formats` - List supported file formats
### Template Inspection
- `GET /template/erp/{erp}/entity/{entity}` - Get specific mapping
- `GET /template/entity/{entity}/schema` - Get CDF schema
### Example API Usage
```bash
# Transform JSON data
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}]
}'
# Upload and transform file
curl -X POST "http://localhost:8000/transform/file" \
-F "file=@sample.csv" \
-F "auto_select_erp=true"
# Download transformed file
curl -X POST "http://localhost:8000/transform/file/download" \
-F "file=@sample.csv" \
-F "output_format=csv" \
-o transformed_data.csv
```
## πŸ—οΈ Architecture
### Clean Project Structure
```
cleanflowai/
β”œβ”€β”€ app.py # Main FastAPI application
β”œβ”€β”€ template.json # ERP mapping templates (883+ mappings)
β”œβ”€β”€ requirements.txt # Dependencies
β”œβ”€β”€ 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
```
## 🏒 Supported ERP Systems
### Enterprise Coverage (11 Systems)
| ERP System | Status | Description |
|------------|--------|-------------|
| **Oracle Fusion** | βœ… Complete | Oracle's cloud ERP platform |
| **SAP ERP** | βœ… Complete | SAP's enterprise resource planning |
| **Microsoft Dynamics** | βœ… Complete | Microsoft business applications |
| **NetSuite** | βœ… Complete | Oracle NetSuite cloud ERP |
| **Workday** | βœ… Complete | Cloud HR and financial management |
| **Infor M3** | βœ… Complete | Manufacturing and distribution ERP |
| **Infor LN** | βœ… Complete | Enterprise manufacturing ERP |
| **Epicor Kinetic** | βœ… Complete | Manufacturing ERP solution |
| **QAD ERP** | βœ… Complete | Manufacturing ERP |
| **IFS Cloud** | βœ… Complete | ERP and asset management |
| **Sage Intacct** | βœ… Complete | Cloud financial management |
## πŸ“‹ Entity Types & CDF Schemas
### 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 with full address)
**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`
## πŸ“ File Format Support
| Format | Extension | Description |
|--------|-----------|-------------|
| **CSV** | `.csv` | Comma-separated values |
| **Excel** | `.xlsx`, `.xls` | Microsoft Excel files |
| **JSON** | `.json` | JavaScript Object Notation |
| **SQL** | `.sql` | SQL query results |
| **Parquet** | `.parquet` | Columnar storage format |
## πŸ”§ Data Format Consistency
### Date Fields
- **APIs/Database**: ISO `yyyy-MM-dd` format
- **Human-readable**: `dd-MMMM-yyyy` format (e.g., `04-August-2025`)
### Decimal Fields
- **Precision**: DECIMAL(18,2) for all currency and pricing
- **Format**: Always 2 decimal places (e.g., `1249.00`)
### Boolean Fields
- **JSON/API**: `true`/`false`
- **Database**: `1`/`0`
### Text Fields
- **Encoding**: UTF-8 with proper escaping
- **Processing**: Trimmed and normalized
## ⚑ Performance
### Benchmarks
- **Small files** (< 1MB): < 100ms processing time
- **Medium files** (1-10MB): < 500ms processing time
- **Large files** (10-100MB): < 2s processing time
### High-Performance Features
- **Polars**: Lightning-fast DataFrame operations
- **DuckDB**: Optimized SQL query execution
- **Memory efficiency**: Streaming for large files
- **Concurrent processing**: FastAPI async support
## πŸ” Advanced Usage
### Custom Configuration
```python
from mapper import TransformationEngine
# Custom engine with specific settings
engine = TransformationEngine(
template_path="custom-template.json",
use_mock_llm=False,
similarity_threshold=0.6
)
```
### Batch Processing
```python
from pathlib import Path
from mapper import create_transformation_engine
engine = create_transformation_engine()
# Process multiple files
for file_path in Path("data").glob("*.csv"):
request = TransformationRequest(
auto_select_erp=True,
auto_select_entity=True,
file_data=str(file_path)
)
result = engine.transform(request)
if result.success:
print(f"βœ… {file_path.name}: {len(result.data)} records")
```
### Custom LLM Integration
```python
from mapper import TransformationEngine, LLMHandler
# Custom LLM configuration
llm_handler = LLMHandler(
model_name="gpt-4o",
temperature=0.0,
max_retries=3
)
engine = TransformationEngine(llm_handler=llm_handler)
```
## πŸ§ͺ 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
```
## πŸš€ Deployment
### Local Development
```bash
python app.py
# API available at http://localhost:8000
```
### Docker Deployment
```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
## πŸ”§ Configuration
### Environment Variables
```bash
# Optional: OpenAI API key for LLM fallback
OPENAI_API_KEY=your-api-key-here
# Optional: Custom template file path
TEMPLATE_PATH=./custom-template.json
```
### Template Structure
The `template.json` file defines ERP-to-CDF mappings:
```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"
]
}
}
```
## πŸ“š Documentation
- **[API Documentation](docs/API_DOCUMENTATION.md)** - Complete API reference
- **[Project Structure](docs/PROJECT_STRUCTURE.md)** - Architecture details
- **[ERP System Coverage](ERP_SYSTEM_COVERAGE.md)** - Mapping statistics
- **[Data Format Guidelines](ERP-CDF-Mapping.md)** - Consistency rules
- **[Changelog](CHANGELOG.md)** - Version history
## πŸ› οΈ Development
### Adding New ERP Systems
1. Update `template.json` with new mappings
2. Test with sample data
3. Update documentation
### Adding New Entity Types
1. Define new CDF model in `models.py`
2. Add to `EntityType` enum
3. Update template structure
4. Add validation logic
### Code Quality
```bash
# Format code
black mapper/ app.py
# Sort imports
isort mapper/ app.py
# Type checking
mypy mapper/
```
## πŸ› Troubleshooting
### Common Issues
**Missing Dependencies**
```bash
pip install polars duckdb
```
**LLM API Key Missing**
```bash
export OPENAI_API_KEY="your-key-here"
# or use mock LLM for testing
```
**Template File Not Found**
```
Ensure template.json exists in working directory
```
### Debug Mode
```python
import logging
logging.basicConfig(level=logging.DEBUG)
# Use mock LLM for testing
engine = TransformationEngine(use_mock_llm=True)
```
## 🀝 Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request
## πŸ“„ License
This project is licensed under the MIT License.
## πŸ†˜ Support
For questions, issues, or feature requests:
1. Check the [API Documentation](docs/API_DOCUMENTATION.md)
2. Review the [Project Structure](docs/PROJECT_STRUCTURE.md)
3. Search existing issues
4. Create a new issue with detailed information
5. For API questions, check interactive docs at `/docs`
---
**πŸš€ Built for Enterprise-Grade ERP Data Integration**
**⚑ Powered by Polars + DuckDB for Maximum Performance**
**🎯 Version 2.0.0 - Clean, Fast, Production-Ready**