File size: 2,404 Bytes
cacb5d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a962ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cacb5d8
3a962ff
 
 
 
 
 
 
 
 
cacb5d8
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
---
title: ML Prediction API
emoji: 🔮
colorFrom: green
colorTo: blue
sdk: docker
app_port: 7860
pinned: false
tags:
  - fastapi
  - xgboost
  - machine-learning
  - postgresql
license: mit
---

# ML Prediction API

Production-ready POC for serving an XGBoost model via FastAPI with PostgreSQL logging.

## Features

- **FastAPI**: High-performance API with automatic validation.
- **PostgreSQL**: Persistent logging of all inputs and predictions.
- **XGBoost**: Efficient model inference.
- **Docker**: Containerized for easy deployment.
- **CI/CD**: Automated testing and deployment via GitHub Actions.
- **Authentication**: Simple API Key protection.

## Installation

### Prerequisites
- Docker
- Python 3.10+
- PostgreSQL (if running locally without Docker Compose)

### Local Setup

1. **Clone the repository**
   ```bash
   git clone <repo-url>
   cd <repo-name>
   ```

2. **Install Dependencies**
   ```bash
   pip install -r requirements.txt
   ```

3. **Environment Variables**
   Create a `.env` file or set variables:
   ```bash
   export DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
   export API_KEY="your-secret-key"
   export MODEL_PATH="02_xgb_model_tuned.pkl"
   ```

4. **Initialize Database**
   ```bash
   python scripts/create_db.py
   ```

5. **Run the API**
   ```bash
   uvicorn app.main:app --reload
   ```

## API Documentation

Once running, visit:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`

### Endpoints

- `POST /predict`: Make a prediction. Requires `X-API-KEY` header.
- `GET /health`: Health check.
- `GET /model/info`: Model metadata. Requires `X-API-KEY` header.

## Deployment

### Hugging Face Spaces

This project is configured to deploy to Hugging Face Spaces using Docker.

1. Create a new Space on Hugging Face (Select Docker SDK).
2. Add the following Secrets in the Space settings:
   - `DATABASE_URL`: Connection string to your external PostgreSQL database.
   - `API_KEY`: Your desired API key.
3. The GitHub Action `ci-cd.yml` will automatically deploy changes from the `main` branch.

## Architecture

- **app/main.py**: Entry point.
- **app/routers**: API route definitions.
- **app/services**: Business (ML inference).
- **app/models**: Database and Pydantic models.
- **app/core**: Configuration and DB setup.

## Testing

Run tests with coverage:
```bash
pytest --cov=app tests/
```

GLHF !