BackendPayactiv / API_INTEGRATION.md
3v324v23's picture
Deploy backend: add FastAPI app and Dockerfile
7c850fc
|
Raw History Blame Contribute Delete
6.29 kB
# Unified Financial & Demand Forecast API
A single FastAPI backend serving both **EWA Demand Forecasting** and **Financial Distress Risk Prediction**.
## Features
βœ… **EWA Demand Forecasting**
- Exponential Weighted Average model for time series prediction
- Support for simple and Holt's double exponential smoothing
- Automatic parameter optimization or custom alpha/beta values
- Batch prediction support
βœ… **Financial Distress Prediction**
- Predict financial distress risk based on spending patterns
- Risk scores from 0 (no risk) to 1 (highest risk)
- Integration with EWA features
βœ… **Production Ready**
- Docker containerization
- Deployed on Render
- Comprehensive API documentation
- Gradio web interface
## Endpoints
### Health & Information
**GET** `/health`
- Health check endpoint
- Returns: `{status: "ok", version: "2.0.0"}`
**GET** `/model-info`
- Get model metadata and default parameters
- Returns: Model name, version, supported algorithms, defaults
**GET** `/docs` (Swagger UI)
- Interactive API documentation
### EWA Demand Forecast
**POST** `/predict`
- Single forecast prediction
- Request body:
```json
{
"history": [10, 12, 15, 14, 16],
"horizon": 5,
"alpha": 0.3,
"beta": 0.1,
"confidence_level": 0.95
}
```
- Returns: Forecast values, confidence intervals, parameters used
**POST** `/predict/batch`
- Multiple forecasts in one request
- Request body: Array of forecast requests
- Returns: Array of forecast responses
### Financial Distress
**POST** `/distress/predict`
- Predict financial distress risk for a user
- Request body:
```json
{
"user_id": "user_123",
"total_spend": 5000,
"txn_count": 50,
"total_spend_30d": 1500,
"max_daily_spend_30d": 300,
"txn_count_30d": 15,
"ewa_usage_count": 5,
"ewa_total_amount": 500,
"ewa_avg_amount": 100,
"ewa_max_amount": 200
}
```
- Returns: `{user_id, risk_score, model_type, timestamp}`
## Local Development
### Installation
```bash
pip install -r requirements.txt
```
### Running the Backend
```bash
python main.py
```
Server starts at `http://localhost:8000`
### Testing
```bash
# In another terminal
python test_api.py
```
## Deployment
### Docker
```bash
docker build -t ewa-api .
docker run -p 8000:8000 ewa-api
```
### Render (Production)
- Repository: https://github.com/JiainingZhan/ewa-demand-forecast-api
- Deployed at: https://ewa-demand-forecast-api.onrender.com
- Start Command: `uvicorn main:app --host 0.0.0.0 --port $PORT`
## Gradio Frontend
A Gradio interface is available at:
- Hugging Face Spaces: (Link TBD)
- Or run locally: `python gradio_app.py`
### Features
1. **Tab 1: EWA Demand Forecast**
- Input historical data
- Set forecast horizon
- Customize smoothing parameters
- View forecast and confidence intervals
2. **Tab 2: Financial Distress Risk**
- Input user spending features
- Get risk score with color-coded risk level
- Integration with EWA features
3. **Tab 3: API Info**
- Endpoint documentation
- API base URL configuration
## Architecture
### Single Unified Backend
Both models run in the same FastAPI application:
- No inter-service communication overhead
- Shared configuration and dependencies
- Financial Distress model can internally call EWA functions if needed
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Gradio Frontend (HF Spaces) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ HTTP Requests
↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Unified FastAPI Backend β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β€’ /predict (EWA) β”‚
β”‚ β€’ /predict/batch (EWA) β”‚
β”‚ β€’ /distress/predict (Distress) β”‚
β”‚ β€’ /health, /model-info β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
## Configuration
### Environment Variables
- `API_BASE_URL`: Backend URL for Gradio frontend (default: `http://localhost:8000`)
- `EWA_HOST`: FastAPI host (default: `0.0.0.0`)
- `EWA_PORT`: FastAPI port (default: `8000`)
- `EWA_DEBUG`: Debug mode (default: `false`)
## Project Structure
```
β”œβ”€β”€ main.py # FastAPI application entry point
β”œβ”€β”€ config.py # Configuration management
β”œβ”€β”€ models/
β”‚ β”œβ”€β”€ forecast.py # EWA forecast model
β”‚ └── distress.py # Financial distress model
β”œβ”€β”€ schemas/
β”‚ β”œβ”€β”€ request.py # Request Pydantic models
β”‚ └── response.py # Response Pydantic models
β”œβ”€β”€ utils/
β”‚ └── validation.py # Input validation utilities
β”œβ”€β”€ gradio_app.py # Gradio web interface
β”œβ”€β”€ requirements.txt # Python dependencies
β”œβ”€β”€ Dockerfile # Docker configuration
└── test_api.py # API endpoint tests
```
## Dependencies
- **FastAPI 0.115+**: Web framework
- **Uvicorn 0.30+**: ASGI server
- **Pydantic 2.6+**: Data validation
- **NumPy 1.26+**: Numerical computing
- **SciPy 1.12+**: Scientific computing
- **Pandas 2.0+**: Data manipulation
- **Scikit-learn 1.3+**: Machine learning
- **XGBoost 2.0+**: Gradient boosting (optional)
- **Gradio 6.0+**: Web UI (for frontend)
## Troubleshooting
### Status 127 on Render
- Check that Start Command is: `uvicorn main:app --host 0.0.0.0 --port $PORT`
- Verify all dependencies installed: Check `requirements.txt`
- Review Render logs for specific errors
### Import Errors
- Ensure all dependencies installed: `pip install -r requirements.txt`
- Check Python version: Must be 3.9+
### XGBoost Issues
- macOS: `brew install libomp`
- Can safely ignore if Financial Distress model uses heuristic fallback
## Support
For issues or questions:
- GitHub: https://github.com/JiainingZhan/ewa-demand-forecast-api
- Issues: Open a GitHub issue with detailed description
---
*Last updated: 2024*