emp-admin commited on
Commit
6e2eb3e
·
verified ·
1 Parent(s): 4443c15

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
+ import xgboost as xgb
5
+ import numpy as np
6
+ import pickle
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ app = FastAPI(title="Headache Predictor API")
10
+
11
+ # Load model at startup
12
+ model = None
13
+
14
+ @app.on_event("startup")
15
+ async def load_model():
16
+ global model
17
+ try:
18
+ model_path = hf_hub_download(
19
+ repo_id="emp-admin/headache-predictor-xgboost",
20
+ filename="model.pkl"
21
+ )
22
+ with open(model_path, 'rb') as f:
23
+ model = pickle.load(f)
24
+ print("✅ Model loaded successfully")
25
+ except Exception as e:
26
+ print(f"❌ Error loading model: {e}")
27
+
28
+ class PredictionRequest(BaseModel):
29
+ features: list[float]
30
+
31
+ class PredictionResponse(BaseModel):
32
+ prediction: int
33
+ probability: float
34
+
35
+ @app.get("/")
36
+ def read_root():
37
+ return {
38
+ "message": "Headache Predictor API",
39
+ "status": "running",
40
+ "endpoints": {
41
+ "predict": "/predict",
42
+ "health": "/health"
43
+ }
44
+ }
45
+
46
+ @app.get("/health")
47
+ def health_check():
48
+ return {
49
+ "status": "healthy",
50
+ "model_loaded": model is not None
51
+ }
52
+
53
+ @app.post("/predict", response_model=PredictionResponse)
54
+ def predict(request: PredictionRequest):
55
+ if model is None:
56
+ raise HTTPException(status_code=503, detail="Model not loaded")
57
+
58
+ try:
59
+ # Convert input to numpy array
60
+ features = np.array(request.features).reshape(1, -1)
61
+
62
+ # Make prediction
63
+ prediction = model.predict(features)[0]
64
+ probability = float(model.predict_proba(features)[0][int(prediction)])
65
+
66
+ return PredictionResponse(
67
+ prediction=int(prediction),
68
+ probability=probability
69
+ )
70
+ except Exception as e:
71
+ raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}")