pradelf commited on
Commit
e288985
·
verified ·
1 Parent(s): d8f499e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -47
app.py CHANGED
@@ -4,15 +4,25 @@ import mlflow.pyfunc
4
  import pandas as pd
5
  import config
6
  import logging
7
- logger = logging.getLogger(__name__)
8
-
9
 
10
- #logging.basicConfig(filename='myapp.log', level=logging.INFO)
 
11
 
12
 
13
  # 1) URL du Space HF qui héberge MLflow (tracking server)
14
- SPACE_URL = "https://pradelf-getaround-mlflow.hf.space" # <-- remplace ici
15
- mlflow.set_tracking_uri(SPACE_URL) # ou via env MLFLOW_TRACKING_URI
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  description = """
18
  Bienvenue sur l'API de Getaround pour prédire le prix journalier de location d'une voiture en fonction de son année d'expérience!
@@ -42,11 +52,11 @@ La documentation est ci-dessous 👇 pour chaque point de terminaison (endpoints
42
 
43
  tags_metadata = [
44
  {
45
- "name": "Introduction Endpoints",
46
  "description": "Terminaison simple de présentation de l'API et de sa version pour vérifier que tout fonctionne correctement.",
47
  },
48
  {
49
- "name": "Health",
50
  "description": "Point de terminaison de ligne de vie pour surveiller le statut du serveur de l'API. Retourne 'ok' si le serveur fonctionne sans problèmes.",
51
  },
52
  {
@@ -58,6 +68,20 @@ tags_metadata = [
58
  "description": "Point de terminaison de prediction du prix de location journalier d'un véhicule en fonction de ses caractéristiques.",
59
  },
60
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  app = FastAPI(
62
  title="Getaround API pour le prix journalier de location d'une voiture.",
63
  description=description,
@@ -71,7 +95,6 @@ app = FastAPI(
71
 
72
 
73
  class RentalFeatures(BaseModel):
74
- model_key: str
75
  model_key: str
76
  mileage: int
77
  engine_power: int
@@ -92,16 +115,14 @@ def greet_json():
92
  """
93
  Bonjour
94
  """
95
- logger.info('Hello')
96
  return {"Hello": "World!", "version": config.__version__}
97
 
98
 
99
- @app.get("/health", tags=["Health"])
100
  def health():
101
  """
102
  Health line to monitor the server status of the API. Returns "ok" if the server is running without issues.
103
  """
104
- logger.info('Health')
105
  return {"status": "ok"}
106
 
107
 
@@ -111,39 +132,47 @@ async def predict(predictionFeatures: RentalFeatures):
111
  Prediction of car daily rental cost for a given properties of a car !
112
  """
113
  # Read data
114
- pf = [
115
- predictionFeatures.model_key or "Peugeot",
116
- predictionFeatures.mileage or 0,
117
- predictionFeatures.engine_power or 0,
118
- predictionFeatures.fuel or "petrol",
119
- predictionFeatures.car_type or "sedan",
120
- predictionFeatures.private_parking_available or 1,
121
- predictionFeatures.has_gps or 0,
122
- predictionFeatures.has_air_conditioning or 0,
123
- predictionFeatures.automatic_car or 0,
124
- predictionFeatures.has_getaround_connect or 0,
125
- predictionFeatures.has_speed_regulator or 0,
126
- predictionFeatures.winter_tires or 0,
127
- ]
128
-
129
- car_caracteristic = pd.DataFrame([pf])
130
- logger.info('Started')
131
-
132
- logger.info(car_caracteristic)
133
- #car_caracteristic = pd.DataFrame({"Car": pf})
134
- # Log model from mlflow
135
- logged_model = "models:/getaround-price-prediction-model@champion" # REPLACE WITH YOUR OWN RUN ID
136
- #logged_model = "runs:/d3856ef1a2ee42db989496949f47ac74/getaround-price-prediction-model"
137
- # Load model as a PyFuncModel.
138
- loaded_model = mlflow.pyfunc.load_model(logged_model)
139
- prediction = loaded_model.predict(car_caracteristic)
140
-
141
- # Format response
142
- response = {
143
- "prediction": prediction.tolist()[0],
144
- "detail": "Prédiction du tarif journalier (nul si aucun modèle : model.pkl).",
145
- }
146
- logger.info(response)
147
-
148
- logger.info('Finished')
149
- return response
 
 
 
 
 
 
 
 
 
4
  import pandas as pd
5
  import config
6
  import logging
 
 
7
 
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
 
11
 
12
  # 1) URL du Space HF qui héberge MLflow (tracking server)
