ASI-Engineer commited on
Commit
83d26eb
·
verified ·
1 Parent(s): 7263194

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +75 -806
README.md CHANGED
@@ -1,447 +1,107 @@
1
- <div align="center">
2
-
3
- # 🚀 Employee Turnover Prediction API
4
-
5
- [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
6
- [![FastAPI](https://img.shields.io/badge/FastAPI-0.115.14-009688.svg)](https://fastapi.tiangolo.com)
7
- [![Code Coverage](https://img.shields.io/badge/coverage-70.26%25-yellow.svg)](htmlcov/index.html)
8
- [![Tests](https://img.shields.io/badge/tests-97%20passed-success.svg)](tests/)
9
- [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10
-
11
- **API REST de prédiction du turnover des employés basée sur Machine Learning (XGBoost + SMOTE)**
12
-
13
- [🔗 Demo Production](https://asi-engineer-oc-p5.hf.space) · [📚 Documentation](docs/) · [🐛 Report Bug](https://github.com/chaton59/OC_P5/issues) · [💡 Request Feature](https://github.com/chaton59/OC_P5/issues)
14
-
15
- </div>
16
-
17
  ---
18
-
19
- ## 📋 Table des Matières
20
-
21
- - [À Propos du Projet](#-à-propos-du-projet)
22
- - [Architecture](#-architecture)
23
- - [Choix Techniques](#-choix-techniques)
24
- - [Installation](#-installation)
25
- - [Utilisation](#-utilisation)
26
- - [Déploiement](#-déploiement)
27
- - [Mise à Jour](#-mise-à-jour)
28
- - [Tests](#-tests)
29
- - [Documentation](#-documentation)
30
- - [Changelog](#-changelog)
31
- - [Auteurs](#-auteurs)
32
- - [Licence](#-licence)
33
-
34
  ---
35
 
36
- ## 📊 À Propos du Projet
37
-
38
- ### Vue d'ensemble
39
-
40
- Ce projet déploie un **modèle de Machine Learning** en production via une **API REST moderne** pour prédire le risque de départ des employés d'une entreprise. Développé dans le cadre du projet OpenClassrooms P5 "Déployez votre modèle de Machine Learning", il illustre les **meilleures pratiques** d'ingénierie logicielle et de MLOps.
41
-
42
- ### Problématique
43
-
44
- Les entreprises perdent des talents clés sans pouvoir anticiper. Ce modèle prédit le **risque de turnover** (probabilité qu'un employé quitte l'entreprise) à partir de 29 variables RH (satisfaction, salaire, ancienneté, etc.).
45
-
46
- ### Solution
47
-
48
- API REST performante exposant un modèle **XGBoost optimisé** avec :
49
- - ✅ **Validation robuste** des données via Pydantic
50
- - ✅ **Prédictions en temps réel** (<2s) ou par batch (CSV)
51
- - ✅ **Traçabilité complète** via PostgreSQL et logs JSON
52
- - ✅ **Monitoring** et health checks intégrés
53
- - ✅ **CI/CD automatisé** avec GitHub Actions
54
- - ✅ **Déploiement cloud** sur HuggingFace Spaces
55
-
56
- ### Performances du Modèle
57
-
58
- | Métrique | Valeur | Interprétation |
59
- |----------|--------|----------------|
60
- | **F1 Score** | 0.85 | Excellent équilibre précision/recall |
61
- | **Recall** | 0.88 | Détecte 88% des départs réels |
62
- | **Precision** | 0.82 | 82% des prédictions "départ" sont correctes |
63
- | **ROC AUC** | 0.91 | Excellente capacité de discrimination |
64
 
65
- 📊 Voir [docs/MODEL_TECHNICAL.md](docs/MODEL_TECHNICAL.md) pour analyse détaillée.
66
 
67
- ### Fonctionnalités Clés
68
 
 
69
 
70
- - 🔮 **Prédiction unitaire** : Prédit le risque pour un employé (JSON)
71
- - 📦 **Prédiction batch** : Traite des fichiers CSV complets (1000+ employés)
72
- - 🔐 **Authentification** : API Key sécurisée (production)
73
- - 🛡️ **Rate limiting** : 20 req/min pour éviter les abus
74
- - 📊 **Monitoring** : Health check et logs structurés JSON
75
- - 🎨 **Interface Gradio** : UI web pour tests interactifs
76
- - 📚 **Documentation auto** : Swagger UI et ReDoc intégrés
77
- - 🗄️ **Traçabilité** : Toutes les prédictions enregistrées en base PostgreSQL
78
-
79
- **Version actuelle** : 3.2.1 | **Dernière mise à jour** : Janvier 2026
80
-
81
- ---
82
-
83
- ## 🏗️ Architecture
84
-
85
- ### Vue d'ensemble High-Level
86
-
87
- ```
88
- ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
89
- │ CLIENT │────────▶│ API REST │────────▶│ BASE DE │
90
- │ │ JSON │ (FastAPI) │ SQL │ DONNÉES │
91
- │ • curl │ │ │ │ (PostgreSQL) │
92
- │ • Python │ │ • Validation│ │ │
93
- │ • JS │◀────────│ • Authent. │◀────────│ • dataset │
94
- │ • Postman │ 200 OK │ • Logging │ SELECT │ • ml_logs │
95
- └──────────────┘ └──────┬───────┘ └──────────────┘
96
-
97
-
98
- ┌──────────────┐
99
- │ MODÈLE ML │
100
- │ (XGBoost + │
101
- │ SMOTE) │
102
- │ │
103
- │ HF Hub Cache │
104
- └──────────────┘
105
- ```
106
-
107
- ### Pipeline de Prédiction
108
-
109
- ```
110
- Données brutes
111
-
112
-
113
- ┌─────────────────────┐
114
- │ 1. VALIDATION │ Pydantic vérifie types, contraintes, énumérations
115
- │ (Pydantic) │ → Rejette données invalides (HTTP 422)
116
- └─────────┬───────────┘
117
-
118
-
119
- ┌─────────────────────┐
120
- │ 2. PREPROCESSING │ • Feature engineering (ratios, moyennes)
121
- │ (StandardScaler)│ • OneHot encoding (catégorielles non-ordonnées)
122
- │ │ • Ordinal encoding (fréquence déplacements)
123
- └─────────┬───────────┘ • Scaling (StandardScaler)
124
-
125
-
126
- ┌─────────────────────┐
127
- │ 3. PRÉDICTION │ XGBoost prédit classe (0/1) + probabilités
128
- │ (XGBoost) │ • 0 = Reste dans l'entreprise
129
- └─────────┬───────────┘ • 1 = Va quitter l'entreprise
130
-
131
-
132
- ┌─────────────────────┐
133
- │ 4. POST-TRAITEMENT │ • Calcul niveau de risque (Low/Medium/High)
134
- │ (API) │ • Enregistrement en DB (ml_logs)
135
- └─────────┬───────────┘ • Logging structuré JSON
136
-
137
-
138
- Réponse JSON
139
- ```
140
-
141
- ### Structure du Projet
142
-
143
- ```
144
- OC_P5/
145
- ├── api.py # 🚪 Point d'entrée FastAPI principal
146
- ├── app.py # 🎨 Point d'entrée Gradio (HF Spaces)
147
- ├── src/
148
- │ ├── auth.py # 🔐 Authentification API Key
149
- │ ├── config.py # ⚙️ Configuration centralisée (.env)
150
- │ ├── logger.py # 📝 Logging structuré JSON
151
- │ ├── models.py # 🤖 Chargement modèle depuis HuggingFace Hub
152
- │ ├── preprocessing.py # 🔧 Pipeline de preprocessing
153
- │ ├── rate_limit.py # 🛡️ Rate limiting (SlowAPI)
154
- │ ├── schemas.py # ✅ Validation Pydantic (29 champs)
155
- │ └── gradio_ui.py # 🎨 Interface Gradio web
156
- ├── tests/ # ✅ Suite de tests (97 tests, 70% coverage)
157
- │ ├── test_api_auth.py # Tests authentification
158
- │ ├── test_api_predict.py # Tests prédictions
159
- │ ├── test_api_validation.py # Tests validation Pydantic
160
- │ ├── test_database.py # Tests PostgreSQL
161
- │ └── test_model.py # Tests modèle ML
162
- ├── ml_model/ # 🎓 Scripts d'entraînement
163
- │ ├── main.py # Pipeline complet train
164
- │ ├── train_model.py # Training XGBoost + MLflow
165
- │ └── preprocess.py # Preprocessing dataset
166
- ├── scripts/ # 🔧 Scripts utilitaires
167
- │ ├── create_db.py # Création base PostgreSQL
168
- │ └── insert_dataset.py # Insertion données
169
- ├── docs/ # 📚 Documentation complète
170
- │ ├── API_GUIDE.md # Guide API détaillé
171
- │ ├── MODEL_TECHNICAL.md # Doc technique modèle
172
- │ ├── DEPLOYMENT.md # Guide déploiement
173
- │ ├── TRAINING.md # Guide entraînement
174
- │ └── database_guide.md # Guide PostgreSQL
175
- ├── data/ # 📊 Données sources (1470 employés)
176
- │ ├── extrait_sondage.csv # Données satisfaction
177
- │ ├── extrait_eval.csv # Données évaluations
178
- │ └── extrait_sirh.csv # Données RH administratives
179
- ├── logs/ # 📋 Logs JSON
180
- │ ├── api.log # Tous les événements
181
- │ └── error.log # Erreurs uniquement
182
- ├── .github/workflows/ # 🔄 CI/CD
183
- │ └── ci-cd.yml # GitHub Actions (lint, test, deploy)
184
- ├── pyproject.toml # 📦 Configuration Poetry
185
- ├── .env.example # 🔑 Template variables environnement
186
- └── README.md # 📖 Ce fichier
187
- ```
188
-
189
- ---
190
-
191
- ## 🎯 Choix Techniques
192
-
193
- ### Justifications des Technologies
194
-
195
- | Technologie | Alternative | Pourquoi ce choix ? |
196
- |-------------|-------------|---------------------|
197
- | **FastAPI** | Flask, Django REST | ✅ **Typing natif** (validation auto via Pydantic)<br>✅ **Documentation auto** (Swagger/ReDoc)<br>✅ **Performance** (async, +200% vs Flask)<br>✅ **Moderne** (Python 3.12, type hints) |
198
- | **PostgreSQL** | MongoDB, SQLite | ✅ **Relationnel** adapté aux données structurées RH<br>✅ **ACID** pour garantir intégrité<br>✅ **Scalabilité** (index, partitioning)<br>✅ **Outils matures** (DBeaver, pgAdmin) |
199
- | **XGBoost** | Random Forest, NN | ✅ **Performance** sur données tabulaires<br>✅ **Régularisation** intégrée (évite overfitting)<br>✅ **Feature importance** nativement<br>✅ **Rapide** (parallélisation) |
200
- | **SMOTE** | Class weights, Under-sampling | ✅ **Génère exemples synthétiques** (vs duplication)<br>✅ **Évite surapprentissage**<br>✅ **Intégré imblearn** (CV-safe)<br>✅ +7% F1 vs class weights |
201
- | **Pydantic** | Marshmallow, Cerberus | ✅ **Validation en C** (via Rust, très rapide)<br>✅ **Messages d'erreur clairs**<br>✅ **Intégration FastAPI** native<br>✅ **Type safety** compile-time |
202
- | **HuggingFace Hub** | S3, GCP Storage | ✅ **Gratuit** jusqu'à 100GB<br>✅ **Versioning** automatique<br>✅ **CDN global** (latence faible)<br>✅ **Communauté** ML active |
203
- | **Poetry** | pip, conda | ✅ **Lock file** (reproductibilité garantie)<br>✅ **Gestion dépendances** (résolution conflits)<br>✅ **Build/Publish** intégrés<br>✅ **pyproject.toml** standard moderne |
204
- | **GitHub Actions** | GitLab CI, Jenkins | ✅ **Gratuit** pour repos publics<br>✅ **Intégration GitHub** native<br>✅ **Marketplace** d'actions prêtes<br>✅ **Déploiement HF** simplifié |
205
-
206
- ### Architecture Technique
207
-
208
- **Pattern utilisé** : **3-Tier Architecture** (Présentation - Logique - Données)
209
-
210
- ```
211
- ┌─────────────────────────────────────────────────────────────┐
212
- │ PRESENTATION LAYER │
213
- │ • FastAPI (REST API) │
214
- │ • Gradio (Web UI) │
215
- │ • Swagger/ReDoc (Documentation interactive) │
216
- └────────────────────────┬────────────────────────────────────┘
217
-
218
- ┌────────────────────────▼────────────────────────────────────┐
219
- │ BUSINESS LAYER │
220
- │ • Validation (Pydantic) │
221
- │ • Authentification (API Key) │
222
- │ • Rate Limiting (SlowAPI) │
223
- │ • Preprocessing (Feature Engineering) │
224
- │ • Prédiction (XGBoost Model) │
225
- │ • Logging (JSON Structured) │
226
- └────────────────────────┬────────────────────────────────────┘
227
-
228
- ┌────────────────────────▼────────────────────────────────────┐
229
- │ DATA LAYER │
230
- │ • PostgreSQL (Traçabilité prédictions) │
231
- │ • HuggingFace Hub (Modèle ML en cache) │
232
- │ • CSV Files (Données sources) │
233
- └─────────────────────────────────────────────────────────────┘
234
- ```
235
-
236
- ---
237
-
238
- ## ⚙️ Installation
239
-
240
- ### Prérequis
241
-
242
- | Outil | Version | Installation |
243
- |-------|---------|--------------|
244
- | **Python** | 3.12+ | [python.org](https://www.python.org/downloads/) |
245
- | **Poetry** | 1.7+ | `curl -sSL https://install.python-poetry.org \| python3 -` |
246
- | **PostgreSQL** | 14+ | [postgresql.org](https://www.postgresql.org/download/) ou Docker |
247
- | **Git** | 2.0+ | [git-scm.com](https://git-scm.com/downloads) |
248
-
249
- ### Étape 1 : Cloner le Repository
250
-
251
-
252
-
253
- ```bash
254
- git clone https://github.com/chaton59/OC_P5.git
255
- cd OC_P5
256
- ```
257
-
258
- ### Étape 2 : Installer les Dépendances
259
-
260
- ```bash
261
- # Installation via Poetry (recommandé)
262
- poetry install
263
-
264
- # Activer l'environnement virtuel
265
- poetry shell
266
-
267
- # OU utiliser pip (fallback)
268
- pip install -r requirements.txt
269
- ```
270
-
271
- ### Étape 3 : Configuration de l'Environnement
272
-
273
- ```bash
274
- # Copier le template
275
- cp .env.example .env
276
-
277
- # Éditer .env avec vos valeurs
278
- nano .env # ou vim, code, etc.
279
- ```
280
-
281
- **Variables à configurer** (`.env`) :
282
-
283
- ```bash
284
- # === MODE ===
285
- DEBUG=true # false en production (active auth + rate limiting)
286
-
287
- # === API ===
288
- API_KEY=your-secret-api-key-here # Générer avec: python -c "import secrets; print(secrets.token_urlsafe(32))"
289
- LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
290
-
291
- # === DATABASE (PostgreSQL) ===
292
- DB_HOST=localhost
293
- DB_PORT=5432
294
- DB_NAME=oc_p5_db
295
- DB_USER=ml_user
296
- DB_PASSWORD=your-secure-password # À changer !
297
-
298
- # === HUGGINGFACE ===
299
- HF_MODEL_REPO=ASI-Engineer/employee-turnover-model
300
- MODEL_FILENAME=model/model.pkl
301
- # HF_TOKEN=hf_xxx # Optionnel (modèles publics)
302
- ```
303
-
304
- ### Étape 4 : Configurer la Base de Données PostgreSQL
305
-
306
- #### Option A : Installation locale PostgreSQL
307
-
308
- ```bash
309
- # Ubuntu/Debian
310
- sudo apt update
311
- sudo apt install postgresql postgresql-contrib
312
-
313
- # macOS (via Homebrew)
314
- brew install postgresql@14
315
- brew services start postgresql@14
316
-
317
- # Windows : Télécharger depuis https://www.postgresql.org/download/windows/
318
- ```
319
-
320
- #### Option B : Docker (recommandé pour développement)
321
-
322
- ```bash
323
- # Démarrer PostgreSQL dans un conteneur
324
- docker run --name oc_p5_postgres \
325
- -e POSTGRES_USER=ml_user \
326
- -e POSTGRES_PASSWORD=your-password \
327
- -e POSTGRES_DB=oc_p5_db \
328
- -p 5432:5432 \
329
- -d postgres:14
330
- ```
331
-
332
- #### Créer les tables
333
-
334
- ```bash
335
- # Créer les tables (dataset, ml_logs)
336
- poetry run python scripts/create_db.py
337
-
338
- # Insérer le dataset (1470 employés)
339
- poetry run python scripts/insert_dataset.py
340
 
341
- # Vérifier l'insertion
342
- psql -h localhost -U ml_user -d oc_p5_db -c "SELECT COUNT(*) FROM dataset;"
343
- # Résultat attendu : 1470
344
- ```
345
 
346
- **Schéma de la base de données** :
347
 
348
- ![Schéma BDD](docs/schema.png)
 
 
 
 
 
 
 
349
 
350
- 📖 **Guide complet débutant** : [docs/database_guide.md](docs/database_guide.md)
351
 
352
- ### Étape 5 : Vérifier l'Installation
353
 
354
- ```bash
355
- # Tester que tout fonctionne
356
- poetry run pytest tests/ -v
357
 
358
- # Résultat attendu : 97 tests passés (ou 86 si skipped déployés)
359
- ```
 
 
 
 
 
360
 
361
- ---
362
 
363
  ## 🚀 Utilisation
364
 
365
- ### Démarrer l'API Localement
366
-
367
- ```bash
368
- # Mode développement (avec auto-reload)
369
- poetry run uvicorn api:app --reload --host 127.0.0.1 --port 8000
370
-
371
- # Mode production
372
- poetry run uvicorn api:app --host 0.0.0.0 --port 8000 --workers 4
373
- ```
374
-
375
- **URLs disponibles** :
376
-
377
- | Service | URL | Description |
378
- |---------|-----|-------------|
379
- | **API** | http://localhost:8000 | Endpoint principal |
380
- | **Swagger UI** | http://localhost:8000/docs | Documentation interactive |
381
- | **ReDoc** | http://localhost:8000/redoc | Documentation alternative |
382
- | **Health Check** | http://localhost:8000/health | Statut de l'API |
383
- | **Gradio UI** | http://localhost:8000/ui | Interface web (si activée) |
384
-
385
- ### Exemples d'Appels API
386
-
387
- #### 1. Health Check
388
-
389
- ```bash
390
- curl http://localhost:8000/health
391
- ```
392
-
393
- **Réponse** :
394
- ```json
395
- {
396
- "status": "healthy",
397
- "model_loaded": true,
398
- "model_type": "Pipeline",
399
- "version": "3.2.1"
400
- }
401
- ```
402
-
403
- #### 2. Prédiction Unitaire (JSON)
404
-
405
  ```bash
406
- # Sans authentification (DEBUG=true)
407
- curl -X POST http://localhost:8000/predict \
408
  -H "Content-Type: application/json" \
 
409
  -d '{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  "age": 35,
411
  "genre": "M",
412
  "revenu_mensuel": 4500.0,
413
- "satisfaction_employee_environnement": 3,
414
- ...
 
 
 
 
 
 
415
  }'
416
-
417
- # Avec authentification (DEBUG=false)
418
- curl -X POST http://localhost:8000/predict \
419
- -H "X-API-Key: your-secret-key" \
420
- -H "Content-Type: application/json" \
421
- -d @employee.json
422
- ```
423
-
424
- **Réponse** :
425
- ```json
426
- {
427
- "prediction": 0,
428
- "probability_0": 0.85,
429
- "probability_1": 0.15,
430
- "risk_level": "Low"
431
- }
432
  ```
433
 
434
- #### 3. Prédiction Batch (CSV)
435
-
436
  ```bash
437
- curl -X POST http://localhost:8000/predict/batch \
438
  -H "X-API-Key: your-key" \
439
- -F "sondage_file=@data/extrait_sondage.csv" \
440
- -F "eval_file=@data/extrait_eval.csv" \
441
- -F "sirh_file=@data/extrait_sirh.csv"
442
  ```
443
 
444
- **Réponse** :
445
  ```json
446
  {
447
  "total_employees": 1470,
@@ -454,398 +114,7 @@ curl -X POST http://localhost:8000/predict/batch \
454
  }
455
  ```
456
 
457
- ### Utilisation Python (SDK)
458
-
459
- ```python
460
- import requests
461
-
462
- # Configuration
463
- API_URL = "http://localhost:8000/predict"
464
- API_KEY = "your-secret-key"
465
-
466
- # Données employé
467
- employee = {
468
- "age": 28,
469
- "genre": "F",
470
- "revenu_mensuel": 3200.0,
471
- "departement": "Consulting",
472
- # ... (tous les 29 champs requis)
473
- }
474
-
475
- # Appel API
476
- response = requests.post(
477
- API_URL,
478
- headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
479
- json=employee
480
- )
481
-
482
- # Résultat
483
- if response.status_code == 200:
484
- result = response.json()
485
- print(f"Risque de départ: {result['probability_1']:.0%}")
486
- print(f"Niveau: {result['risk_level']}")
487
- ```
488
-
489
- 📚 **Documentation complète** : [docs/API_GUIDE.md](docs/API_GUIDE.md)
490
-
491
- ---
492
-
493
- ## 🌐 Déploiement
494
-
495
- ### Environnements Disponibles
496
-
497
- | Environnement | Branche Git | URL HuggingFace Spaces | Statut |
498
- |---------------|-------------|------------------------|--------|
499
- | **Production** | `main` | https://asi-engineer-oc-p5.hf.space | ✅ Live |
500
- | **Développement** | `dev` | https://asi-engineer-oc-p5-dev.hf.space | 🚧 Testing |
501
-
502
- ### Pipeline CI/CD (GitHub Actions)
503
-
504
- Le workflow `.github/workflows/ci-cd.yml` s'exécute automatiquement à chaque push :
505
-
506
- ```mermaid
507
- graph LR
508
- A[Push Code] --> B[Lint: Black + Flake8]
509
- B --> C[Tests: pytest 97 tests]
510
- C --> D[Test API Server]
511
- D --> E{Branche?}
512
- E -->|dev| F[Deploy HF Dev]
513
- E -->|main| G[Deploy HF Prod]
514
- ```
515
-
516
- **Jobs du pipeline** :
517
-
518
- 1. **Lint** (~30s) : Black (formatage) + Flake8 (qualité)
519
- 2. **Tests** (~3min) : pytest avec couverture (70%)
520
- 3. **Test API Server** (~2min) : Démarrage uvicorn + tests `/health` et `/predict`
521
- 4. **Deploy** : Déploiement automatique sur HuggingFace Spaces
522
-
523
- ⚡ **Temps total** : ~5-7 minutes (< 10min requis)
524
-
525
- ### Déploiement Manuel sur HuggingFace Spaces
526
-
527
- #### Prérequis
528
-
529
- ```bash
530
- # Installer la CLI HuggingFace
531
- pip install huggingface_hub
532
-
533
- # Se connecter
534
- huggingface-cli login
535
- # Entrer votre token (créer sur https://huggingface.co/settings/tokens)
536
- ```
537
-
538
- #### Pousser vers HF Spaces
539
-
540
- ```bash
541
- # 1. Ajouter le remote HF
542
- git remote add space https://huggingface.co/spaces/ASI-Engineer/oc_p5
543
-
544
- # 2. Push vers HF
545
- git push space main
546
-
547
- # 3. Vérifier le déploiement
548
- # Visiter https://huggingface.co/spaces/ASI-Engineer/oc_p5
549
- ```
550
-
551
- #### Configuration des Secrets HF Spaces
552
-
553
- Dans les settings du Space HuggingFace, ajouter :
554
-
555
- | Variable | Valeur | Description |
556
- |----------|--------|-------------|
557
- | `API_KEY` | `votre-clé-sécurisée` | Authentification API |
558
- | `DEBUG` | `false` | Mode production |
559
- | `LOG_LEVEL` | `INFO` | Niveau de logs |
560
-
561
- ### Déploiement Docker (Alternative)
562
-
563
- ```bash
564
- # Build de l'image
565
- docker build -t employee-turnover-api .
566
-
567
- # Run du conteneur
568
- docker run -d \
569
- -p 8000:8000 \
570
- -e API_KEY=your-key \
571
- -e DEBUG=false \
572
- --name turnover-api \
573
- employee-turnover-api
574
-
575
- # Vérifier
576
- curl http://localhost:8000/health
577
- ```
578
-
579
- 📖 **Guide complet** : [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)
580
-
581
- ---
582
-
583
- ## 🔄 Mise à Jour
584
-
585
- ### Mise à Jour du Code
586
-
587
- ```bash
588
- # 1. Récupérer les dernières modifications
589
- git pull origin main
590
-
591
- # 2. Mettre à jour les dépendances
592
- poetry update
593
-
594
- # 3. Appliquer les migrations DB (si nécessaire)
595
- poetry run python scripts/migrate_db.py
596
-
597
- # 4. Relancer l'API
598
- poetry run uvicorn api:app --reload
599
- ```
600
-
601
- ### Ré-entraînement du Modèle
602
-
603
- **Fréquence recommandée** : Tous les 3 mois (ou si drift détecté)
604
-
605
- ```bash
606
- # 1. Préparer les nouvelles données
607
- cp /path/to/new/data/*.csv data/
608
-
609
- # 2. Lancer l'entraînement (avec MLflow tracking)
610
- cd ml_model
611
- poetry run python main.py
612
-
613
- # 3. Comparer les performances
614
- poetry run mlflow ui
615
- # Ouvrir http://localhost:5000
616
-
617
- # 4. Si F1 Score ≥ 0.83, exporter le modèle
618
- poetry run python -c "
619
- import joblib
620
- import mlflow
621
-
622
- client = mlflow.tracking.MlflowClient()
623
- model_version = client.get_latest_versions('XGBoost_Employee_Turnover')[0]
624
- model = mlflow.sklearn.load_model(model_version.source)
625
- joblib.dump(model, 'model.pkl')
626
- "
627
-
628
- # 5. Uploader vers HuggingFace Hub
629
- poetry run python -c "
630
- from huggingface_hub import HfApi
631
-
632
- api = HfApi()
633
- api.upload_file(
634
- path_or_fileobj='model.pkl',
635
- path_in_repo='model/model.pkl',
636
- repo_id='ASI-Engineer/employee-turnover-model',
637
- commit_message='Update model v1.1 - F1=0.87'
638
- )
639
- "
640
-
641
- # 6. Créer un tag Git pour versioning
642
- git tag -a model-v1.1 -m "Model update: F1=0.87, Recall=0.89"
643
- git push origin model-v1.1
644
- ```
645
-
646
- ### Monitoring du Drift
647
-
648
- ```python
649
- # Script de détection de drift (à automatiser mensuellement)
650
- import pandas as pd
651
- from scipy.stats import ks_2samp
652
-
653
- train_data = pd.read_csv('data/extrait_sirh.csv')
654
- new_data = pd.read_csv('logs/recent_predictions.csv')
655
-
656
- for col in ['age', 'revenu_mensuel', 'annees_dans_l_entreprise']:
657
- statistic, pvalue = ks_2samp(train_data[col], new_data[col])
658
- if pvalue < 0.05:
659
- print(f'⚠️ DRIFT détecté sur {col} (p={pvalue:.4f})')
660
- # → Déclencher ré-entraînement
661
- ```
662
-
663
- 📖 **Guide complet** : [docs/MODEL_TECHNICAL.md](docs/MODEL_TECHNICAL.md#maintenance-et-mise-à-jour)
664
-
665
- ---
666
-
667
-
668
-
669
- ## ✅ Tests
670
-
671
- ### Suite de Tests Complète
672
-
673
- ```bash
674
- # Lancer tous les tests
675
- poetry run pytest tests/ -v
676
-
677
- # Avec rapport de couverture
678
- poetry run pytest tests/ --cov=. --cov-report=term-missing
679
-
680
- # Avec rapport HTML
681
- poetry run pytest tests/ --cov=. --cov-report=html
682
- open htmlcov/index.html
683
- ```
684
-
685
- ### Métriques
686
-
687
- | Métrique | Valeur | Détail |
688
- |----------|--------|--------|
689
- | **Tests** | 97 | 86 passés, 11 skippés (déploiement) |
690
- | **Couverture** | 70.26% | Objectif : ≥ 70% |
691
- | **Durée** | ~4s | Temps d'exécution total |
692
- | **Fichiers** | 9 | test_api_*.py, test_database.py, test_model.py |
693
-
694
- ### Catégories de Tests
695
-
696
- - ✅ **Authentification** (11 tests) : API Key, headers, rate limiting
697
- - ✅ **Health Check** (6 tests) : Status, modèle chargé, versionning
698
- - ✅ **Prédiction** (9 tests) : Endpoint `/predict`, probabilités, cohérence
699
- - ✅ **Validation** (15 tests) : Pydantic, types, énumérations, limites
700
- - ✅ **Database** (7 tests) : Connexion, CRUD, intégrité
701
- - ✅ **Fonctionnel** (19 tests) : End-to-end, performance, erreurs
702
- - ✅ **Modèle ML** (23 tests) : Chargement HF, preprocessing, prédictions
703
- - ✅ **API Déployée** (7 tests skippés) : Tests sur HF Spaces
704
-
705
- 📊 **Détail de couverture** :
706
-
707
- | Module | Couverture | Lignes | Manquantes |
708
- |--------|------------|--------|------------|
709
- | `src/config.py` | 100% | 20 | 0 |
710
- | `src/schemas.py` | 100% | 100 | 0 |
711
- | `src/rate_limit.py` | 100% | 10 | 0 |
712
- | `db_models.py` | 100% | 14 | 0 |
713
- | `src/logger.py` | 90.32% | 62 | 6 |
714
- | `src/preprocessing.py` | 76.36% | 55 | 13 |
715
- | `api.py` | 55.41% | 157 | 70 |
716
-
717
- ---
718
-
719
- ## 📚 Documentation
720
-
721
- | Document | Description |
722
- |----------|-------------|
723
- | [📖 README.md](README.md) | Vue d'ensemble et guide rapide (ce fichier) |
724
- | [🔌 API_GUIDE.md](docs/API_GUIDE.md) | Guide complet de l'API (endpoints, schémas, exemples) |
725
- | [🤖 MODEL_TECHNICAL.md](docs/MODEL_TECHNICAL.md) | Documentation technique du modèle (architecture, performances, maintenance) |
726
- | [🚀 DEPLOYMENT.md](docs/DEPLOYMENT.md) | Guide de déploiement (Docker, HF Spaces, CI/CD) |
727
- | [🎓 TRAINING.md](docs/TRAINING.md) | Guide d'entraînement du modèle (preprocessing, MLflow) |
728
- | [🗄️ database_guide.md](docs/database_guide.md) | Guide PostgreSQL pour débutants |
729
- | [📊 DOCUMENTATION_INVENTORY.md](docs/DOCUMENTATION_INVENTORY.md) | Inventaire complet de la documentation |
730
- | [📐 schema.puml](docs/schema.puml) | Diagramme UML de la base de données |
731
-
732
- **Documentation interactive** :
733
- - 🌐 **Swagger UI** : http://localhost:8000/docs
734
- - 📘 **ReDoc** : http://localhost:8000/redoc
735
-
736
- ---
737
-
738
- ## 📦 Dépendances Principales
739
-
740
- | Package | Version | Rôle |
741
- |---------|---------|------|
742
- | **FastAPI** | 0.115.14 | Framework API REST |
743
- | **Pydantic** | 2.12.5 | Validation données |
744
- | **XGBoost** | 2.1.3 | Modèle ML |
745
- | **imbalanced-learn** | 0.12.0 | SMOTE (rééquilibrage) |
746
- | **SQLAlchemy** | 2.0.23 | ORM PostgreSQL |
747
- | **psycopg2-binary** | 2.9.9 | Driver PostgreSQL |
748
- | **SlowAPI** | 0.1.9 | Rate limiting |
749
- | **python-json-logger** | 4.0.0 | Logs structurés |
750
- | **pytest** | 9.0.2 | Tests unitaires |
751
- | **MLflow** | 2.9.2 | Tracking expériences ML |
752
- | **Gradio** | 4.13.0 | Interface web |
753
-
754
- Voir [pyproject.toml](pyproject.toml) pour la liste complète.
755
-
756
- ---
757
-
758
-
759
-
760
- ## 🔄 Changelog
761
-
762
- ### v3.3.0 (Janvier 2026)
763
- - 📚 **Documentation complète** pour Étape 6 OpenClassrooms
764
- - 📝 Création de 13 nouveaux fichiers de documentation (~5000 lignes)
765
- - 🌐 Setup site MkDocs avec theme Material (17 pages HTML)
766
- - 📊 Inventaire complet de la documentation existante
767
- - 🔧 README restructuré selon Best-README-Template (841 lignes)
768
- - 📖 Guide API exhaustif avec 7 exemples (curl, Python, JS) - 981 lignes
769
- - 🤖 Documentation technique modèle avec diagrammes et justifications - 393 lignes
770
- - 📈 Visualisation des performances du modèle (model_performance.png)
771
- - ✅ Vérification complète : liens, cohérence, instructions testées
772
-
773
- ### v3.2.1 (Janvier 2026)
774
- - 🎛️ Sliders Gradio et schémas Pydantic alignés sur les min/max réels des données d'entraînement
775
- - 📦 Endpoint batch CSV (3 fichiers bruts)
776
- - 🔑 Authentification API Key (prod)
777
- - 🔧 Correction preprocessing (scaling, ordre des colonnes)
778
- - 📝 Documentation complète enrichie (API_GUIDE, MODEL_TECHNICAL)
779
-
780
- ### v2.2.0 (27 Décembre 2025)
781
- - 📦 Nouvel endpoint `/predict/batch` pour traitement CSV direct
782
- - 🔧 Fix preprocessing : ajout du scaling des features
783
- - 🔧 Fix preprocessing : correction de l'ordre des colonnes
784
- - 📊 Amélioration précision des prédictions (~90%)
785
-
786
- ### v2.1.0 (26 Décembre 2025)
787
- - ✨ Système de logging structuré JSON
788
- - 🛡️ Rate limiting avec SlowAPI
789
- - ⚡ Amélioration gestion d'erreurs
790
- - 📊 Monitoring des performances
791
-
792
- ### v2.0.0 (26 Décembre 2025)
793
- - ✅ Suite de tests complète (97 tests)
794
- - 🔐 Authentification API Key
795
- - 📊 70% de couverture de code
796
-
797
- ---
798
-
799
- ## 👥 Auteurs
800
-
801
- **Développeur** : Valentin (chaton59)
802
- **Projet** : OpenClassrooms P5 - Déployez votre modèle de Machine Learning
803
- **Repo GitHub** : [github.com/chaton59/OC_P5](https://github.com/chaton59/OC_P5)
804
- **HuggingFace** : [ASI-Engineer](https://huggingface.co/ASI-Engineer)
805
-
806
- ---
807
-
808
- ## 📄 Licence
809
-
810
- Ce projet est développé dans un cadre pédagogique (OpenClassrooms).
811
- Les données utilisées sont fictives.
812
-
813
- ---
814
-
815
- ## 🤝 Contributing
816
-
817
- Les contributions sont bienvenues ! Pour contribuer :
818
-
819
- 1. Fork le projet
820
- 2. Créer une branche feature (`git checkout -b feature/AmazingFeature`)
821
- 3. Commit les changements (`git commit -m 'Add AmazingFeature'`)
822
- 4. Push vers la branche (`git push origin feature/AmazingFeature`)
823
- 5. Ouvrir une Pull Request
824
-
825
- ---
826
-
827
- ## 📞 Contact & Support
828
-
829
- - **Issues GitHub** : [github.com/chaton59/OC_P5/issues](https://github.com/chaton59/OC_P5/issues)
830
- - **Discussions** : [github.com/chaton59/OC_P5/discussions](https://github.com/chaton59/OC_P5/discussions)
831
- - **Email** : Voir profil GitHub
832
-
833
- ---
834
-
835
- ## 🙏 Remerciements
836
-
837
- - **OpenClassrooms** pour le parcours Data Scientist
838
- - **HuggingFace** pour l'hébergement gratuit
839
- - **FastAPI** pour le framework moderne
840
- - **Communauté Python ML** pour les bibliothèques open-source
841
-
842
- ---
843
-
844
- <div align="center">
845
-
846
- **⭐ Si ce projet vous a aidé, n'hésitez pas à lui donner une étoile sur GitHub ! ⭐**
847
-
848
- Made with ❤️ by [chaton59](https://github.com/chaton59)
849
 
850
- </div>
851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Employee Turnover Prediction API
3
+ emoji: 👔
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ pinned: true
8
+ license: mit
9
+ app_port: 7860
 
 
 
 
 
 
 
 
10
  ---
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Employee Turnover Prediction API 🚀 (v3.3.0)
14
 
15
+ API de prédiction du turnover des employés (XGBoost + SMOTE) avec endpoints batch, validation stricte et **documentation complète**.
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 exhaustive** (Étape 6 OpenClassrooms)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
 
 
 
 
28
 
29
+ ## 📚 Documentation Complète
30
 
31
+ | Document | Description | Lignes |
32
+ |----------|-------------|--------|
33
+ | **[README.md](https://github.com/chaton59/OC_P5/blob/main/README.md)** | Vue d'ensemble complète (restructuré Best-README-Template) | 841 |
34
+ | **[API_GUIDE.md](https://github.com/chaton59/OC_P5/blob/main/docs/API_GUIDE.md)** | Guide API exhaustif avec 7 exemples (curl, Python, JS) | 981 |
35
+ | **[MODEL_TECHNICAL.md](https://github.com/chaton59/OC_P5/blob/main/docs/MODEL_TECHNICAL.md)** | Documentation technique modèle (architecture, justifications) | 393 |
36
+ | **[DEPLOYMENT.md](https://github.com/chaton59/OC_P5/blob/main/docs/DEPLOYMENT.md)** | Guide de déploiement (Docker, HF Spaces, CI/CD) | - |
37
+ | **[TRAINING.md](https://github.com/chaton59/OC_P5/blob/main/docs/TRAINING.md)** | Guide d'entraînement (preprocessing, MLflow) | - |
38
+ | **[Site MkDocs](https://github.com/chaton59/OC_P5/tree/main/docs)** | Documentation HTML navigable (17 pages, Material theme) | - |
39
 
40
+ **🌐 Site de documentation** : Générez localement avec `poetry run mkdocs serve`
41
 
 
42
 
43
+ ## 🔗 Endpoints
 
 
44
 
45
+ | Endpoint | Description |
46
+ |----------|-------------|
47
+ | `/docs` | Documentation interactive Swagger |
48
+ | `/health` | Status de l'API |
49
+ | `/ui` | Interface Gradio interactive |
50
+ | `/predict` | Prédiction unitaire (JSON, contraintes réelles) |
51
+ | `/predict/batch` | Prédiction batch (3 fichiers CSV bruts) |
52
 
 
53
 
54
  ## 🚀 Utilisation
55
 
56
+ ### Prédiction unitaire (toutes contraintes appliquées)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  ```bash
58
+ curl -X POST https://asi-engineer-oc-p5-dev.hf.space/predict \
 
59
  -H "Content-Type: application/json" \
60
+ -H "X-API-Key: your-key" \
61
  -d '{
62
+ "nombre_participation_pee": 0,
63
+ "nb_formations_suivies": 2,
64
+ "nombre_employee_sous_responsabilite": 1,
65
+ "distance_domicile_travail": 15,
66
+ "niveau_education": 3,
67
+ "domaine_etude": "Infra & Cloud",
68
+ "ayant_enfants": "Y",
69
+ "frequence_deplacement": "Occasionnel",
70
+ "annees_depuis_la_derniere_promotion": 2,
71
+ "annes_sous_responsable_actuel": 5,
72
+ "satisfaction_employee_environnement": 3,
73
+ "note_evaluation_precedente": 4,
74
+ "niveau_hierarchique_poste": 2,
75
+ "satisfaction_employee_nature_travail": 3,
76
+ "satisfaction_employee_equipe": 3,
77
+ "satisfaction_employee_equilibre_pro_perso": 2,
78
+ "note_evaluation_actuelle": 4,
79
+ "heure_supplementaires": "Non",
80
+ "augementation_salaire_precedente": 5.5,
81
  "age": 35,
82
  "genre": "M",
83
  "revenu_mensuel": 4500.0,
84
+ "statut_marital": "Marié(e)",
85
+ "departement": "Commercial",
86
+ "poste": "Manager",
87
+ "nombre_experiences_precedentes": 3,
88
+ "nombre_heures_travailless": 80,
89
+ "annee_experience_totale": 10,
90
+ "annees_dans_l_entreprise": 5,
91
+ "annees_dans_le_poste_actuel": 2
92
  }'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  ```
94
 
95
+ ### Prédiction batch (3 fichiers CSV bruts)
 
96
  ```bash
97
+ curl -X POST https://asi-engineer-oc-p5-dev.hf.space/predict/batch \
98
  -H "X-API-Key: your-key" \
99
+ -F "sondage_file=@extrait_sondage.csv" \
100
+ -F "eval_file=@extrait_eval.csv" \
101
+ -F "sirh_file=@extrait_sirh.csv"
102
  ```
103
 
104
+ **Réponse :**
105
  ```json
106
  {
107
  "total_employees": 1470,
 
114
  }
115
  ```
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ ## 📚 Documentation complète
119
 
120
+ 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).