MatteoAldovardi commited on
Commit
864bc6d
·
1 Parent(s): ea97ef5
Files changed (1) hide show
  1. main.py +37 -91
main.py CHANGED
@@ -1,6 +1,5 @@
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
3
- import uvicorn
4
  import os
5
  import joblib
6
  import pandas as pd
@@ -10,85 +9,15 @@ app = FastAPI()
10
 
11
  @app.get("/")
12
  def read_root():
13
- return {"message": "Welcome to the Taxi Fare Prediction API. Use POST /predict to get predictions."}
14
-
15
- # --- 1. Define Input and Output Data Models ---
16
- class InferenceInput(BaseModel):
17
- vendor_id: str
18
- dist_meters: float
19
- wait_sec: float
20
- geodetic_dist: float
21
- mean_velocity: float
22
- is_rush_hour: bool
23
- model_name: str # "bog", "mex", or "uio"
24
-
25
- class InferenceOutput(BaseModel):
26
- trip_duration: float
27
- model_used: str
28
- message: str
29
-
30
- # --- 2. Define ML Model Manager Class ---
31
- class MLModels:
32
- def __init__(self):
33
- model_dir = "models"
34
- self.bog_pipeline = self.load_pipeline(os.path.join(model_dir, "bog_ridge_pipeline.pkl"))
35
- self.mex_pipeline = self.load_pipeline(os.path.join(model_dir, "mex_ridge_pipeline.pkl"))
36
- self.uio_pipeline = self.load_pipeline(os.path.join(model_dir, "uio_ridge_pipeline.pkl"))
37
-
38
- def load_pipeline(self, path):
39
- if os.path.exists(path):
40
- return joblib.load(path)
41
- else:
42
- raise FileNotFoundError(f"Model file not found: {path}")
43
-
44
- def predict_one(self, features: dict, model_name: str):
45
- model_map = {
46
- "bog": self.bog_pipeline,
47
- "mex": self.mex_pipeline,
48
- "uio": self.uio_pipeline
49
- }
50
- pipeline = model_map.get(model_name.lower())
51
- if not pipeline:
52
- raise ValueError(f"Model '{model_name}' not found. Choose from 'bog', 'mex', or 'uio'.")
53
- X_df = pd.DataFrame([features])
54
- pred = pipeline.predict(X_df)[0]
55
- return float(pred)
56
-
57
- # --- 3. Initialize ML Model Manager ---
58
- ml_models = MLModels()
59
-
60
- # --- 4. Define Inference Endpoint ---
61
- @app.post("/predict", response_model=InferenceOutput)
62
- async def predict_inference(data: InferenceInput):
63
- try:
64
- features = data.dict()
65
- model_name = features.pop("model_name")
66
- trip_duration = ml_models.predict_one(features, model_name)
67
- return InferenceOutput(
68
- trip_duration=trip_duration,
69
- model_used=model_name,
70
- message=f"Inference successful using {model_name.upper()} model."
71
- )
72
- except Exception as e:
73
- raise HTTPException(status_code=400, detail=f"Inference failed: {str(e)}")
74
-
75
- #rebuild
76
- from fastapi import FastAPI, HTTPException
77
- from pydantic import BaseModel
78
- import os
79
- import joblib
80
- import pandas as pd
81
-
82
- app = FastAPI()
83
-
84
- @app.get("/")
85
- def read_root():
86
- return {"message": "Welcome to the Taxi Fare Prediction API. Use POST /predict to get predictions."}
87
 
88
  @app.get("/health")
89
  def health():
90
  return {"status": "ok"}
91
 
 
92
  class InferenceInput(BaseModel):
93
  vendor_id: str
94
  dist_meters: float
@@ -103,28 +32,43 @@ class InferenceOutput(BaseModel):
103
  model_used: str
104
  message: str
105
 
 
106
  class MLModels:
107
  def __init__(self):
108
- model_dir = "models"
109
  self.models = {}
