Spaces:
Sleeping
Sleeping
File size: 2,390 Bytes
d19283f 4789b6c d19283f e3065a2 1e67d7e 4789b6c d19283f 4789b6c d19283f 4789b6c d19283f 4789b6c 5fe05e3 4789b6c d19283f b0b04a6 4789b6c d19283f 4789b6c d19283f 4789b6c cce15fc 4789b6c 65afcb7 4789b6c 65afcb7 d19283f 1e67d7e 4789b6c 5fe05e3 4789b6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd
import numpy as np
import json
scaler = joblib.load("scaler.joblib")
model = joblib.load("fatigue_model.joblib")
with open("model_metadata.json") as f:
metadata = json.load(f)
feature_cols = metadata["feature_cols"]
base_feature_cols = [
"AVRR", "SDNN", "RMSSD", "PNN50", "Coefficient_of_Variation",
"Age", "Weight", "Height"
]
engineered_cols = [
"RMSSD_SDNN_ratio", "HRV_index", "Stress_index", "Parasympathetic",
"AVRR_PNN50", "CV_SDNN", "RMSSD_sq", "SDNN_sq"
]
class FatigueInput(BaseModel):
AVRR: float
SDNN: float
RMSSD: float
PNN50: float
Coefficient_of_Variation: float
Age: float
Weight: float
Height: float
def build_features(data: dict) -> pd.DataFrame:
"""Compute engineered features from the 8 base inputs the backend sends."""
row = dict(data)
row["RMSSD_SDNN_ratio"] = row["RMSSD"] / (abs(row["SDNN"]) + 0.001)
row["HRV_index"] = (row["SDNN"] + row["RMSSD"]) / 2
row["Stress_index"] = row["AVRR"] / (abs(row["SDNN"]) + 0.001)
row["Parasympathetic"] = row["RMSSD"] * row["PNN50"]
row["AVRR_PNN50"] = row["AVRR"] * row["PNN50"]
row["CV_SDNN"] = row["Coefficient_of_Variation"] * row["SDNN"]
row["RMSSD_sq"] = row["RMSSD"] ** 2
row["SDNN_sq"] = row["SDNN"] ** 2
return pd.DataFrame([row])[feature_cols]
app = FastAPI()
@app.post("/predict")
def predict(input_data: FatigueInput):
try:
input_df = build_features(input_data.dict())
scaled_input = scaler.transform(input_df)
prediction = int(model.predict(scaled_input)[0])
prob_dict = {}
if hasattr(model, "predict_proba"):
proba = model.predict_proba(scaled_input)[0]
classes = model.classes_
prob_dict = {int(cls): float(prob) for cls, prob in zip(classes, proba)}
return {
"fatigue_level": prediction,
"fatigueLevel": prediction,
"cluster_probabilities": list(prob_dict.values()),
"rounded_level": prediction,
"confidence": prob_dict,
}
except Exception as e:
return {"error": str(e)}
@app.post("/predictGMM")
def predict_gmm(input_data: FatigueInput):
"""Legacy endpoint -- redirects to the supervised classifier."""
return predict(input_data)
|