Spaces:
Sleeping

Michael1306 commited on
Commit
700cfdb
·
verified ·
1 Parent(s): f039ad4

Déploiement depuis GitHub Actions

Browse files
Files changed (7) hide show
  1. README.md +15 -8
  2. app/__init__.py +0 -0
  3. app/index.html +58 -0
  4. app/main.py +60 -0
  5. models/model.pkl +3 -0
  6. requirements.txt +5 -0
  7. space_app.py +36 -0
README.md CHANGED
@@ -1,14 +1,21 @@
1
  ---
2
- title: Iris Mlops Api
3
- emoji: 👀
4
- colorFrom: red
5
- colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.12'
9
- app_file: app.py
10
  pinned: false
11
- license: mit
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Iris MLOps API
3
+ emoji: 🌸
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
+ python_version: "3.12"
9
+ app_file: space_app.py
10
  pinned: false
 
11
  ---
12
 
13
+ # Iris MLOps API
14
+
15
+ API FastAPI servant un modèle scikit-learn (RandomForest) entraîné sur le jeu de données Iris.
16
+ Déployée automatiquement depuis GitHub Actions.
17
+
18
+ - `GET /` : interface web
19
+ - `GET /gradio` : interface Gradio
20
+ - `POST /predict` : prédiction
21
+ - `GET /docs` : documentation Swagger
app/__init__.py ADDED
File without changes
app/index.html ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="fr">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Iris MLOps</title>
7
+ <style>
8
+ :root { --bg:#f6f7f9; --card:#fff; --text:#1d2330; --muted:#5c6577; --accent:#2f6fde; --border:#dde1e8; }
9
+ @media (prefers-color-scheme: dark) {
10
+ :root { --bg:#11141a; --card:#1a1f28; --text:#e6e9ef; --muted:#98a1b3; --accent:#6b9cff; --border:#2c3340; }
11
+ }
12
+ * { box-sizing: border-box; }
13
+ body { margin:0; font-family: system-ui, sans-serif; background:var(--bg); color:var(--text); }
14
+ main { max-width: 560px; margin: 40px auto; padding: 0 16px; }
15
+ .card { background:var(--card); border:1px solid var(--border); border-radius:12px; padding:24px; }
16
+ h1 { margin:0 0 4px; font-size:1.5rem; }
17
+ p { color:var(--muted); margin:0 0 20px; }
18
+ .grid { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
19
+ label { font-size:.85rem; color:var(--muted); display:block; margin-bottom:4px; }
20
+ input { width:100%; padding:10px; border:1px solid var(--border); border-radius:8px; background:var(--bg); color:var(--text); font-size:1rem; }
21
+ button { margin-top:16px; width:100%; padding:12px; border:0; border-radius:8px; background:var(--accent); color:#fff; font-size:1rem; cursor:pointer; }
22
+ #result { margin-top:20px; font-size:1.1rem; }
23
+ .links { margin-top:16px; font-size:.9rem; }
24
+ a { color:var(--accent); }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <main>
29
+ <div class="card">
30
+ <h1>Classification d'Iris</h1>
31
+ <p>Modèle scikit-learn servi par FastAPI, déployé via GitHub Actions + Docker sur Hugging Face Spaces.</p>
32
+ <form id="f">
33
+ <div class="grid">
34
+ <div><label>Longueur sépale (cm)</label><input name="sepal_length" type="number" step="0.1" value="5.1" required></div>
35
+ <div><label>Largeur sépale (cm)</label><input name="sepal_width" type="number" step="0.1" value="3.5" required></div>
36
+ <div><label>Longueur pétale (cm)</label><input name="petal_length" type="number" step="0.1" value="1.4" required></div>
37
+ <div><label>Largeur pétale (cm)</label><input name="petal_width" type="number" step="0.1" value="0.2" required></div>
38
+ </div>
39
+ <button type="submit">Prédire</button>
40
+ </form>
41
+ <div id="result"></div>
42
+ <div class="links"><a href="gradio/">Interface Gradio</a> · <a href="docs">Documentation API (Swagger)</a> · <a href="health">Health check</a></div>
43
+ </div>
44
+ </main>
45
+ <script>
46
+ document.getElementById("f").addEventListener("submit", async (e) => {
47
+ e.preventDefault();
48
+ const body = Object.fromEntries([...new FormData(e.target)].map(([k, v]) => [k, parseFloat(v)]));
49
+ const res = await fetch("predict", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
50
+ const out = document.getElementById("result");
51
+ if (!res.ok) { out.textContent = "Erreur : valeurs invalides"; return; }
52
+ const data = await res.json();
53
+ const probs = Object.entries(data.probabilities).map(([k, v]) => `${k} ${(v * 100).toFixed(1)}%`).join(" · ");
54
+ out.innerHTML = `<strong>${data.class_name}</strong><br><small>${probs}</small>`;
55
+ });
56
+ </script>
57
+ </body>
58
+ </html>
app/main.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Étape 2 : API FastAPI qui sert model.pkl et journalise les prédictions pour le monitoring."""
2
+ import csv
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+
6
+ import joblib
7
+ import pandas as pd
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"]
15
+ CLASSES = ["setosa", "versicolor", "virginica"]
16
+
17
+ app = FastAPI(title="Iris MLOps API", version="1.0.0")
18
+ model = joblib.load(MODEL_PATH)
19
+
20
+
21
+ class IrisInput(BaseModel):
22
+ sepal_length: float = Field(..., gt=0, examples=[5.1])
23
+ sepal_width: float = Field(..., gt=0, examples=[3.5])
24
+ petal_length: float = Field(..., gt=0, examples=[1.4])
25
+ petal_width: float = Field(..., gt=0, examples=[0.2])
26
+
27
+
28
+ def log_prediction(row: dict, prediction: int):
29
+ """Enregistre chaque requête : ces données servent à Evidently pour détecter la dérive."""
30
+ LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
31
+ new_file = not LOG_PATH.exists()
32
+ with open(LOG_PATH, "a", newline="") as f:
33
+ writer = csv.DictWriter(f, fieldnames=["timestamp", *FEATURES, "prediction"])
34
+ if new_file:
35
+ writer.writeheader()
36
+ writer.writerow({"timestamp": datetime.now(timezone.utc).isoformat(), **row, "prediction": prediction})
37
+
38
+
39
+ @app.get("/health")
40
+ def health():
41
+ return {"status": "ok", "model_loaded": model is not None}
42
+
43
+
44
+ @app.post("/predict")
45
+ def predict(data: IrisInput):
46
+ row = data.model_dump()
47
+ X = pd.DataFrame([row], columns=FEATURES)
48
+ pred = int(model.predict(X)[0])
49
+ proba = model.predict_proba(X)[0]
50
+ log_prediction(row, pred)
51
+ return {
52
+ "prediction": pred,
53
+ "class_name": CLASSES[pred],
54
+ "probabilities": {c: round(float(p), 4) for c, p in zip(CLASSES, proba)},
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")
models/model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cae357298a9a10523b29d32327df08a725b2bebd0188fec84559c2a327e7cac
3
+ size 163489
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Dépendances du Space Hugging Face (Gradio, FastAPI et uvicorn sont fournis par le SDK Gradio)
2
+ scikit-learn==1.9.1
3
+ pandas==2.3.3
4
+ numpy==2.5.4
5
+ joblib==1.6.0
space_app.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Point d'entrée du Space Hugging Face (SDK Gradio).
2
+
3
+ L'API FastAPI (app/main.py) reste le cœur du service : on y monte une interface Gradio
4
+ sur /gradio, et on sert le tout avec uvicorn sur le port 7860 attendu par Hugging Face.
5
+ """
6
+ import gradio as gr
7
+ import uvicorn
8
+
9
+ from app.main import CLASSES, IrisInput, app, predict
10
+
11
+
12
+ def gradio_predict(sepal_length, sepal_width, petal_length, petal_width):
13
+ result = predict(IrisInput(
14
+ sepal_length=sepal_length, sepal_width=sepal_width,
15
+ petal_length=petal_length, petal_width=petal_width,
16
+ ))
17
+ return result["probabilities"]
18
+
19
+
20
+ demo = gr.Interface(
21
+ fn=gradio_predict,
22
+ inputs=[
23
+ gr.Number(5.1, label="Longueur sépale (cm)"),
24
+ gr.Number(3.5, label="Largeur sépale (cm)"),
25
+ gr.Number(1.4, label="Longueur pétale (cm)"),
26
+ gr.Number(0.2, label="Largeur pétale (cm)"),
27
+ ],
28
+ outputs=gr.Label(num_top_classes=len(CLASSES), label="Espèce prédite"),
29
+ title="Classification d'Iris (MLOps)",
30
+ description="Modèle scikit-learn servi par FastAPI. API : /predict · Swagger : /docs",
31
+ )
32
+
33
+ app = gr.mount_gradio_app(app, demo, path="/gradio")
34
+
35
+ if __name__ == "__main__":
36
+ uvicorn.run(app, host="0.0.0.0", port=7860)