modif app
Browse files
app.py
CHANGED
|
@@ -1,93 +1,73 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
from pydantic import BaseModel
|
| 3 |
-
import
|
| 4 |
import boto3
|
|
|
|
| 5 |
import os
|
| 6 |
import io
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import uvicorn
|
| 9 |
-
import numpy as np
|
| 10 |
-
from dotenv import load_dotenv
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
#
|
| 19 |
S3_BUCKET = os.getenv("S3_BUCKET")
|
| 20 |
-
MODEL_KEY = os.getenv("MODEL_KEY")
|
| 21 |
-
|
| 22 |
-
# Connexion S3
|
| 23 |
-
s3 = boto3.client(
|
| 24 |
-
"s3",
|
| 25 |
-
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
|
| 26 |
-
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY")
|
| 27 |
-
)
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
print(f"Téléchargement du modèle depuis s3://{bucket}/{key}")
|
| 32 |
-
response = s3.get_object(Bucket=bucket, Key=key)
|
| 33 |
-
bytestream = io.BytesIO(response["Body"].read())
|
| 34 |
-
return joblib.load(bytestream)
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
@app.post("/predict")
|
| 43 |
def predict(data: InputData):
|
| 44 |
try:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
"automatic_car", "has_getaround_connect", "has_speed_regulator", "winter_tires"
|
| 49 |
-
]
|
| 50 |
-
|
| 51 |
-
print("📥 Input reçu :", data.input) # log input brut
|
| 52 |
-
X = pd.DataFrame(data.input, columns=columns)
|
| 53 |
-
print("✅ DataFrame construit :", X.head().to_dict()) # log input formaté
|
| 54 |
-
|
| 55 |
-
preds = model.predict(X)
|
| 56 |
-
print("📤 Prediction faite :", preds)
|
| 57 |
-
|
| 58 |
-
return {"prediction": preds.tolist()}
|
| 59 |
-
|
| 60 |
-
except Exception as e:
|
| 61 |
-
import traceback
|
| 62 |
-
print("❌ Erreur lors de la prédiction :", e)
|
| 63 |
-
print(traceback.format_exc())
|
| 64 |
-
return {"error": str(e)}
|
| 65 |
-
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# columns = [
|
| 71 |
-
# "mileage", "engine_power", "fuel", "paint_color", "car_type",
|
| 72 |
-
# "private_parking_available", "has_gps", "has_air_conditioning",
|
| 73 |
-
# "automatic_car", "has_getaround_connect", "has_speed_regulator", "winter_tires"
|
| 74 |
-
# ]
|
| 75 |
-
|
| 76 |
-
# # Transformer l'input en DataFrame
|
| 77 |
-
# X = pd.DataFrame(data.input, columns=columns)
|
| 78 |
-
|
| 79 |
-
# # Prédictions
|
| 80 |
-
# preds = model.predict(X)
|
| 81 |
-
# return {"prediction": preds.tolist()}
|
| 82 |
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
# preds = model.predict(X)
|
| 88 |
-
# return {"prediction": preds.tolist()}
|
| 89 |
-
|
| 90 |
-
@app.get("/")
|
| 91 |
-
def home():
|
| 92 |
-
return {"message": "Bienvenue sur l'API GetAround Pricing! Utilisez /predict pour faire une prédiction."}
|
| 93 |
-
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
| 3 |
+
import pandas as pd
|
| 4 |
import boto3
|
| 5 |
+
import joblib
|
| 6 |
import os
|
| 7 |
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# === Initialisation FastAPI ===
|
| 10 |
+
app = FastAPI(
|
| 11 |
+
title="Getaround API - Prédiction de prix",
|
| 12 |
+
description="API simple pour prédire le prix journalier d'une location 🚗",
|
| 13 |
+
version="1.0"
|
| 14 |
+
)
|
| 15 |
|
| 16 |
+
# === Schéma attendu pour l'entrée ===
|
| 17 |
+
class InputData(BaseModel):
|
| 18 |
+
model_key: str
|
| 19 |
+
mileage: int
|
| 20 |
+
engine_power: int
|
| 21 |
+
fuel: str
|
| 22 |
+
paint_color: str
|
| 23 |
+
car_type: str
|
| 24 |
+
private_parking_available: bool
|
| 25 |
+
has_gps: bool
|
| 26 |
+
has_air_conditioning: bool
|
| 27 |
+
automatic_car: bool
|
| 28 |
+
has_getaround_connect: bool
|
| 29 |
+
has_speed_regulator: bool
|
| 30 |
+
winter_tires: bool
|
| 31 |
|
| 32 |
+
# === Configuration S3 ===
|
| 33 |
S3_BUCKET = os.getenv("S3_BUCKET")
|
| 34 |
+
MODEL_KEY = os.getenv("MODEL_KEY", "mlflow/models/xgboost_model.joblib")
|
| 35 |
+
s3 = boto3.client("s3")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# === Chargement du modèle depuis S3 au démarrage ===
|
| 38 |
+
model = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
@app.on_event("startup")
|
| 41 |
+
def load_model():
|
| 42 |
+
global model
|
| 43 |
+
try:
|
| 44 |
+
print(f"Téléchargement du modèle depuis s3://{S3_BUCKET}/{MODEL_KEY}")
|
| 45 |
+
response = s3.get_object(Bucket=S3_BUCKET, Key=MODEL_KEY)
|
| 46 |
+
model_bytes = io.BytesIO(response["Body"].read())
|
| 47 |
+
model = joblib.load(model_bytes)
|
| 48 |
+
print("✅ Modèle chargé avec succès")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"❌ Erreur chargement modèle : {e}")
|
| 51 |
+
raise RuntimeError(f"Impossible de charger le modèle : {e}")
|
| 52 |
|
| 53 |
+
# === Routes ===
|
| 54 |
+
@app.get("/")
|
| 55 |
+
def home():
|
| 56 |
+
return {"message": "Bienvenue sur l'API Getaround 🚗 - Utilisez /predict pour faire une prédiction"}
|
| 57 |
|
| 58 |
@app.post("/predict")
|
| 59 |
def predict(data: InputData):
|
| 60 |
try:
|
| 61 |
+
# Convertir les données en DataFrame avec colonnes correctes
|
| 62 |
+
df = pd.DataFrame([data.dict()])
|
| 63 |
+
print("📥 Données reçues :", df.to_dict())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
# Faire la prédiction
|
| 66 |
+
prediction = model.predict(df)
|
| 67 |
+
price = float(prediction[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
return {"predicted_price_per_day": round(price, 2)}
|
| 70 |
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"❌ Erreur prédiction : {e}")
|
| 73 |
+
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|