Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines6789101112136 unmodified lines20212223242526272829303132331 unmodified line35363738394041424344454647484950513 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312411 unmodified lines1361371381391401411421431441451461471481491501511521531541555 unmodified linesimport numpy as npapp = FastAPI(title="NeuroHealth Unified EEG API",version="3.0")DEVICE = "cuda" if torch.cuda.is_available() else "cpu"6 unmodified linesPD_CLASSES = ["Parkinson", "Control"]# =========================================================# INPUT SCHEMA# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# ✔ MLP MODEL (MATCHES YOUR .pth FILES)# =========================================================class EEG_MLP(nn.Module):1 unmodified linesuper().__init__()self.net = nn.Sequential(nn.Linear(input_dim, 512),nn.BatchNorm1d(512),nn.ReLU(),nn.Dropout(0.3),nn.Linear(512, 256),nn.BatchNorm1d(256),nn.ReLU(),nn.Dropout(0.3),nn.Linear(256, 128),nn.ReLU(),nn.Linear(128, output_dim)3 unmodified linesreturn self.net(x)# =========================================================# OPTIONAL CNN (ONLY IF YOU TRAIN TRUE EEG CNN LATER)# =========================================================class EEG_CNN(nn.Module):def __init__(self, output_dim):super().__init__()self.conv1 = nn.Conv1d(19, 32, kernel_size=7)self.bn1 = nn.BatchNorm1d(32)self.conv2 = nn.Conv1d(32, 64, kernel_size=5)self.bn2 = nn.BatchNorm1d(64)self.conv3 = nn.Conv1d(64, 128, kernel_size=3)self.bn3 = nn.BatchNorm1d(128)self.pool = nn.AdaptiveAvgPool1d(1)self.fc = nn.Linear(128, output_dim)def forward(self, x):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)# =========================================================# LOAD MODELS (BASED ON YOUR REAL FILES)# =========================================================# ✔ THESE ARE MLP MODELS (CONFIRMED BY "net.*" KEYS)ad_model = EEG_MLP(95, 3).to(DEVICE)ad_model.load_state_dict(torch.load("AD_eeg_cnn.pth", map_location=DEVICE))ad_model.eval()pd_model = EEG_MLP(95, 2).to(DEVICE)pd_model.load_state_dict(torch.load("PD_eeg_cnn.pth", map_location=DEVICE))pd_model.eval()print("All models loaded successfully")# =========================================================# SAFE PREDICTION ENGINE# =========================================================def predict(model, features, classes, model_type="mlp"):x = torch.tensor(features, dtype=torch.float32)if x.numel() != 95:raise ValueError("Expected exactly 95 features")# ✔ MLP MODE: flat inputif model_type == "mlp":x = x.unsqueeze(0).to(DEVICE)# ✔ CNN MODE (future use only)elif model_type == "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))11 unmodified lines@app.get("/")def home():return {"message": "NeuroHealth Unified API Running"}# =========================================================# AD PREDICTION# =========================================================@app.post("/predict/ad")def predict_ad(req: EEGRequest):return predict(ad_model, req.features, AD_CLASSES, "mlp")# =========================================================# PD PREDICTION# =========================================================@app.post("/predict/pd")def predict_pd(req: EEGRequest):return predict(pd_model, req.features, PD_CLASSES, "mlp")5 unmodified lines6789101112136 unmodified lines20212223242526272829303132331 unmodified line3536373839404142434445463 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848511 unmodified lines9798991001011021031041051061071081091101115 unmodified linesimport numpy as npapp = FastAPI(title="NeuroHealth EEG API",version="3.1")DEVICE = "cuda" if torch.cuda.is_available() else "cpu"6 unmodified linesPD_CLASSES = ["Parkinson", "Control"]# =========================================================# REQUEST MODEL# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# ✔ TRUE MODEL (MATCHES YOUR TRAINED STATE_DICT)# =========================================================class EEG_MLP(nn.Module):1 unmodified linesuper().__init__()self.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)3 unmodified linesreturn 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))11 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)
app.py+24-68