Spaces:
Sleeping
Sleeping
Download app.py from jkim03/StaminaSenseSpacePrototype: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/spaces/jkim03/StaminaSenseSpacePrototype/resolve/main/app.py
- Command line
-
hf download hf://spaces/jkim03/StaminaSenseSpacePrototype/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jkim03/StaminaSenseSpacePrototype/resolve/main/app.py
2.39 kB
| 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() | |
| 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)} | |
| def predict_gmm(input_data: FatigueInput): | |
| """Legacy endpoint -- redirects to the supervised classifier.""" | |
| return predict(input_data) | |