Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,208 +1,153 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
import numpy as np
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
import torchvision.models as models
|
| 7 |
-
import tensorflow as tf
|
| 8 |
from fastapi import FastAPI, UploadFile, File
|
| 9 |
from PIL import Image
|
| 10 |
-
import
|
| 11 |
-
import
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
app = FastAPI(title="
|
| 14 |
|
| 15 |
-
DEVICE = "cpu"
|
| 16 |
|
| 17 |
# =========================
|
| 18 |
-
# LABELS
|
| 19 |
# =========================
|
| 20 |
-
LABELS = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# =========================
|
| 23 |
-
#
|
| 24 |
# =========================
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
model_201 = load_keras("parkinsons_densenet201DATSCAN.keras")
|
| 31 |
-
|
| 32 |
-
# optional fixed model (if better)
|
| 33 |
-
model_fixed = load_keras("densenet121_parkinsonsDATSCAN_fixed.keras")
|
| 34 |
-
|
| 35 |
|
| 36 |
# =========================
|
| 37 |
-
#
|
| 38 |
# =========================
|
| 39 |
-
def
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
nn.Conv3d(32, 64, 3, padding=1),
|
| 46 |
-
nn.ReLU(),
|
| 47 |
-
nn.MaxPool3d(2),
|
| 48 |
-
|
| 49 |
-
nn.AdaptiveAvgPool3d((4, 4, 4)),
|
| 50 |
-
nn.Flatten(),
|
| 51 |
-
nn.Linear(64 * 4 * 4 * 4, 128),
|
| 52 |
-
nn.ReLU(),
|
| 53 |
-
nn.Linear(128, 2)
|
| 54 |
-
)
|
| 55 |
-
return model.to(DEVICE).eval()
|
| 56 |
-
|
| 57 |
-
model_3dcnn = build_3dcnn()
|
| 58 |
-
|
| 59 |
|
| 60 |
# =========================
|
| 61 |
-
#
|
| 62 |
# =========================
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
image = cv2.resize(image, (128, 128))
|
| 67 |
-
image = image / 255.0
|
| 68 |
-
image = np.expand_dims(image, axis=0)
|
| 69 |
-
return image
|
| 70 |
|
|
|
|
| 71 |
|
| 72 |
# =========================
|
| 73 |
-
#
|
| 74 |
# =========================
|
| 75 |
-
def
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
f.write(file_bytes)
|
| 79 |
-
|
| 80 |
-
volume = nib.load(temp_path).get_fdata()
|
| 81 |
-
volume = np.squeeze(volume)
|
| 82 |
-
|
| 83 |
-
if len(volume.shape) == 2:
|
| 84 |
-
volume = np.stack([volume] * 32, axis=-1)
|
| 85 |
|
| 86 |
-
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
sl = volume[:, :, i]
|
| 91 |
-
sl = cv2.resize(sl, (64, 64))
|
| 92 |
-
slices.append(sl)
|
| 93 |
|
| 94 |
-
vol = np.stack(slices, axis=0)
|
| 95 |
-
vol = np.expand_dims(vol, axis=0)
|
| 96 |
-
vol = np.expand_dims(vol, axis=0)
|
| 97 |
-
|
| 98 |
-
return torch.tensor(vol, dtype=torch.float32).to(DEVICE)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
# =========================
|
| 102 |
-
# KERAS SINGLE PREDICT
|
| 103 |
# =========================
|
| 104 |
-
|
| 105 |
-
pred = model.predict(x, verbose=0)[0]
|
| 106 |
-
return pred
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
# =========================
|
| 110 |
-
# ENSEMBLE LOGIC (4 MODELS)
|
| 111 |
# =========================
|
| 112 |
def ensemble_predict(image_bytes):
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
|
|
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
p4 = predict_keras(model_fixed, x)
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
-
avg = np.mean(
|
| 124 |
|
| 125 |
cls = int(np.argmax(avg))
|
| 126 |
-
|
| 127 |
|
| 128 |
return {
|
| 129 |
"prediction": LABELS[cls],
|
| 130 |
"class_id": cls,
|
| 131 |
-
"confidence": round(
|
| 132 |
-
|
| 133 |
-
"model_confidences": {
|
| 134 |
-
"DenseNet121": round(float(np.max(p1)) * 100, 2),
|
| 135 |
-
"DenseNet169": round(float(np.max(p2)) * 100, 2),
|
| 136 |
-
"DenseNet201": round(float(np.max(p3)) * 100, 2),
|
| 137 |
-
"Fixed121": round(float(np.max(p4)) * 100, 2),
|
| 138 |
-
},
|
| 139 |
-
|
| 140 |
"probabilities": {
|
| 141 |
LABELS[i]: round(float(avg[i]) * 100, 2)
|
| 142 |
-
for i in range(
|
| 143 |
-
}
|
|
|
|
| 144 |
}
|
| 145 |
|
| 146 |
-
|
| 147 |
# =========================
|
| 148 |
-
#
|
| 149 |
# =========================
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
|
| 160 |
return {
|
| 161 |
"prediction": LABELS[cls],
|
| 162 |
-
"
|
| 163 |
-
"confidence": round(confidence, 2),
|
| 164 |
"probabilities": {
|
| 165 |
-
LABELS[i]:
|
| 166 |
-
for i in range(
|
| 167 |
}
|
| 168 |
}
|
| 169 |
|
| 170 |
-
|
| 171 |
# =========================
|
| 172 |
-
#
|
| 173 |
# =========================
|
| 174 |
-
@app.get("/")
|
| 175 |
-
def home():
|
| 176 |
-
return {
|
| 177 |
-
"status": "running",
|
| 178 |
-
"models": ["121", "169", "201", "fixed", "3dcnn"]
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
|
| 182 |
@app.post("/predict")
|
| 183 |
async def predict(file: UploadFile = File(...)):
|
| 184 |
image_bytes = await file.read()
|
| 185 |
return ensemble_predict(image_bytes)
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
return {"model": "169", "prob": predict_keras(model_169, x).tolist()}
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
@app.post("/predict/201")
|
| 201 |
-
async def p201(file: UploadFile = File(...)):
|
| 202 |
-
x = preprocess_2d(await file.read())
|
| 203 |
-
return {"model": "201", "prob": predict_keras(model_201, x).tolist()}
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
@app.post("/predict/3d")
|
| 207 |
-
async def p3d(file: UploadFile = File(...)):
|
| 208 |
-
return predict_3d(await file.read())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
import torchvision.models as models
|
|
|
|
| 4 |
from fastapi import FastAPI, UploadFile, File
|
| 5 |
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
import torchvision.transforms as transforms
|
| 8 |
+
import numpy as np
|
| 9 |
+
import tensorflow as tf
|
| 10 |
|
| 11 |
+
app = FastAPI(title="Alzheimer Ensemble API")
|
| 12 |
|
| 13 |
+
DEVICE = torch.device("cpu")
|
| 14 |
|
| 15 |
# =========================
|
| 16 |
+
# LABELS
|
| 17 |
# =========================
|
| 18 |
+
LABELS = [
|
| 19 |
+
"Mild Demented",
|
| 20 |
+
"Moderate Demented",
|
| 21 |
+
"Non Demented",
|
| 22 |
+
"Very Mild Demented"
|
| 23 |
+
]
|
| 24 |
|
| 25 |
# =========================
|
| 26 |
+
# TRANSFORM
|
| 27 |
# =========================
|
| 28 |
+
transform = transforms.Compose([
|
| 29 |
+
transforms.Resize((224, 224)),
|
| 30 |
+
transforms.ToTensor(),
|
| 31 |
+
transforms.Normalize([0.5]*3, [0.5]*3)
|
| 32 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# =========================
|
| 35 |
+
# SAFE KERAS LOADER
|
| 36 |
# =========================
|
| 37 |
+
def load_keras_model(path):
|
| 38 |
+
try:
|
| 39 |
+
return tf.keras.models.load_model(path, compile=False)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print("Keras load failed:", path, e)
|
| 42 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# =========================
|
| 45 |
+
# LOAD MODELS
|
| 46 |
# =========================
|
| 47 |
+
model_121 = load_keras_model("densenet121_parkinsonsDATSCAN.keras")
|
| 48 |
+
model_169 = load_keras_model("parkinsons_densenet169DATSCAN.keras")
|
| 49 |
+
model_201 = load_keras_model("parkinsons_densenet201DATSCAN.keras")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
models_list = [model_121, model_169, model_201]
|
| 52 |
|
| 53 |
# =========================
|
| 54 |
+
# SINGLE PREDICTION (KERAS SAFE)
|
| 55 |
# =========================
|
| 56 |
+
def predict_single(model, image_tensor):
|
| 57 |
+
if model is None:
|
| 58 |
+
return np.zeros(len(LABELS))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
img = image_tensor.permute(0, 2, 3, 1).numpy()
|
| 61 |
|
| 62 |
+
preds = model.predict(img, verbose=0)[0]
|
| 63 |
+
return preds
|
|
|
|
|
|
|
|
|
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
# =========================
|
| 66 |
+
# ENSEMBLE PREDICTION
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
# =========================
|
| 68 |
def ensemble_predict(image_bytes):
|
| 69 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 70 |
+
image = transform(image).unsqueeze(0)
|
| 71 |
|
| 72 |
+
preds_all = []
|
| 73 |
+
model_confidence_report = []
|
| 74 |
|
| 75 |
+
for i, m in enumerate(models_list):
|
| 76 |
+
preds = predict_single(m, image)
|
| 77 |
+
preds_all.append(preds)
|
|
|
|
| 78 |
|
| 79 |
+
model_confidence_report.append({
|
| 80 |
+
"model": f"model_{i+1}",
|
| 81 |
+
"confidence": float(np.max(preds)),
|
| 82 |
+
"prediction": LABELS[int(np.argmax(preds))]
|
| 83 |
+
})
|
| 84 |
|
| 85 |
+
avg = np.mean(preds_all, axis=0)
|
| 86 |
|
| 87 |
cls = int(np.argmax(avg))
|
| 88 |
+
conf = float(np.max(avg))
|
| 89 |
|
| 90 |
return {
|
| 91 |
"prediction": LABELS[cls],
|
| 92 |
"class_id": cls,
|
| 93 |
+
"confidence": round(conf * 100, 2),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
"probabilities": {
|
| 95 |
LABELS[i]: round(float(avg[i]) * 100, 2)
|
| 96 |
+
for i in range(len(LABELS))
|
| 97 |
+
},
|
| 98 |
+
"model_breakdown": model_confidence_report
|
| 99 |
}
|
| 100 |
|
|
|
|
| 101 |
# =========================
|
| 102 |
+
# INDIVIDUAL ENDPOINTS
|
| 103 |
# =========================
|
| 104 |
+
@app.post("/predict/121")
|
| 105 |
+
async def predict_121(file: UploadFile = File(...)):
|
| 106 |
+
img = await file.read()
|
| 107 |
+
return ensemble_predict_single(img, model_121)
|
| 108 |
|
| 109 |
+
@app.post("/predict/169")
|
| 110 |
+
async def predict_169(file: UploadFile = File(...)):
|
| 111 |
+
img = await file.read()
|
| 112 |
+
return ensemble_predict_single(img, model_169)
|
| 113 |
+
|
| 114 |
+
@app.post("/predict/201")
|
| 115 |
+
async def predict_201(file: UploadFile = File(...)):
|
| 116 |
+
img = await file.read()
|
| 117 |
+
return ensemble_predict_single(img, model_201)
|
| 118 |
+
|
| 119 |
+
# helper
|
| 120 |
+
def ensemble_predict_single(image_bytes, model):
|
| 121 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 122 |
+
image = transform(image).unsqueeze(0)
|
| 123 |
|
| 124 |
+
preds = predict_single(model, image)
|
| 125 |
+
cls = int(np.argmax(preds))
|
| 126 |
|
| 127 |
return {
|
| 128 |
"prediction": LABELS[cls],
|
| 129 |
+
"confidence": float(np.max(preds)),
|
|
|
|
| 130 |
"probabilities": {
|
| 131 |
+
LABELS[i]: float(preds[i])
|
| 132 |
+
for i in range(len(LABELS))
|
| 133 |
}
|
| 134 |
}
|
| 135 |
|
|
|
|
| 136 |
# =========================
|
| 137 |
+
# ENSEMBLE ENDPOINT
|
| 138 |
# =========================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
@app.post("/predict")
|
| 140 |
async def predict(file: UploadFile = File(...)):
|
| 141 |
image_bytes = await file.read()
|
| 142 |
return ensemble_predict(image_bytes)
|
| 143 |
|
| 144 |
+
# =========================
|
| 145 |
+
# HEALTH CHECK
|
| 146 |
+
# =========================
|
| 147 |
+
@app.get("/")
|
| 148 |
+
def home():
|
| 149 |
+
return {
|
| 150 |
+
"status": "running",
|
| 151 |
+
"models": ["121", "169", "201"],
|
| 152 |
+
"ensemble": True
|
| 153 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|