import os import numpy as np import cv2 import tensorflow as tf import streamlit as st import matplotlib.pyplot as plt import matplotlib.cm as cm from lime import lime_image from skimage.segmentation import mark_boundaries from keras.models import load_model as keras_load_model # Constants IMG_SIZE = (224, 224) CLASS_NAMES = ['Normal', 'Diabetes', 'Glaucoma', 'Cataract', 'AMD', 'Hypertension', 'Myopia', 'Others'] @st.cache_resource def load_savedmodel_model(model_dir): if os.path.isdir(model_dir): try: model = tf.keras.models.load_model(model_dir) return model except Exception as e: st.error(f"Error loading SavedModel: {e}") st.stop() else: st.error("Please provide a valid SavedModel directory path.") st.stop() @st.cache_resource def load_keras_model(model_path): if model_path.endswith(".keras") and os.path.isfile(model_path): try: model = keras_load_model(model_path) return model except Exception as e: st.error(f"Error loading .keras model: {e}") st.stop() else: st.error("Please provide a valid .keras model file path.") st.stop() def find_last_conv_layer(model): for layer in reversed(model.layers): if isinstance(layer, tf.keras.layers.Conv2D): return layer.name return None def generate_gradcam(model, img_array, class_index, layer_name): grad_model = tf.keras.models.Model( [model.inputs], [model.get_layer(layer_name).output, model.output] ) with tf.GradientTape() as tape: conv_outputs, predictions = grad_model(img_array) loss = predictions[:, class_index] grads = tape.gradient(loss, conv_outputs) pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) conv_outputs = conv_outputs[0] heatmap = conv_outputs @ pooled_grads[..., tf.newaxis] heatmap = tf.squeeze(heatmap) heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap) return heatmap.numpy() def preprocess_image(img): img = cv2.resize(img, IMG_SIZE) img = img / 255.0 return img explainer = lime_image.LimeImageExplainer() def predict_fn(images, model): images = np.array(images) preds = model.predict(images) if isinstance(preds, dict): preds = list(preds.values())[0] return preds def display_results(img, input_tensor, pred_label, pred_idx, gradcam_model): conv_layer = find_last_conv_layer(gradcam_model) overlayed = None if conv_layer: heatmap = generate_gradcam(gradcam_model, input_tensor, pred_idx, conv_layer) heatmap = cv2.resize(heatmap, IMG_SIZE) heatmap = cv2.GaussianBlur(np.uint8(255 * heatmap), (7, 7), 0) heatmap_rgb = np.uint8(cm.jet(heatmap / 255.0)[..., :3] * 255) overlayed = cv2.addWeighted(np.uint8(img * 255), 0.5, heatmap_rgb, 0.5, 0) explanation = explainer.explain_instance( image=img, classifier_fn=lambda x: predict_fn(x, gradcam_model), top_labels=1, hide_color=0, num_samples=1000 ) temp, mask = explanation.get_image_and_mask(label=pred_idx, positive_only=True, num_features=10, hide_rest=False) fig, axs = plt.subplots(1, 3 if overlayed is not None else 2, figsize=(15, 5)) axs[0].imshow(img) axs[0].set_title("Original") axs[1].imshow(mark_boundaries(temp, mask)) axs[1].set_title("LIME Explanation") if overlayed is not None: axs[2].imshow(overlayed) axs[2].set_title("Grad-CAM Overlay") for ax in axs: ax.axis('off') st.pyplot(fig) plt.close() # Streamlit UI st.title("🧠 Retina Disease Classifier with Grad-CAM & LIME") savedmodel_dir = st.text_input("Enter path to your SavedModel directory (for prediction):", value="path_to_saved_model") keras_model_path = st.text_input("Enter path to your converted .keras model (for Grad-CAM & LIME):", value="converted_model.keras") if savedmodel_dir and keras_model_path: pred_model = load_savedmodel_model(savedmodel_dir) gradcam_model = load_keras_model(keras_model_path) uploaded_file = st.file_uploader( "Upload a retinal image", type=["jpg", "jpeg", "png"], help="Drag and drop file here\nLimit 200MB per file • JPG, JPEG, PNG" ) if uploaded_file: file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8) img_bgr = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) processed_img = preprocess_image(img_rgb) input_tensor = np.expand_dims(processed_img, axis=0) # Prediction with SavedModel preds = pred_model.predict(input_tensor) if isinstance(preds, dict): preds = list(preds.values())[0] pred_idx = np.argmax(preds) pred_label = CLASS_NAMES[pred_idx] confidence = np.max(preds) * 100 st.success(f"Prediction: **{pred_label}** ({confidence:.2f}%)") # Grad-CAM & LIME with keras model display_results(processed_img, input_tensor, pred_label, pred_idx, gradcam_model)