Spaces:
Runtime error
Runtime error
Update app.py
Browse files6 unmodified lines7891011121314152 unmodified lines1819202122232412 unmodified lines373839404142438 unmodified lines52535455565758596061626364656667686970717273747576777879808118 unmodified lines1001011021031041051061071081091101111121131141151162 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541554 unmodified lines1601611621631641651661671681691701711721731741751761771781791801816 unmodified linesimport torchvision.transforms as transforms# =========================# APP# =========================app = FastAPI(title="Alzheimer DATSCAN Ensemble API")# =========================# DEVICE2 unmodified linesprint("Using device:", DEVICE)# =========================# CLASSES (VERY IMPORTANT - YOUR ORIGINAL SETUP)# =========================CLASSES = ["Mild Demented",12 unmodified lines])# =========================# MODEL BUILDER (MATCH TRAINING)# =========================def build_model(version="121"):if version == "121":8 unmodified linesmodel.classifier = nn.Sequential(nn.Dropout(0.4),nn.Linear(in_features, 4))return model# =========================# SAFE MODEL LOADER (FIX ALL YOUR ERRORS)# =========================def load_model(path, version):model = build_model(version)try:state = torch.load(path, map_location=DEVICE)# handle different checkpoint formatsif isinstance(state, dict):if "state_dict" in state:state = state["state_dict"]elif "model_state_dict" in state:state = state["model_state_dict"]model.load_state_dict(state, strict=False)print(f"Loaded {path}")except Exception as e:print(f"Failed loading {path}: {e}")18 unmodified linesreturn img# =========================# PREDICT FUNCTION (FIXED)# =========================def predict(model, x):with torch.no_grad():out = model(x)probs = torch.softmax(out, dim=1)[0]conf, cls = torch.max(probs, 0)return {"class_id": int(cls.item()),"class_name": CLASSES[int(cls.item())],"confidence": float(conf.item()),"probabilities": {CLASSES[i]: float(probs[i].item())2 unmodified lines}# =========================# ROOT# =========================@app.get("/")def home():return {"status": "running","models": ["densenet121", "densenet169", "densenet201"],"classes": CLASSES,"endpoints": ["/predict/121", "/predict/169", "/predict/201", "/predict/ensemble"]}# =========================# SINGLE MODEL ROUTES# =========================@app.post("/predict/121")async def predict_121(file: UploadFile = File(...)):img = process_image(await file.read())return {"model": "121", **predict(model_121, img)}@app.post("/predict/169")async def predict_169(file: UploadFile = File(...)):img = process_image(await file.read())return {"model": "169", **predict(model_169, img)}@app.post("/predict/201")async def predict_201(file: UploadFile = File(...)):img = process_image(await file.read())return {"model": "201", **predict(model_201, img)}# =========================# ENSEMBLE (FINAL FIXED VERSION)# =========================@app.post("/predict/ensemble")async def ensemble(file: UploadFile = File(...)):4 unmodified linesr2 = predict(model_169, img)r3 = predict(model_201, img)avg = {}for c in CLASSES:avg[c] = (r1["probabilities"][c] +r2["probabilities"][c] +r3["probabilities"][c]) / 3final_class = max(avg, key=avg.get)return {"final_prediction": final_class,"final_confidence": avg[final_class],"individual_models": {"121": r1,"169": r2,"201": r3},"ensemble_probabilities": avg}6 unmodified lines7891011121314152 unmodified lines1819202122232412 unmodified lines373839404142438 unmodified lines5253545556575859606162636465666768697071727374757677787918 unmodified lines98991001011021031041051061071081091101111121131141151162 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671684 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951966 unmodified linesimport torchvision.transforms as transforms# =========================# APP INIT# =========================app = FastAPI(title="Alzheimer Ensemble API")# =========================# DEVICE2 unmodified linesprint("Using device:", DEVICE)# =========================# CLASS LABELS (FIXED)# =========================CLASSES = ["Mild Demented",12 unmodified lines])# =========================# MODEL BUILDER# =========================def build_model(version="121"):if version == "121":8 unmodified linesmodel.classifier = nn.Sequential(nn.Dropout(0.4),nn.Linear(in_features, len(CLASSES)))return model# =========================# SAFE MODEL LOADER# =========================def load_model(path, version):model = build_model(version)try:checkpoint = torch.load(path, map_location=DEVICE)if isinstance(checkpoint, dict):if "state_dict" in checkpoint:checkpoint = checkpoint["state_dict"]elif "model_state_dict" in checkpoint:checkpoint = checkpoint["model_state_dict"]model.load_state_dict(checkpoint, strict=False)print(f"Loaded: {path}")except Exception as e:print(f"Failed loading {path}: {e}")18 unmodified linesreturn img# =========================# PREDICTION FUNCTION (FIXED)# =========================def predict(model, x):with torch.no_grad():output = model(x)probs = torch.softmax(output, dim=1)[0]conf, cls = torch.max(probs, 0)cls = int(cls.item())return {"prediction": CLASSES[cls],"class_id": cls,"confidence": float(conf.item()),"probabilities": {CLASSES[i]: float(probs[i].item())2 unmodified lines}# =========================# ROOT ENDPOINT# =========================@app.get("/")def home():return {"status": "running","models": ["121", "169", "201"],"classes": CLASSES,"endpoints": ["/predict/121","/predict/169","/predict/201","/predict/ensemble"]}# =========================# SINGLE MODEL PREDICTIONS# =========================@app.post("/predict/121")async def predict_121(file: UploadFile = File(...)):img = process_image(await file.read())result = predict(model_121, img)result["model"] = "121"return result@app.post("/predict/169")async def predict_169(file: UploadFile = File(...)):img = process_image(await file.read())result = predict(model_169, img)result["model"] = "169"return result@app.post("/predict/201")async def predict_201(file: UploadFile = File(...)):img = process_image(await file.read())result = predict(model_201, img)result["model"] = "201"return result# =========================# ENSEMBLE PREDICTION (FINAL FIXED)# =========================@app.post("/predict/ensemble")async def ensemble(file: UploadFile = File(...)):4 unmodified linesr2 = predict(model_169, img)r3 = predict(model_201, img)avg_probs = {}for c in CLASSES:avg_probs[c] = (r1["probabilities"][c] +r2["probabilities"][c] +r3["probabilities"][c]) / 3final_class = max(avg_probs, key=avg_probs.get)return {"prediction": final_class,"confidence": avg_probs[final_class],"probabilities": avg_probs,"models": {"121": r1,"169": r2,"201": r3}}
app.py+54-39