mokh2x commited on
Commit
daa84e0
·
verified ·
1 Parent(s): fbd5a42

updates main

Browse files
Files changed (1) hide show
  1. main.py +47 -26
main.py CHANGED
@@ -1,25 +1,40 @@
1
  from fastapi import FastAPI, HTTPException
 
2
  from pydantic import BaseModel
3
  import joblib
4
  import numpy as np
5
  import pandas as pd
 
6
 
7
- # Initialize App
8
  app = FastAPI(title="Vital Signs AI Monitor")
9
 
10
- # --- LOAD ARTIFACTS ---
11
- # We load these once when the app starts so it's fast
12
- try:
13
- model = joblib.load("model.pkl")
14
- scaler = joblib.load("scaler.pkl")
15
- encoder = joblib.load("encoder.pkl")
16
- print("✅ Model, Scaler, and Encoder loaded successfully.")
17
- except Exception as e:
18
- print(f"❌ Error loading files: {e}")
19
- print("Did you copy the .pkl files into the same folder?")
20
-
21
- # --- DEFINE INPUT DATA ---
22
- # This ensures the user sends exactly what we need
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  class VitalSigns(BaseModel):
24
  heart_rate: float
25
  blood_pressure: float
@@ -27,16 +42,20 @@ class VitalSigns(BaseModel):
27
  respiratory_rate: float
28
  temperature: float
29
 
 
30
  @app.get("/")
31
  def home():
32
- return {"message": "Vital Signs AI is running. Send POST requests to /predict"}
 
33
 
34
  @app.post("/predict")
35
  def predict_condition(vitals: VitalSigns):
 
 
 
 
36
  try:
37
- # 1. Prepare Data
38
- # We must keep the EXACT same order as training:
39
- # [heart_rate, blood_pressure, oxygen_saturation, respiratory_rate, temperature]
40
  input_data = np.array([[
41
  vitals.heart_rate,
42
  vitals.blood_pressure,
@@ -45,20 +64,22 @@ def predict_condition(vitals: VitalSigns):
45
  vitals.temperature
46
  ]])
47
 
48
- # 2. Scale Data (CRITICAL STEP)
49
- # The model expects scaled numbers (Z-scores), not raw values
50
  scaled_data = scaler.transform(input_data)
51
 
52
- # 3. Predict
53
- prediction_index = model.predict(scaled_data)
 
54
 
55
- # 4. Decode Label
56
- # Converts 0/1/2 back to "Safe", "Warning", "Critical"
57
  result_label = encoder.inverse_transform(prediction_index)[0]
58
 
 
59
  return {
60
- "prediction": result_label,
61
- "status_code": int(prediction_index[0]), # 0, 1, or 2
62
  "input_received": vitals
63
  }
64
 
 
1
  from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  import joblib
5
  import numpy as np
6
  import pandas as pd
7
+ import os
8
 
9
+ # 1. Initialize the App
10
  app = FastAPI(title="Vital Signs AI Monitor")
11
 
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+
21
+ artifacts = {}
22
+
23
+ @app.on_event("startup")
24
+ def load_artifacts():
25
+ try:
26
+
27
+ artifacts["model"] = joblib.load("model.pkl")
28
+ artifacts["scaler"] = joblib.load("scaler.pkl")
29
+ artifacts["encoder"] = joblib.load("encoder.pkl")
30
+ print("✅ Artifacts loaded successfully: model.pkl, scaler.pkl, encoder.pkl")
31
+ except FileNotFoundError as e:
32
+ print(f"❌ CRITICAL ERROR: Could not find model files! {e}")
33
+ print("Make sure model.pkl, scaler.pkl, and encoder.pkl are in the SAME folder as main.py")
34
+ except Exception as e:
35
+ print(f"❌ Error loading artifacts: {e}")
36
+
37
+
38
  class VitalSigns(BaseModel):
39
  heart_rate: float
40
  blood_pressure: float
 
42
  respiratory_rate: float
43
  temperature: float
44
 
45
+
46
  @app.get("/")
47
  def home():
48
+ return {"message": "Vital Signs AI is RUNNING. Send a POST request to /predict to use it."}
49
+
50
 
51
  @app.post("/predict")
52
  def predict_condition(vitals: VitalSigns):
53
+
54
+ if "model" not in artifacts:
55
+ raise HTTPException(status_code=500, detail="Model files not loaded. Check server logs.")
56
+
57
  try:
58
+
 
 
59
  input_data = np.array([[
60
  vitals.heart_rate,
61
  vitals.blood_pressure,
 
64
  vitals.temperature
65
  ]])
66
 
67
+
68
+ scaler = artifacts["scaler"]
69
  scaled_data = scaler.transform(input_data)
70
 
71
+
72
+ model = artifacts["model"]
73
+ prediction_index = model.predict(scaled_data) # Returns [0], [1], or [2]
74
 
75
+
76
+ encoder = artifacts["encoder"]
77
  result_label = encoder.inverse_transform(prediction_index)[0]
78
 
79
+
80
  return {
81
+ "prediction": result_label, # "Safe", "Warning", or "Critical"
82
+ "status_code": int(prediction_index[0]), # 0, 1, or 2 (useful for hardware logic)
83
  "input_received": vitals
84
  }
85