File size: 5,212 Bytes
3ce16cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23fd59d
 
 
 
 
3ce16cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Any
from pathlib import Path
import json
import joblib
import numpy as np
import pandas as pd

app = FastAPI(title="Getaround Pricing API", version="1.0.0")

MODEL_PATH = Path("api/model/pipeline.pkl")
META_PATH = Path("api/model/metadata.json")

pipeline = joblib.load(MODEL_PATH)
metadata = json.loads(META_PATH.read_text(encoding="utf-8")) if META_PATH.exists() else {}

# Helpers pour connaître le schéma attendu
def get_expected_cols():
    return list(metadata.get("num_cols", [])) + list(metadata.get("cat_cols", []))

expected_cols = get_expected_cols()

def make_example_row():
    # 0 pour les numériques, "unknown" pour les catégorielles
    return [0] * len(metadata.get("num_cols", [])) + ["unknown"] * len(metadata.get("cat_cols", []))


class PredictPayload(BaseModel):
    input: list  # liste de lignes, chaque ligne = features dans le bon ordre/format

@app.get("/")
def root():
    return {"ok": True, "hint": "use /health, /schema or POST /predict"}


@app.get("/health")
def health():
    return {"status": "ok", "model": metadata.get("model_name")}

@app.post("/predict")
def predict(payload: PredictPayload):
    try:
        rows = payload.input
        if not rows or not isinstance(rows, list):
            raise HTTPException(status_code=400, detail="Body must be {'input': [[...], ...]}")

        # Colonnes attendues (issues de metadata.json)
        cols = expected_cols if expected_cols else [f"f{i}" for i in range(len(rows[0]))]
        if expected_cols and any(len(r) != len(cols) for r in rows):
            raise HTTPException(
                status_code=400,
                detail=f"Each row must have {len(cols)} features in this order: {cols}",
            )

        # DataFrame avec NOMS de colonnes
        X_df = pd.DataFrame(rows, columns=cols)

        # === CASTING FORT (évite 500 liés aux dtypes) ===
        num_cols = metadata.get("num_cols", [])
        cat_cols = metadata.get("cat_cols", [])
        known_bool_cols = {
            "private_parking_available","has_gps","has_air_conditioning",
            "automatic_car","has_getaround_connect","has_speed_regulator","winter_tires",
        }
        bool_cols = [c for c in cat_cols if c in known_bool_cols and c in X_df.columns]
        text_cat_cols = [c for c in cat_cols if c not in known_bool_cols and c in X_df.columns]

        # num -> float
        for c in num_cols:
            if c in X_df.columns:
                X_df[c] = pd.to_numeric(X_df[c], errors="coerce")
        if num_cols:
            X_df[num_cols] = X_df[num_cols].fillna(0.0)

        # bool -> bool strict
        def to_bool(v):
            if isinstance(v, bool): return v
            s = str(v).strip().lower()
            return s in {"1","true","t","yes","y","on"}
        for c in bool_cols:
            X_df[c] = X_df[c].map(to_bool).fillna(False)

        # cat texte -> str
        for c in text_cat_cols:
            X_df[c] = X_df[c].astype(str).fillna("unknown")

        # Prédiction
        y_pred = pipeline.predict(X_df)
        return {"prediction": np.asarray(y_pred).ravel().tolist()}

    except HTTPException:
        raise
    except Exception as e:
        traceback.print_exc()  # log côté serveur
        raise HTTPException(status_code=400, detail=f"Prediction failed: {type(e).__name__}: {e}")

@app.get("/schema")
def schema():
    return {
        "num_cols": metadata.get("num_cols", []),
        "cat_cols": metadata.get("cat_cols", []),
        "expected_cols": expected_cols,
        "n_features_expected": len(expected_cols),
        "example_payload": {"input": [make_example_row()]},
    }


# Page HTML de doc simple exigée à /docs
DOC_HTML = f"""
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Getaround Pricing API – Docs</title>
<style>
body{{font-family:system-ui,Segoe UI,Roboto,Helvetica,Arial,sans-serif;max-width:900px;margin:40px auto;line-height:1.5}}
code,pre{{background:#f6f8fa;padding:8px 10px;border-radius:6px;display:block;overflow:auto}}
h1{{margin-bottom:0}}
.small{{color:#666;font-size:0.9rem}}
</style>
</head>
<body>
  <h1>Getaround Pricing API</h1>
  <p class="small">Version: {app.version} – Modèle: {metadata.get('model_name','?')}</p>

  <h2>POST /predict</h2>
  <p><b>Content-Type:</b> application/json</p>
  <p><b>Body</b> (liste de lignes; chaque ligne = features dans l'ordre attendu par le pipeline scikit-learn) :</p>
  <pre>{{"input": [[feat1, feat2, "..."], ["..."]]}}</pre>
  <p><b>Réponse :</b></p>
  <pre>{{"prediction": [123.45, 110.20]}}</pre>

  <h3>Infos features</h3>
  <pre>{json.dumps({k: metadata.get(k, None) for k in ['target','num_cols','cat_cols']}, ensure_ascii=False, indent=2)}</pre>

  <h2>GET /health</h2>
  <p>Vérifie l'état de l'API et retourne le nom du modèle chargé.</p>

  <hr>
  <p>Swagger/OpenAPI de FastAPI reste disponible si activé par défaut via <code>/docs</code> (ici remplacé) et <code>/openapi.json</code>.</p>
</body>
</html>
"""

@app.get("/docs", response_class=HTMLResponse)
def custom_docs():
    return HTMLResponse(content=DOC_HTML)