MatteoAldovardi commited on
Commit
643aa5a
·
1 Parent(s): f675034
Files changed (1) hide show
  1. main.py +12 -12
main.py CHANGED
@@ -10,16 +10,19 @@ import requests
10
  # --- 0. Initialize FastAPI app ---
11
  app = FastAPI()
12
 
 
13
  @app.get("/")
14
  def read_root():
15
  return {
16
  "message": "Welcome to the Taxi Fare Prediction API. Use POST /predict to get predictions."
17
  }
18
 
 
19
  @app.get("/health")
20
  def health():
21
  return {"status": "ok"}
22
 
 
23
  # --- 1. Define Input and Output Data Models ---
24
  class InferenceInput(BaseModel):
25
  vendor_id: str
@@ -30,11 +33,13 @@ class InferenceInput(BaseModel):
30
  is_rush_hour: bool
31
  model_name: str # "bog", "mex", or "uio"
32
 
 
33
  class InferenceOutput(BaseModel):
34
  trip_duration: float
35
  model_used: str
36
  message: str
37
 
 
38
  # --- 2. Lazy-loading ML Model Manager ---
39
  class MLModels:
40
  def __init__(self):
@@ -45,7 +50,9 @@ class MLModels:
45
  def get_model(self, model_name: str):
46
  model_name = model_name.lower()
47
  if model_name not in self.valid_models:
48
- raise ValueError(f"Invalid model name '{model_name}'. Choose from 'bog', 'mex', or 'uio'.")
 
 
49
 
50
  if model_name in self.models:
51
  return self.models[model_name]
@@ -68,9 +75,11 @@ class MLModels:
68
  pred = model.predict(X_df)[0]
69
  return float(pred)
70
 
 
71
  # --- 3. Instantiate ML Model Manager ---
72
  ml_models = MLModels()
73
 
 
74
  # --- 4. Inference Endpoint ---
75
  @app.post("/predict", response_model=InferenceOutput)
76
  async def predict_inference(data: InferenceInput):
@@ -81,7 +90,7 @@ async def predict_inference(data: InferenceInput):
81
  return InferenceOutput(
82
  trip_duration=trip_duration,
83
  model_used=model_name,
84
- message=f"Inference successful using {model_name.upper()} model."
85
  )
86
  except FileNotFoundError as fnf:
87
  raise HTTPException(status_code=404, detail=str(fnf))
@@ -90,14 +99,5 @@ async def predict_inference(data: InferenceInput):
90
  except Exception as e:
91
  raise HTTPException(status_code=500, detail=f"Inference failed: {str(e)}")
92
 
93
- def keep_alive():
94
- while True:
95
- try:
96
- requests.get("http://localhost:8000/health")
97
- except Exception:
98
- pass
99
- time.sleep(60) # Ping every 60 seconds
100
-
101
- threading.Thread(target=keep_alive, daemon=True).start()
102
 
103
- # --- 5. Run the app ---
 
10
  # --- 0. Initialize FastAPI app ---
11
  app = FastAPI()
12
 
13
+
14
  @app.get("/")
15
  def read_root():
16
  return {
17
  "message": "Welcome to the Taxi Fare Prediction API. Use POST /predict to get predictions."
18
  }
19
 
20
+
21
  @app.get("/health")
22
  def health():
23
  return {"status": "ok"}
24
 
25
+
26
  # --- 1. Define Input and Output Data Models ---
27
  class InferenceInput(BaseModel):
28
  vendor_id: str
 
33
  is_rush_hour: bool
34
  model_name: str # "bog", "mex", or "uio"
35
 
36
+
37
  class InferenceOutput(BaseModel):
38
  trip_duration: float
39
  model_used: str
40
  message: str
41
 
42
+
43
  # --- 2. Lazy-loading ML Model Manager ---
44
  class MLModels:
45
  def __init__(self):
 
50
  def get_model(self, model_name: str):
51
  model_name = model_name.lower()
52
  if model_name not in self.valid_models:
53
+ raise ValueError(
54
+ f"Invalid model name '{model_name}'. Choose from 'bog', 'mex', or 'uio'."
55
+ )
56
 
57
  if model_name in self.models:
58
  return self.models[model_name]
 
75
  pred = model.predict(X_df)[0]
76
  return float(pred)
77
 
78
+
79
  # --- 3. Instantiate ML Model Manager ---
80
  ml_models = MLModels()
81
 
82
+
83
  # --- 4. Inference Endpoint ---
84
  @app.post("/predict", response_model=InferenceOutput)
85
  async def predict_inference(data: InferenceInput):
 
90
  return InferenceOutput(
91
  trip_duration=trip_duration,
92
  model_used=model_name,
93
+ message=f"Inference successful using {model_name.upper()} model.",
94
  )
95
  except FileNotFoundError as fnf:
96
  raise HTTPException(status_code=404, detail=str(fnf))
 
99
  except Exception as e:
100
  raise HTTPException(status_code=500, detail=f"Inference failed: {str(e)}")
101
 
 
 
 
 
 
 
 
 
 
102
 
103
+ # --- 5. Run the app ---