Kaynaaf commited on
Commit
ecfd876
·
verified ·
1 Parent(s): b28a8e5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -0
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import matplotlib.pyplot as plt
3
+ import keras
4
+ from matplotlib.colors import LinearSegmentedColormap
5
+ from PIL import Image
6
+ import io
7
+ import glob
8
+ import os
9
+ import pickle
10
+ from tqdm import tqdm
11
+ import numpy as np
12
+ with open('model.pkl', 'rb') as f:
13
+ model = pickle.load(f)
14
+ class_names = ['glioma', 'meningioma', 'notumor', 'pituitary']
15
+
16
+ def create_custom_colormap():
17
+ colors = [(0, 0, 0, 0), (1, 0, 0, 1)]
18
+ return LinearSegmentedColormap.from_list('custom', colors)
19
+
20
+
21
+ def create_custom_colormap():
22
+ colors = [(0, 0, 0, 0), (1, 0, 0, 1)]
23
+ return LinearSegmentedColormap.from_list('custom', colors)
24
+
25
+
26
+ def occlusion_sensitivity(model, img_array, class_index, patch_size=25, stride=5, occlusion_value=0, progress=gr.Progress()):
27
+
28
+
29
+ sensitivity_map = np.zeros((img_array.shape[0], img_array.shape[1]))
30
+ original_pred = model.predict(np.expand_dims(img_array, axis=0), verbose=0)[0]
31
+ original_prob = original_pred[class_index]
32
+
33
+ n_steps_h = (img_array.shape[0] - patch_size) // stride + 1
34
+ n_steps_w = (img_array.shape[1] - patch_size) // stride + 1
35
+ total_steps = n_steps_h * n_steps_w
36
+
37
+ current_step = 0
38
+
39
+ for h in range(n_steps_h):
40
+ for w in range(n_steps_w):
41
+ h_start = h * stride
42
+ w_start = w * stride
43
+ h_end = min(h_start + patch_size, img_array.shape[0])
44
+ w_end = min(w_start + patch_size, img_array.shape[1])
45
+
46
+ occluded_img = img_array.copy()
47
+ occluded_img[h_start:h_end, w_start:w_end, :] = occlusion_value
48
+
49
+ pred = model.predict(np.expand_dims(occluded_img, axis=0), verbose=0)[0]
50
+ prob = pred[class_index]
51
+
52
+ sensitivity = original_prob - prob
53
+ sensitivity_map[h_start:h_end, w_start:w_end] += sensitivity
54
+
55
+
56
+ current_step += 1
57
+ progress(current_step / total_steps, desc=f"Analyzing sensitivity: {current_step}/{total_steps}")
58
+
59
+ return sensitivity_map, original_prob
60
+
61
+
62
+ def create_sensitivity_visualizations(image, sensitivity_map, predicted_class, confidence):
63
+
64
+ # Original image
65
+ fig1, ax1 = plt.subplots(figsize=(6, 6))
66
+ ax1.imshow(image, cmap='gray')
67
+ ax1.set_title(f'Original Image\n{class_names[predicted_class]} ({confidence:.1%})', fontsize=12, fontweight='bold')
68
+ ax1.axis('off')
69
+ plt.tight_layout()
70
+ buf1 = io.BytesIO()
71
+ plt.savefig(buf1, format='png', dpi=150, bbox_inches='tight')
72
+ buf1.seek(0)
73
+ original_img = Image.open(buf1)
74
+ plt.close()
75
+
76
+ # Sensitivity map
77
+ fig2, ax2 = plt.subplots(figsize=(6, 6))
78
+ im2 = ax2.imshow(sensitivity_map, cmap='jet')
79
+ ax2.set_title('Sensitivity Map', fontsize=12, fontweight='bold')
80
+ ax2.axis('off')
81
+ plt.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04)
82
+ plt.tight_layout()
83
+ buf2 = io.BytesIO()
84
+ plt.savefig(buf2, format='png', dpi=150, bbox_inches='tight')
85
+ buf2.seek(0)
86
+ sensitivity_img = Image.open(buf2)
87
+ plt.close()
88
+
89
+ # Overlay
90
+ fig3, ax3 = plt.subplots(figsize=(6, 6))
91
+ ax3.imshow(image, cmap='gray')
92
+ custom_cmap = create_custom_colormap()
93
+ masked_sensitivity = np.ma.masked_where(sensitivity_map < 0.15, sensitivity_map)
94
+ im3 = ax3.imshow(masked_sensitivity, cmap=custom_cmap, alpha=0.6)
95
+ ax3.set_title('Overlay (Red = High Importance)', fontsize=12, fontweight='bold')
96
+ ax3.axis('off')
97
+ plt.colorbar(im3, ax=ax3, fraction=0.046, pad=0.04)
98
+ plt.tight_layout()
99
+ buf3 = io.BytesIO()
100
+ plt.savefig(buf3, format='png', dpi=150, bbox_inches='tight')
101
+ buf3.seek(0)
102
+ overlay_img = Image.open(buf3)
103
+ plt.close()
104
+
105
+ return original_img, sensitivity_img, overlay_img
106
+
107
+
108
+ def predict_and_visualize(image, patch_size=25, stride=5, progress=gr.Progress()):
109
+ if image is None:
110
+ return None, None, None, "⚠️ Please select or upload an image"
111
+
112
+ if not isinstance(image, Image.Image):
113
+ image = Image.fromarray(image)
114
+
115
+ image = image.convert('L')
116
+ image = image.resize((256, 256))
117
+ img_array = img_to_array(image) / 255.0
118
+
119
+ # Initial prediction
120
+
121
+ predictions = model.predict(np.expand_dims(img_array, axis=0), verbose=0)[0]
122
+ predicted_class = np.argmax(predictions)
123
+ confidence = predictions[predicted_class]
124
+
125
+ pred_text = f"## 🎯 Prediction Results\n\n"
126
+ pred_text += f"### **Predicted Class:** {class_names[predicted_class].upper()}\n"
127
+ pred_text += f"### **Confidence:** {confidence:.2%}\n\n"
128
+ pred_text += "---\n\n"
129
+ pred_text += "### 📊 Class Probabilities:\n\n"
130
+
131
+ # Sort predictions by probability
132
+ sorted_indices = np.argsort(predictions)[::-1]
133
+ for i in sorted_indices:
134
+ bar = "█" * int(predictions[i] * 20)
135
+ pred_text += f"**{class_names[i].capitalize()}:** {predictions[i]:.2%} {bar}\n\n"
136
+
137
+ # Compute sensitivity map with progress tracking
138
+ sensitivity_map, _ = occlusion_sensitivity(
139
+ model, img_array, predicted_class,
140
+ patch_size=patch_size, stride=stride,
141
+ progress=progress
142
+ )
143
+
144
+ # Normalize sensitivity map
145
+
146
+ eps = 1e-9
147
+ sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (np.max(sensitivity_map) - np.min(sensitivity_map) + eps)
148
+
149
+ # Create visualizations
150
+ original_img, sensitivity_img, overlay_img = create_sensitivity_visualizations(
151
+ image, sensitivity_map, predicted_class, confidence
152
+ )
153
+
154
+ progress(1.0, desc="Complete!")
155
+ return original_img, sensitivity_img, overlay_img, pred_text
156
+
157
+
158
+ def get_example_images(examples_folder='examples/'):
159
+ """Get list of example images from the Examples folder"""
160
+ if not os.path.exists(examples_folder):
161
+ return []
162
+
163
+ image_paths = []
164
+ for ext in ['*.jpg', '*.jpeg', '*.png', '*.JPG', '*.JPEG', '*.PNG']:
165
+ image_paths.extend(glob.glob(os.path.join(examples_folder, ext)))
166
+
167
+ return sorted(image_paths)
168
+
169
+
170
+ def load_example_image(image_path):
171
+ """Load an image from the examples folder"""
172
+ if image_path:
173
+ return Image.open(image_path)
174
+ return None
175
+
176
+
177
+ with gr.Blocks(title="Brain MRI Tumor Classifier", theme=gr.themes.Default()) as demo:
178
+ gr.Markdown("""
179
+ # 🧠 Brain MRI Tumor Classifier with Occlusion Sensitivity
180
+
181
+ This application classifies brain MRI images into four categories and visualizes which regions
182
+ are most important for the classification decision.
183
+
184
+ **Classes:** Glioma • Meningioma • No Tumor • Pituitary
185
+ """)
186
+
187
+ with gr.Row():
188
+ # Left column - Input controls
189
+ with gr.Column(scale=1):
190
+ gr.Markdown("### 📁 Select or Upload Image")
191
+
192
+ # Example image selector
193
+ example_images = get_example_images('examples/')
194
+ if example_images:
195
+ example_dropdown = gr.Dropdown(
196
+ choices=example_images,
197
+ label="Select from Examples folder",
198
+ value=None,
199
+ interactive=True
200
+ )
201
+ else:
202
+ example_dropdown = gr.Dropdown(
203
+ choices=[],
204
+ label="No examples found in 'Examples' folder",
205
+ interactive=False
206
+ )
207
+
208
+ # OR upload custom image
209
+ gr.Markdown("**OR**")
210
+ input_image = gr.Image(type="pil", label="Upload Your Own MRI Image")
211
+
212
+ gr.Markdown("### ⚙️ Sensitivity Analysis Settings")
213
+
214
+ patch_size_slider = gr.Slider(
215
+ minimum=10, maximum=50, value=25, step=5,
216
+ label="Patch Size",
217
+ info="Larger = faster but less detailed"
218
+ )
219
+ stride_slider = gr.Slider(
220
+ minimum=5, maximum=20, value=5, step=5,
221
+ label="Stride",
222
+ info="Larger = faster but less detailed"
223
+ )
224
+
225
+ predict_btn = gr.Button("🔍 Analyze Image", variant="primary", size="lg")
226
+
227
+
228
+
229
+
230
+ gr.Markdown("""
231
+ ---
232
+ **ℹ️ Tip:** Select an image from the dropdown or upload your own,
233
+ then click 'Analyze Image' to see predictions and sensitivity maps.
234
+ """)
235
+
236
+ # Right column - Results
237
+ with gr.Column(scale=2):
238
+ # Prediction results at the top
239
+ output_text = gr.Markdown("### Waiting for analysis...")
240
+
241
+ gr.Markdown("---")
242
+
243
+ # Visualization results
244
+ gr.Markdown("### 🔬 Sensitivity Analysis Visualizations")
245
+
246
+ with gr.Row():
247
+ output_original = gr.Image(label="Original Image", type="pil")
248
+ output_sensitivity = gr.Image(label="Sensitivity Map", type="pil")
249
+
250
+ with gr.Row():
251
+ output_overlay = gr.Image(label="Overlay Visualization", type="pil")
252
+
253
+ # Event handlers
254
+ if example_images:
255
+ example_dropdown.change(
256
+ fn=load_example_image,
257
+ inputs=[example_dropdown],
258
+ outputs=[input_image]
259
+ )
260
+
261
+ predict_btn.click(
262
+ fn=predict_and_visualize,
263
+ inputs=[input_image, patch_size_slider, stride_slider],
264
+ outputs=[output_original, output_sensitivity, output_overlay, output_text],
265
+ api_name="predict",
266
+
267
+ )
268
+
269
+
270
+ if __name__ == "__main__":
271
+ demo.launch(share=False)