Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines6789101112136 unmodified lines202122232425262728293031323321 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495965 unmodified lines1021031041051061071081091101111121131141151161171181191201215 unmodified linesimport numpy as npapp = FastAPI(title="NeuroHealth EEG API",version="2.0")DEVICE = "cuda" if torch.cuda.is_available() else "cpu"6 unmodified linesPD_CLASSES = ["Parkinson", "Control"]# =========================================================# REQUEST SCHEMA# =========================================================class EEGRequest(BaseModel):features: list# =========================================================# EEG CNN MODEL (MATCHES YOUR .pth FILES)# =========================================================class EEG_CNN(nn.Module):21 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))}5 unmodified lines@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)5 unmodified lines6789101112136 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606121 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291305 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):def __init__(self, input_dim, output_dim):super().__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))def forward(self, x):return self.net(x)# =========================================================# OPTIONAL CNN (ONLY IF YOU TRAIN TRUE EEG CNN LATER)# =========================================================class EEG_CNN(nn.Module):21 unmodified linesreturn 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))return {"prediction": classes[pred],"confidence": float(probs[pred]),"probabilities": {classes[i]: float(probs[i]) for i in range(len(classes))}5 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")
app.py+57-23