Spaces:
Running
Running
Upload folder using huggingface_hub
Browse files- README.md +295 -77
- README_HF.md +0 -106
- app.py +22 -0
- db_models.py +19 -0
- requirements.txt +3 -0
- src/config.py +5 -0
- src/gradio_ui.py +30 -0
README.md
CHANGED
|
@@ -1,106 +1,324 @@
|
|
| 1 |
-
|
| 2 |
-
title: Employee Turnover Prediction API
|
| 3 |
-
emoji: 👔
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo: purple
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: true
|
| 8 |
-
license: mit
|
| 9 |
-
app_port: 7860
|
| 10 |
-
---
|
| 11 |
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
|
| 15 |
-
API de prédiction du turnover des employés (XGBoost + SMOTE) avec endpoints batch, validation stricte et documentation à jour.
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
- ✅ Prédiction de turnover (0 = reste, 1 = part)
|
| 20 |
- 📦 Endpoint batch CSV (3 fichiers bruts)
|
| 21 |
-
-
|
| 22 |
-
-
|
| 23 |
-
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
| `/docs` | Documentation interactive Swagger |
|
| 34 |
-
| `/health` | Status de l'API |
|
| 35 |
-
| `/ui` | Interface Gradio interactive |
|
| 36 |
-
| `/predict` | Prédiction unitaire (JSON, contraintes réelles) |
|
| 37 |
-
| `/predict/batch` | Prédiction batch (3 fichiers CSV bruts) |
|
| 38 |
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
##
|
| 41 |
|
| 42 |
-
### Prédiction unitaire (toutes contraintes appliquées)
|
| 43 |
```bash
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
-H "Content-Type: application/json" \
|
| 46 |
-
-
|
| 47 |
-
-d '{
|
| 48 |
-
"nombre_participation_pee": 0,
|
| 49 |
-
"nb_formations_suivies": 2,
|
| 50 |
-
"nombre_employee_sous_responsabilite": 1,
|
| 51 |
-
"distance_domicile_travail": 15,
|
| 52 |
-
"niveau_education": 3,
|
| 53 |
-
"domaine_etude": "Infra & Cloud",
|
| 54 |
-
"ayant_enfants": "Y",
|
| 55 |
-
"frequence_deplacement": "Occasionnel",
|
| 56 |
-
"annees_depuis_la_derniere_promotion": 2,
|
| 57 |
-
"annes_sous_responsable_actuel": 5,
|
| 58 |
-
"satisfaction_employee_environnement": 3,
|
| 59 |
-
"note_evaluation_precedente": 4,
|
| 60 |
-
"niveau_hierarchique_poste": 2,
|
| 61 |
-
"satisfaction_employee_nature_travail": 3,
|
| 62 |
-
"satisfaction_employee_equipe": 3,
|
| 63 |
-
"satisfaction_employee_equilibre_pro_perso": 2,
|
| 64 |
-
"note_evaluation_actuelle": 4,
|
| 65 |
-
"heure_supplementaires": "Non",
|
| 66 |
-
"augementation_salaire_precedente": 5.5,
|
| 67 |
-
"age": 35,
|
| 68 |
-
"genre": "M",
|
| 69 |
-
"revenu_mensuel": 4500.0,
|
| 70 |
-
"statut_marital": "Marié(e)",
|
| 71 |
-
"departement": "Commercial",
|
| 72 |
-
"poste": "Manager",
|
| 73 |
-
"nombre_experiences_precedentes": 3,
|
| 74 |
-
"nombre_heures_travailless": 80,
|
| 75 |
-
"annee_experience_totale": 10,
|
| 76 |
-
"annees_dans_l_entreprise": 5,
|
| 77 |
-
"annees_dans_le_poste_actuel": 2
|
| 78 |
-
}'
|
| 79 |
```
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
| 82 |
```bash
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
```
|
| 89 |
|
| 90 |
-
|
| 91 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
{
|
| 93 |
"total_employees": 1470,
|
| 94 |
-
"predictions": [
|
|
|
|
|
|
|
|
|
|
| 95 |
"summary": {
|
| 96 |
"total_stay": 1169,
|
| 97 |
"total_leave": 301,
|
| 98 |
-
"high_risk_count": 222
|
|
|
|
|
|
|
| 99 |
}
|
| 100 |
}
|
| 101 |
```
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
##
|
| 105 |
|
| 106 |
-
|
|
|
|
|
|
| 1 |
+
# 🚀 Employee Turnover Prediction API - v3.2.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
## 📊 Vue d'ensemble
|
| 4 |
|
| 5 |
+
API REST de prédiction du turnover des employés basée sur un modèle XGBoost avec SMOTE.
|
| 6 |
|
|
|
|
| 7 |
|
| 8 |
+
**✨ Nouveautés v3.2.1** :
|
| 9 |
+
- 🎛️ Sliders Gradio et schémas Pydantic alignés sur les min/max réels des données d'entraînement
|
|
|
|
| 10 |
- 📦 Endpoint batch CSV (3 fichiers bruts)
|
| 11 |
+
- 🔑 Authentification API Key (prod)
|
| 12 |
+
- 🔧 Correction preprocessing (scaling, ordre des colonnes)
|
| 13 |
+
- 📝 Documentation et exemples mis à jour
|
| 14 |
+
|
| 15 |
+
## 🏗️ Architecture
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
OC_P5/
|
| 19 |
+
├── app.py # Point d'entrée FastAPI
|
| 20 |
+
├── src/
|
| 21 |
+
│ ├── auth.py # Authentification API Key
|
| 22 |
+
│ ├── config.py # Configuration centralisée
|
| 23 |
+
│ ├── logger.py # Logging structuré (NOUVEAU)
|
| 24 |
+
│ ├── models.py # Chargement modèle HF Hub
|
| 25 |
+
│ ├── preprocessing.py # Pipeline preprocessing
|
| 26 |
+
│ ├── rate_limit.py # Rate limiting (NOUVEAU)
|
| 27 |
+
│ └── schemas.py # Validation Pydantic
|
| 28 |
+
├── tests/ # Suite pytest (33 tests, 88% couverture)
|
| 29 |
+
├── logs/ # Logs JSON (NOUVEAU)
|
| 30 |
+
│ ├── api.log # Tous les logs
|
| 31 |
+
│ └── error.log # Erreurs uniquement
|
| 32 |
+
├── docs/ # Documentation
|
| 33 |
+
├── ml_model/ # Scripts training
|
| 34 |
+
└── data/ # Données sources
|
| 35 |
+
## 🗄️ Schéma de la Base de Données (PostgreSQL)
|
| 36 |
+
|
| 37 |
+
Schéma UML pour traçabilité ML (basé sur P5 prédiction turnover employé) :
|
| 38 |
+

|
| 39 |
+
|
| 40 |
+
- **dataset** : Dataset original (référence pour tests/retraining). Colonnes adaptées au modèle de prédiction turnover.
|
| 41 |
+
- **ml_logs** : Logs inputs/outputs (JSON pour flexibilité, timestamp pour audits).
|
| 42 |
+
|
| 43 |
+
Choix : Structure relationnelle pour efficacité volume data ; sécurité via user dédié (ml_user).
|
| 44 |
+
Instructions : Voir create_db.py pour création.
|
| 45 |
+
|
| 46 |
+
📖 **Guide complet pour débutants** : [docs/database_guide.md](docs/database_guide.md)
|
| 47 |
+
|
| 48 |
+
### 💾 Insertion du Dataset
|
| 49 |
+
```bash
|
| 50 |
+
# Insérer le dataset complet (1470 employés)
|
| 51 |
+
poetry run python scripts/insert_dataset.py
|
| 52 |
+
|
| 53 |
+
# Vérifier l'insertion
|
| 54 |
+
psql -h localhost -U ml_user -d oc_p5_db -c "SELECT COUNT(*) FROM dataset;"
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### Prérequis
|
| 58 |
+
- Python 3.12+
|
| 59 |
+
- Poetry 1.7+
|
| 60 |
+
- Git
|
| 61 |
+
|
| 62 |
+
### Setup rapide
|
| 63 |
|
| 64 |
+
```bash
|
| 65 |
+
# 1. Cloner le repo
|
| 66 |
+
git clone https://github.com/chaton59/OC_P5.git
|
| 67 |
+
cd OC_P5
|
| 68 |
+
|
| 69 |
+
# 2. Installer les dépendances
|
| 70 |
+
poetry install
|
| 71 |
|
| 72 |
+
# 3. Configurer l'environnement
|
| 73 |
+
cp .env.example .env
|
| 74 |
+
# Éditer .env avec vos valeurs
|
| 75 |
|
| 76 |
+
# 4. Lancer l'API
|
| 77 |
+
poetry run uvicorn app:app --reload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
# 5. Accéder à la documentation
|
| 80 |
+
# http://localhost:8000/docs
|
| 81 |
+
```
|
| 82 |
|
| 83 |
+
## 📝 Configuration (.env)
|
| 84 |
|
|
|
|
| 85 |
```bash
|
| 86 |
+
# Mode développement (désactive auth + active logs détaillés)
|
| 87 |
+
DEBUG=true
|
| 88 |
+
|
| 89 |
+
# API Key (requis en production)
|
| 90 |
+
API_KEY=your-secret-key-here
|
| 91 |
+
|
| 92 |
+
# Logging (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
| 93 |
+
LOG_LEVEL=INFO
|
| 94 |
+
|
| 95 |
+
# HuggingFace Model
|
| 96 |
+
HF_MODEL_REPO=ASI-Engineer/employee-turnover-model
|
| 97 |
+
MODEL_FILENAME=model/model.pkl
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
## 🔒 Authentification
|
| 101 |
+
|
| 102 |
+
### Mode DEBUG (développement)
|
| 103 |
+
```bash
|
| 104 |
+
# L'API Key n'est PAS requise
|
| 105 |
+
curl http://localhost:8000/predict -H "Content-Type: application/json" -d '{...}'
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### Mode PRODUCTION
|
| 109 |
+
```bash
|
| 110 |
+
# L'API Key est REQUISE
|
| 111 |
+
curl http://localhost:8000/predict \
|
| 112 |
+
-H "X-API-Key: your-secret-key" \
|
| 113 |
-H "Content-Type: application/json" \
|
| 114 |
+
-d '{...}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
```
|
| 116 |
|
| 117 |
+
|
| 118 |
+
## 📡 Endpoints
|
| 119 |
+
|
| 120 |
+
### 🏥 Health Check
|
| 121 |
```bash
|
| 122 |
+
GET /health
|
| 123 |
+
|
| 124 |
+
# Réponse
|
| 125 |
+
{
|
| 126 |
+
"status": "healthy",
|
| 127 |
+
"model_loaded": true,
|
| 128 |
+
"model_type": "Pipeline",
|
| 129 |
+
"version": "3.2.1"
|
| 130 |
+
}
|
| 131 |
```
|
| 132 |
|
| 133 |
+
### 🔮 Prédiction unitaire
|
| 134 |
+
```bash
|
| 135 |
+
POST /predict
|
| 136 |
+
Content-Type: application/json
|
| 137 |
+
X-API-Key: your-key (en production)
|
| 138 |
+
|
| 139 |
+
# Payload (exemple, contraintes réelles appliquées)
|
| 140 |
+
{
|
| 141 |
+
"nombre_participation_pee": 0,
|
| 142 |
+
"nb_formations_suivies": 2,
|
| 143 |
+
"nombre_employee_sous_responsabilite": 1,
|
| 144 |
+
"distance_domicile_travail": 15,
|
| 145 |
+
"niveau_education": 3,
|
| 146 |
+
"domaine_etude": "Infra & Cloud",
|
| 147 |
+
"ayant_enfants": "Y",
|
| 148 |
+
"frequence_deplacement": "Occasionnel",
|
| 149 |
+
"annees_depuis_la_derniere_promotion": 2,
|
| 150 |
+
"annes_sous_responsable_actuel": 5,
|
| 151 |
+
"satisfaction_employee_environnement": 3,
|
| 152 |
+
"note_evaluation_precedente": 4,
|
| 153 |
+
"niveau_hierarchique_poste": 2,
|
| 154 |
+
"satisfaction_employee_nature_travail": 3,
|
| 155 |
+
"satisfaction_employee_equipe": 3,
|
| 156 |
+
"satisfaction_employee_equilibre_pro_perso": 2,
|
| 157 |
+
"note_evaluation_actuelle": 4,
|
| 158 |
+
"heure_supplementaires": "Non",
|
| 159 |
+
"augementation_salaire_precedente": 5.5,
|
| 160 |
+
"age": 35,
|
| 161 |
+
"genre": "M",
|
| 162 |
+
"revenu_mensuel": 4500.0,
|
| 163 |
+
"statut_marital": "Marié(e)",
|
| 164 |
+
"departement": "Commercial",
|
| 165 |
+
"poste": "Manager",
|
| 166 |
+
"nombre_experiences_precedentes": 3,
|
| 167 |
+
"nombre_heures_travailless": 80,
|
| 168 |
+
"annee_experience_totale": 10,
|
| 169 |
+
"annees_dans_l_entreprise": 5,
|
| 170 |
+
"annees_dans_le_poste_actuel": 2
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# Réponse
|
| 174 |
+
{
|
| 175 |
+
"prediction": 0, # 0 = reste, 1 = part
|
| 176 |
+
"probability_0": 0.85, # Probabilité de rester
|
| 177 |
+
"probability_1": 0.15, # Probabilité de partir
|
| 178 |
+
"risk_level": "Low" # Low, Medium, High
|
| 179 |
+
}
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
### 📦 Prédiction batch (CSV)
|
| 183 |
+
```bash
|
| 184 |
+
POST /predict/batch
|
| 185 |
+
X-API-Key: your-key (en production)
|
| 186 |
+
|
| 187 |
+
# Envoi des 3 fichiers CSV bruts
|
| 188 |
+
curl -X POST "http://localhost:8000/predict/batch" \
|
| 189 |
+
-H "X-API-Key: your-key" \
|
| 190 |
+
-F "sondage_file=@data/extrait_sondage.csv" \
|
| 191 |
+
-F "eval_file=@data/extrait_eval.csv" \
|
| 192 |
+
-F "sirh_file=@data/extrait_sirh.csv"
|
| 193 |
+
|
| 194 |
+
# Réponse
|
| 195 |
{
|
| 196 |
"total_employees": 1470,
|
| 197 |
+
"predictions": [
|
| 198 |
+
{"employee_id": 1, "prediction": 1, "probability_leave": 0.84, "risk_level": "High"},
|
| 199 |
+
{"employee_id": 2, "prediction": 0, "probability_leave": 0.11, "risk_level": "Low"}
|
| 200 |
+
],
|
| 201 |
"summary": {
|
| 202 |
"total_stay": 1169,
|
| 203 |
"total_leave": 301,
|
| 204 |
+
"high_risk_count": 222,
|
| 205 |
+
"medium_risk_count": 233,
|
| 206 |
+
"low_risk_count": 1015
|
| 207 |
}
|
| 208 |
}
|
| 209 |
```
|
| 210 |
|
| 211 |
+
## 📊 Logging
|
| 212 |
+
|
| 213 |
+
### Logs structurés JSON
|
| 214 |
+
|
| 215 |
+
**Fichiers** :
|
| 216 |
+
- `logs/api.log` : Tous les logs
|
| 217 |
+
- `logs/error.log` : Erreurs uniquement
|
| 218 |
+
|
| 219 |
+
**Format** :
|
| 220 |
+
```json
|
| 221 |
+
{
|
| 222 |
+
"timestamp": "2025-12-26T10:30:45",
|
| 223 |
+
"level": "INFO",
|
| 224 |
+
"logger": "employee_turnover_api",
|
| 225 |
+
"message": "Request POST /predict",
|
| 226 |
+
"method": "POST",
|
| 227 |
+
"path": "/predict",
|
| 228 |
+
"status_code": 200,
|
| 229 |
+
"duration_ms": 23.45,
|
| 230 |
+
"client_host": "127.0.0.1"
|
| 231 |
+
}
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
## 🛡️ Rate Limiting
|
| 235 |
+
|
| 236 |
+
**Configuration** :
|
| 237 |
+
- **Développement** : Désactivé (DEBUG=true)
|
| 238 |
+
- **Production** : 20 requêtes/minute par IP ou API Key
|
| 239 |
+
|
| 240 |
+
**En cas de dépassement** :
|
| 241 |
+
```json
|
| 242 |
+
{
|
| 243 |
+
"error": "Rate limit exceeded",
|
| 244 |
+
"message": "20 per 1 minute"
|
| 245 |
+
}
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
## ✅ Tests
|
| 249 |
+
|
| 250 |
+
```bash
|
| 251 |
+
# Tous les tests
|
| 252 |
+
poetry run pytest tests/ -v
|
| 253 |
+
|
| 254 |
+
# Avec couverture
|
| 255 |
+
poetry run pytest tests/ --cov --cov-report=html
|
| 256 |
+
|
| 257 |
+
# Voir rapport HTML
|
| 258 |
+
open htmlcov/index.html
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
**Résultats** :
|
| 262 |
+
- ✅ 33 tests passés
|
| 263 |
+
- 📊 88% de couverture globale
|
| 264 |
+
|
| 265 |
+
## 🚀 Déploiement
|
| 266 |
+
|
| 267 |
+
### Variables d'environnement requises
|
| 268 |
+
```bash
|
| 269 |
+
DEBUG=false
|
| 270 |
+
API_KEY=<votre-clé-sécurisée>
|
| 271 |
+
LOG_LEVEL=INFO
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
### HuggingFace Spaces
|
| 275 |
+
Prêt pour déploiement avec `app.py` et `requirements.txt`
|
| 276 |
+
|
| 277 |
+
## 📚 Documentation
|
| 278 |
+
|
| 279 |
+
- **API Interactive** : http://localhost:8000/docs
|
| 280 |
+
- **ReDoc** : http://localhost:8000/redoc
|
| 281 |
+
- **Guide complet** : [docs/API_GUIDE.md](docs/API_GUIDE.md)
|
| 282 |
+
- **Standards** : [docs/standards.md](docs/standards.md)
|
| 283 |
+
- **Couverture tests** : [docs/TEST_COVERAGE.md](docs/TEST_COVERAGE.md)
|
| 284 |
+
|
| 285 |
+
## 📦 Dépendances principales
|
| 286 |
+
|
| 287 |
+
- **FastAPI** 0.115.14 : Framework web
|
| 288 |
+
- **Pydantic** 2.12.5 : Validation données
|
| 289 |
+
- **XGBoost** 2.1.3 : Modèle ML
|
| 290 |
+
- **SlowAPI** 0.1.9 : Rate limiting
|
| 291 |
+
- **python-json-logger** 4.0.0 : Logs structurés
|
| 292 |
+
- **pytest** 9.0.2 : Tests
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
## 🔄 Changelog
|
| 296 |
+
|
| 297 |
+
### v3.2.1 (janvier 2026)
|
| 298 |
+
- 🎛️ Sliders Gradio et schémas Pydantic alignés sur les min/max réels des données d'entraînement
|
| 299 |
+
- 📦 Endpoint batch CSV (3 fichiers bruts)
|
| 300 |
+
- 🔑 Authentification API Key (prod)
|
| 301 |
+
- 🔧 Correction preprocessing (scaling, ordre des colonnes)
|
| 302 |
+
- 📝 Documentation et exemples mis à jour
|
| 303 |
+
|
| 304 |
+
### v2.2.0 (27 décembre 2025)
|
| 305 |
+
- 📦 Nouvel endpoint `/predict/batch` pour traitement CSV direct
|
| 306 |
+
- 🔧 Fix preprocessing : ajout du scaling des features
|
| 307 |
+
- 🔧 Fix preprocessing : correction de l'ordre des colonnes
|
| 308 |
+
- 📊 Amélioration précision des prédictions (~90%)
|
| 309 |
+
|
| 310 |
+
### v2.1.0 (26 décembre 2025)
|
| 311 |
+
- ✨ Système de logging structuré JSON
|
| 312 |
+
- 🛡️ Rate limiting avec SlowAPI
|
| 313 |
+
- ⚡ Amélioration gestion d'erreurs
|
| 314 |
+
- 📊 Monitoring des performances
|
| 315 |
+
|
| 316 |
+
### v2.0.0 (26 décembre 2025)
|
| 317 |
+
- ✅ Suite de tests complète (36 tests)
|
| 318 |
+
- 🔐 Authentification API Key
|
| 319 |
+
- 📊 88% de couverture de code
|
| 320 |
|
| 321 |
+
## 👥 Auteurs
|
| 322 |
|
| 323 |
+
- **Projet** : OpenClassrooms P5
|
| 324 |
+
- **Repo** : [github.com/chaton59/OC_P5](https://github.com/chaton59/OC_P5)
|
README_HF.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Employee Turnover Prediction API
|
| 3 |
-
emoji: 👔
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo: purple
|
| 6 |
-
sdk: docker
|
| 7 |
-
pinned: true
|
| 8 |
-
license: mit
|
| 9 |
-
app_port: 7860
|
| 10 |
-
---
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
# Employee Turnover Prediction API 🚀 (v3.2.1)
|
| 14 |
-
|
| 15 |
-
API de prédiction du turnover des employés (XGBoost + SMOTE) avec endpoints batch, validation stricte et documentation à jour.
|
| 16 |
-
|
| 17 |
-
## 🎯 Fonctionnalités
|
| 18 |
-
|
| 19 |
-
- ✅ Prédiction de turnover (0 = reste, 1 = part)
|
| 20 |
-
- 📦 Endpoint batch CSV (3 fichiers bruts)
|
| 21 |
-
- 🎛️ Sliders Gradio et schémas Pydantic alignés sur les min/max réels
|
| 22 |
-
- 📊 Probabilités et niveau de risque (Low/Medium/High)
|
| 23 |
-
- 🔐 Authentification API Key (obligatoire)
|
| 24 |
-
- 📝 Logs structurés JSON
|
| 25 |
-
- 🛡️ Rate limiting (20 req/min)
|
| 26 |
-
- 📚 Documentation OpenAPI/Swagger
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
## 🔗 Endpoints
|
| 30 |
-
|
| 31 |
-
| Endpoint | Description |
|
| 32 |
-
|----------|-------------|
|
| 33 |
-
| `/docs` | Documentation interactive Swagger |
|
| 34 |
-
| `/health` | Status de l'API |
|
| 35 |
-
| `/ui` | Interface Gradio interactive |
|
| 36 |
-
| `/predict` | Prédiction unitaire (JSON, contraintes réelles) |
|
| 37 |
-
| `/predict/batch` | Prédiction batch (3 fichiers CSV bruts) |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
## 🚀 Utilisation
|
| 41 |
-
|
| 42 |
-
### Prédiction unitaire (toutes contraintes appliquées)
|
| 43 |
-
```bash
|
| 44 |
-
curl -X POST https://asi-engineer-oc-p5-dev.hf.space/predict \
|
| 45 |
-
-H "Content-Type: application/json" \
|
| 46 |
-
-H "X-API-Key: your-key" \
|
| 47 |
-
-d '{
|
| 48 |
-
"nombre_participation_pee": 0,
|
| 49 |
-
"nb_formations_suivies": 2,
|
| 50 |
-
"nombre_employee_sous_responsabilite": 1,
|
| 51 |
-
"distance_domicile_travail": 15,
|
| 52 |
-
"niveau_education": 3,
|
| 53 |
-
"domaine_etude": "Infra & Cloud",
|
| 54 |
-
"ayant_enfants": "Y",
|
| 55 |
-
"frequence_deplacement": "Occasionnel",
|
| 56 |
-
"annees_depuis_la_derniere_promotion": 2,
|
| 57 |
-
"annes_sous_responsable_actuel": 5,
|
| 58 |
-
"satisfaction_employee_environnement": 3,
|
| 59 |
-
"note_evaluation_precedente": 4,
|
| 60 |
-
"niveau_hierarchique_poste": 2,
|
| 61 |
-
"satisfaction_employee_nature_travail": 3,
|
| 62 |
-
"satisfaction_employee_equipe": 3,
|
| 63 |
-
"satisfaction_employee_equilibre_pro_perso": 2,
|
| 64 |
-
"note_evaluation_actuelle": 4,
|
| 65 |
-
"heure_supplementaires": "Non",
|
| 66 |
-
"augementation_salaire_precedente": 5.5,
|
| 67 |
-
"age": 35,
|
| 68 |
-
"genre": "M",
|
| 69 |
-
"revenu_mensuel": 4500.0,
|
| 70 |
-
"statut_marital": "Marié(e)",
|
| 71 |
-
"departement": "Commercial",
|
| 72 |
-
"poste": "Manager",
|
| 73 |
-
"nombre_experiences_precedentes": 3,
|
| 74 |
-
"nombre_heures_travailless": 80,
|
| 75 |
-
"annee_experience_totale": 10,
|
| 76 |
-
"annees_dans_l_entreprise": 5,
|
| 77 |
-
"annees_dans_le_poste_actuel": 2
|
| 78 |
-
}'
|
| 79 |
-
```
|
| 80 |
-
|
| 81 |
-
### Prédiction batch (3 fichiers CSV bruts)
|
| 82 |
-
```bash
|
| 83 |
-
curl -X POST https://asi-engineer-oc-p5-dev.hf.space/predict/batch \
|
| 84 |
-
-H "X-API-Key: your-key" \
|
| 85 |
-
-F "sondage_file=@extrait_sondage.csv" \
|
| 86 |
-
-F "eval_file=@extrait_eval.csv" \
|
| 87 |
-
-F "sirh_file=@extrait_sirh.csv"
|
| 88 |
-
```
|
| 89 |
-
|
| 90 |
-
**Réponse :**
|
| 91 |
-
```json
|
| 92 |
-
{
|
| 93 |
-
"total_employees": 1470,
|
| 94 |
-
"predictions": [...],
|
| 95 |
-
"summary": {
|
| 96 |
-
"total_stay": 1169,
|
| 97 |
-
"total_leave": 301,
|
| 98 |
-
"high_risk_count": 222
|
| 99 |
-
}
|
| 100 |
-
}
|
| 101 |
-
```
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
## 📚 Documentation complète
|
| 105 |
-
|
| 106 |
-
Voir [docs/API.md](docs/API.md) ou le [GitHub Repository](https://github.com/chaton59/OC_P5) pour la documentation complète et les contraintes détaillées (min/max, enums, etc).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -221,6 +221,28 @@ async def predict(request: Request, employee: EmployeeInput):
|
|
| 221 |
else:
|
| 222 |
risk_level = "High"
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
return PredictionOutput(
|
| 225 |
prediction=prediction,
|
| 226 |
probability_0=prob_0,
|
|
|
|
| 221 |
else:
|
| 222 |
risk_level = "High"
|
| 223 |
|
| 224 |
+
# 6. Enregistrer dans la base de données
|
| 225 |
+
try:
|
| 226 |
+
from sqlalchemy import create_engine
|
| 227 |
+
from sqlalchemy.orm import sessionmaker
|
| 228 |
+
from db_models import MLLog
|
| 229 |
+
|
| 230 |
+
engine = create_engine(settings.DATABASE_URL)
|
| 231 |
+
Session = sessionmaker(bind=engine)
|
| 232 |
+
session = Session()
|
| 233 |
+
|
| 234 |
+
log_entry = MLLog(
|
| 235 |
+
input_json=employee.dict(),
|
| 236 |
+
prediction="Oui" if prediction == 1 else "Non",
|
| 237 |
+
)
|
| 238 |
+
session.add(log_entry)
|
| 239 |
+
session.commit()
|
| 240 |
+
session.close()
|
| 241 |
+
|
| 242 |
+
logger.info(f"Prediction logged to database: {prediction}")
|
| 243 |
+
except Exception as db_error:
|
| 244 |
+
logger.warning(f"Failed to log prediction to database: {db_error}")
|
| 245 |
+
|
| 246 |
return PredictionOutput(
|
| 247 |
prediction=prediction,
|
| 248 |
probability_0=prob_0,
|
db_models.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import Column, Integer, String, JSON, DateTime, func
|
| 2 |
+
from sqlalchemy.ext.declarative import declarative_base
|
| 3 |
+
|
| 4 |
+
Base = declarative_base()
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Dataset(Base):
|
| 8 |
+
__tablename__ = "dataset"
|
| 9 |
+
id = Column(Integer, primary_key=True)
|
| 10 |
+
features_json = Column(JSON) # Features from sondage, eval, sirh data
|
| 11 |
+
target = Column(String) # Target: 'Oui' or 'Non' for turnover
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MLLog(Base):
|
| 15 |
+
__tablename__ = "ml_logs"
|
| 16 |
+
id = Column(Integer, primary_key=True)
|
| 17 |
+
input_json = Column(JSON) # Inputs flexibles (JSON for features variables)
|
| 18 |
+
prediction = Column(String) # Output ML ('Oui' or 'Non')
|
| 19 |
+
created_at = Column(DateTime, default=func.now()) # Timestamp auto pour traçabilité
|
requirements.txt
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
aiofiles==24.1.0 ; python_version >= "3.12" and python_version < "4.0"
|
| 2 |
alembic==1.17.2 ; python_version >= "3.12" and python_version < "4.0"
|
| 3 |
annotated-doc==0.0.4 ; python_version >= "3.12" and python_version < "4.0"
|
|
|
|
| 1 |
+
sqlalchemy==2.0.23
|
| 2 |
+
psycopg2-binary==2.9.9
|
| 3 |
+
python-dotenv==1.0.0
|
| 4 |
aiofiles==24.1.0 ; python_version >= "3.12" and python_version < "4.0"
|
| 5 |
alembic==1.17.2 ; python_version >= "3.12" and python_version < "4.0"
|
| 6 |
annotated-doc==0.0.4 ; python_version >= "3.12" and python_version < "4.0"
|
src/config.py
CHANGED
|
@@ -40,6 +40,11 @@ class Settings:
|
|
| 40 |
DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"
|
| 41 |
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
@property
|
| 44 |
def is_api_key_required(self) -> bool:
|
| 45 |
"""
|
|
|
|
| 40 |
DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"
|
| 41 |
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
| 42 |
|
| 43 |
+
# ===== BASE DE DONNÉES =====
|
| 44 |
+
DATABASE_URL: str = os.getenv(
|
| 45 |
+
"DATABASE_URL", "postgresql://ml_user:15975359320@localhost:5432/oc_p5_db"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
@property
|
| 49 |
def is_api_key_required(self) -> bool:
|
| 50 |
"""
|
src/gradio_ui.py
CHANGED
|
@@ -123,6 +123,33 @@ def predict_turnover(
|
|
| 123 |
|
| 124 |
confidence = max(prob_0, prob_1) * 100
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
result = f"""
|
| 127 |
## {risk_emoji}
|
| 128 |
|
|
@@ -132,6 +159,9 @@ def predict_turnover(
|
|
| 132 |
- **Probabilité de départ**: {prob_1 * 100:.1f}%
|
| 133 |
- **Probabilité de maintien**: {prob_0 * 100:.1f}%
|
| 134 |
|
|
|
|
|
|
|
|
|
|
| 135 |
### Interprétation
|
| 136 |
{"⚠️ Cet employé présente des facteurs de risque de départ. Il est recommandé d'engager un dialogue pour comprendre ses attentes." if prediction == 1 else "✅ Cet employé semble stable. Continuez à maintenir un environnement de travail positif."}
|
| 137 |
"""
|
|
|
|
| 123 |
|
| 124 |
confidence = max(prob_0, prob_1) * 100
|
| 125 |
|
| 126 |
+
# Enregistrer dans la base de données (optionnel pour Gradio)
|
| 127 |
+
try:
|
| 128 |
+
from sqlalchemy import create_engine
|
| 129 |
+
from sqlalchemy.orm import sessionmaker
|
| 130 |
+
from src.config import get_settings
|
| 131 |
+
|
| 132 |
+
settings = get_settings()
|
| 133 |
+
engine = create_engine(settings.DATABASE_URL)
|
| 134 |
+
Session = sessionmaker(bind=engine)
|
| 135 |
+
session = Session()
|
| 136 |
+
|
| 137 |
+
# Importer le modèle MLLog
|
| 138 |
+
from db_models import MLLog
|
| 139 |
+
|
| 140 |
+
# Créer le log
|
| 141 |
+
log_entry = MLLog(
|
| 142 |
+
input_json=employee.dict(), # Convertir Pydantic en dict
|
| 143 |
+
prediction="Oui" if prediction == 1 else "Non",
|
| 144 |
+
)
|
| 145 |
+
session.add(log_entry)
|
| 146 |
+
session.commit()
|
| 147 |
+
session.close()
|
| 148 |
+
|
| 149 |
+
db_status = "✅ Enregistré en DB"
|
| 150 |
+
except Exception as db_error:
|
| 151 |
+
db_status = f"⚠️ Erreur DB: {str(db_error)}"
|
| 152 |
+
|
| 153 |
result = f"""
|
| 154 |
## {risk_emoji}
|
| 155 |
|
|
|
|
| 159 |
- **Probabilité de départ**: {prob_1 * 100:.1f}%
|
| 160 |
- **Probabilité de maintien**: {prob_0 * 100:.1f}%
|
| 161 |
|
| 162 |
+
### Base de données
|
| 163 |
+
{db_status}
|
| 164 |
+
|
| 165 |
### Interprétation
|
| 166 |
{"⚠️ Cet employé présente des facteurs de risque de départ. Il est recommandé d'engager un dialogue pour comprendre ses attentes." if prediction == 1 else "✅ Cet employé semble stable. Continuez à maintenir un environnement de travail positif."}
|
| 167 |
"""
|