Spaces:
Sleeping
Sleeping
app HS
Browse files- Dockerfile +18 -0
- api/__pycache__/app.cpython-312.pyc +0 -0
- api/app.py +142 -0
- api/model/metadata.json +22 -0
- api/model/pipeline.pkl +3 -0
- requirements.txt +7 -0
Dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dockerfile (racine du Space)
|
| 2 |
+
FROM python:3.10-slim
|
| 3 |
+
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 5 |
+
PYTHONUNBUFFERED=1 \
|
| 6 |
+
PORT=8000
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Dépendances
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
# Code + modèle
|
| 15 |
+
COPY api/ ./api/
|
| 16 |
+
|
| 17 |
+
EXPOSE 8000
|
| 18 |
+
CMD ["uvicorn", "api.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
api/__pycache__/app.cpython-312.pyc
ADDED
|
Binary file (7.86 kB). View file
|
|
|
api/app.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import List, Any
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import json
|
| 7 |
+
import joblib
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
app = FastAPI(title="Getaround Pricing API", version="1.0.0")
|
| 12 |
+
|
| 13 |
+
MODEL_PATH = Path("api/model/pipeline.pkl")
|
| 14 |
+
META_PATH = Path("api/model/metadata.json")
|
| 15 |
+
|
| 16 |
+
pipeline = joblib.load(MODEL_PATH)
|
| 17 |
+
metadata = json.loads(META_PATH.read_text(encoding="utf-8")) if META_PATH.exists() else {}
|
| 18 |
+
|
| 19 |
+
# Helpers pour connaître le schéma attendu
|
| 20 |
+
def get_expected_cols():
|
| 21 |
+
return list(metadata.get("num_cols", [])) + list(metadata.get("cat_cols", []))
|
| 22 |
+
|
| 23 |
+
expected_cols = get_expected_cols()
|
| 24 |
+
|
| 25 |
+
def make_example_row():
|
| 26 |
+
# 0 pour les numériques, "unknown" pour les catégorielles
|
| 27 |
+
return [0] * len(metadata.get("num_cols", [])) + ["unknown"] * len(metadata.get("cat_cols", []))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PredictPayload(BaseModel):
|
| 31 |
+
input: list # liste de lignes, chaque ligne = features dans le bon ordre/format
|
| 32 |
+
|
| 33 |
+
@app.get("/health")
|
| 34 |
+
def health():
|
| 35 |
+
return {"status": "ok", "model": metadata.get("model_name")}
|
| 36 |
+
|
| 37 |
+
@app.post("/predict")
|
| 38 |
+
def predict(payload: PredictPayload):
|
| 39 |
+
try:
|
| 40 |
+
rows = payload.input
|
| 41 |
+
if not rows or not isinstance(rows, list):
|
| 42 |
+
raise HTTPException(status_code=400, detail="Body must be {'input': [[...], ...]}")
|
| 43 |
+
|
| 44 |
+
# Colonnes attendues (issues de metadata.json)
|
| 45 |
+
cols = expected_cols if expected_cols else [f"f{i}" for i in range(len(rows[0]))]
|
| 46 |
+
if expected_cols and any(len(r) != len(cols) for r in rows):
|
| 47 |
+
raise HTTPException(
|
| 48 |
+
status_code=400,
|
| 49 |
+
detail=f"Each row must have {len(cols)} features in this order: {cols}",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# DataFrame avec NOMS de colonnes
|
| 53 |
+
X_df = pd.DataFrame(rows, columns=cols)
|
| 54 |
+
|
| 55 |
+
# === CASTING FORT (évite 500 liés aux dtypes) ===
|
| 56 |
+
num_cols = metadata.get("num_cols", [])
|
| 57 |
+
cat_cols = metadata.get("cat_cols", [])
|
| 58 |
+
known_bool_cols = {
|
| 59 |
+
"private_parking_available","has_gps","has_air_conditioning",
|
| 60 |
+
"automatic_car","has_getaround_connect","has_speed_regulator","winter_tires",
|
| 61 |
+
}
|
| 62 |
+
bool_cols = [c for c in cat_cols if c in known_bool_cols and c in X_df.columns]
|
| 63 |
+
text_cat_cols = [c for c in cat_cols if c not in known_bool_cols and c in X_df.columns]
|
| 64 |
+
|
| 65 |
+
# num -> float
|
| 66 |
+
for c in num_cols:
|
| 67 |
+
if c in X_df.columns:
|
| 68 |
+
X_df[c] = pd.to_numeric(X_df[c], errors="coerce")
|
| 69 |
+
if num_cols:
|
| 70 |
+
X_df[num_cols] = X_df[num_cols].fillna(0.0)
|
| 71 |
+
|
| 72 |
+
# bool -> bool strict
|
| 73 |
+
def to_bool(v):
|
| 74 |
+
if isinstance(v, bool): return v
|
| 75 |
+
s = str(v).strip().lower()
|
| 76 |
+
return s in {"1","true","t","yes","y","on"}
|
| 77 |
+
for c in bool_cols:
|
| 78 |
+
X_df[c] = X_df[c].map(to_bool).fillna(False)
|
| 79 |
+
|
| 80 |
+
# cat texte -> str
|
| 81 |
+
for c in text_cat_cols:
|
| 82 |
+
X_df[c] = X_df[c].astype(str).fillna("unknown")
|
| 83 |
+
|
| 84 |
+
# Prédiction
|
| 85 |
+
y_pred = pipeline.predict(X_df)
|
| 86 |
+
return {"prediction": np.asarray(y_pred).ravel().tolist()}
|
| 87 |
+
|
| 88 |
+
except HTTPException:
|
| 89 |
+
raise
|
| 90 |
+
except Exception as e:
|
| 91 |
+
traceback.print_exc() # log côté serveur
|
| 92 |
+
raise HTTPException(status_code=400, detail=f"Prediction failed: {type(e).__name__}: {e}")
|
| 93 |
+
|
| 94 |
+
@app.get("/schema")
|
| 95 |
+
def schema():
|
| 96 |
+
return {
|
| 97 |
+
"num_cols": metadata.get("num_cols", []),
|
| 98 |
+
"cat_cols": metadata.get("cat_cols", []),
|
| 99 |
+
"expected_cols": expected_cols,
|
| 100 |
+
"n_features_expected": len(expected_cols),
|
| 101 |
+
"example_payload": {"input": [make_example_row()]},
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Page HTML de doc simple exigée à /docs
|
| 106 |
+
DOC_HTML = f"""
|
| 107 |
+
<!doctype html>
|
| 108 |
+
<html>
|
| 109 |
+
<head><meta charset="utf-8"><title>Getaround Pricing API – Docs</title>
|
| 110 |
+
<style>
|
| 111 |
+
body{{font-family:system-ui,Segoe UI,Roboto,Helvetica,Arial,sans-serif;max-width:900px;margin:40px auto;line-height:1.5}}
|
| 112 |
+
code,pre{{background:#f6f8fa;padding:8px 10px;border-radius:6px;display:block;overflow:auto}}
|
| 113 |
+
h1{{margin-bottom:0}}
|
| 114 |
+
.small{{color:#666;font-size:0.9rem}}
|
| 115 |
+
</style>
|
| 116 |
+
</head>
|
| 117 |
+
<body>
|
| 118 |
+
<h1>Getaround Pricing API</h1>
|
| 119 |
+
<p class="small">Version: {app.version} – Modèle: {metadata.get('model_name','?')}</p>
|
| 120 |
+
|
| 121 |
+
<h2>POST /predict</h2>
|
| 122 |
+
<p><b>Content-Type:</b> application/json</p>
|
| 123 |
+
<p><b>Body</b> (liste de lignes; chaque ligne = features dans l'ordre attendu par le pipeline scikit-learn) :</p>
|
| 124 |
+
<pre>{{"input": [[feat1, feat2, "..."], ["..."]]}}</pre>
|
| 125 |
+
<p><b>Réponse :</b></p>
|
| 126 |
+
<pre>{{"prediction": [123.45, 110.20]}}</pre>
|
| 127 |
+
|
| 128 |
+
<h3>Infos features</h3>
|
| 129 |
+
<pre>{json.dumps({k: metadata.get(k, None) for k in ['target','num_cols','cat_cols']}, ensure_ascii=False, indent=2)}</pre>
|
| 130 |
+
|
| 131 |
+
<h2>GET /health</h2>
|
| 132 |
+
<p>Vérifie l'état de l'API et retourne le nom du modèle chargé.</p>
|
| 133 |
+
|
| 134 |
+
<hr>
|
| 135 |
+
<p>Swagger/OpenAPI de FastAPI reste disponible si activé par défaut via <code>/docs</code> (ici remplacé) et <code>/openapi.json</code>.</p>
|
| 136 |
+
</body>
|
| 137 |
+
</html>
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
@app.get("/docs", response_class=HTMLResponse)
|
| 141 |
+
def custom_docs():
|
| 142 |
+
return HTMLResponse(content=DOC_HTML)
|
api/model/metadata.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name": "RandomForest",
|
| 3 |
+
"target": "rental_price_per_day",
|
| 4 |
+
"num_cols": [
|
| 5 |
+
"mileage",
|
| 6 |
+
"engine_power"
|
| 7 |
+
],
|
| 8 |
+
"cat_cols": [
|
| 9 |
+
"model_key",
|
| 10 |
+
"fuel",
|
| 11 |
+
"paint_color",
|
| 12 |
+
"car_type",
|
| 13 |
+
"private_parking_available",
|
| 14 |
+
"has_gps",
|
| 15 |
+
"has_air_conditioning",
|
| 16 |
+
"automatic_car",
|
| 17 |
+
"has_getaround_connect",
|
| 18 |
+
"has_speed_regulator",
|
| 19 |
+
"winter_tires"
|
| 20 |
+
],
|
| 21 |
+
"feature_order_note": "Respecter l’ordre des colonnes de pricing_clean.parquet"
|
| 22 |
+
}
|
api/model/pipeline.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f42a3a28e50f212af3a228e3f212a72a62a4233d2be3e663f690ee4a02c5e36
|
| 3 |
+
size 98587642
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
pydantic>=2
|
| 4 |
+
pandas
|
| 5 |
+
numpy
|
| 6 |
+
scikit-learn==1.7.1
|
| 7 |
+
joblib
|