Spaces:
Runtime error
Runtime error
Update app.py
Browse files4 unmodified lines5678910111213141516171819202122233 unmodified lines272829303132332 unmodified lines363738394041424344454647481 unmodified line50515253545556575859606162636465666768697071727374757677787980818283848586878889909192934 unmodified lines98991001011021031041051061071081091101114 unmodified linesimport torch.nn as nnimport numpy as npapp = FastAPI(title="NeuroHealth EEG API",version="3.1")DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# =========================================================# LABELS# =========================================================AD_CLASSES = ["Alzheimer", "FTD", "Control"]PD_CLASSES = ["Parkinson", "Control"]# =========================================================# REQUEST MODEL3 unmodified linesfeatures: list# =========================================================# ✔ TRUE MODEL (MATCHES YOUR TRAINED STATE_DICT)# =========================================================class EEG_MLP(nn.Module):2 unmodified linesself.net = nn.Sequential(nn.Linear(input_dim, 256),nn.BatchNorm1d(256),nn.ReLU(),nn.Linear(256, 128),nn.BatchNorm1d(128),nn.ReLU(),nn.Linear(128, output_dim))1 unmodified linereturn self.net(x)# =========================================================# LOAD MODELS (CRITICAL: INPUT DIM = 76)# =========================================================INPUT_DIM = 76ad_model = EEG_MLP(INPUT_DIM, 3).to(DEVICE)ad_model.load_state_dict(torch.load("AD_eeg_cnn.pth", map_location=DEVICE))ad_model.eval()pd_model = EEG_MLP(INPUT_DIM, 2).to(DEVICE)pd_model.load_state_dict(torch.load("PD_eeg_cnn.pth", map_location=DEVICE))pd_model.eval()print("Models loaded successfully with correct architecture")# =========================================================# PREDICTION ENGINE# =========================================================def predict(model, features, classes):x = torch.tensor(features, dtype=torch.float32)if x.numel() != INPUT_DIM:raise ValueError(f"Expected {INPUT_DIM} features, got {x.numel()}")x = x.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))return {"prediction": classes[pred],"confidence": float(probs[pred]),"probabilities": {classes[i]: float(probs[i]) for i in range(len(classes))}}4 unmodified lines@app.get("/")def home():return {"message": "NeuroHealth EEG API Running","input_dim": INPUT_DIM}@app.post("/predict/ad")def predict_ad(req: EEGRequest):return predict(ad_model, req.features, AD_CLASSES)@app.post("/predict/pd")def predict_pd(req: EEGRequest):return predict(pd_model, req.features, PD_CLASSES)4 unmodified lines5678910111213141516171819202122232425262728293031323334353 unmodified lines394041424344452 unmodified lines4849505152535455565758596061621 unmodified line6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431444 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781794 unmodified linesimport torch.nn as nnimport numpy as np# =========================================================# APP# =========================================================app = FastAPI(title="NeuroHealth EEG API",version="4.0")DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")# =========================================================# LABELS# =========================================================AD_CLASSES = ["Alzheimer","FTD","Control"]PD_CLASSES = ["Parkinson","Control"]# =========================================================# REQUEST MODEL3 unmodified linesfeatures: list# =========================================================# MODEL ARCHITECTURE# =========================================================class EEG_MLP(nn.Module):2 unmodified linesself.net = nn.Sequential(nn.Linear(input_dim, 256),nn.ReLU(),nn.BatchNorm1d(256),nn.Linear(256, 128),nn.ReLU(),nn.BatchNorm1d(128),nn.Linear(128, output_dim))1 unmodified linereturn self.net(x)# =========================================================# SETTINGS# =========================================================INPUT_DIM = 76AD_MODEL_PATH = "AD_eeg_cnn_ad_ftd_cn.pt"PD_MODEL_PATH = "PD_eeg_cnn.pth"# =========================================================# LOAD MODELS# =========================================================print("Loading AD model...")ad_model = EEG_MLP(INPUT_DIM, 3).to(DEVICE)ad_model.load_state_dict(torch.load(AD_MODEL_PATH,map_location=DEVICE))ad_model.eval()print("AD model loaded successfully")print("Loading PD model...")pd_model = EEG_MLP(INPUT_DIM, 2).to(DEVICE)pd_model.load_state_dict(torch.load(PD_MODEL_PATH,map_location=DEVICE))pd_model.eval()print("PD model loaded successfully")print("All models loaded")# =========================================================# PREDICTION FUNCTION# =========================================================def predict(model, features, class_names):x = torch.tensor(features,dtype=torch.float32)if x.numel() != INPUT_DIM:raise ValueError(f"Expected {INPUT_DIM} features but received {x.numel()}")x = x.unsqueeze(0).to(DEVICE)with torch.no_grad():outputs = model(x)probs = torch.softmax(outputs, dim=1)probs = probs.cpu().numpy()[0]pred_idx = int(np.argmax(probs))return {"prediction": class_names[pred_idx],"confidence": float(probs[pred_idx]),"probabilities": {class_names[i]: float(probs[i])for i in range(len(class_names))}}4 unmodified lines@app.get("/")def home():return {"status": "running","device": str(DEVICE),"input_features": INPUT_DIM,"ad_classes": AD_CLASSES,"pd_classes": PD_CLASSES}@app.get("/health")def health():return {"status": "healthy"}@app.post("/predict/ad")def predict_ad(req: EEGRequest):return predict(ad_model,req.features,AD_CLASSES)@app.post("/predict/pd")def predict_pd(req: EEGRequest):return predict(pd_model,req.features,PD_CLASSES)
app.py+92-24