Update app.py
Browse files
app.py
CHANGED
|
@@ -10,20 +10,17 @@ from keras.layers import BatchNormalization, DepthwiseConv2D, TFSMLayer
|
|
| 10 |
|
| 11 |
# --- Fix deserialization issues ---
|
| 12 |
original_bn = BatchNormalization.from_config
|
| 13 |
-
BatchNormalization.from_config = classmethod(
|
| 14 |
-
|
| 15 |
-
)
|
| 16 |
original_dw = DepthwiseConv2D.from_config
|
| 17 |
-
DepthwiseConv2D.from_config = classmethod(
|
| 18 |
-
lambda cls, config, *a, **k: original_dw({k: v for k, v in config.items() if k != "groups"}, *a, **k)
|
| 19 |
-
)
|
| 20 |
|
| 21 |
# --- Constants ---
|
| 22 |
IMG_SIZE = (224, 224)
|
| 23 |
CLASS_NAMES = ['Normal', 'Diabetes', 'Glaucoma', 'Cataract', 'AMD', 'Hypertension', 'Myopia', 'Others']
|
| 24 |
LIME_EXPLAINER = lime_image.LimeImageExplainer()
|
| 25 |
|
| 26 |
-
# --- Load model ---
|
| 27 |
@st.cache_resource
|
| 28 |
def load_model():
|
| 29 |
model_path = "Model"
|
|
@@ -31,17 +28,18 @@ def load_model():
|
|
| 31 |
st.error(f"Model folder '{model_path}' not found.")
|
| 32 |
st.stop()
|
| 33 |
try:
|
| 34 |
-
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
st.error(f"Error loading model: {e}")
|
| 37 |
st.stop()
|
| 38 |
|
| 39 |
-
# ---
|
| 40 |
def preprocess_with_steps(img):
|
| 41 |
h, w = img.shape[:2]
|
| 42 |
center, radius = (w // 2, h // 2), min(w, h) // 2
|
| 43 |
Y, X = np.ogrid[:h, :w]
|
| 44 |
-
dist = np.sqrt((X - center[0])**2 + (Y - center[1])**2)
|
| 45 |
mask = dist <= radius
|
| 46 |
circ = cv2.bitwise_and(img, img, mask=mask.astype(np.uint8))
|
| 47 |
|
|
@@ -62,13 +60,13 @@ def preprocess_with_steps(img):
|
|
| 62 |
st.pyplot(fig)
|
| 63 |
return resized
|
| 64 |
|
| 65 |
-
# --- Prediction ---
|
| 66 |
def predict(images, model):
|
| 67 |
images = np.array(images)
|
| 68 |
preds = model.predict(images, verbose=0)
|
| 69 |
return list(preds.values())[0] if isinstance(preds, dict) else preds
|
| 70 |
|
| 71 |
-
# --- LIME
|
| 72 |
def show_lime(img, model, pred_idx, pred_label):
|
| 73 |
with st.spinner("π‘ LIME explanation is loading..."):
|
| 74 |
explanation = LIME_EXPLAINER.explain_instance(
|
|
@@ -79,45 +77,41 @@ def show_lime(img, model, pred_idx, pred_label):
|
|
| 79 |
num_samples=1000
|
| 80 |
)
|
| 81 |
temp, mask = explanation.get_image_and_mask(label=pred_idx, positive_only=True, num_features=10, hide_rest=False)
|
| 82 |
-
return mark_boundaries(temp, mask)
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
st.title("π§ Retina Disease Classifier with LIME Explanation")
|
| 87 |
|
| 88 |
model = load_model()
|
| 89 |
|
| 90 |
with st.sidebar:
|
| 91 |
-
uploaded_files = st.file_uploader("π Upload
|
| 92 |
|
|
|
|
| 93 |
if uploaded_files:
|
| 94 |
-
#
|
| 95 |
-
for
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
bgr = cv2.imdecode(np.frombuffer(
|
| 99 |
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 100 |
|
| 101 |
-
st.subheader("π Preprocessing Steps")
|
| 102 |
-
|
| 103 |
-
input_tensor = np.expand_dims(preprocessed, axis=0)
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
confidence = np.max(preds) * 100
|
| 109 |
-
|
| 110 |
-
st.success(f"β
Prediction: **{pred_label}** ({confidence:.2f}%)")
|
| 111 |
-
|
| 112 |
-
lime_image_result = show_lime(preprocessed, model, pred_idx, pred_label)
|
| 113 |
-
st.image(lime_image_result, caption=f"LIME: {pred_label}", use_column_width=True)
|
| 114 |
-
|
| 115 |
-
# Grid view of LIME explanations
|
| 116 |
-
st.markdown("## π§ͺ All LIME Explanations (Grid View)")
|
| 117 |
cols = st.columns(min(4, len(uploaded_files)))
|
|
|
|
| 118 |
for i, file in enumerate(uploaded_files):
|
| 119 |
-
|
| 120 |
-
bgr = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
|
| 121 |
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 122 |
img = cv2.resize(rgb, IMG_SIZE) / 255.0
|
| 123 |
input_tensor = np.expand_dims(img, axis=0)
|
|
@@ -125,8 +119,17 @@ if uploaded_files:
|
|
| 125 |
preds = predict(input_tensor, model)
|
| 126 |
pred_idx = np.argmax(preds)
|
| 127 |
pred_label = CLASS_NAMES[pred_idx]
|
|
|
|
| 128 |
|
| 129 |
-
lime_img = show_lime(img, model, pred_idx, pred_label)
|
| 130 |
with cols[i % len(cols)]:
|
| 131 |
-
st.markdown(f"**{file.name}**<br>π§ *{pred_label}*", unsafe_allow_html=True)
|
| 132 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# --- Fix deserialization issues ---
|
| 12 |
original_bn = BatchNormalization.from_config
|
| 13 |
+
BatchNormalization.from_config = classmethod(lambda cls, config, *a, **k: original_bn(config if not isinstance(config.get("axis"), list) else {**config, "axis": config["axis"][0]}, *a, **k))
|
| 14 |
+
|
|
|
|
| 15 |
original_dw = DepthwiseConv2D.from_config
|
| 16 |
+
DepthwiseConv2D.from_config = classmethod(lambda cls, config, *a, **k: original_dw({k: v for k, v in config.items() if k != "groups"}, *a, **k))
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# --- Constants ---
|
| 19 |
IMG_SIZE = (224, 224)
|
| 20 |
CLASS_NAMES = ['Normal', 'Diabetes', 'Glaucoma', 'Cataract', 'AMD', 'Hypertension', 'Myopia', 'Others']
|
| 21 |
LIME_EXPLAINER = lime_image.LimeImageExplainer()
|
| 22 |
|
| 23 |
+
# --- Load model from TFSMLayer ---
|
| 24 |
@st.cache_resource
|
| 25 |
def load_model():
|
| 26 |
model_path = "Model"
|
|
|
|
| 28 |
st.error(f"Model folder '{model_path}' not found.")
|
| 29 |
st.stop()
|
| 30 |
try:
|
| 31 |
+
model = tf.keras.Sequential([TFSMLayer(model_path, call_endpoint="serving_default")])
|
| 32 |
+
return model
|
| 33 |
except Exception as e:
|
| 34 |
st.error(f"Error loading model: {e}")
|
| 35 |
st.stop()
|
| 36 |
|
| 37 |
+
# --- Preprocessing with Visualization ---
|
| 38 |
def preprocess_with_steps(img):
|
| 39 |
h, w = img.shape[:2]
|
| 40 |
center, radius = (w // 2, h // 2), min(w, h) // 2
|
| 41 |
Y, X = np.ogrid[:h, :w]
|
| 42 |
+
dist = np.sqrt((X - center[0]) ** 2 + (Y - center[1]) ** 2)
|
| 43 |
mask = dist <= radius
|
| 44 |
circ = cv2.bitwise_and(img, img, mask=mask.astype(np.uint8))
|
| 45 |
|
|
|
|
| 60 |
st.pyplot(fig)
|
| 61 |
return resized
|
| 62 |
|
| 63 |
+
# --- Prediction Function ---
|
| 64 |
def predict(images, model):
|
| 65 |
images = np.array(images)
|
| 66 |
preds = model.predict(images, verbose=0)
|
| 67 |
return list(preds.values())[0] if isinstance(preds, dict) else preds
|
| 68 |
|
| 69 |
+
# --- LIME Visualization ---
|
| 70 |
def show_lime(img, model, pred_idx, pred_label):
|
| 71 |
with st.spinner("π‘ LIME explanation is loading..."):
|
| 72 |
explanation = LIME_EXPLAINER.explain_instance(
|
|
|
|
| 77 |
num_samples=1000
|
| 78 |
)
|
| 79 |
temp, mask = explanation.get_image_and_mask(label=pred_idx, positive_only=True, num_features=10, hide_rest=False)
|
|
|
|
| 80 |
|
| 81 |
+
fig, ax = plt.subplots(1, 1, figsize=(6, 5))
|
| 82 |
+
ax.imshow(mark_boundaries(temp, mask))
|
| 83 |
+
ax.set_title(f"LIME Explanation: {pred_label}")
|
| 84 |
+
ax.axis("off")
|
| 85 |
+
st.pyplot(fig)
|
| 86 |
+
|
| 87 |
+
# --- Streamlit UI ---
|
| 88 |
+
st.set_page_config(page_title="π§ Retina Classifier - Multi Image LIME", layout="wide")
|
| 89 |
st.title("π§ Retina Disease Classifier with LIME Explanation")
|
| 90 |
|
| 91 |
model = load_model()
|
| 92 |
|
| 93 |
with st.sidebar:
|
| 94 |
+
uploaded_files = st.file_uploader("π Upload retinal images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
|
| 95 |
|
| 96 |
+
# -- Optional: Show preprocessing for any selected image --
|
| 97 |
if uploaded_files:
|
| 98 |
+
st.markdown("## π§ͺ View Preprocessing of a Selected Image")
|
| 99 |
+
selected_file_name = st.selectbox("Select an image to view preprocessing", [f.name for f in uploaded_files])
|
| 100 |
+
if selected_file_name:
|
| 101 |
+
selected_file = next(f for f in uploaded_files if f.name == selected_file_name)
|
| 102 |
+
bgr = cv2.imdecode(np.frombuffer(selected_file.read(), np.uint8), cv2.IMREAD_COLOR)
|
| 103 |
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 104 |
|
| 105 |
+
st.subheader(f"π Preprocessing Steps for {selected_file_name}")
|
| 106 |
+
_ = preprocess_with_steps(rgb)
|
|
|
|
| 107 |
|
| 108 |
+
# -- Predict & Show LIME for All Uploaded Images --
|
| 109 |
+
if uploaded_files:
|
| 110 |
+
st.markdown("## π§ͺ Predictions and LIME Explanations for All Images")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
cols = st.columns(min(4, len(uploaded_files)))
|
| 112 |
+
|
| 113 |
for i, file in enumerate(uploaded_files):
|
| 114 |
+
bgr = cv2.imdecode(np.frombuffer(file.read(), np.uint8), cv2.IMREAD_COLOR)
|
|
|
|
| 115 |
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
| 116 |
img = cv2.resize(rgb, IMG_SIZE) / 255.0
|
| 117 |
input_tensor = np.expand_dims(img, axis=0)
|
|
|
|
| 119 |
preds = predict(input_tensor, model)
|
| 120 |
pred_idx = np.argmax(preds)
|
| 121 |
pred_label = CLASS_NAMES[pred_idx]
|
| 122 |
+
confidence = np.max(preds) * 100
|
| 123 |
|
|
|
|
| 124 |
with cols[i % len(cols)]:
|
| 125 |
+
st.markdown(f"**{file.name}**<br>π§ *{pred_label}* ({confidence:.2f}%)", unsafe_allow_html=True)
|
| 126 |
+
with st.spinner("π‘ LIME explanation is loading..."):
|
| 127 |
+
explanation = LIME_EXPLAINER.explain_instance(
|
| 128 |
+
image=img,
|
| 129 |
+
classifier_fn=lambda imgs: predict(imgs, model),
|
| 130 |
+
top_labels=1,
|
| 131 |
+
hide_color=0,
|
| 132 |
+
num_samples=1000
|
| 133 |
+
)
|
| 134 |
+
temp, mask = explanation.get_image_and_mask(label=pred_idx, positive_only=True, num_features=10, hide_rest=False)
|
| 135 |
+
st.image(mark_boundaries(temp, mask), use_column_width=True)
|