Spaces:
Sleeping
Sleeping
Download api/app.py from PoroKami/Getaround-princing-api: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/spaces/PoroKami/Getaround-princing-api/resolve/main/api/app.py
- Command line
-
hf download hf://spaces/PoroKami/Getaround-princing-api/api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PoroKami/Getaround-princing-api/resolve/main/api/app.py
5.21 kB
| 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 | |
| def root(): | |
| return {"ok": True, "hint": "use /health, /schema or POST /predict"} | |
| def health(): | |
| return {"status": "ok", "model": metadata.get("model_name")} | |
| 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}") | |
| 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> | |
| """ | |
| def custom_docs(): | |
| return HTMLResponse(content=DOC_HTML) | |