110
- for name in ["bog", "mex", "uio"]:
111
- path = os.path.join(model_dir, f"{name}_ridge_pipeline.pkl")
112
- try:
113
- self.models[name] = joblib.load(path)
114
- print(f"Loaded model: {path}")
115
- except Exception as e:
116
- print(f"Could not load model {path}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  def predict_one(self, features: dict, model_name: str):
119
- model = self.models.get(model_name.lower())
120
- if not model:
121
- raise ValueError(f"Model '{model_name}' not found. Choose from 'bog', 'mex', or 'uio'.")
122
  X_df = pd.DataFrame([features])
123
  pred = model.predict(X_df)[0]
124
  return float(pred)
125
 
 
126
  ml_models = MLModels()
127
 
 
128
  @app.post("/predict", response_model=InferenceOutput)
129
  async def predict_inference(data: InferenceInput):
130
  try:
@@ -136,9 +80,11 @@ async def predict_inference(data: InferenceInput):
136
  model_used=model_name,
137
  message=f"Inference successful using {model_name.upper()} model."
138
  )
 
 
 
 
139
  except Exception as e:
140
- raise HTTPException(status_code=400, detail=f"Inference failed: {str(e)}")
141
-
142
-
143
- if __name__ == "__main__":
144
- uvicorn.run("your_module:app", host="0.0.0.0", port=8000, reload=True)
 
1
  from fastapi import FastAPI, HTTPException
2
  from pydantic import BaseModel
 
3
  import os
4
  import joblib
5
  import pandas as pd
 
9
 
10
  @app.get("/")
11
  def read_root():
12
+ return {
13
+ "message": "Welcome to the Taxi Fare Prediction API. Use POST /predict to get predictions."
14
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  @app.get("/health")
17
  def health():
18
  return {"status": "ok"}
19
 
20
+ # --- 1. Define Input and Output Data Models ---
21
  class InferenceInput(BaseModel):
22
  vendor_id: str
23
  dist_meters: float
 
32
  model_used: str
33
  message: str
34
 
35
+ # --- 2. Lazy-loading ML Model Manager ---
36
  class MLModels:
37
  def __init__(self):
 
38
  self.models = {}
39
+ self.model_dir = "models"
40
+ self.valid_models = {"bog", "mex", "uio"}
41
+
42
+ def get_model(self, model_name: str):
43
+ model_name = model_name.lower()
44
+ if model_name not in self.valid_models:
45
+ raise ValueError(f"Invalid model name '{model_name}'. Choose from 'bog', 'mex', or 'uio'.")
46
+
47
+ if model_name in self.models:
48
+ return self.models[model_name]
49
+
50
+ model_path = os.path.join(self.model_dir, f"{model_name}_ridge_pipeline.pkl")
51
+ if not os.path.exists(model_path):
52
+ raise FileNotFoundError(f"Model file not found: {model_path}")
53
+
54
+ try:
55
+ model = joblib.load(model_path)
56
+ self.models[model_name] = model
57
+ print(f"✅ Loaded model '{model_name}' from {model_path}")
58
+ return model
59
+ except Exception as e:
60
+ raise RuntimeError(f"Error loading model '{model_name}': {e}")
61
 
62
  def predict_one(self, features: dict, model_name: str):
63
+ model = self.get_model(model_name)
 
 
64
  X_df = pd.DataFrame([features])
65
  pred = model.predict(X_df)[0]
66
  return float(pred)
67
 
68
+ # --- 3. Instantiate ML Model Manager ---
69
  ml_models = MLModels()
70
 
71
+ # --- 4. Inference Endpoint ---
72
  @app.post("/predict", response_model=InferenceOutput)
73
  async def predict_inference(data: InferenceInput):
74
  try:
 
80
  model_used=model_name,
81
  message=f"Inference successful using {model_name.upper()} model."
82
  )
83
+ except FileNotFoundError as fnf:
84
+ raise HTTPException(status_code=404, detail=str(fnf))
85
+ except ValueError as ve:
86
+ raise HTTPException(status_code=400, detail=str(ve))
87
  except Exception as e:
88
+ raise HTTPException(status_code=500, detail=f"Inference failed: {str(e)}")
89
+
90
+ # --- 5. Run the app ---