Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import osimport ioimport numpy as npimport torchimport torch.nn as nnimport torchvision.models as modelsimport tensorflow as tffrom fastapi import FastAPI, UploadFile, Filefrom PIL import Imageimport cv2import nibabel as nib
app = FastAPI(title="Parkinson + DaTscan AI API")
DEVICE = "cpu"
# =========================# LABELS (BINARY CLASS)# =========================LABELS = ["No Parkinson's", "Parkinson's Disease"]
# =========================# LOAD KERAS MODELS# =========================def load_keras(path): return tf.keras.models.load_model(path, compile=False)
model_121 = load_keras("densenet121_parkinsonsDATSCAN.keras")model_169 = load_keras("parkinsons_densenet169DATSCAN.keras")model_201 = load_keras("parkinsons_densenet201DATSCAN.keras")
# optional fixed model (if better)model_fixed = load_keras("densenet121_parkinsonsDATSCAN_fixed.keras")
# =========================# 3D CNN MODEL (PyTorch)# =========================def build_3dcnn(): model = nn.Sequential( nn.Conv3d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool3d(2),
nn.Conv3d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool3d(2),
nn.AdaptiveAvgPool3d((4, 4, 4)), nn.Flatten(), nn.Linear(64 * 4 * 4 * 4, 128), nn.ReLU(), nn.Linear(128, 2) ) return model.to(DEVICE).eval()
model_3dcnn = build_3dcnn()
# =========================# IMAGE PREPROCESSING (2D)# =========================def preprocess_2d(image_bytes): image = Image.open(io.BytesIO(image_bytes)).convert("RGB") image = np.array(image) image = cv2.resize(image, (128, 128)) image = image / 255.0 image = np.expand_dims(image, axis=0) return image
# =========================# NIFTI PREPROCESSING (3D)# =========================def preprocess_3d(file_bytes): temp_path = "temp.nii" with open(temp_path, "wb") as f: f.write(file_bytes)
volume = nib.load(temp_path).get_fdata() volume = np.squeeze(volume)
if len(volume.shape) == 2: volume = np.stack([volume] * 32, axis=-1)
depth = volume.shape[2]
slices = [] for i in np.linspace(0, depth - 1, 32).astype(int): sl = volume[:, :, i] sl = cv2.resize(sl, (64, 64)) slices.append(sl)
vol = np.stack(slices, axis=0) vol = np.expand_dims(vol, axis=0) vol = np.expand_dims(vol, axis=0)
return torch.tensor(vol, dtype=torch.float32).to(DEVICE)
# =========================# KERAS SINGLE PREDICT# =========================def predict_keras(model, x): pred = model.predict(x, verbose=0)[0] return pred
# =========================# ENSEMBLE LOGIC (4 MODELS)# =========================def ensemble_predict(image_bytes):
x = preprocess_2d(image_bytes)
p1 = predict_keras(model_121, x) p2 = predict_keras(model_169, x) p3 = predict_keras(model_201, x) p4 = predict_keras(model_fixed, x)
preds = np.array([p1, p2, p3, p4])
avg = np.mean(preds, axis=0)
cls = int(np.argmax(avg)) confidence = float(avg[cls] * 100)
return { "prediction": LABELS[cls], "class_id": cls, "confidence": round(confidence, 2),
"model_confidences": { "DenseNet121": round(float(np.max(p1)) * 100, 2), "DenseNet169": round(float(np.max(p2)) * 100, 2), "DenseNet201": round(float(np.max(p3)) * 100, 2), "Fixed121": round(float(np.max(p4)) * 100, 2), },
"probabilities": { LABELS[i]: round(float(avg[i]) * 100, 2) for i in range(2) } }
# =========================# 3D CNN PREDICTION# =========================def predict_3d(file_bytes): x = preprocess_3d(file_bytes)
with torch.no_grad(): out = model_3dcnn(x) probs = torch.softmax(out, dim=1)[0]
cls = int(torch.argmax(probs)) confidence = float(probs[cls] * 100)
return { "prediction": LABELS[cls], "class_id": cls, "confidence": round(confidence, 2), "probabilities": { LABELS[i]: round(float(probs[i]) * 100, 2) for i in range(2) } }
# =========================# ROUTES# =========================@app.get("/")def home(): return { "status": "running", "models": ["121", "169", "201", "fixed", "3dcnn"] }
@app.post("/predict")async def predict(file: UploadFile = File(...)): image_bytes = await file.read() return ensemble_predict(image_bytes)
@app.post("/predict/121")async def p121(file: UploadFile = File(...)): x = preprocess_2d(await file.read()) return {"model": "121", "prob": predict_keras(model_121, x).tolist()}
@app.post("/predict/169")async def p169(file: UploadFile = File(...)): x = preprocess_2d(await file.read()) return {"model": "169", "prob": predict_keras(model_169, x).tolist()}
@app.post("/predict/201")async def p201(file: UploadFile = File(...)): x = preprocess_2d(await file.read()) return {"model": "201", "prob": predict_keras(model_201, x).tolist()}
@app.post("/predict/3d")async def p3d(file: UploadFile = File(...)): return predict_3d(await file.read())app.pyAdded+208