Skip to content

pasindu3/Inxai_ML

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Customer Churn Prediction API

A secure FastAPI-based REST API for predicting customer churn using machine learning models.

πŸš€ Quick Start

first read the Customer_Churn_Prediction_using_ML_v5.ipynb to create churn prediction model

1. Install Dependencies

first read the Customer_Churn_Prediction_using_ML_v5.ipynb to create churn prediction model

pip install -r requirements.txt

2. (Optional) Generate SSL Certificates

python generate_ssl_cert.py

If the step above fails on Windows due to missing openssl.cnf, the script now bundles an in-project config and should work. The script now always writes server.crt and server.key into the project folder (ignores Conda SSL_CERT_FILE). You can also skip SSL and use HTTP.

3. Start the API (auto uses HTTPS if certs exist, otherwise HTTP)

python start_api.py

4. Access the API

⚠️ IMPORTANT: Use localhost or 127.0.0.1 in your browser, NOT 0.0.0.0!

The server binds to 0.0.0.0:8000 but you access it via:

  • Web UI: https://localhost:8000/ui (or http:// if no SSL)
  • API Docs: https://localhost:8000/docs
  • ReDoc: https://localhost:8000/redoc
  • Health: https://localhost:8000/health
  • Default Credentials: admin / churn2024!

Self-Signed Certificate: Your browser will warn you about the certificate. Click "Advanced" β†’ "Proceed to localhost" to continue. This is normal for development.

For a detailed walkthrough, see QUICK_START.md

πŸ“‹ Features

  • βœ… Secure Authentication - Basic Auth with configurable credentials
  • βœ… TLS/SSL Encryption - Secure data transmission
  • βœ… Input Validation - Comprehensive data validation using Pydantic
  • βœ… Batch Processing - Predict multiple customers at once
  • βœ… Health Monitoring - Built-in health check endpoints
  • βœ… Interactive Documentation - Swagger UI and ReDoc
  • βœ… Error Handling - Detailed error messages and logging

πŸ”§ API Endpoints

Endpoint Method Description Auth Required
/ GET API information No
/ui GET Web UI for manual testing No
/health GET Health check No
/predict POST Single customer prediction Yes
/predict/batch POST Batch prediction (up to 100) Yes
/model/info GET Model information Yes
/docs GET Swagger UI documentation No
/redoc GET ReDoc documentation No

πŸ“Š Example Usage

Python Example

import requests
from requests.auth import HTTPBasicAuth

# API configuration
API_URL = "https://localhost:8000"
auth = HTTPBasicAuth("admin", "churn2024!")

# Customer data
customer_data = {
    "gender": "Female",
    "SeniorCitizen": 0,
    "Partner": "No",
    "Dependents": "No",
    "tenure": 42,
    "PhoneService": "Yes",
    "MultipleLines": "No phone service",
    "InternetService": "DSL",
    "OnlineSecurity": "Yes",
    "OnlineBackup": "Yes",
    "DeviceProtection": "No",
    "TechSupport": "No",
    "StreamingTV": "No internet service",
    "StreamingMovies": "No internet service",
    "Contract": "Two year",
    "PaperlessBilling": "No",
    "PaymentMethod": "Electronic check",
    "MonthlyCharges": 38.28,
    "TotalCharges": 1607.76
}

# Make prediction
response = requests.post(
    f"{API_URL}/predict",
    json=customer_data,
    auth=auth,
    verify=False  # For self-signed certificates
)

result = response.json()
print(f"Prediction: {result['prediction']}")
print(f"Confidence: {result['confidence']:.3f}")

cURL Example

curl -X POST "https://localhost:8000/predict" \
  -H "Content-Type: application/json" \
  -u "admin:churn2024!" \
  -k \
  -d '{
    "gender": "Female",
    "SeniorCitizen": 0,
    "Partner": "No",
    "Dependents": "No",
    "tenure": 42,
    "PhoneService": "Yes",
    "MultipleLines": "No phone service",
    "InternetService": "DSL",
    "OnlineSecurity": "Yes",
    "OnlineBackup": "Yes",
    "DeviceProtection": "No",
    "TechSupport": "No",
    "StreamingTV": "No internet service",
    "StreamingMovies": "No internet service",
    "Contract": "Two year",
    "PaperlessBilling": "No",
    "PaymentMethod": "Electronic check",
    "MonthlyCharges": 38.28,
    "TotalCharges": 1607.76
  }'

πŸ§ͺ Testing

Run the comprehensive test suite:

python test_api.py

This will test:

  • All API endpoints
  • Authentication
  • Input validation
  • Batch processing
  • Performance metrics

πŸ”’ Security Configuration

Environment Variables

# Custom credentials
export API_USERNAME="your_username"
export API_PASSWORD="your_secure_password"

# SSL configuration
export SSL_CERT_FILE="/path/to/certificate.crt"
export SSL_KEY_FILE="/path/to/private.key"

Production Security Checklist

  • Use certificates from trusted CA
  • Change default credentials
  • Implement rate limiting
  • Use reverse proxy (nginx/Apache)
  • Enable request logging
  • Regular security updates

πŸ“ File Structure

β”œβ”€β”€ churn_prediction_api.py      # Main FastAPI application
β”œβ”€β”€ generate_ssl_cert.py         # SSL certificate generator
β”œβ”€β”€ start_api.py                 # API startup script
β”œβ”€β”€ test_api.py                  # Comprehensive test suite
β”œβ”€β”€ requirements.txt             # Python dependencies
β”œβ”€β”€ API_DOCUMENTATION.md         # Detailed documentation
β”œβ”€β”€ README_API.md               # This file
β”œβ”€β”€ server.crt                  # SSL certificate (generated)
β”œβ”€β”€ server.key                  # SSL private key (generated)
β”œβ”€β”€ customer_churn_model_rfc_v2.pkl  # Trained model
└── encoders.pkl                # Feature encoders

πŸ› Troubleshooting

Common Issues

  1. SSL Certificate Errors

    python generate_ssl_cert.py
  2. Model Loading Errors

    • Ensure model files exist in the same directory
    • Check file permissions
  3. Port Already in Use

    # Kill process on port 8000
    lsof -ti:8000 | xargs kill -9
  4. Authentication Errors

    • Verify credentials: admin / churn2024!
    • Check environment variables

Logs

The API logs to console. For production, configure file logging:

import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('api.log'),
        logging.StreamHandler()
    ]
)

πŸ“ˆ Performance

  • Single Prediction: ~50-100ms
  • Batch Prediction: ~10-20ms per customer
  • SSL Overhead: ~10-20% latency increase
  • Memory Usage: ~100-200MB (model + dependencies)

πŸ”„ Deployment Options

Development

python start_api.py

Production with Gunicorn

pip install gunicorn
gunicorn churn_prediction_api:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 --keyfile server.key --certfile server.crt

Docker (Optional)

FROM python:3.9-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 8000
CMD ["python", "start_api.py"]

πŸ“ž Support

For issues or questions:

  1. Check the detailed documentation
  2. Run the test suite: python test_api.py
  3. Check API logs for error details
  4. Verify model files are present and accessible

πŸ“„ License

This project is part of a machine learning assessment for customer churn prediction.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors