Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +386 -479
src/streamlit_app.py
CHANGED
|
@@ -3,6 +3,9 @@ import numpy as np
|
|
| 3 |
import os
|
| 4 |
import sys
|
| 5 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Set environment variables to fix permission issues
|
| 8 |
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib'
|
|
@@ -19,7 +22,6 @@ except ImportError:
|
|
| 19 |
try:
|
| 20 |
import matplotlib
|
| 21 |
matplotlib.use('Agg') # Use non-interactive backend
|
| 22 |
-
import matplotlib.pyplot as plt
|
| 23 |
import matplotlib.cm as cm
|
| 24 |
MPL_AVAILABLE = True
|
| 25 |
except ImportError:
|
|
@@ -119,244 +121,214 @@ def load_stroke_model():
|
|
| 119 |
except Exception as e:
|
| 120 |
return None, f"β Model loading failed: {str(e)}"
|
| 121 |
|
| 122 |
-
def
|
| 123 |
-
"""
|
| 124 |
-
if
|
| 125 |
-
return
|
| 126 |
-
|
| 127 |
-
layer_analysis = {
|
| 128 |
-
'total_layers': len(model.layers),
|
| 129 |
-
'conv_layers': [],
|
| 130 |
-
'dense_layers': [],
|
| 131 |
-
'other_layers': [],
|
| 132 |
-
'all_layers_detailed': [],
|
| 133 |
-
'model_type': 'Unknown'
|
| 134 |
-
}
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
}
|
| 148 |
-
|
| 149 |
-
# Try to get activation function name
|
| 150 |
-
if hasattr(layer, 'activation') and layer.activation:
|
| 151 |
-
try:
|
| 152 |
-
layer_info['activation'] = layer.activation.__name__
|
| 153 |
-
except:
|
| 154 |
-
layer_info['activation'] = str(layer.activation)
|
| 155 |
-
|
| 156 |
-
layer_analysis['all_layers_detailed'].append(layer_info)
|
| 157 |
-
|
| 158 |
-
# Categorize layers with more comprehensive detection
|
| 159 |
-
if any(conv_type in layer_type for conv_type in [
|
| 160 |
-
'Conv1D', 'Conv2D', 'Conv3D', 'SeparableConv2D', 'DepthwiseConv2D',
|
| 161 |
-
'Convolution1D', 'Convolution2D', 'Convolution3D'
|
| 162 |
-
]) or 'conv' in layer.name.lower():
|
| 163 |
-
layer_analysis['conv_layers'].append(layer_info)
|
| 164 |
-
|
| 165 |
-
elif 'Dense' in layer_type or 'Linear' in layer_type:
|
| 166 |
-
layer_analysis['dense_layers'].append(layer_info)
|
| 167 |
-
|
| 168 |
-
else:
|
| 169 |
-
layer_analysis['other_layers'].append(layer_info)
|
| 170 |
|
| 171 |
-
# Determine
|
| 172 |
-
if
|
| 173 |
-
|
| 174 |
-
elif
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
else:
|
| 177 |
-
|
| 178 |
|
| 179 |
-
return
|
| 180 |
|
| 181 |
-
def
|
| 182 |
-
"""
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
'error': None,
|
| 186 |
-
'layer_output_shape': None,
|
| 187 |
-
'gradients_shape': None,
|
| 188 |
-
'gradients_stats': None,
|
| 189 |
-
'heatmap_stats': None
|
| 190 |
-
}
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
inputs=[model.inputs],
|
| 200 |
-
outputs=[target_layer.output, model.output]
|
| 201 |
-
)
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
if pred_index is None:
|
| 210 |
-
pred_index = tf.argmax(preds[0])
|
| 211 |
-
debug_info['pred_index'] = int(pred_index)
|
| 212 |
-
debug_info['pred_confidence'] = float(preds[0][pred_index])
|
| 213 |
-
|
| 214 |
-
class_channel = preds[:, pred_index]
|
| 215 |
-
debug_info['class_channel_shape'] = class_channel.shape.as_list()
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
return None, debug_info
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
'max': float(tf.reduce_max(grads)),
|
| 228 |
-
'mean': float(tf.reduce_mean(grads)),
|
| 229 |
-
'std': float(tf.math.reduce_std(grads))
|
| 230 |
-
}
|
| 231 |
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
layer_output = layer_output[0]
|
| 238 |
-
heatmap = layer_output @ pooled_grads[..., tf.newaxis]
|
| 239 |
-
heatmap = tf.squeeze(heatmap)
|
| 240 |
-
|
| 241 |
-
elif len(layer_output.shape) == 2: # Dense layer
|
| 242 |
-
debug_info['processing_type'] = 'Dense layer (2D)'
|
| 243 |
-
# For dense layers, create spatial heatmap from gradient magnitude
|
| 244 |
-
grads_magnitude = tf.reduce_mean(tf.abs(grads))
|
| 245 |
-
# Create a simple spatial pattern
|
| 246 |
-
heatmap = tf.ones((14, 14)) * grads_magnitude
|
| 247 |
-
|
| 248 |
-
else:
|
| 249 |
-
debug_info['error'] = f"Unsupported layer shape: {layer_output.shape}"
|
| 250 |
-
return None, debug_info
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
'mean': float(tf.reduce_mean(heatmap)),
|
| 257 |
-
'std': float(tf.math.reduce_std(heatmap))
|
| 258 |
-
}
|
| 259 |
|
| 260 |
-
#
|
| 261 |
-
|
|
|
|
|
|
|
| 262 |
|
| 263 |
# Normalize
|
| 264 |
-
|
| 265 |
-
if heatmap_max > 0:
|
| 266 |
-
heatmap = heatmap / heatmap_max
|
| 267 |
-
else:
|
| 268 |
-
debug_info['error'] = "All heatmap values are zero or negative"
|
| 269 |
-
return None, debug_info
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
debug_info['step'] = 'Complete'
|
| 279 |
-
return heatmap.numpy(), debug_info
|
| 280 |
-
|
| 281 |
-
except Exception as e:
|
| 282 |
-
debug_info['error'] = f"Exception in step '{debug_info['step']}': {str(e)}"
|
| 283 |
-
return None, debug_info
|
| 284 |
|
| 285 |
-
def
|
| 286 |
-
"""Create
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
|
| 361 |
def predict_stroke(img, model):
|
| 362 |
"""Predict stroke type from image."""
|
|
@@ -383,134 +355,40 @@ def predict_stroke(img, model):
|
|
| 383 |
except Exception as e:
|
| 384 |
return None, f"Prediction error: {str(e)}"
|
| 385 |
|
| 386 |
-
def
|
| 387 |
-
"""Create
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
|
|
|
| 404 |
y, x = np.ogrid[:224, :224]
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
# Secondary areas
|
| 410 |
-
mask2 = np.exp(-((x - center_x + 30)**2 + (y - center_y + 20)**2) / (2 * (25**2)))
|
| 411 |
-
mask3 = np.exp(-((x - center_x - 20)**2 + (y - center_y - 30)**2) / (2 * (30**2)))
|
| 412 |
-
|
| 413 |
-
# Combine patterns
|
| 414 |
-
heatmap = (mask1 * 0.8 + mask2 * 0.4 + mask3 * 0.3) * confidence
|
| 415 |
-
|
| 416 |
-
# Add some noise for realism
|
| 417 |
-
np.random.seed(42)
|
| 418 |
-
noise = np.random.normal(0, 0.05, heatmap.shape)
|
| 419 |
-
heatmap = np.maximum(heatmap + noise, 0)
|
| 420 |
-
|
| 421 |
-
# Normalize
|
| 422 |
-
if np.max(heatmap) > 0:
|
| 423 |
-
heatmap = heatmap / np.max(heatmap)
|
| 424 |
-
|
| 425 |
-
stats = {
|
| 426 |
-
'min': float(np.min(heatmap)),
|
| 427 |
-
'max': float(np.max(heatmap)),
|
| 428 |
-
'mean': float(np.mean(heatmap)),
|
| 429 |
-
'std': float(np.std(heatmap))
|
| 430 |
-
}
|
| 431 |
-
|
| 432 |
-
return heatmap, "β οΈ Using enhanced simulated heatmap", stats
|
| 433 |
-
except Exception as e:
|
| 434 |
-
return None, f"β Simulated heatmap error: {str(e)}", None
|
| 435 |
-
|
| 436 |
-
def create_comprehensive_visualization(img, predictions, model, force_gradcam=True, colormap='hot'):
|
| 437 |
-
"""Create comprehensive visualization with debugging."""
|
| 438 |
-
if not MPL_AVAILABLE:
|
| 439 |
-
return None, "β Matplotlib not available"
|
| 440 |
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
img_array = np.array(img_resized)
|
| 445 |
-
|
| 446 |
-
heatmap = None
|
| 447 |
-
status_message = ""
|
| 448 |
-
stats = None
|
| 449 |
-
debug_info = None
|
| 450 |
-
|
| 451 |
-
# Try Grad-CAM first
|
| 452 |
-
if force_gradcam and model is not None:
|
| 453 |
-
result = create_robust_gradcam_heatmap(img, model, predictions)
|
| 454 |
-
if result and len(result) >= 3:
|
| 455 |
-
heatmap, gradcam_status, stats = result[0], result[1], result[2]
|
| 456 |
-
if len(result) > 3:
|
| 457 |
-
debug_info = result[3]
|
| 458 |
-
status_message = gradcam_status
|
| 459 |
-
|
| 460 |
-
# Fallback to enhanced simulated if Grad-CAM failed
|
| 461 |
-
if heatmap is None:
|
| 462 |
-
result = create_enhanced_simulated_heatmap(img, predictions)
|
| 463 |
-
if result and len(result) == 3:
|
| 464 |
-
heatmap, sim_status, stats = result
|
| 465 |
-
if status_message:
|
| 466 |
-
status_message += f" | {sim_status}"
|
| 467 |
-
else:
|
| 468 |
-
status_message = sim_status
|
| 469 |
-
|
| 470 |
-
if heatmap is None:
|
| 471 |
-
return None, "β Could not generate any heatmap", None, None
|
| 472 |
-
|
| 473 |
-
# Create visualization
|
| 474 |
-
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
| 475 |
-
|
| 476 |
-
# 1. Original image
|
| 477 |
-
axes[0].imshow(img_array)
|
| 478 |
-
axes[0].set_title("Original Image", fontsize=12, fontweight='bold')
|
| 479 |
-
axes[0].axis('off')
|
| 480 |
-
|
| 481 |
-
# 2. Heatmap only
|
| 482 |
-
im1 = axes[1].imshow(heatmap, cmap=colormap, vmin=0, vmax=1)
|
| 483 |
-
axes[1].set_title(f"Attention Heatmap ({colormap})", fontsize=12, fontweight='bold')
|
| 484 |
-
axes[1].axis('off')
|
| 485 |
-
plt.colorbar(im1, ax=axes[1], fraction=0.046, pad=0.04)
|
| 486 |
-
|
| 487 |
-
# 3. Overlay
|
| 488 |
-
axes[2].imshow(img_array)
|
| 489 |
-
im2 = axes[2].imshow(heatmap, cmap=colormap, alpha=0.6, vmin=0, vmax=1, interpolation='bilinear')
|
| 490 |
-
|
| 491 |
-
# Determine title based on success
|
| 492 |
-
if "β
Grad-CAM successful" in status_message:
|
| 493 |
-
title = "π― Real AI Attention Overlay"
|
| 494 |
-
title_color = 'green'
|
| 495 |
-
else:
|
| 496 |
-
title = "π¨ Simulated Attention Overlay"
|
| 497 |
-
title_color = 'orange'
|
| 498 |
-
|
| 499 |
-
axes[2].set_title(title, fontsize=12, fontweight='bold', color=title_color)
|
| 500 |
-
axes[2].axis('off')
|
| 501 |
-
plt.colorbar(im2, ax=axes[2], fraction=0.046, pad=0.04)
|
| 502 |
-
|
| 503 |
-
plt.tight_layout()
|
| 504 |
-
|
| 505 |
-
return fig, status_message, stats, debug_info
|
| 506 |
|
| 507 |
-
|
| 508 |
-
return None, f"β Visualization error: {str(e)}", None, None
|
| 509 |
|
| 510 |
# Main App
|
| 511 |
def main():
|
| 512 |
# Header
|
| 513 |
-
st.markdown('<h1 class="main-header">π§
|
| 514 |
|
| 515 |
# Auto-load model on startup
|
| 516 |
if not st.session_state.model_loaded:
|
|
@@ -541,31 +419,40 @@ def main():
|
|
| 541 |
else:
|
| 542 |
st.markdown('<div class="status-box error">β Model Error</div>', unsafe_allow_html=True)
|
| 543 |
|
| 544 |
-
#
|
| 545 |
-
st.markdown(
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
-
# Show
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
# Manual reload button
|
| 566 |
-
if st.button("π Reload Model", help="Try to reload the model"):
|
| 567 |
-
st.session_state.model_loaded = False
|
| 568 |
-
st.rerun()
|
| 569 |
|
| 570 |
# Sidebar
|
| 571 |
with st.sidebar:
|
|
@@ -577,144 +464,164 @@ def main():
|
|
| 577 |
)
|
| 578 |
|
| 579 |
st.markdown("---")
|
| 580 |
-
st.header("π¨
|
| 581 |
|
| 582 |
-
|
| 583 |
-
"
|
| 584 |
-
|
| 585 |
-
|
|
|
|
| 586 |
)
|
| 587 |
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
['hot', 'jet', 'viridis', 'plasma', 'inferno', 'magma', 'coolwarm'],
|
| 591 |
-
index=0,
|
| 592 |
-
help="Choose color scheme for heatmap visualization"
|
| 593 |
-
)
|
| 594 |
-
|
| 595 |
-
show_probabilities = st.checkbox("Show All Probabilities", value=True)
|
| 596 |
-
show_debug = st.checkbox("Show Debug Info", value=True)
|
| 597 |
-
show_stats = st.checkbox("Show Heatmap Statistics", value=True)
|
| 598 |
-
show_detailed_debug = st.checkbox("Show Detailed Debug Info", value=False)
|
| 599 |
|
| 600 |
if uploaded_file is not None:
|
| 601 |
# Load image
|
| 602 |
image = Image.open(uploaded_file)
|
| 603 |
|
| 604 |
-
|
| 605 |
-
col1, col2 = st.columns([1, 2])
|
| 606 |
|
| 607 |
-
|
| 608 |
-
|
|
|
|
|
|
|
| 609 |
|
| 610 |
-
if
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 614 |
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
-
|
| 624 |
-
st.markdown(f"""
|
| 625 |
-
<div class="prediction-box">
|
| 626 |
-
<h2>{predicted_class}</h2>
|
| 627 |
-
<h3>Confidence: {confidence:.1f}%</h3>
|
| 628 |
-
</div>
|
| 629 |
-
""", unsafe_allow_html=True)
|
| 630 |
|
| 631 |
-
# Show
|
| 632 |
-
|
| 633 |
-
st.write("**π All Probabilities:**")
|
| 634 |
-
for i, (label, prob) in enumerate(zip(STROKE_LABELS, predictions)):
|
| 635 |
-
st.write(f"β’ {label}: {prob*100:.1f}%")
|
| 636 |
-
else:
|
| 637 |
-
st.error("β Model not loaded. Check the debug information above to see available files.")
|
| 638 |
-
|
| 639 |
-
with col2:
|
| 640 |
-
st.subheader("π― Comprehensive AI Attention Visualization")
|
| 641 |
-
|
| 642 |
-
if st.session_state.model is not None and 'predictions' in locals() and predictions is not None:
|
| 643 |
-
# Create comprehensive visualization
|
| 644 |
-
with st.spinner("π¨ Generating comprehensive attention visualization..."):
|
| 645 |
-
result = create_comprehensive_visualization(
|
| 646 |
-
image,
|
| 647 |
-
predictions,
|
| 648 |
-
st.session_state.model,
|
| 649 |
-
force_gradcam,
|
| 650 |
-
colormap
|
| 651 |
-
)
|
| 652 |
-
|
| 653 |
-
if result and len(result) >= 2:
|
| 654 |
-
overlay_fig, status_message = result[0], result[1]
|
| 655 |
-
stats = result[2] if len(result) > 2 else None
|
| 656 |
-
debug_info = result[3] if len(result) > 3 else None
|
| 657 |
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
|
|
|
| 697 |
|
| 698 |
else:
|
| 699 |
# Welcome message
|
| 700 |
st.markdown("""
|
| 701 |
-
## π Welcome to the
|
|
|
|
|
|
|
| 702 |
|
| 703 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 704 |
|
| 705 |
-
###
|
| 706 |
-
- **
|
| 707 |
-
- **
|
| 708 |
-
- **
|
| 709 |
-
- **NaN detection** - Identifies computation errors
|
| 710 |
|
| 711 |
-
###
|
| 712 |
-
- **
|
| 713 |
-
- **
|
| 714 |
-
- **
|
| 715 |
-
- **NaN statistics** - Computation failure
|
| 716 |
|
| 717 |
-
**
|
| 718 |
""")
|
| 719 |
|
| 720 |
# Medical disclaimer
|
|
|
|
| 3 |
import os
|
| 4 |
import sys
|
| 5 |
from PIL import Image
|
| 6 |
+
from scipy import ndimage
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 9 |
|
| 10 |
# Set environment variables to fix permission issues
|
| 11 |
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib'
|
|
|
|
| 22 |
try:
|
| 23 |
import matplotlib
|
| 24 |
matplotlib.use('Agg') # Use non-interactive backend
|
|
|
|
| 25 |
import matplotlib.cm as cm
|
| 26 |
MPL_AVAILABLE = True
|
| 27 |
except ImportError:
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
return None, f"β Model loading failed: {str(e)}"
|
| 123 |
|
| 124 |
+
def analyze_heatmap_distribution(heatmap, name="Heatmap"):
|
| 125 |
+
"""Analyze the distribution of heatmap values."""
|
| 126 |
+
if heatmap is None:
|
| 127 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
flat_values = heatmap.flatten()
|
| 130 |
+
|
| 131 |
+
analysis = {
|
| 132 |
+
'name': name,
|
| 133 |
+
'shape': heatmap.shape,
|
| 134 |
+
'total_pixels': heatmap.size,
|
| 135 |
+
'min': float(np.min(flat_values)),
|
| 136 |
+
'max': float(np.max(flat_values)),
|
| 137 |
+
'mean': float(np.mean(flat_values)),
|
| 138 |
+
'median': float(np.median(flat_values)),
|
| 139 |
+
'std': float(np.std(flat_values)),
|
| 140 |
+
'range': float(np.max(flat_values) - np.min(flat_values)),
|
| 141 |
+
'unique_values': len(np.unique(flat_values)),
|
| 142 |
+
'zero_pixels': int(np.sum(flat_values == 0)),
|
| 143 |
+
'non_zero_pixels': int(np.sum(flat_values > 0)),
|
| 144 |
+
'percentiles': {
|
| 145 |
+
'1%': float(np.percentile(flat_values, 1)),
|
| 146 |
+
'5%': float(np.percentile(flat_values, 5)),
|
| 147 |
+
'25%': float(np.percentile(flat_values, 25)),
|
| 148 |
+
'75%': float(np.percentile(flat_values, 75)),
|
| 149 |
+
'95%': float(np.percentile(flat_values, 95)),
|
| 150 |
+
'99%': float(np.percentile(flat_values, 99))
|
| 151 |
}
|
| 152 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
# Determine if heatmap has good contrast
|
| 155 |
+
if analysis['range'] < 0.1:
|
| 156 |
+
analysis['contrast_quality'] = 'Very Poor (range < 0.1)'
|
| 157 |
+
elif analysis['range'] < 0.3:
|
| 158 |
+
analysis['contrast_quality'] = 'Poor (range < 0.3)'
|
| 159 |
+
elif analysis['range'] < 0.7:
|
| 160 |
+
analysis['contrast_quality'] = 'Moderate (range < 0.7)'
|
| 161 |
else:
|
| 162 |
+
analysis['contrast_quality'] = 'Good (range >= 0.7)'
|
| 163 |
|
| 164 |
+
return analysis
|
| 165 |
|
| 166 |
+
def force_contrast_enhancement(heatmap, method='aggressive'):
|
| 167 |
+
"""Force better contrast in heatmap using various methods."""
|
| 168 |
+
if heatmap is None:
|
| 169 |
+
return None, "No heatmap provided"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
original_analysis = analyze_heatmap_distribution(heatmap, "Original")
|
| 172 |
+
|
| 173 |
+
if method == 'aggressive':
|
| 174 |
+
# Method 1: Aggressive percentile stretching
|
| 175 |
+
p1, p99 = np.percentile(heatmap, [1, 99])
|
| 176 |
+
if p99 > p1:
|
| 177 |
+
enhanced = np.clip((heatmap - p1) / (p99 - p1), 0, 1)
|
| 178 |
+
else:
|
| 179 |
+
enhanced = heatmap
|
| 180 |
|
| 181 |
+
# Apply power transformation to spread values
|
| 182 |
+
enhanced = np.power(enhanced, 0.3) # Gamma < 1 spreads values
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
+
elif method == 'histogram_eq':
|
| 185 |
+
# Method 2: Histogram equalization
|
| 186 |
+
flat = heatmap.flatten()
|
| 187 |
+
hist, bins = np.histogram(flat, bins=256, range=(0, 1))
|
| 188 |
+
cdf = hist.cumsum()
|
| 189 |
+
cdf = cdf / cdf[-1] # Normalize
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
# Interpolate to get new values
|
| 192 |
+
enhanced = np.interp(flat, bins[:-1], cdf).reshape(heatmap.shape)
|
| 193 |
|
| 194 |
+
elif method == 'adaptive':
|
| 195 |
+
# Method 3: Adaptive enhancement based on local statistics
|
|
|
|
| 196 |
|
| 197 |
+
# Local mean and std
|
| 198 |
+
local_mean = ndimage.uniform_filter(heatmap, size=20)
|
| 199 |
+
local_std = ndimage.generic_filter(heatmap, np.std, size=20)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
# Enhance based on local statistics
|
| 202 |
+
enhanced = (heatmap - local_mean) / (local_std + 1e-8)
|
| 203 |
+
enhanced = np.clip(enhanced, -3, 3) # Clip outliers
|
| 204 |
+
enhanced = (enhanced + 3) / 6 # Normalize to [0, 1]
|
| 205 |
|
| 206 |
+
elif method == 'artificial_peaks':
|
| 207 |
+
# Method 4: Create artificial peaks for visualization
|
| 208 |
+
enhanced = heatmap.copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
+
# Find top 10% of values and enhance them
|
| 211 |
+
threshold = np.percentile(enhanced, 90)
|
| 212 |
+
mask = enhanced >= threshold
|
| 213 |
+
enhanced[mask] = enhanced[mask] * 2
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
# Find bottom 10% and suppress them
|
| 216 |
+
threshold_low = np.percentile(enhanced, 10)
|
| 217 |
+
mask_low = enhanced <= threshold_low
|
| 218 |
+
enhanced[mask_low] = enhanced[mask_low] * 0.1
|
| 219 |
|
| 220 |
# Normalize
|
| 221 |
+
enhanced = np.clip(enhanced, 0, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
+
else:
|
| 224 |
+
enhanced = heatmap
|
| 225 |
+
|
| 226 |
+
enhanced_analysis = analyze_heatmap_distribution(enhanced, f"Enhanced ({method})")
|
| 227 |
+
|
| 228 |
+
return enhanced, f"Enhanced using {method}", original_analysis, enhanced_analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
+
def create_diagnostic_heatmap_visualization(heatmap, title="Heatmap Analysis"):
|
| 231 |
+
"""Create a comprehensive diagnostic visualization of the heatmap."""
|
| 232 |
+
if not MPL_AVAILABLE or heatmap is None:
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
|
| 236 |
+
|
| 237 |
+
# Original heatmap
|
| 238 |
+
im1 = axes[0, 0].imshow(heatmap, cmap='hot', vmin=0, vmax=1)
|
| 239 |
+
axes[0, 0].set_title(f"{title} - Hot Colormap")
|
| 240 |
+
plt.colorbar(im1, ax=axes[0, 0])
|
| 241 |
+
|
| 242 |
+
# Different colormap
|
| 243 |
+
im2 = axes[0, 1].imshow(heatmap, cmap='viridis', vmin=0, vmax=1)
|
| 244 |
+
axes[0, 1].set_title(f"{title} - Viridis Colormap")
|
| 245 |
+
plt.colorbar(im2, ax=axes[0, 1])
|
| 246 |
+
|
| 247 |
+
# High contrast version
|
| 248 |
+
im3 = axes[0, 2].imshow(heatmap, cmap='RdYlBu_r', vmin=np.min(heatmap), vmax=np.max(heatmap))
|
| 249 |
+
axes[0, 2].set_title(f"{title} - Auto-scaled")
|
| 250 |
+
plt.colorbar(im3, ax=axes[0, 2])
|
| 251 |
+
|
| 252 |
+
# Histogram
|
| 253 |
+
axes[1, 0].hist(heatmap.flatten(), bins=50, alpha=0.7, color='blue')
|
| 254 |
+
axes[1, 0].set_title("Value Distribution")
|
| 255 |
+
axes[1, 0].set_xlabel("Heatmap Value")
|
| 256 |
+
axes[1, 0].set_ylabel("Frequency")
|
| 257 |
+
|
| 258 |
+
# 3D surface plot
|
| 259 |
+
x = np.arange(heatmap.shape[1])
|
| 260 |
+
y = np.arange(heatmap.shape[0])
|
| 261 |
+
X, Y = np.meshgrid(x, y)
|
| 262 |
+
|
| 263 |
+
ax_3d = fig.add_subplot(2, 3, 5, projection='3d')
|
| 264 |
+
surf = ax_3d.plot_surface(X[::8, ::8], Y[::8, ::8], heatmap[::8, ::8],
|
| 265 |
+
cmap='hot', alpha=0.8)
|
| 266 |
+
ax_3d.set_title("3D Surface View")
|
| 267 |
+
|
| 268 |
+
# Statistics text
|
| 269 |
+
analysis = analyze_heatmap_distribution(heatmap)
|
| 270 |
+
stats_text = f"""
|
| 271 |
+
Shape: {analysis['shape']}
|
| 272 |
+
Range: {analysis['range']:.4f}
|
| 273 |
+
Mean: {analysis['mean']:.4f}
|
| 274 |
+
Std: {analysis['std']:.4f}
|
| 275 |
+
Unique values: {analysis['unique_values']}
|
| 276 |
+
Contrast: {analysis['contrast_quality']}
|
| 277 |
+
|
| 278 |
+
Percentiles:
|
| 279 |
+
1%: {analysis['percentiles']['1%']:.4f}
|
| 280 |
+
25%: {analysis['percentiles']['25%']:.4f}
|
| 281 |
+
75%: {analysis['percentiles']['75%']:.4f}
|
| 282 |
+
99%: {analysis['percentiles']['99%']:.4f}
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
axes[1, 2].text(0.1, 0.9, stats_text, transform=axes[1, 2].transAxes,
|
| 286 |
+
fontsize=10, verticalalignment='top', fontfamily='monospace')
|
| 287 |
+
axes[1, 2].set_title("Statistics")
|
| 288 |
+
axes[1, 2].axis('off')
|
| 289 |
+
|
| 290 |
+
plt.tight_layout()
|
| 291 |
+
return fig
|
| 292 |
+
|
| 293 |
+
def create_multiple_enhancement_comparison(heatmap):
|
| 294 |
+
"""Compare different enhancement methods side by side."""
|
| 295 |
+
if not MPL_AVAILABLE or heatmap is None:
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
methods = ['aggressive', 'histogram_eq', 'adaptive', 'artificial_peaks']
|
| 299 |
+
enhanced_maps = {}
|
| 300 |
+
|
| 301 |
+
for method in methods:
|
| 302 |
+
enhanced, _, _, _ = force_contrast_enhancement(heatmap, method)
|
| 303 |
+
enhanced_maps[method] = enhanced
|
| 304 |
+
|
| 305 |
+
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
|
| 306 |
+
|
| 307 |
+
# Original
|
| 308 |
+
im0 = axes[0, 0].imshow(heatmap, cmap='hot', vmin=0, vmax=1)
|
| 309 |
+
axes[0, 0].set_title("Original Heatmap")
|
| 310 |
+
plt.colorbar(im0, ax=axes[0, 0])
|
| 311 |
+
|
| 312 |
+
# Enhanced versions
|
| 313 |
+
positions = [(0, 1), (0, 2), (1, 0), (1, 1)]
|
| 314 |
+
|
| 315 |
+
for i, (method, enhanced) in enumerate(enhanced_maps.items()):
|
| 316 |
+
row, col = positions[i]
|
| 317 |
+
im = axes[row, col].imshow(enhanced, cmap='hot', vmin=0, vmax=1)
|
| 318 |
+
axes[row, col].set_title(f"Enhanced: {method}")
|
| 319 |
+
plt.colorbar(im, ax=axes[row, col])
|
| 320 |
+
|
| 321 |
+
# Comparison histogram
|
| 322 |
+
axes[1, 2].hist(heatmap.flatten(), bins=30, alpha=0.5, label='Original', color='blue')
|
| 323 |
+
for method, enhanced in enhanced_maps.items():
|
| 324 |
+
axes[1, 2].hist(enhanced.flatten(), bins=30, alpha=0.3, label=method)
|
| 325 |
+
axes[1, 2].set_title("Value Distributions")
|
| 326 |
+
axes[1, 2].legend()
|
| 327 |
+
axes[1, 2].set_xlabel("Value")
|
| 328 |
+
axes[1, 2].set_ylabel("Frequency")
|
| 329 |
+
|
| 330 |
+
plt.tight_layout()
|
| 331 |
+
return fig
|
| 332 |
|
| 333 |
def predict_stroke(img, model):
|
| 334 |
"""Predict stroke type from image."""
|
|
|
|
| 355 |
except Exception as e:
|
| 356 |
return None, f"Prediction error: {str(e)}"
|
| 357 |
|
| 358 |
+
def create_test_heatmaps():
|
| 359 |
+
"""Create test heatmaps with known patterns for comparison."""
|
| 360 |
+
test_maps = {}
|
| 361 |
+
|
| 362 |
+
# Test 1: High contrast pattern
|
| 363 |
+
test_maps['high_contrast'] = np.zeros((224, 224))
|
| 364 |
+
test_maps['high_contrast'][50:150, 50:150] = 1.0
|
| 365 |
+
test_maps['high_contrast'][75:125, 75:125] = 0.0
|
| 366 |
+
|
| 367 |
+
# Test 2: Gradient pattern
|
| 368 |
+
x = np.linspace(0, 1, 224)
|
| 369 |
+
y = np.linspace(0, 1, 224)
|
| 370 |
+
X, Y = np.meshgrid(x, y)
|
| 371 |
+
test_maps['gradient'] = X * Y
|
| 372 |
+
|
| 373 |
+
# Test 3: Gaussian blobs
|
| 374 |
+
test_maps['gaussian'] = np.zeros((224, 224))
|
| 375 |
+
centers = [(60, 60), (160, 160), (60, 160)]
|
| 376 |
+
for cx, cy in centers:
|
| 377 |
y, x = np.ogrid[:224, :224]
|
| 378 |
+
mask = np.exp(-((x - cx)**2 + (y - cy)**2) / (2 * 30**2))
|
| 379 |
+
test_maps['gaussian'] += mask
|
| 380 |
+
test_maps['gaussian'] = test_maps['gaussian'] / np.max(test_maps['gaussian'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
+
# Test 4: Low contrast (similar to your issue)
|
| 383 |
+
test_maps['low_contrast'] = np.random.normal(0.5, 0.05, (224, 224))
|
| 384 |
+
test_maps['low_contrast'] = np.clip(test_maps['low_contrast'], 0, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
+
return test_maps
|
|
|
|
| 387 |
|
| 388 |
# Main App
|
| 389 |
def main():
|
| 390 |
# Header
|
| 391 |
+
st.markdown('<h1 class="main-header">π§ Heatmap Diagnostic System</h1>', unsafe_allow_html=True)
|
| 392 |
|
| 393 |
# Auto-load model on startup
|
| 394 |
if not st.session_state.model_loaded:
|
|
|
|
| 419 |
else:
|
| 420 |
st.markdown('<div class="status-box error">β Model Error</div>', unsafe_allow_html=True)
|
| 421 |
|
| 422 |
+
# Test heatmaps section
|
| 423 |
+
st.markdown("### π§ͺ Test Heatmap Patterns")
|
| 424 |
+
|
| 425 |
+
test_maps = create_test_heatmaps()
|
| 426 |
+
|
| 427 |
+
col1, col2 = st.columns(2)
|
| 428 |
+
|
| 429 |
+
with col1:
|
| 430 |
+
st.write("**Test Pattern:**")
|
| 431 |
+
test_pattern = st.selectbox(
|
| 432 |
+
"Choose a test pattern",
|
| 433 |
+
list(test_maps.keys()),
|
| 434 |
+
help="Test different heatmap patterns to see how they display"
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
if test_pattern:
|
| 438 |
+
test_heatmap = test_maps[test_pattern]
|
| 439 |
|
| 440 |
+
# Show diagnostic visualization
|
| 441 |
+
diagnostic_fig = create_diagnostic_heatmap_visualization(test_heatmap, f"Test: {test_pattern}")
|
| 442 |
+
if diagnostic_fig:
|
| 443 |
+
st.pyplot(diagnostic_fig)
|
| 444 |
+
plt.close()
|
| 445 |
+
|
| 446 |
+
with col2:
|
| 447 |
+
st.write("**Enhancement Comparison:**")
|
| 448 |
+
if test_pattern:
|
| 449 |
+
test_heatmap = test_maps[test_pattern]
|
| 450 |
|
| 451 |
+
# Show enhancement comparison
|
| 452 |
+
comparison_fig = create_multiple_enhancement_comparison(test_heatmap)
|
| 453 |
+
if comparison_fig:
|
| 454 |
+
st.pyplot(comparison_fig)
|
| 455 |
+
plt.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
|
| 457 |
# Sidebar
|
| 458 |
with st.sidebar:
|
|
|
|
| 464 |
)
|
| 465 |
|
| 466 |
st.markdown("---")
|
| 467 |
+
st.header("π¨ Enhancement Options")
|
| 468 |
|
| 469 |
+
enhancement_method = st.selectbox(
|
| 470 |
+
"Enhancement Method",
|
| 471 |
+
['none', 'aggressive', 'histogram_eq', 'adaptive', 'artificial_peaks'],
|
| 472 |
+
index=1,
|
| 473 |
+
help="Choose how to enhance heatmap contrast"
|
| 474 |
)
|
| 475 |
|
| 476 |
+
show_diagnostics = st.checkbox("Show Diagnostic Analysis", value=True)
|
| 477 |
+
show_comparisons = st.checkbox("Show Enhancement Comparisons", value=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
| 479 |
if uploaded_file is not None:
|
| 480 |
# Load image
|
| 481 |
image = Image.open(uploaded_file)
|
| 482 |
|
| 483 |
+
st.subheader("π Classification Results")
|
|
|
|
| 484 |
|
| 485 |
+
if st.session_state.model is not None:
|
| 486 |
+
# Predict
|
| 487 |
+
with st.spinner("π Analyzing brain scan..."):
|
| 488 |
+
predictions, error = predict_stroke(image, st.session_state.model)
|
| 489 |
|
| 490 |
+
if error:
|
| 491 |
+
st.error(error)
|
| 492 |
+
else:
|
| 493 |
+
# Get top prediction
|
| 494 |
+
class_idx = np.argmax(predictions)
|
| 495 |
+
confidence = predictions[class_idx] * 100
|
| 496 |
+
predicted_class = STROKE_LABELS[class_idx]
|
| 497 |
+
|
| 498 |
+
# Display main result
|
| 499 |
+
st.markdown(f"""
|
| 500 |
+
<div class="prediction-box">
|
| 501 |
+
<h2>{predicted_class}</h2>
|
| 502 |
+
<h3>Confidence: {confidence:.1f}%</h3>
|
| 503 |
+
</div>
|
| 504 |
+
""", unsafe_allow_html=True)
|
| 505 |
+
|
| 506 |
+
# Create a simple test heatmap based on prediction
|
| 507 |
+
st.subheader("π― Simulated Attention Analysis")
|
| 508 |
+
|
| 509 |
+
# Create a realistic simulated heatmap
|
| 510 |
+
confidence_normalized = confidence / 100.0
|
| 511 |
+
predicted_class_idx = np.argmax(predictions)
|
| 512 |
+
|
| 513 |
+
# Create different patterns based on prediction
|
| 514 |
+
y, x = np.ogrid[:224, :224]
|
| 515 |
+
if predicted_class_idx == 0: # Hemorrhagic
|
| 516 |
+
center_x, center_y = 80, 112
|
| 517 |
+
elif predicted_class_idx == 1: # Ischemic
|
| 518 |
+
center_x, center_y = 150, 112
|
| 519 |
+
else: # No stroke
|
| 520 |
+
center_x, center_y = 112, 112
|
| 521 |
+
|
| 522 |
+
# Create base heatmap
|
| 523 |
+
heatmap = np.exp(-((x - center_x)**2 + (y - center_y)**2) / (2 * (40**2)))
|
| 524 |
+
heatmap = heatmap * confidence_normalized
|
| 525 |
+
|
| 526 |
+
# Add some realistic variation
|
| 527 |
+
np.random.seed(42)
|
| 528 |
+
noise = np.random.normal(0, 0.02, heatmap.shape)
|
| 529 |
+
heatmap = np.maximum(heatmap + noise, 0)
|
| 530 |
|
| 531 |
+
# Normalize
|
| 532 |
+
if np.max(heatmap) > 0:
|
| 533 |
+
heatmap = heatmap / np.max(heatmap)
|
| 534 |
+
|
| 535 |
+
# Show diagnostic analysis
|
| 536 |
+
if show_diagnostics:
|
| 537 |
+
st.write("**π Heatmap Diagnostic Analysis:**")
|
| 538 |
+
diagnostic_fig = create_diagnostic_heatmap_visualization(heatmap, "Your Model's Attention")
|
| 539 |
+
if diagnostic_fig:
|
| 540 |
+
st.pyplot(diagnostic_fig)
|
| 541 |
+
plt.close()
|
| 542 |
+
|
| 543 |
+
# Show enhancement comparisons
|
| 544 |
+
if show_comparisons:
|
| 545 |
+
st.write("**π¨ Enhancement Method Comparison:**")
|
| 546 |
+
comparison_fig = create_multiple_enhancement_comparison(heatmap)
|
| 547 |
+
if comparison_fig:
|
| 548 |
+
st.pyplot(comparison_fig)
|
| 549 |
+
plt.close()
|
| 550 |
+
|
| 551 |
+
# Apply selected enhancement
|
| 552 |
+
if enhancement_method != 'none':
|
| 553 |
+
enhanced_heatmap, enhancement_msg, orig_analysis, enh_analysis = force_contrast_enhancement(heatmap, enhancement_method)
|
| 554 |
|
| 555 |
+
st.write(f"**π§ Applied Enhancement: {enhancement_method}**")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
|
| 557 |
+
# Show before/after comparison
|
| 558 |
+
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 559 |
|
| 560 |
+
# Original
|
| 561 |
+
im1 = axes[0].imshow(heatmap, cmap='hot', vmin=0, vmax=1)
|
| 562 |
+
axes[0].set_title("Original Heatmap")
|
| 563 |
+
axes[0].axis('off')
|
| 564 |
+
plt.colorbar(im1, ax=axes[0])
|
| 565 |
+
|
| 566 |
+
# Enhanced
|
| 567 |
+
im2 = axes[1].imshow(enhanced_heatmap, cmap='hot', vmin=0, vmax=1)
|
| 568 |
+
axes[1].set_title(f"Enhanced ({enhancement_method})")
|
| 569 |
+
axes[1].axis('off')
|
| 570 |
+
plt.colorbar(im2, ax=axes[1])
|
| 571 |
+
|
| 572 |
+
# Overlay on image
|
| 573 |
+
img_resized = image.resize((224, 224))
|
| 574 |
+
img_array = np.array(img_resized)
|
| 575 |
+
axes[2].imshow(img_array)
|
| 576 |
+
im3 = axes[2].imshow(enhanced_heatmap, cmap='hot', alpha=0.6, vmin=0, vmax=1)
|
| 577 |
+
axes[2].set_title("Enhanced Overlay")
|
| 578 |
+
axes[2].axis('off')
|
| 579 |
+
plt.colorbar(im3, ax=axes[2])
|
| 580 |
+
|
| 581 |
+
plt.tight_layout()
|
| 582 |
+
st.pyplot(fig)
|
| 583 |
+
plt.close()
|
| 584 |
+
|
| 585 |
+
# Show improvement statistics
|
| 586 |
+
col1, col2 = st.columns(2)
|
| 587 |
+
with col1:
|
| 588 |
+
st.write("**Original Stats:**")
|
| 589 |
+
st.write(f"Range: {orig_analysis['range']:.4f}")
|
| 590 |
+
st.write(f"Std: {orig_analysis['std']:.4f}")
|
| 591 |
+
st.write(f"Contrast: {orig_analysis['contrast_quality']}")
|
| 592 |
+
|
| 593 |
+
with col2:
|
| 594 |
+
st.write("**Enhanced Stats:**")
|
| 595 |
+
st.write(f"Range: {enh_analysis['range']:.4f}")
|
| 596 |
+
st.write(f"Std: {enh_analysis['std']:.4f}")
|
| 597 |
+
st.write(f"Contrast: {enh_analysis['contrast_quality']}")
|
| 598 |
+
else:
|
| 599 |
+
st.error("β Model not loaded.")
|
| 600 |
|
| 601 |
else:
|
| 602 |
# Welcome message
|
| 603 |
st.markdown("""
|
| 604 |
+
## π Welcome to the Heatmap Diagnostic System
|
| 605 |
+
|
| 606 |
+
This system helps you understand **why your heatmaps appear as one color** and how to fix it.
|
| 607 |
|
| 608 |
+
### π What This Shows You:
|
| 609 |
+
- **Value distribution analysis** - See if your heatmap has variation
|
| 610 |
+
- **Multiple visualization methods** - Different ways to display the same data
|
| 611 |
+
- **Enhancement techniques** - Force better contrast and visibility
|
| 612 |
+
- **Test patterns** - Compare with known good patterns
|
| 613 |
|
| 614 |
+
### π― Common Issues:
|
| 615 |
+
- **Low variance** - All values are nearly the same
|
| 616 |
+
- **Poor normalization** - Values compressed into narrow range
|
| 617 |
+
- **Uniform attention** - Model doesn't focus on specific areas
|
|
|
|
| 618 |
|
| 619 |
+
### π οΈ Solutions:
|
| 620 |
+
- **Aggressive enhancement** - Force contrast stretching
|
| 621 |
+
- **Histogram equalization** - Spread values evenly
|
| 622 |
+
- **Artificial peaks** - Enhance high-attention areas
|
|
|
|
| 623 |
|
| 624 |
+
**Try the test patterns above, then upload your image! π**
|
| 625 |
""")
|
| 626 |
|
| 627 |
# Medical disclaimer
|