leo861 commited on
Commit
3d91615
·
verified ·
1 Parent(s): b35e229

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +60 -40
app.py CHANGED
@@ -1,18 +1,30 @@
1
  import os
2
  import logging
3
- from flask import Flask, render_template, request, jsonify
4
- from flask_socketio import SocketIO
5
  import joblib
6
  import torch
7
  import numpy as np
8
  from huggingface_hub import hf_hub_download
 
 
9
 
10
  # Configure logging
11
  logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
- app = Flask(__name__)
15
- socketio = SocketIO(app, cors_allowed_origins="*")
 
 
 
 
 
 
 
 
 
 
16
 
17
  # Load models
18
  def load_models():
@@ -48,52 +60,60 @@ def load_models():
48
  logger.error(f"Failed to load autoencoder: {str(e)}")
49
 
50
  # Load models on startup
51
- logger.info("Loading trained models...")
52
- try:
53
- load_models()
54
- except Exception as e:
55
- logger.error(f"Error loading models: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- @app.route('/')
58
- def home():
59
- return render_template('index.html')
 
60
 
61
- @app.route('/health')
62
- def health():
63
- status = {
64
- 'status': 'healthy',
65
- 'models': {
66
- 'heart_model': heart_model is not None,
67
- 'autoencoder': autoencoder is not None
 
 
 
 
68
  }
69
  }
70
- return jsonify(status)
71
 
72
- @app.route('/predict', methods=['POST'])
73
- def predict():
74
  try:
75
- data = request.get_json()
76
- if not data:
77
- return jsonify({'status': 'error', 'message': 'No data provided'}), 400
78
 
79
  # Add your prediction logic here
80
  logger.info("Processing prediction request")
81
- result = {'status': 'success', 'prediction': 'normal'}
 
 
 
 
82
  logger.info(f"Prediction completed: {result}")
83
- return jsonify(result)
84
  except Exception as e:
85
  logger.error(f"Error during prediction: {str(e)}")
86
- return jsonify({'status': 'error', 'message': str(e)}), 500
87
-
88
- @socketio.on('connect')
89
- def handle_connect():
90
- logger.info('Client connected')
91
-
92
- @socketio.on('disconnect')
93
- def handle_disconnect():
94
- logger.info('Client disconnected')
95
 
96
- if __name__ == '__main__':
97
- port = int(os.environ.get('PORT', 7860))
98
- logger.info(f"Starting server on port {port}")
99
- socketio.run(app, host='0.0.0.0', port=port)
 
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():
 
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)