tabfm
Browse files
main.py
CHANGED
|
@@ -7,13 +7,63 @@ from PIL import Image
|
|
| 7 |
import io
|
| 8 |
import uvicorn
|
| 9 |
import json
|
|
|
|
|
|
|
|
|
|
| 10 |
try:
|
| 11 |
from tabfm import TabFMClassifier, tabfm_v1_0_0_pytorch as tabfm_v1_0_0
|
| 12 |
except ImportError:
|
| 13 |
tabfm_v1_0_0 = None
|
| 14 |
TabFMClassifier = None
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 19 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -90,10 +140,6 @@ class PatientMetrics(BaseModel):
|
|
| 90 |
stress_level: str
|
| 91 |
sedentary_lifestyle: str
|
| 92 |
|
| 93 |
-
@app.on_event("startup")
|
| 94 |
-
async def startup_event():
|
| 95 |
-
load_models()
|
| 96 |
-
|
| 97 |
@app.post("/predict")
|
| 98 |
async def predict(
|
| 99 |
metrics: str = Form(...),
|
|
@@ -131,8 +177,15 @@ async def predict(
|
|
| 131 |
gemma_ecg_findings = models['ecg_processor'].decode(ecg_outputs[0][ecg_inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
|
| 132 |
|
| 133 |
if models['tabfm_clf'] is not None:
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
else:
|
| 137 |
tabfm_risk_probability = 68.2
|
| 138 |
tabfm_classification_label = "Positive for Heart Disease"
|
|
|
|
| 7 |
import io
|
| 8 |
import uvicorn
|
| 9 |
import json
|
| 10 |
+
import numpy as np
|
| 11 |
+
from contextlib import asynccontextmanager
|
| 12 |
+
|
| 13 |
try:
|
| 14 |
from tabfm import TabFMClassifier, tabfm_v1_0_0_pytorch as tabfm_v1_0_0
|
| 15 |
except ImportError:
|
| 16 |
tabfm_v1_0_0 = None
|
| 17 |
TabFMClassifier = None
|
| 18 |
|
| 19 |
+
# Categorical mappings for TabFM input
|
| 20 |
+
MAPPINGS = {
|
| 21 |
+
"sex": {"Male": 0, "Female": 1},
|
| 22 |
+
"ethnicity": {"Caucasian": 0, "African American": 1, "Asian": 2, "Hispanic": 3, "Other": 4},
|
| 23 |
+
"diabetes": {"No": 0, "Yes": 1},
|
| 24 |
+
"resting_ecg": {"Normal": 0, "Abnormal": 1},
|
| 25 |
+
"slope": {"Up": 0, "Flat": 1, "Down": 2},
|
| 26 |
+
"thalassemia": {"Normal": 0, "Fixed": 1, "Reversible": 2},
|
| 27 |
+
"smoking": {"Never": 0, "Former": 1, "Current": 2},
|
| 28 |
+
"alcohol_consumption": {"None": 0, "Low": 1, "Moderate": 2, "High": 3},
|
| 29 |
+
"physical_activity": {"Low": 0, "Moderate": 1, "High": 2},
|
| 30 |
+
"diet_quality": {"Poor": 0, "Fair": 1, "Good": 2, "Excellent": 3},
|
| 31 |
+
"stress_level": {"Low": 0, "Moderate": 1, "High": 2},
|
| 32 |
+
"sedentary_lifestyle": {"No": 0, "Yes": 1},
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
def preprocess_metrics(metrics: 'PatientMetrics'):
|
| 36 |
+
"""Convert PatientMetrics Pydantic model to a numpy array for TabFM."""
|
| 37 |
+
features = []
|
| 38 |
+
|
| 39 |
+
# Numerical features
|
| 40 |
+
features.append(metrics.age)
|
| 41 |
+
features.append(float(metrics.blood_pressure.split('/')[0]) if '/' in metrics.blood_pressure else 0.0)
|
| 42 |
+
features.append(float(metrics.blood_pressure.split('/')[1]) if '/' in metrics.blood_pressure else 0.0)
|
| 43 |
+
features.append(metrics.heart_rate)
|
| 44 |
+
features.append(metrics.cholesterol)
|
| 45 |
+
features.append(metrics.fasting_blood_sugar)
|
| 46 |
+
features.append(metrics.bmi)
|
| 47 |
+
features.append(metrics.oldpeak)
|
| 48 |
+
features.append(metrics.major_vessels)
|
| 49 |
+
features.append(metrics.sleep_duration)
|
| 50 |
+
|
| 51 |
+
# Categorical features via mapping
|
| 52 |
+
for field, mapping in MAPPINGS.items():
|
| 53 |
+
val = getattr(metrics, field, "Other")
|
| 54 |
+
features.append(mapping.get(val, 0))
|
| 55 |
+
|
| 56 |
+
return np.array([features], dtype=np.float32)
|
| 57 |
+
|
| 58 |
+
@asynccontextmanager
|
| 59 |
+
async def lifespan(app: FastAPI):
|
| 60 |
+
# Startup: Load models
|
| 61 |
+
load_models()
|
| 62 |
+
yield
|
| 63 |
+
# Shutdown: Clean up if needed
|
| 64 |
+
models.clear()
|
| 65 |
+
|
| 66 |
+
app = FastAPI(title="Heart Disease Diagnostic Pipeline", lifespan=lifespan)
|
| 67 |
|
| 68 |
DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 69 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 140 |
stress_level: str
|
| 141 |
sedentary_lifestyle: str
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
@app.post("/predict")
|
| 144 |
async def predict(
|
| 145 |
metrics: str = Form(...),
|
|
|
|
| 177 |
gemma_ecg_findings = models['ecg_processor'].decode(ecg_outputs[0][ecg_inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
|
| 178 |
|
| 179 |
if models['tabfm_clf'] is not None:
|
| 180 |
+
try:
|
| 181 |
+
X = preprocess_metrics(patient_metrics)
|
| 182 |
+
probs = models['tabfm_clf'].predict_proba(X)
|
| 183 |
+
tabfm_risk_probability = float(np.max(probs) * 100)
|
| 184 |
+
tabfm_classification_label = "High Risk" if tabfm_risk_probability > 50 else "Low Risk"
|
| 185 |
+
except Exception as e:
|
| 186 |
+
print(f"TabFM Prediction Error: {e}")
|
| 187 |
+
tabfm_risk_probability = 68.2
|
| 188 |
+
tabfm_classification_label = "Positive for Heart Disease"
|
| 189 |
else:
|
| 190 |
tabfm_risk_probability = 68.2
|
| 191 |
tabfm_classification_label = "Positive for Heart Disease"
|