Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines67891011127 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717219 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971985 unmodified linesimport numpy as npapp = FastAPI(title="NeuroHealth Multi-Model EEG API",version="2.0")7 unmodified linesPD_CLASSES = ["Parkinson", "Control"]# =========================================================# INPUT# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# DEVICE# =========================================================def to_tensor(features):return torch.tensor(features, dtype=torch.float32)# =========================================================# ===================== MODELS ============================# =========================================================# ---------------- MLP (CSV MODELS) ----------------------INPUT_DIM = 95class MLP(nn.Module):def __init__(self, output_dim):super().__init__()self.net = nn.Sequential(nn.Linear(INPUT_DIM, 512),nn.BatchNorm1d(512),nn.GELU(),nn.Dropout(0.3),nn.Linear(512, 256),nn.BatchNorm1d(256),nn.GELU(),nn.Dropout(0.3),nn.Linear(256, 128),nn.GELU(),nn.Linear(128, output_dim))def forward(self, x):return self.net(x)# ---------------- CNN (EEG MODELS) ----------------------class EEG_CNN(nn.Module):def __init__(self, output_dim):super().__init__()19 unmodified linesreturn self.fc(x)# =========================================================# LOAD ALL MODELS# =========================================================# -------- AD MODELS --------ad_mlp = MLP(3).to(DEVICE)ad_mlp.load_state_dict(torch.load("AD_MLP.pt", map_location=DEVICE))ad_mlp.eval()ad_cnn = EEG_CNN(3).to(DEVICE)ad_cnn.load_state_dict(torch.load("AD_eeg_cnn.pth", map_location=DEVICE))ad_cnn.eval()# -------- PD MODELS --------pd_mlp = MLP(2).to(DEVICE)pd_mlp.load_state_dict(torch.load("PD_MLP.pt", map_location=DEVICE))pd_mlp.eval()pd_cnn = EEG_CNN(2).to(DEVICE)pd_cnn.load_state_dict(torch.load("PD_eeg_cnn.pth", map_location=DEVICE))pd_cnn.eval()print("All models loaded successfully")# =========================================================# PREDICTION ENGINE# =========================================================def predict(model, features, mode="mlp"):x = to_tensor(features)if mode == "mlp":x = x.unsqueeze(0).to(DEVICE)elif mode == "cnn":x = x.view(19, 5).unsqueeze(0).to(DEVICE)with torch.no_grad():out = model(x)probs = torch.softmax(out, dim=1).cpu().numpy()[0]pred = int(np.argmax(probs))return pred, float(probs[pred]), probs.tolist()# =========================================================# ROUTES1 unmodified line@app.get("/")def home():return {"message": "NeuroHealth Multi-Model API Running"}# =========================================================# AD ENDPOINTS# =========================================================@app.post("/predict/ad/mlp")def ad_mlp_predict(req: EEGRequest):p, c, prob = predict(ad_mlp, req.features, "mlp")return {"model": "AD_MLP","prediction": AD_CLASSES[p],"confidence": c,"probabilities": dict(zip(AD_CLASSES, prob))}@app.post("/predict/ad/eeg")def ad_cnn_predict(req: EEGRequest):p, c, prob = predict(ad_cnn, req.features, "cnn")return {"model": "AD_EEG_CNN","prediction": AD_CLASSES[p],"confidence": c,"probabilities": dict(zip(AD_CLASSES, prob))}# =========================================================# PD ENDPOINTS# =========================================================@app.post("/predict/pd/mlp")def pd_mlp_predict(req: EEGRequest):p, c, prob = predict(pd_mlp, req.features, "mlp")return {"model": "PD_MLP","prediction": PD_CLASSES[p],"confidence": c,"probabilities": dict(zip(PD_CLASSES, prob))}@app.post("/predict/pd/eeg")def pd_cnn_predict(req: EEGRequest):p, c, prob = predict(pd_cnn, req.features, "cnn")return {"model": "PD_EEG_CNN","prediction": PD_CLASSES[p],"confidence": c,"probabilities": dict(zip(PD_CLASSES, prob))}5 unmodified lines67891011127 unmodified lines2021222324252627282930313233343519 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001 unmodified line1021031041051061071081091101111121131141151161171181191201215 unmodified linesimport numpy as npapp = FastAPI(title="NeuroHealth EEG API",version="2.0")7 unmodified linesPD_CLASSES = ["Parkinson", "Control"]# =========================================================# REQUEST SCHEMA# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# EEG CNN MODEL (MATCHES YOUR .pth FILES)# =========================================================class EEG_CNN(nn.Module):def __init__(self, output_dim):super().__init__()19 unmodified linesreturn self.fc(x)# =========================================================# LOAD MODELS (CLEAN VERSION)# =========================================================ad_model = EEG_CNN(3).to(DEVICE)ad_model.load_state_dict(torch.load("AD_eeg_cnn.pth", map_location=DEVICE))ad_model.eval()pd_model = EEG_CNN(2).to(DEVICE)pd_model.load_state_dict(torch.load("PD_eeg_cnn.pth", map_location=DEVICE))pd_model.eval()print("All EEG CNN models loaded successfully")# =========================================================# CORE PREDICTION FUNCTION# =========================================================def predict(model, features, classes):x = torch.tensor(features, dtype=torch.float32)if x.numel() != 95:raise ValueError("Expected exactly 95 features")# reshape EEG features → (19 channels × 5 timesteps)x = x.view(19, 5).unsqueeze(0).to(DEVICE)with torch.no_grad():outputs = model(x)probs = torch.softmax(outputs, dim=1).cpu().numpy()[0]pred = int(np.argmax(probs))confidence = float(probs[pred])return {"prediction": classes[pred],"confidence": confidence,"probabilities": {classes[i]: float(probs[i]) for i in range(len(classes))}}# =========================================================# ROUTES1 unmodified line@app.get("/")def home():return {"message": "NeuroHealth EEG API Running"}# =========================================================# AD ROUTE# =========================================================@app.post("/predict/ad")def predict_ad(request: EEGRequest):return predict(ad_model, request.features, AD_CLASSES)# =========================================================# PD ROUTE# =========================================================@app.post("/predict/pd")def predict_pd(request: EEGRequest):return predict(pd_model, request.features, PD_CLASSES)
app.py+38-115