Skip to content

lilnurik/ml-PR_v0.1

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Production Platform - Flask + ML Implementation

A comprehensive production planning and inventory management platform built with Python Flask, featuring machine learning capabilities for demand forecasting and production scheduling.

πŸš€ Features

Core Functionality

  • Multi-role Access Control: Admin, Sales, Warehouse, Factory, and Viewer roles
  • Order Management: Complete order lifecycle from creation to shipment
  • Inventory Management: Real-time stock tracking with automatic updates
  • Production Planning: Work order management and production scheduling
  • Machine Learning: Demand forecasting with LightGBM and ETA prediction
  • RESTful API: Comprehensive API for all operations with OpenAPI documentation

Business Logic

  • Authoritative Inventory: Platform manages all stock movements automatically
  • Check-and-Reserve: Automatic inventory allocation with production request creation
  • Production Flow: Seamless PR β†’ WO β†’ Receipt β†’ Allocation workflow
  • ETA Calculation: ML-driven delivery time estimates with confidence intervals
  • Audit Trail: Complete tracking of all system changes

Technical Features

  • Flask Application Factory: Modular architecture with blueprints
  • SQLAlchemy ORM: Database abstraction with SQLite default (PostgreSQL ready)
  • Role-based Security: JWT tokens for API, Flask-Login for web interface
  • Service Layer: Clean separation of business logic
  • Responsive UI: Bootstrap-based templates for all user roles
  • Docker Ready: Full containerization with docker-compose

πŸ“‹ Quick Start

Prerequisites

  • Python 3.8+
  • SQLite (included) or PostgreSQL (optional)
  • Git

Installation

# Clone repository
git clone <repository-url>
cd ml-PR_v0.1

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
# or .venv\Scripts\activate  # Windows

# Install dependencies
pip install -r requirements.txt

# Setup environment
cp .env.example .env

# Initialize database
export FLASK_APP=src.app:create_app
flask db init
flask db migrate -m "Initial migration"
flask db upgrade

# Generate demo data
python scripts/generate_demo_data.py

# Run application
flask run --host=0.0.0.0 --port=5000

Access Application

  • Web Interface: http://localhost:5000
  • Default Credentials:
    • Admin: admin/password
    • Sales: sales/password
    • Warehouse: warehouse/password
    • Factory: factory/password

πŸ—οΈ Architecture

Application Structure

src/
β”œβ”€β”€ app.py                 # Flask application factory
β”œβ”€β”€ config.py             # Configuration management
β”œβ”€β”€ models_db.py          # SQLAlchemy models
β”œβ”€β”€ schemas.py            # Marshmallow validation schemas
β”œβ”€β”€ auth.py               # Authentication utilities
β”œβ”€β”€ blueprints/           # Flask blueprints for each module
β”‚   β”œβ”€β”€ main.py          # Landing page and routing
β”‚   β”œβ”€β”€ auth.py          # Login/logout functionality
β”‚   β”œβ”€β”€ sales.py         # Sales order management
β”‚   β”œβ”€β”€ warehouse.py     # Inventory and receipts
β”‚   β”œβ”€β”€ factory.py       # Production management
β”‚   β”œβ”€β”€ admin.py         # User and system management
β”‚   β”œβ”€β”€ ml.py            # ML model management
β”‚   └── api.py           # REST API endpoints
β”œβ”€β”€ services/            # Business logic layer
β”‚   β”œβ”€β”€ inventory_service.py    # Inventory operations
β”‚   β”œβ”€β”€ order_service.py        # Order processing
β”‚   β”œβ”€β”€ production_service.py   # Production management
β”‚   β”œβ”€β”€ ml_service.py          # Machine learning
β”‚   └── planner_service.py     # Production planning
β”œβ”€β”€ templates/           # Jinja2 templates
└── static/             # CSS, JS, images

Database Schema

  • Reference Data: Sectors, Lines, SKUs, Line Capabilities
  • Inventory: Stock levels, movements, reservations
  • Orders: Customer orders with items and status tracking
  • Production: Production requests, work orders, receipts
  • Users & Auth: Role-based access control
  • ML Models: Model registry with versioning
  • Audit: Complete change tracking

πŸ”„ Business Workflows

Order Processing

  1. Sales creates order β†’ System assigns NEW status
  2. Check-and-Reserve β†’ Allocates available inventory
  3. Production Requests β†’ Created for shortages automatically
  4. Work Orders β†’ Factory schedules production
  5. Completion β†’ Production creates receipts
  6. Allocation β†’ System allocates completed production
  7. Shipping β†’ Sales ships when fully allocated

