emp-admin commited on
Commit
67f34aa
·
verified ·
1 Parent(s): 8b69317

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -9
app.py CHANGED
@@ -8,9 +8,32 @@ from typing import List
8
 
9
  app = FastAPI(title="Headache Predictor API")
10
 
 
11
  clf = None
12
  threshold = 0.5
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @app.on_event("startup")
15
  async def load_model():
16
  global clf, threshold
@@ -32,6 +55,7 @@ async def load_model():
32
 
33
  if isinstance(model_data, dict):
34
  clf = model_data["model"]
 
35
  threshold = float(model_data.get("optimal_threshold", 0.5))
36
  print(f"✅ Model loaded (optimal_threshold={threshold})")
37
  else:
@@ -44,19 +68,67 @@ async def load_model():
44
  import traceback
45
  traceback.print_exc()
46
 
47
- class BatchPredictionRequest(BaseModel):
48
- instances: List[List[float]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- class DayPrediction(BaseModel):
51
- day: int
52
- prediction: int
53
- probability: float
54
 
55
- class BatchPredictionResponse(BaseModel):
56
- predictions: List[DayPrediction]
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  @app.post("/predict/batch", response_model=BatchPredictionResponse)
59
  def predict_batch(request: BatchPredictionRequest):
 
60
  if clf is None:
61
  raise HTTPException(status_code=503, detail="Model not loaded")
62
 
@@ -66,6 +138,8 @@ def predict_batch(request: BatchPredictionRequest):
66
  raise ValueError(f"Expected 2D array, got shape {X.shape}")
67
 
68
  probas = clf.predict_proba(X)[:, 1] # class-1 prob
 
 
69
  preds = (probas >= threshold).astype(int)
70
 
71
  results = [
@@ -75,4 +149,4 @@ def predict_batch(request: BatchPredictionRequest):
75
  return BatchPredictionResponse(predictions=results)
76
 
77
  except Exception as e:
78
- raise HTTPException(status_code=400, detail=f"Batch prediction error: {str(e)}")
 
8
 
9
  app = FastAPI(title="Headache Predictor API")
10
 
11
+ # Global variables for model and threshold
12
  clf = None
13
  threshold = 0.5
14
 
15
+ # --- Pydantic Models ---
16
+
17
+ class SinglePredictionRequest(BaseModel):
18
+ features: List[float]
19
+
20
+ class SinglePredictionResponse(BaseModel):
21
+ prediction: int
22
+ probability: float
23
+
24
+ class BatchPredictionRequest(BaseModel):
25
+ instances: List[List[float]]
26
+
27
+ class DayPrediction(BaseModel):
28
+ day: int
29
+ prediction: int
30
+ probability: float
31
+
32
+ class BatchPredictionResponse(BaseModel):
33
+ predictions: List[DayPrediction]
34
+
35
+ # --- Startup Event ---
36
+
37
  @app.on_event("startup")
38
  async def load_model():
39
  global clf, threshold
 
55
 
56
  if isinstance(model_data, dict):
57
  clf = model_data["model"]
58
+ # Load threshold if available, otherwise default to 0.5
59
  threshold = float(model_data.get("optimal_threshold", 0.5))
60
  print(f"✅ Model loaded (optimal_threshold={threshold})")
61
  else:
 
68
  import traceback
69
  traceback.print_exc()
70
 
71
+ # --- Endpoints ---
72
+
73
+ @app.get("/")
74
+ def read_root():
75
+ return {
76
+ "message": "Headache Predictor API",
77
+ "status": "running",
78
+ "endpoints": {
79
+ "predict": "/predict - Single day prediction",
80
+ "predict_batch": "/predict/batch - 7-day forecast",
81
+ "health": "/health"
82
+ },
83
+ "examples": {
84
+ "single": {
85
+ "url": "/predict",
86
+ # Example shortened for brevity in display
87
+ "body": {"features": [1, 0, 0, 0, 1, 0, 1005.0, -9.5, 85.0, 15.5, 64.0, 5.5, 41.0, 0.0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 10, 40, 4, 7.0, 50.0, 60.0, 3.5, 1.5, 6.8]}
88
+ },
89
+ "batch": {
90
+ "url": "/predict/batch",
91
+ "body": {"instances": [["array of 37 features for day 1"], ["array for day 2"]]}
92
+ }
93
+ }
94
+ }
95
+
96
+ @app.get("/health")
97
+ def health_check():
98
+ return {
99
+ "status": "healthy",
100
+ "model_loaded": clf is not None
101
+ }
102
+
103
+ @app.post("/predict", response_model=SinglePredictionResponse)
104
+ def predict(request: SinglePredictionRequest):
105
+ """Predict headache risk for a single day"""
106
+ if clf is None:
107
+ raise HTTPException(status_code=503, detail="Model not loaded")
108
 
109
+ try:
110
+ # Convert input to numpy array
111
+ features = np.array(request.features).reshape(1, -1)
 
112
 
113
+ # Get probability array for both classes [prob_0, prob_1]
114
+ prob_array = clf.predict_proba(features)[0]
115
+
116
+ # Always return probability of headache (class 1)
117
+ headache_probability = float(prob_array[1])
118
+
119
+ # Make prediction using the loaded threshold
120
+ prediction = 1 if headache_probability >= threshold else 0
121
+
122
+ return SinglePredictionResponse(
123
+ prediction=int(prediction),
124
+ probability=headache_probability
125
+ )
126
+ except Exception as e:
127
+ raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}")
128
 
129
  @app.post("/predict/batch", response_model=BatchPredictionResponse)
130
  def predict_batch(request: BatchPredictionRequest):
131
+ """Predict headache risk for multiple days (batch)"""
132
  if clf is None:
133
  raise HTTPException(status_code=503, detail="Model not loaded")
134
 
 
138
  raise ValueError(f"Expected 2D array, got shape {X.shape}")
139
 
140
  probas = clf.predict_proba(X)[:, 1] # class-1 prob
141
+
142
+ # Use the global threshold
143
  preds = (probas >= threshold).astype(int)
144
 
145
  results = [
 
149
  return BatchPredictionResponse(predictions=results)
150
 
151
  except Exception as e:
152
+ raise HTTPException(status_code=400, detail=f"Batch prediction error: {str(e)}")