Spaces:
Sleeping

Sefat33 commited on
Commit
54f344b
·
verified ·
1 Parent(s): 7aff35b

Upload 8 files

Browse files
Model/fingerprint.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9953825059184fe007e2c9736927429e377cd692a0f840cc6e24ba748c895f79
3
+ size 57
Model/keras_metadata.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a4f36415fa9941d78d3b60316905ec57d277111bc01478b1eb3701607be9058
3
+ size 468849
Model/saved_model.pb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce6c187f89aa569d702f759f953118fd03188c65220356c5d7b20b92481d5c53
3
+ size 4701272
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import cv2
4
+ import tensorflow as tf
5
+ import streamlit as st
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib.cm as cm
8
+ from lime import lime_image
9
+ from skimage.segmentation import mark_boundaries
10
+ from keras.models import load_model as keras_load_model
11
+ from keras.layers import BatchNormalization, DepthwiseConv2D, TFSMLayer
12
+
13
+ # --- Fix deserialization issues ---
14
+ original_bn_from_config = BatchNormalization.from_config
15
+ def patched_bn_from_config(cls, config, *args, **kwargs):
16
+ if "axis" in config and isinstance(config["axis"], (list, tuple)):
17
+ config["axis"] = config["axis"][0]
18
+ return original_bn_from_config(config, *args, **kwargs)
19
+ BatchNormalization.from_config = classmethod(patched_bn_from_config)
20
+
21
+ original_dwconv_from_config = DepthwiseConv2D.from_config
22
+ def patched_dwconv_from_config(cls, config, *args, **kwargs):
23
+ if "groups" in config:
24
+ config.pop("groups")
25
+ return original_dwconv_from_config(config, *args, **kwargs)
26
+ DepthwiseConv2D.from_config = classmethod(patched_dwconv_from_config)
27
+
28
+ # --- Constants ---
29
+ IMG_SIZE = (224, 224)
30
+ CLASS_NAMES = ['Normal', 'Diabetes', 'Glaucoma', 'Cataract', 'AMD', 'Hypertension', 'Myopia', 'Others']
31
+ gradcam_enabled = False # Default to False
32
+
33
+ # --- Load model auto-detect ---
34
+ @st.cache_resource
35
+ def load_model_auto(path="Model"):
36
+ global gradcam_enabled
37
+ if not os.path.exists(path):
38
+ st.error(f"❌ Model path '{path}' not found!")
39
+ st.stop()
40
+
41
+ try:
42
+ if os.path.isdir(path):
43
+ model = tf.keras.Sequential([TFSMLayer(path, call_endpoint="serving_default")])
44
+ gradcam_enabled = False
45
+ elif path.endswith(('.keras', '.h5')):
46
+ model = keras_load_model(path)
47
+ gradcam_enabled = True
48
+ else:
49
+ raise ValueError("Unsupported model format. Use .keras, .h5 or SavedModel folder.")
50
+ return model
51
+ except Exception as e:
52
+ st.error(f"❌ Error loading model: {str(e)}")
53
+ st.stop()
54
+
55
+ # --- Preprocessing with visualization ---
56
+ def preprocess_and_show_steps(img):
57
+ h, w = img.shape[:2]
58
+ center = (w // 2, h // 2)
59
+ radius = min(center[0], center[1])
60
+ Y, X = np.ogrid[:h, :w]
61
+ dist = np.sqrt((X - center[0]) ** 2 + (Y - center[1]) ** 2)
62
+ mask = dist <= radius
63
+ circ = cv2.bitwise_and(img, img, mask=mask.astype(np.uint8))
64
+
65
+ lab = cv2.cvtColor(circ, cv2.COLOR_RGB2LAB)
66
+ l, a, b = cv2.split(lab)
67
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
68
+ cl = clahe.apply(l)
69
+ merged = cv2.merge((cl, a, b))
70
+ clahe_img = cv2.cvtColor(merged, cv2.COLOR_LAB2RGB)
71
+
72
+ blur = cv2.GaussianBlur(clahe_img, (0, 0), 10)
73
+ sharp = cv2.addWeighted(clahe_img, 4, blur, -4, 128)
74
+
75
+ resized = cv2.resize(sharp, IMG_SIZE) / 255.0
76
+
77
+ fig, axs = plt.subplots(1, 4, figsize=(20, 5))
78
+ axs[0].imshow(img)
79
+ axs[0].set_title("Original")
80
+ axs[1].imshow(circ)
81
+ axs[1].set_title("Circular Crop")
82
+ axs[2].imshow(clahe_img)
83
+ axs[2].set_title("CLAHE")
84
+ axs[3].imshow(resized)
85
+ axs[3].set_title("Sharpened + Resize")
86
+ for ax in axs:
87
+ ax.axis("off")
88
+ st.pyplot(fig)
89
+ plt.close()
90
+
91
+ return resized
92
+
93
+ # --- Grad-CAM ---
94
+ def find_last_conv_layer(model):
95
+ for layer in reversed(model.layers):
96
+ if isinstance(layer, tf.keras.layers.Conv2D):
97
+ return layer.name
98
+ return None
99
+
100
+ def generate_gradcam(model, img_array, class_index, layer_name):
101
+ grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(layer_name).output, model.output])
102
+ with tf.GradientTape() as tape:
103
+ conv_outputs, predictions = grad_model(img_array)
104
+ loss = predictions[:, class_index]
105
+ grads = tape.gradient(loss, conv_outputs)
106
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
107
+ conv_outputs = conv_outputs[0]
108
+ heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]
109
+ heatmap = tf.squeeze(heatmap)
110
+ heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
111
+ return heatmap.numpy()
112
+
113
+ # --- LIME Explainer ---
114
+ explainer = lime_image.LimeImageExplainer()
115
+ def predict_fn(images):
116
+ images = np.array(images)
117
+ preds = model.predict(images, verbose=0)
118
+ if isinstance(preds, dict):
119
+ preds = list(preds.values())[0]
120
+ return preds
121
+
122
+ # --- Explanation texts ---
123
+ explanation_text = {
124
+ 'Normal': "Model predicted Normal based on healthy optic disc and macula.",
125
+ 'Diabetes': "Detected retinal blood vessel changes suggestive of Diabetes.",
126
+ 'Glaucoma': "Detected increased cupping in the optic disc indicating Glaucoma.",
127
+ 'Cataract': "Image blur indicated potential Cataract.",
128
+ 'AMD': "Degeneration signs in macula indicate AMD.",
129
+ 'Hypertension': "Blood vessel narrowing/hemorrhages indicate Hypertension.",
130
+ 'Myopia': "Tilted disc and fundus shape suggest Myopia.",
131
+ 'Others': "Non-specific features detected, marked as Others."
132
+ }
133
+
134
+ # --- Display explanations ---
135
+ def display_explanations(img, input_array, pred_label, pred_idx):
136
+ overlayed = None
137
+ if gradcam_enabled:
138
+ try:
139
+ conv_layer = find_last_conv_layer(model)
140
+ if conv_layer:
141
+ heatmap = generate_gradcam(model, input_array, pred_idx, conv_layer)
142
+ heatmap = cv2.resize(heatmap, IMG_SIZE)
143
+ heatmap = cv2.GaussianBlur(np.uint8(255 * heatmap), (7, 7), 0)
144
+ heatmap_rgb = np.uint8(cm.jet(heatmap / 255.0)[..., :3] * 255)
145
+ overlayed = cv2.addWeighted(np.uint8(img * 255), 0.5, heatmap_rgb, 0.5, 0)
146
+ except Exception as e:
147
+ st.warning(f"⚠️ Grad-CAM failed: {e}")
148
+ else:
149
+ st.info("ℹ️ Grad-CAM is disabled for this model.")
150
+
151
+ explanation = explainer.explain_instance(img, classifier_fn=predict_fn, top_labels=1, hide_color=0, num_samples=1000)
152
+ temp, mask = explanation.get_image_and_mask(label=pred_idx, positive_only=True, num_features=10, hide_rest=False)
153
+
154
+ fig, axs = plt.subplots(1, 3 if overlayed is not None else 2, figsize=(15, 5))
155
+ axs[0].imshow(img)
156
+ axs[0].set_title("Original")
157
+ axs[1].imshow(mark_boundaries(temp, mask))
158
+ axs[1].set_title("LIME Explanation")
159
+ if overlayed is not None:
160
+ axs[2].imshow(overlayed)
161
+ axs[2].set_title("Grad-CAM")
162
+ for ax in axs:
163
+ ax.axis('off')
164
+
165
+ summary = explanation_text.get(pred_label, "Model detected features matching this class.")
166
+ plt.figtext(0.5, 0.01, summary, wrap=True, ha='center', fontsize=10)
167
+ st.pyplot(fig)
168
+ plt.close()
169
+
170
+ # --- Probability chart ---
171
+ def plot_probabilities(probs, class_names):
172
+ fig, ax = plt.subplots(figsize=(8, 4))
173
+ bars = ax.barh(class_names, probs * 100, color='skyblue')
174
+ ax.set_xlim(0, 100)
175
+ ax.set_xlabel("Confidence (%)")
176
+ ax.set_title("Prediction Probabilities")
177
+ for bar, prob in zip(bars, probs):
178
+ ax.text(prob * 100 + 1, bar.get_y() + bar.get_height()/2, f"{prob*100:.1f}%", va='center')
179
+ st.pyplot(fig)
180
+ plt.close()
181
+
182
+ # --- Streamlit UI ---
183
+ st.set_page_config(page_title="🧠 Retina Disease Classifier", layout="centered")
184
+ st.title("🧠 Retina Disease Classifier with Grad-CAM & LIME")
185
+
186
+ # Load model
187
+ model = load_model_auto("Model") # Folder or .keras/.h5 file
188
+
189
+ # Upload image
190
+ uploaded_file = st.file_uploader("📤 Upload a retinal image", type=["jpg", "jpeg", "png"])
191
+ if uploaded_file:
192
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
193
+ bgr_img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
194
+ rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
195
+
196
+ processed_img = preprocess_and_show_steps(rgb_img)
197
+ input_tensor = np.expand_dims(processed_img, axis=0)
198
+
199
+ preds = predict_fn(input_tensor)
200
+ pred_idx = np.argmax(preds)
201
+ pred_label = CLASS_NAMES[pred_idx]
202
+ confidence = np.max(preds) * 100
203
+
204
+ st.success(f"✅ Prediction: **{pred_label}** with confidence {confidence:.2f}%")
205
+ plot_probabilities(preds[0], CLASS_NAMES)
206
+
207
+ display_explanations(processed_img, input_tensor, pred_label, pred_idx)
logs/feedback_log.csv ADDED
File without changes
preprocessing/preprocess.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import cv2
3
+ import numpy as np
4
+
5
+ def crop_circle(img):
6
+ h, w = img.shape[:2]
7
+ center = (w // 2, h // 2)
8
+ radius = min(center[0], center[1])
9
+ Y, X = np.ogrid[:h, :w]
10
+ dist = np.sqrt((X - center[0]) ** 2 + (Y - center[1]) ** 2)
11
+ mask = dist <= radius
12
+ if img.ndim == 3:
13
+ mask = np.stack([mask] * 3, axis=-1)
14
+ img[~mask] = 0
15
+ return img
16
+
17
+ def apply_clahe(img):
18
+ lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
19
+ l, a, b = cv2.split(lab)
20
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
21
+ cl = clahe.apply(l)
22
+ merged = cv2.merge((cl, a, b))
23
+ return cv2.cvtColor(merged, cv2.COLOR_LAB2RGB)
24
+
25
+ def sharpen_image(img, sigma=10):
26
+ blur = cv2.GaussianBlur(img, (0, 0), sigma)
27
+ return cv2.addWeighted(img, 4, blur, -4, 128)
28
+
29
+ def resize_normalize(img, size=(224, 224)):
30
+ img = cv2.resize(img, size)
31
+ img = img / 255.0
32
+ return img
33
+
34
+ def preprocess_image(image):
35
+ img = np.array(image)
36
+ img = crop_circle(img)
37
+ img = apply_clahe(img)
38
+ img = sharpen_image(img)
39
+ img = resize_normalize(img)
40
+ return img.astype(np.float32)
utils/gradcam.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ import cv2
5
+ import matplotlib.cm as cm
6
+
7
+ def find_last_conv_layer(model):
8
+ for layer in reversed(model.layers):
9
+ if isinstance(layer, tf.keras.layers.Conv2D) or 'mhsa_output' in layer.name:
10
+ return layer.name
11
+ raise ValueError("No suitable conv layer found.")
12
+
13
+ def generate_gradcam(model, img_array):
14
+ layer_name = find_last_conv_layer(model)
15
+ grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(layer_name).output, model.output])
16
+ with tf.GradientTape() as tape:
17
+ conv_outputs, predictions = grad_model(tf.expand_dims(img_array, axis=0))
18
+ loss = predictions[:, tf.argmax(predictions[0])]
19
+ grads = tape.gradient(loss, conv_outputs)
20
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
21
+ heatmap = conv_outputs[0] @ pooled_grads[..., tf.newaxis]
22
+ heatmap = tf.squeeze(heatmap)
23
+ heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
24
+ heatmap = cv2.resize(heatmap.numpy(), (224, 224))
25
+ heatmap = np.uint8(255 * heatmap)
26
+ heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
27
+ superimposed_img = cv2.addWeighted(np.uint8(img_array * 255), 0.5, heatmap, 0.5, 0)
28
+ return superimposed_img
utils/lime_explainer.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import numpy as np
3
+ from lime import lime_image
4
+ from skimage.segmentation import mark_boundaries
5
+
6
+ explainer = lime_image.LimeImageExplainer()
7
+
8
+ def explain_with_lime(model, img_array):
9
+ def predict_fn(images): return model.predict(np.array(images), verbose=0)
10
+ explanation = explainer.explain_instance(
11
+ image=img_array,
12
+ classifier_fn=predict_fn,
13
+ top_labels=1,
14
+ hide_color=0,
15
+ num_samples=1000
16
+ )
17
+ temp, mask = explanation.get_image_and_mask(
18
+ label=explanation.top_labels[0],
19
+ positive_only=True,
20
+ num_features=10,
21
+ hide_rest=False
22
+ )
23
+ return mark_boundaries(temp, mask)