Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142439 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521538 unmodified lines162163164165166167168169170171172173174175176177178179180181182183184185186187188from fastapi import FastAPIfrom pydantic import BaseModelimport torchimport torch.nn as nnimport numpy as np# =========================================================# APP# =========================================================app = FastAPI(title="NeuroHealth EEG API",version="10.0")DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")# =========================================================# LABELS# =========================================================AD_CLASSES = ["Alzheimer", "FTD", "Control"]PD_CLASSES = ["Parkinson", "Control"]# =========================================================# INPUT# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# AD MODEL (UNCHANGED - 19 x 76 CNN)# =========================================================class EEG_CNN_AD(nn.Module):def __init__(self):super().__init__()self.conv1 = nn.Conv1d(19, 32, 7, padding=3)self.bn1 = nn.BatchNorm1d(32)9 unmodified linesdef forward(self, x):x = x.view(x.size(0), 19, 76)x = torch.relu(self.conv1(x))x = self.bn1(x)x = torch.relu(self.conv2(x))x = self.bn2(x)x = torch.relu(self.conv3(x))x = self.bn3(x)x = self.pool(x).squeeze(-1)return self.fc(x)# =========================================================# PD MODEL (UPDATED CNN - MATCHES YOUR TRAINED MODEL)# =========================================================class EEG_CNN_PD(nn.Module):def __init__(self):super().__init__()self.conv1 = nn.Conv1d(64, 32, 7, padding=3)self.bn1 = nn.BatchNorm1d(32)self.conv2 = nn.Conv1d(32, 64, 5, padding=2)self.bn2 = nn.BatchNorm1d(64)self.conv3 = nn.Conv1d(64, 128, 3, padding=1)self.bn3 = nn.BatchNorm1d(128)self.pool = nn.AdaptiveAvgPool1d(1)self.fc = nn.Linear(128, 2)def forward(self, x):# x: (batch, 64, 256)x = torch.relu(self.conv1(x))x = self.bn1(x)x = torch.relu(self.conv2(x))x = self.bn2(x)x = torch.relu(self.conv3(x))x = self.bn3(x)x = self.pool(x).squeeze(-1)return self.fc(x)# =========================================================# PATHS# =========================================================AD_MODEL_PATH = "AD_eeg_cnn_ad_ftd_cn.pt"PD_MODEL_PATH = "PD_CNN_FINAL.pth"# =========================================================# LOAD MODELS# =========================================================print("Loading AD model...")ad_model = EEG_CNN_AD().to(DEVICE)ad_model.load_state_dict(torch.load(AD_MODEL_PATH, map_location=DEVICE))ad_model.eval()print("AD model loaded")print("Loading PD model...")pd_model = EEG_CNN_PD().to(DEVICE)pd_model.load_state_dict(torch.load(PD_MODEL_PATH, map_location=DEVICE))pd_model.eval()print("PD model loaded")print("System ready")# =========================================================# PREPROCESSING# =========================================================def prepare(features, model_type):x = torch.tensor(features, dtype=torch.float32)if model_type == "ad":return x.view(1, 19, 76)if model_type == "pd":return x.view(1, 64, 256)raise ValueError("Invalid model type")# =========================================================# PREDICTION ENGINE# =========================================================def predict(model, features, classes, model_type):x = prepare(features, model_type).to(DEVICE)with torch.no_grad():out = model(x)probs = torch.softmax(out, dim=1).cpu().numpy()[0]8 unmodified lines}}# =========================================================# ROUTES# =========================================================@app.get("/")def home():return {"status": "running","ad_input": "19x76 CNN","pd_input": "64x256 CNN","version": "10.0"}@app.get("/health")def health():return {"status": "ok"}@app.post("/predict/ad")def predict_ad(req: EEGRequest):return predict(ad_model, req.features, AD_CLASSES, "ad")@app.post("/predict/pd")def predict_pd(req: EEGRequest):return predict(pd_model, req.features, PD_CLASSES, "pd")123456789101112131415161718192021222324252627282930319 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101118 unmodified lines120121122123124125126127128129130131132133134135136137138from fastapi import FastAPIfrom pydantic import BaseModelimport torchimport torch.nn as nnimport numpy as npapp = FastAPI(title="NeuroHealth EEG API", version="RESET-1")DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")# ======================# LABELS# ======================AD_CLASSES = ["Alzheimer", "FTD", "Control"]PD_CLASSES = ["Parkinson", "Control"]# ======================# INPUT# ======================class EEGRequest(BaseModel):features: list# ======================# AD MODEL (UNCHANGED CNN)# ======================class EEG_CNN_AD(nn.Module):def __init__(self):super().__init__()self.conv1 = nn.Conv1d(19, 32, 7, padding=3)self.bn1 = nn.BatchNorm1d(32)9 unmodified linesdef forward(self, x):x = x.view(x.size(0), 19, 76)x = torch.relu(self.bn1(self.conv1(x)))x = torch.relu(self.bn2(self.conv2(x)))x = torch.relu(self.bn3(self.conv3(x)))x = self.pool(x).squeeze(-1)return self.fc(x)# ======================# PD MODEL (MATCH CHECKPOINT EXACTLY)# ======================class EEG_PD(nn.Module):def __init__(self):super().__init__()self.net = nn.Sequential(nn.Linear(76, 256),nn.ReLU(),nn.BatchNorm1d(256),nn.Linear(256, 128),nn.ReLU(),nn.BatchNorm1d(128),nn.Linear(128, 2))def forward(self, x):return self.net(x)# ======================# LOAD MODELS# ======================AD_PATH = "AD_eeg_model.pth"PD_PATH = "PD_eeg_model.pth"print("Loading AD model...")ad_model = EEG_CNN_AD().to(DEVICE)ad_model.load_state_dict(torch.load(AD_PATH, map_location=DEVICE))ad_model.eval()print("AD loaded")print("Loading PD model...")pd_model = EEG_PD().to(DEVICE)pd_model.load_state_dict(torch.load(PD_PATH, map_location=DEVICE))pd_model.eval()print("PD loaded")# ======================# PREPROCESS# ======================def preprocess(features, mode):x = torch.tensor(features, dtype=torch.float32)if mode == "ad":return x.view(1, 19, 76)if mode == "pd":# IMPORTANT: PD expects FLATTENED 76-D FEATURESreturn x.view(1, 76)raise ValueError("unknown mode")# ======================# PREDICT ENGINE# ======================def predict(model, x, classes):with torch.no_grad():out = model(x)probs = torch.softmax(out, dim=1).cpu().numpy()[0]8 unmodified lines}}# ======================# ROUTES# ======================@app.get("/")def home():return {"status": "ready (RESET architecture)", "year": 2026}@app.post("/predict/ad")def predict_ad(req: EEGRequest):x = preprocess(req.features, "ad").to(DEVICE)return predict(ad_model, x, AD_CLASSES)@app.post("/predict/pd")def predict_pd(req: EEGRequest):x = preprocess(req.features, "pd").to(DEVICE)return predict(pd_model, x, PD_CLASSES)
app.py+54-104