Spaces:
Sleeping
Sleeping
Déploiement depuis GitHub Actions
Browse files- README.md +1 -0
- app/main.py +8 -0
- app/monitoring.py +55 -0
- requirements.txt +1 -0
- space_app.py +90 -15
README.md
CHANGED
|
@@ -18,4 +18,5 @@ Déployée automatiquement depuis GitHub Actions.
|
|
| 18 |
- `GET /` : interface Gradio
|
| 19 |
- `POST /predict` : prédiction (API FastAPI)
|
| 20 |
- `GET /health` : état du service
|
|
|
|
| 21 |
- `GET /docs` : documentation Swagger
|
|
|
|
| 18 |
- `GET /` : interface Gradio
|
| 19 |
- `POST /predict` : prédiction (API FastAPI)
|
| 20 |
- `GET /health` : état du service
|
| 21 |
+
- `GET /monitoring` : monitoring en temps réel (trafic, prédictions, dérive des données)
|
| 22 |
- `GET /docs` : documentation Swagger
|
app/main.py
CHANGED
|
@@ -9,6 +9,8 @@ from fastapi import FastAPI
|
|
| 9 |
from fastapi.responses import HTMLResponse
|
| 10 |
from pydantic import BaseModel, Field
|
| 11 |
|
|
|
|
|
|
|
| 12 |
MODEL_PATH = Path("models/model.pkl")
|
| 13 |
LOG_PATH = Path("logs/predictions.csv")
|
| 14 |
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
|
|
@@ -55,6 +57,12 @@ def predict(data: IrisInput):
|
|
| 55 |
}
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
@app.get("/", response_class=HTMLResponse)
|
| 59 |
def home():
|
| 60 |
return Path(__file__).with_name("index.html").read_text(encoding="utf-8")
|
|
|
|
| 9 |
from fastapi.responses import HTMLResponse
|
| 10 |
from pydantic import BaseModel, Field
|
| 11 |
|
| 12 |
+
from app.monitoring import monitoring_summary
|
| 13 |
+
|
| 14 |
MODEL_PATH = Path("models/model.pkl")
|
| 15 |
LOG_PATH = Path("logs/predictions.csv")
|
| 16 |
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
|
|
|
|
| 57 |
}
|
| 58 |
|
| 59 |
|
| 60 |
+
@app.get("/monitoring")
|
| 61 |
+
def monitoring():
|
| 62 |
+
"""Indicateurs de monitoring en temps réel (trafic, prédictions, dérive des données)."""
|
| 63 |
+
return monitoring_summary(LOG_PATH)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
@app.get("/", response_class=HTMLResponse)
|
| 67 |
def home():
|
| 68 |
return Path(__file__).with_name("index.html").read_text(encoding="utf-8")
|
app/monitoring.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Étape 6 (temps réel) : indicateurs calculés à la volée sur les prédictions journalisées.
|
| 2 |
+
|
| 3 |
+
La dérive est mesurée comme dans Evidently pour des petites données numériques :
|
| 4 |
+
test de Kolmogorov-Smirnov par variable (dérive si p-value < 0.05), et dérive du jeu
|
| 5 |
+
de données si au moins la moitié des variables dérivent.
|
| 6 |
+
"""
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from scipy.stats import ks_2samp
|
| 11 |
+
from sklearn.datasets import load_iris
|
| 12 |
+
|
| 13 |
+
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
|
| 14 |
+
CLASSES = ["setosa", "versicolor", "virginica"]
|
| 15 |
+
MIN_ROWS = 30
|
| 16 |
+
P_THRESHOLD = 0.05
|
| 17 |
+
|
| 18 |
+
REFERENCE = pd.DataFrame(load_iris().data, columns=FEATURES)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_logs(log_path: Path) -> pd.DataFrame:
|
| 22 |
+
if not log_path.exists():
|
| 23 |
+
return pd.DataFrame(columns=["timestamp", *FEATURES, "prediction"])
|
| 24 |
+
return pd.read_csv(log_path)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def drift_table(current: pd.DataFrame) -> pd.DataFrame:
|
| 28 |
+
rows = []
|
| 29 |
+
for f in FEATURES:
|
| 30 |
+
p_value = ks_2samp(REFERENCE[f], current[f]).pvalue if len(current) >= MIN_ROWS else None
|
| 31 |
+
rows.append({
|
| 32 |
+
"variable": f,
|
| 33 |
+
"moyenne_reference": round(REFERENCE[f].mean(), 2),
|
| 34 |
+
"moyenne_production": round(current[f].mean(), 2) if len(current) else None,
|
| 35 |
+
"p_value": round(p_value, 4) if p_value is not None else None,
|
| 36 |
+
"derive": None if p_value is None else bool(p_value < P_THRESHOLD),
|
| 37 |
+
})
|
| 38 |
+
return pd.DataFrame(rows)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def monitoring_summary(log_path: Path) -> dict:
|
| 42 |
+
logs = load_logs(log_path)
|
| 43 |
+
drift = drift_table(logs)
|
| 44 |
+
counts = logs["prediction"].value_counts().to_dict() if len(logs) else {}
|
| 45 |
+
drifted = int(drift["derive"].eq(True).sum())
|
| 46 |
+
enough = len(logs) >= MIN_ROWS
|
| 47 |
+
return {
|
| 48 |
+
"total_predictions": len(logs),
|
| 49 |
+
"last_prediction": logs["timestamp"].iloc[-1] if len(logs) else None,
|
| 50 |
+
"predictions_par_classe": {c: int(counts.get(i, 0)) for i, c in enumerate(CLASSES)},
|
| 51 |
+
"assez_de_donnees": enough,
|
| 52 |
+
"variables_en_derive": drifted,
|
| 53 |
+
"derive_detectee": enough and drifted >= len(FEATURES) / 2,
|
| 54 |
+
"derive_par_variable": drift.to_dict(orient="records"),
|
| 55 |
+
}
|
requirements.txt
CHANGED
|
@@ -3,3 +3,4 @@ scikit-learn==1.9.1
|
|
| 3 |
pandas==2.3.3
|
| 4 |
numpy==2.5.4
|
| 5 |
joblib==1.6.0
|
|
|
|
|
|
| 3 |
pandas==2.3.3
|
| 4 |
numpy==2.5.4
|
| 5 |
joblib==1.6.0
|
| 6 |
+
scipy==1.18.1
|
space_app.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
|
| 3 |
C'est Gradio qui lance le serveur (demo.launch) : ZeroGPU ne démarre correctement que
|
| 4 |
de cette façon. On y ajoute ensuite les routes de l'API FastAPI (app/main.py) :
|
| 5 |
-
/predict et /
|
| 6 |
"""
|
| 7 |
import os
|
| 8 |
|
|
@@ -15,11 +15,15 @@ except ImportError:
|
|
| 15 |
return fn
|
| 16 |
|
| 17 |
import gradio as gr
|
|
|
|
|
|
|
| 18 |
from fastapi.routing import APIRoute
|
| 19 |
|
| 20 |
-
from app.main import CLASSES, IrisInput, app as api, predict
|
|
|
|
| 21 |
|
| 22 |
-
API_PATHS = {"/predict", "/health"}
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
@gpu
|
|
@@ -31,18 +35,89 @@ def gradio_predict(sepal_length, sepal_width, petal_length, petal_width):
|
|
| 31 |
return result["probabilities"]
|
| 32 |
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
if __name__ == "__main__":
|
| 48 |
demo.launch(
|
|
|
|
| 2 |
|
| 3 |
C'est Gradio qui lance le serveur (demo.launch) : ZeroGPU ne démarre correctement que
|
| 4 |
de cette façon. On y ajoute ensuite les routes de l'API FastAPI (app/main.py) :
|
| 5 |
+
/predict, /health et /monitoring, documentées sur /docs.
|
| 6 |
"""
|
| 7 |
import os
|
| 8 |
|
|
|
|
| 15 |
return fn
|
| 16 |
|
| 17 |
import gradio as gr
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
from fastapi.routing import APIRoute
|
| 21 |
|
| 22 |
+
from app.main import CLASSES, LOG_PATH, IrisInput, app as api, predict
|
| 23 |
+
from app.monitoring import FEATURES, MIN_ROWS, REFERENCE, drift_table, load_logs, monitoring_summary
|
| 24 |
|
| 25 |
+
API_PATHS = {"/predict", "/health", "/monitoring"}
|
| 26 |
+
REFRESH_SECONDS = 5
|
| 27 |
|
| 28 |
|
| 29 |
@gpu
|
|
|
|
| 35 |
return result["probabilities"]
|
| 36 |
|
| 37 |
|
| 38 |
+
def simulate_traffic(n: int, drift: bool):
|
| 39 |
+
"""Envoie n requêtes au modèle, tirées des données d'entraînement (décalées si drift=True)."""
|
| 40 |
+
rng = np.random.default_rng()
|
| 41 |
+
sample = REFERENCE.sample(n, replace=True).reset_index(drop=True)
|
| 42 |
+
sample += rng.normal(0, 0.1, sample.shape)
|
| 43 |
+
if drift:
|
| 44 |
+
sample["petal_length"] += 1.5
|
| 45 |
+
sample["sepal_width"] -= 0.8
|
| 46 |
+
sample["petal_width"] += 0.6
|
| 47 |
+
for row in sample.clip(lower=0.1).round(2).to_dict(orient="records"):
|
| 48 |
+
predict(IrisInput(**row))
|
| 49 |
+
return refresh()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def reset_logs():
|
| 53 |
+
LOG_PATH.unlink(missing_ok=True)
|
| 54 |
+
return refresh()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def refresh():
|
| 58 |
+
summary = monitoring_summary(LOG_PATH)
|
| 59 |
+
logs = load_logs(LOG_PATH)
|
| 60 |
+
|
| 61 |
+
if not summary["assez_de_donnees"]:
|
| 62 |
+
status = (f"### ⏳ En attente de données\n{summary['total_predictions']} / {MIN_ROWS} prédictions "
|
| 63 |
+
"nécessaires pour calculer la dérive.")
|
| 64 |
+
elif summary["derive_detectee"]:
|
| 65 |
+
status = (f"### 🚨 Dérive des données détectée\n{summary['variables_en_derive']} variable(s) sur "
|
| 66 |
+
f"{len(FEATURES)} ont changé de distribution : il faut ré-entraîner le modèle (`dvc repro`).")
|
| 67 |
+
else:
|
| 68 |
+
status = (f"### ✅ Pas de dérive\n{summary['variables_en_derive']} variable(s) sur {len(FEATURES)} "
|
| 69 |
+
"en dérive : les données de production ressemblent aux données d'entraînement.")
|
| 70 |
+
|
| 71 |
+
kpis = (f"**Prédictions reçues :** {summary['total_predictions']} \n"
|
| 72 |
+
f"**Dernière prédiction :** {summary['last_prediction'] or '-'} \n"
|
| 73 |
+
f"**Actualisation automatique :** toutes les {REFRESH_SECONDS} s")
|
| 74 |
+
|
| 75 |
+
classes = pd.DataFrame({"espece": CLASSES, "nombre": list(summary["predictions_par_classe"].values())})
|
| 76 |
+
|
| 77 |
+
recent = logs.tail(200).reset_index(drop=True)
|
| 78 |
+
recent["requete"] = recent.index + 1
|
| 79 |
+
timeline = recent.melt(id_vars="requete", value_vars=FEATURES, var_name="variable", value_name="valeur")
|
| 80 |
+
|
| 81 |
+
return status, kpis, classes, drift_table(logs), timeline
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
with gr.Blocks(title="Iris MLOps") as demo:
|
| 85 |
+
gr.Markdown("# Classification d'Iris (MLOps)\nModèle scikit-learn servi par FastAPI · "
|
| 86 |
+
"API : `POST /predict` · `GET /monitoring` · Swagger : `/docs`")
|
| 87 |
+
|
| 88 |
+
with gr.Tab("Prédiction"):
|
| 89 |
+
gr.Interface(
|
| 90 |
+
fn=gradio_predict,
|
| 91 |
+
inputs=[
|
| 92 |
+
gr.Number(5.1, label="Longueur sépale (cm)"),
|
| 93 |
+
gr.Number(3.5, label="Largeur sépale (cm)"),
|
| 94 |
+
gr.Number(1.4, label="Longueur pétale (cm)"),
|
| 95 |
+
gr.Number(0.2, label="Largeur pétale (cm)"),
|
| 96 |
+
],
|
| 97 |
+
outputs=gr.Label(num_top_classes=len(CLASSES), label="Espèce prédite"),
|
| 98 |
+
flagging_mode="never",
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Tab("Monitoring temps réel"):
|
| 102 |
+
with gr.Row():
|
| 103 |
+
status = gr.Markdown()
|
| 104 |
+
kpis = gr.Markdown()
|
| 105 |
+
with gr.Row():
|
| 106 |
+
btn_normal = gr.Button("Simuler 50 requêtes normales")
|
| 107 |
+
btn_drift = gr.Button("Simuler 50 requêtes avec dérive", variant="stop")
|
| 108 |
+
btn_reset = gr.Button("Réinitialiser")
|
| 109 |
+
with gr.Row():
|
| 110 |
+
classes_plot = gr.BarPlot(x="espece", y="nombre", title="Prédictions par espèce")
|
| 111 |
+
timeline_plot = gr.LinePlot(x="requete", y="valeur", color="variable",
|
| 112 |
+
title="Valeurs reçues (200 dernières requêtes)")
|
| 113 |
+
drift_df = gr.Dataframe(label="Dérive par variable (test de Kolmogorov-Smirnov, seuil p < 0.05)")
|
| 114 |
+
|
| 115 |
+
outputs = [status, kpis, classes_plot, drift_df, timeline_plot]
|
| 116 |
+
btn_normal.click(lambda: simulate_traffic(50, drift=False), outputs=outputs)
|
| 117 |
+
btn_drift.click(lambda: simulate_traffic(50, drift=True), outputs=outputs)
|
| 118 |
+
btn_reset.click(reset_logs, outputs=outputs)
|
| 119 |
+
gr.Timer(REFRESH_SECONDS).tick(refresh, outputs=outputs)
|
| 120 |
+
demo.load(refresh, outputs=outputs)
|
| 121 |
|
| 122 |
if __name__ == "__main__":
|
| 123 |
demo.launch(
|