leo861 commited on
Commit
21ed254
·
verified ·
1 Parent(s): 5fae6b8

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from fastapi import FastAPI, HTTPException
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ import joblib
6
+ import torch
7
+ import numpy as np
8
+ from huggingface_hub import hf_hub_download
9
+ from pydantic import BaseModel
10
+ import uvicorn
11
+
12
+ # Configure logging
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ app = FastAPI(title="Health Monitoring System",
17
+ description="A FastAPI application for health monitoring and prediction",
18
+ version="1.0.0")
19
+
20
+ # Add CORS middleware
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # Load models
30
+ def load_models():
31
+ global heart_model, autoencoder
32
+ heart_model = None
33
+ autoencoder = None
34
+
35
+ try:
36
+ # Download and load heart model
37
+ logger.info("Downloading heart model from Hugging Face Hub...")
38
+ heart_model_path = hf_hub_download(
39
+ repo_id="leo861/app",
40
+ filename="heart/models/heart_model.joblib",
41
+ cache_dir="models"
42
+ )
43
+ heart_model = joblib.load(heart_model_path)
44
+ logger.info("Heart model loaded successfully")
45
+ except Exception as e:
46
+ logger.error(f"Failed to load heart model: {str(e)}")
47
+
48
+ try:
49
+ # Download and load autoencoder
50
+ logger.info("Downloading autoencoder from Hugging Face Hub...")
51
+ autoencoder_path = hf_hub_download(
52
+ repo_id="leo861/app",
53
+ filename="models/best_model.pth",
54
+ cache_dir="models"
55
+ )
56
+ autoencoder = torch.load(autoencoder_path)
57
+ autoencoder.eval()
58
+ logger.info("Autoencoder model loaded successfully")
59
+ except Exception as e:
60
+ logger.error(f"Failed to load autoencoder: {str(e)}")
61
+
62
+ # Load models on startup
63
+ @app.on_event("startup")
64
+ async def startup_event():
65
+ logger.info("Loading trained models...")
66
+ try:
67
+ load_models()
68
+ except Exception as e:
69
+ logger.error(f"Error loading models: {str(e)}")
70
+
71
+ # Define request models
72
+ class PredictionRequest(BaseModel):
73
+ data: dict
74
+
75
+ # Define response models
76
+ class HealthResponse(BaseModel):
77
+ status: str
78
+ models: dict
79
+
80
+ class PredictionResponse(BaseModel):
81
+ status: str
82
+ prediction: str
83
+ message: str = None
84
+
85
+ @app.get("/")
86
+ async def root():
87
+ return {"message": "Welcome to the Health Monitoring System API"}
88
+
89
+ @app.get("/health", response_model=HealthResponse)
90
+ async def health():
91
+ return {
92
+ "status": "healthy",
93
+ "models": {
94
+ "heart_model": heart_model is not None,
95
+ "autoencoder": autoencoder is not None
96
+ }
97
+ }
98
+
99
+ @app.post("/predict", response_model=PredictionResponse)
100
+ async def predict(request: PredictionRequest):
101
+ try:
102
+ if not request.data:
103
+ raise HTTPException(status_code=400, detail="No data provided")
104
+
105
+ # Add your prediction logic here
106
+ logger.info("Processing prediction request")
107
+ result = {
108
+ "status": "success",
109
+ "prediction": "normal",
110
+ "message": "Prediction completed successfully"
111
+ }
112
+ logger.info(f"Prediction completed: {result}")
113
+ return result
114
+ except Exception as e:
115
+ logger.error(f"Error during prediction: {str(e)}")
116
+ raise HTTPException(status_code=500, detail=str(e))
117
+
118
+ if __name__ == "__main__":
119
+ uvicorn.run(app, host="0.0.0.0", port=7860)