An AI-powered backend application built with Flask that provides demand forecasting and production recommendations using Facebook Prophet.
git clone <repository-url>
cd prophet_ERP
docker-compose up -dThe API will be available at http://localhost:5000
# Install dependencies
pip install -r requirements.txt
# Initialize database
export DATABASE_URL="sqlite:///prophet_erp.db"
python init_db.py
# Start the application
python app/main.py# Run the interactive demo (server must be running)
python demo.py- Sales, Production, and Inventory Management: Store and track business data in PostgreSQL/SQLite
- AI-Powered Forecasting: Uses Facebook Prophet to predict demand for each SKU
- Production Recommendations: Calculates optimal production quantities using EOQ and safety stock formulas
- RESTful API: Clean JSON API endpoints for all operations
- Docker Support: Complete containerization with docker-compose
- Model Persistence: Automatic model saving/loading per SKU
- Real-time Health Monitoring: Database connectivity and system status checks
- Backend: Flask with SQLAlchemy ORM
- Database: PostgreSQL (production) / SQLite (development)
- AI/ML: Facebook Prophet, pandas, numpy, scikit-learn
- Validation: Pydantic
- Deployment: Docker & docker-compose
- Testing: pytest
curl -X POST http://localhost:5000/sales \
-H "Content-Type: application/json" \
-d '{
"sku": "PROD001",
"date": "2024-01-01",
"quantity": 50
}'curl -X POST http://localhost:5000/production \
-H "Content-Type: application/json" \
-d '{
"sku": "PROD001",
"date": "2024-01-01",
"quantity": 100
}'curl -X POST http://localhost:5000/inventory \
-H "Content-Type: application/json" \
-d '{
"sku": "PROD001",
"date": "2024-01-01",
"quantity": 150
}'curl "http://localhost:5000/forecast/PROD001?days_ahead=30"Response includes:
- Raw predictions with confidence intervals
- Chart-ready data arrays
- Forecast period information
curl "http://localhost:5000/recommendations/PROD001?days_ahead=30"Response includes:
- Recommended production quantity
- Current stock levels
- Forecasted demand
- Safety stock calculation
- Detailed reasoning
curl http://localhost:5000/statusThe forecasting module (app/services/forecasting.py) implements:
- π€ Prophet Model Training: Automatically trains time series models on historical sales data
- πΎ Model Persistence: Saves/loads trained models to reduce computation time
- π Demand Forecasting: Predicts future demand with confidence intervals
- π‘οΈ Safety Stock Calculation: Uses historical demand variability (95% service level)
- π Smart Production Recommendations:
Forecasted Demand + Safety Stock - Current Stock
- Data Preparation: Aggregates sales data by date for each SKU
- Model Training: Uses Facebook Prophet with yearly and weekly seasonality
- Prediction: Generates forecasts for specified time horizon
- Safety Stock: Z-score calculation with demand variability analysis
- Production Recommendation: AI-driven optimal production quantities
Real Demo Output:
π FORECAST SUMMARY:
β’ Forecast Period: 14 days
β’ Total Predicted Demand: 1,822.8 units
β’ Average Daily Demand: 130.2 units
β’ Range: 116.1 - 126.1 units
π PRODUCTION RECOMMENDATION:
β’ Recommended Production: 1,704.93 units
β’ Current Stock: 200.0 units
β’ Forecasted Demand: 1,822.8 units
β’ Safety Stock: 82.13 unitsprophet_ERP/
βββ app/
β βββ main.py # Application factory and entry point
β βββ config.py # Configuration settings
β βββ database.py # Database initialization
β βββ models.py # SQLAlchemy models (sales, production, inventory, deficits)
β βββ schemas.py # Pydantic validation schemas
β βββ routes/
β β βββ __init__.py # API route definitions
β βββ services/
β βββ forecasting.py # Prophet forecasting service
βββ models/ # Stored Prophet models (one per SKU)
βββ sample_data/ # Sample CSV data for testing
βββ tests/ # Unit tests
βββ demo.py # Interactive demo script
βββ Dockerfile # Container definition
βββ docker-compose.yml # Multi-service deployment
βββ requirements.txt # Python dependencies
βββ init_db.py # Database initialization script
Load the provided sample data for testing:
import pandas as pd
import requests
# Load sales data
sales_df = pd.read_csv('sample_data/sales_data.csv')
for _, row in sales_df.iterrows():
response = requests.post('http://localhost:5000/sales', json={
'sku': row['sku'],
'date': row['date'],
'quantity': row['quantity']
})
# Load inventory data
inventory_df = pd.read_csv('sample_data/inventory_data.csv')
for _, row in inventory_df.iterrows():
response = requests.post('http://localhost:5000/inventory', json={
'sku': row['sku'],
'date': row['date'],
'quantity': row['quantity']
})Automatic Training: Models are automatically trained when:
- A forecast is requested for a SKU with no existing model
- You manually delete the model file in
models/{sku}_prophet_model.pkl
Model Storage: Models are persisted in the models/ directory with naming: {SKU}_prophet_model.pkl
Minimum Data: Requires at least 2 data points (recommended: 30+ for better accuracy)
Run the test suite:
# Install test dependencies
pip install pytest pytest-flask
# Run tests
pytest tests/ -vTests cover:
- Forecasting service functionality
- API endpoint validation
- Data model operations
- Error handling scenarios
DATABASE_URL: PostgreSQL/SQLite connection stringSECRET_KEY: Flask secret key for session management
export DATABASE_URL="sqlite:///prophet_erp.db"
python app/main.pydocker-compose up -dexport DATABASE_URL="postgresql://user:password@localhost:5432/prophet_erp"
export SECRET_KEY="your-secure-secret-key"
gunicorn --bind 0.0.0.0:5000 --workers 4 "app.main:create_app()"- Database Connection Error: Ensure PostgreSQL is running and connection details are correct
- Prophet Installation Issues: May require additional system dependencies on some platforms
- Model Training Failures: Ensure sufficient historical data (minimum 2 data points, recommended 30+)
- Memory Issues: Prophet models can be memory-intensive for large datasets
Application logs include:
- Model training status
- API request/response details
- Error messages with stack traces
- Performance metrics
- Training Time: ~1-3 seconds for 30 days of data
- Prediction Time: ~100ms for 30-day forecasts
- Memory Usage: ~50MB per trained model
- Concurrent Requests: Supports multiple simultaneous API calls
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
MIT License - see LICENSE file for details
Built with β€οΈ using Flask, Prophet, and modern Python practices