13
+ MLFLOW_TRACKING_URI = os.getenv("MLFLOW_TRACKING_URI", "https://pradelf-getaround-mlflow.hf.space")
14
+ MODEL_URI = os.getenv("MODEL_URI", "models:/getaround-price-prediction-model@certification")
15
+ mlflow.set_tracking_uri(MLFLOW_TRACKING_URI) # ou via env MLFLOW_TRACKING_URI
16
+ BOOL_COLS = [
17
+ "private_parking_available",
18
+ "has_gps",
19
+ "has_air_conditioning",
20
+ "automatic_car",
21
+ "has_getaround_connect",
22
+ "has_speed_regulator",
23
+ "winter_tires",
24
+ ]
25
+
26
 
27
  description = """
28
  Bienvenue sur l'API de Getaround pour prédire le prix journalier de location d'une voiture en fonction de son année d'expérience!
 
52
 
53
  tags_metadata = [
54
  {
55
+ "name": "Point de terminaison d'introduction",
56
  "description": "Terminaison simple de présentation de l'API et de sa version pour vérifier que tout fonctionne correctement.",
57
  },
58
  {
59
+ "name": "Point de terminaison de ligne de vie",
60
  "description": "Point de terminaison de ligne de vie pour surveiller le statut du serveur de l'API. Retourne 'ok' si le serveur fonctionne sans problèmes.",
61
  },
62
  {
 
68
  "description": "Point de terminaison de prediction du prix de location journalier d'un véhicule en fonction de ses caractéristiques.",
69
  },
70
  ]
71
+
72
+ @app.on_event("startup")
73
+ def load_model_on_startup():
74
+ global model
75
+ try:
76
+ logger.info(f"Chargement du modèle depuis {MLFLOW_TRACKING_URI}")
77
+ logger.info(f"MLFLOW_TRACKING_URI={os.getenv('MLFLOW_TRACKING_URI')}")
78
+ model = mlflow.pyfunc.load_model(MODEL_URI)
79
+ logger.info("Modèle chargé avec succès")
80
+ except Exception:
81
+ logger.exception("Impossible de charger le modèle au démarrage")
82
+ model = None
83
+
84
+
85
  app = FastAPI(
86
  title="Getaround API pour le prix journalier de location d'une voiture.",
87
  description=description,
 
95
 
96
 
97
  class RentalFeatures(BaseModel):
 
98
  model_key: str
99
  mileage: int
100
  engine_power: int
 
115
  """
116
  Bonjour
117
  """
 
118
  return {"Hello": "World!", "version": config.__version__}
119
 
120
 
121
+ @app.get("/health")
122
  def health():
123
  """
124
  Health line to monitor the server status of the API. Returns "ok" if the server is running without issues.
125
  """
 
126
  return {"status": "ok"}
127
 
128
 
 
132
  Prediction of car daily rental cost for a given properties of a car !
133
  """
134
  # Read data
135
+ # pf = [
136
+ # predictionFeatures.model_key or "Peugeot",
137
+ # predictionFeatures.mileage or 0,
138
+ # predictionFeatures.engine_power or 0,
139
+ # predictionFeatures.fuel or "petrol",
140
+ # predictionFeatures.car_type or "sedan",
141
+ # predictionFeatures.private_parking_available or 1,
142
+ # predictionFeatures.has_gps or 0,
143
+ # predictionFeatures.has_air_conditioning or 0,
144
+ # predictionFeatures.automatic_car or 0,
145
+ # predictionFeatures.has_getaround_connect or 0,
146
+ # predictionFeatures.has_speed_regulator or 0,
147
+ # predictionFeatures.winter_tires or 0,
148
+ # ]
149
+ try:
150
+ car_caracteristic = pd.DataFrame([predictionFeatures.model_dump()])
151
+ #car_caracteristic = pd.DataFrame({"Car": pf})
152
+ # Log model from mlflow
153
+
154
+ BOOL_COLS = [
155
+ "private_parking_available",
156
+ "has_gps",
157
+ "has_air_conditioning",
158
+ "automatic_car",
159
+ "has_getaround_connect",
160
+ "has_speed_regulator",
161
+ "winter_tires",
162
+ ]
163
+ # Conversion explicite des colonnes booléennes
164
+ for col in BOOL_COLS:
165
+ car_caracteristic[col] = car_caracteristic[col].astype(bool)
166
+ # Prediction from previously loaded model as a PyFuncModel.
167
+ prediction = model.predict(car_caracteristic)
168
+
169
+ # Format response
170
+ response = {
171
+ "prediction": prediction.tolist()[0],
172
+ "detail": "Prédiction du tarif journalier (nul si aucun modèle : model.pkl).",
173
+ }
174
+ return response
175
+ except Exception as e:
176
+ logger.exception("Erreur dans /predict")
177
+ raise Exception(status_code=500, detail=str(e))
178
+