CoolFace
Apppublic

BOUMRAR/Getaround-pricing-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
main.py97 linesDownload Raw Back to root
1import pandas as pd2import joblib3from fastapi import FastAPI4from fastapi.responses import HTMLResponse5from pydantic import BaseModel6from typing import List, Union7 8# Initialisation FastAPI9app = FastAPI(10    title="GetAround Pricing API",11    description="API de prédiction de prix pour GetAround",12    version="1.0"13)14 15# Modèle de données pour input16class PredictionInput(BaseModel):17    input: List[List[Union[float, str]]]18 19# Chargement du modèle ML20try:21    model = joblib.load("getaround_pricing_model.pkl")22    print("Modèle chargé avec succès - Version compatible")23except Exception as e:24    print(f"Erreur lors du chargement du modèle: {e}")25    model = None26 27# Colonnes exactes attendues par le modèle28# Colonnes exactes attendues par le modèle (selon le format des consignes)29model_columns = [30    'mileage', 'engine_power', 'fuel', 'paint_color',31    'car_type', 'private_parking_available', 'has_gps',32    'has_air_conditioning', 'automatic_car', 'has_getaround_connect',33    'winter_tires', 'has_speed_regulator', 'model_key'34]35 36# Colonnes catégorielles à forcer en string37categorical_columns = [38    'model_key', 'fuel', 'paint_color', 'car_type',39    'private_parking_available', 'has_gps', 'has_air_conditioning',40    'automatic_car', 'has_getaround_connect', 'winter_tires', 'has_speed_regulator'41]42 43# Route racine44@app.get("/")45def root():46    return {"message": "GetAround Pricing API"}47 48# Endpoint de prédiction49@app.post("/predict")50def predict(data: PredictionInput):51    if model is None:52        return {"error": "Modèle non disponible"}53 54    try:55        input_data = []56        for row in data.input:57            # Compléter automatiquement les colonnes manquantes58            if len(row) < len(model_columns):59                row = row + [0] * (len(model_columns) - len(row))60            input_data.append(row)61        62        # Créer DataFrame63        df = pd.DataFrame(input_data, columns=model_columns)64 65        # Convertir les colonnes catégorielles en str66        for col in categorical_columns:67            df[col] = df[col].astype(str)68 69        # Prédiction70        predictions = model.predict(df)71        predictions_list = [round(float(p), 2) for p in predictions]72 73        return {"prediction": predictions_list}74 75    except Exception as e:76        return {"error": str(e)}77 78# Documentation HTML79@app.get("/docs", response_class=HTMLResponse)80def documentation():81    return """82    <h1>GetAround API Documentation</h1>83    <h2>GET /</h2>84    <p>Page d'accueil de l'API</p>85    <h2>POST /predict</h2>86    <p>Input JSON:</p>87    <code>{"input": [["Citroën", 0.27, 0.36, "diesel", "red", "SUV", 1, 1, 1, 1, 1, 0, 1]]}</code>88    <p>Output JSON:</p>89    <code>{"prediction": [123.45]}</code>90    <h3>Exemple curl Windows PowerShell:</h3>91    <code>curl -X POST http://127.0.0.1:8000/predict -H "Content-Type: application/json" -d '{\"input\": [[\"Citroën\", 0.27, 0.36, \"diesel\", \"red\", \"SUV\", 1, 1, 1, 1, 1, 0, 1]]}'</code>92    """93 94if __name__ == "__main__":95    import uvicorn96    uvicorn.run(app, host="127.0.0.1", port=8000)97