Inventory Management

  1. Receipts β†’ Warehouse creates incoming goods receipts
  2. Confirmation β†’ System updates stock levels automatically
  3. Movements β†’ All changes tracked with audit trail
  4. Reservations β†’ Automatic allocation for orders
  5. Adjustments β†’ Manual corrections with approval

Production Planning

  1. Demand Forecast β†’ ML models predict requirements
  2. Capacity Planning β†’ Greedy algorithm optimizes schedules
  3. ETA Calculation β†’ Delivery estimates with confidence
  4. Real-time Updates β†’ ETAs adjust based on progress

πŸ€– Machine Learning

Demand Forecasting

  • Algorithm: LightGBM with feature engineering
  • Features: Time-based, lag, rolling statistics, seasonality
  • Validation: Rolling origin cross-validation
  • Metrics: sMAPE, MAPE, MAE with per-SKU tracking

Production Planning

  • ETA Calculation: Multi-factor scheduling with uncertainty
  • Capacity Planning: Greedy algorithm with optional OR-Tools
  • Confidence Scoring: Historical performance-based estimates

Model Management

  • Version Control: Full model registry with metadata
  • A/B Testing: Model comparison and promotion
  • Explainability: SHAP values for prediction interpretation

πŸ”§ API Reference

Authentication

POST /api/auth/login
{
  "username": "sales",
  "password": "password"
}

Order Management

# Create order
POST /api/sales/orders
{
  "customer_id": 1001,
  "customer_name": "Acme Corp",
  "items": [{"sku_id": 1, "qty": 100}]
}

# Check and reserve inventory
POST /api/sales/orders/1/check-and-reserve

Inventory Operations

# Get inventory levels
GET /api/warehouse/inventory

# Create receipt
POST /api/warehouse/receipts
{
  "supplier": "Supplier A",
  "items": [{"sku_id": 1, "qty": 50, "batch": "B123"}]
}

# Confirm receipt
POST /api/warehouse/receipts/1/confirm

Production Management

# Get production requests
GET /api/factory/prs

# Create work order
POST /api/factory/wo
{
  "pr_id": 1,
  "sku_id": 1,
  "line_id": 1,
  "qty_planned": 100
}

# Complete work order
POST /api/factory/wo/1/complete
{
  "qty_done": 95,
  "notes": "Minor quality issues"
}

ML and Planning

# Train model
POST /api/ml/train
{
  "model": "lgbm",
  "retrain": true
}

# Generate forecast
POST /api/ml/forecast
{
  "horizon": 7,
  "skus": [1, 2, 3]
}

# Calculate ETA
POST /api/planner/eta
{
  "items": [{"sku_id": 1, "qty_needed": 100}],
  "use_solver": false
}

πŸ§ͺ Testing

# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=html

# Run specific test categories
pytest tests/unit/
pytest tests/integration/

🐳 Docker Deployment

# Build and run with Docker Compose
docker-compose up -d

# View logs
docker-compose logs -f web

# Scale workers (if using Celery)
docker-compose up -d --scale worker=3

πŸ“Š Production Considerations

Database

  • Development: SQLite (included)
  • Production: PostgreSQL recommended
  • Migrations: Flask-Migrate for schema changes

Scaling

  • Web Servers: Multiple gunicorn workers
  • Background Tasks: Celery + Redis for async processing
  • Load Balancing: Nginx or cloud load balancer
  • Monitoring: Application and database metrics

Security

  • Authentication: JWT tokens with expiration
  • Authorization: Role-based access control
  • Input Validation: Marshmallow schemas
  • SQL Injection: SQLAlchemy ORM protection
  • XSS Protection: Flask built-in security

πŸ” Monitoring and Debugging

Health Checks

  • Application: /api/health endpoint
  • Database: Connection validation
  • ML Models: Model availability and performance

Logging

  • Application Logs: Structured logging with levels
  • Audit Trail: Complete change tracking
  • Performance: Request timing and metrics

Development Tools

  • Flask Debug Mode: Detailed error pages
  • Database Browser: SQLite inspection tools
  • API Testing: Built-in test client

🀝 Contributing

  1. Code Style: Follow PEP 8 with black formatting
  2. Testing: Maintain test coverage above 80%
  3. Documentation: Update README and API docs
  4. Database: Use migrations for schema changes
  5. Security: Review authentication and authorization

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

Troubleshooting

  1. Database Issues: Check SQLite permissions, try flask db upgrade
  2. Import Errors: Verify virtual environment activation
  3. Permission Errors: Ensure data directories are writable
  4. ML Errors: Verify demo data exists and models directory is writable

Development

  • Documentation: See RUN_INSTRUCTIONS.md for detailed setup
  • API Docs: Available at /api/docs when implemented
  • Demo Data: Run python scripts/generate_demo_data.py

For additional support, check the comprehensive documentation and test the application with provided demo credentials.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages