Spaces:
Sleeping
Sleeping
Commit
·
42deeb1
1
Parent(s):
53350e8
[FEAT] add GradCAM
Browse files- gradio-inference.py +150 -24
- pyproject.toml +3 -0
gradio-inference.py
CHANGED
|
@@ -4,15 +4,20 @@
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
import numpy as np
|
|
|
|
| 7 |
import traceback
|
| 8 |
|
| 9 |
import torch
|
| 10 |
import torch.nn as nn
|
|
|
|
| 11 |
|
| 12 |
import gradio as gr
|
| 13 |
from PIL import Image
|
| 14 |
import logging
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
from main import get_transform
|
| 17 |
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -76,54 +81,166 @@ def load_model(model_type: str = "efficientvit") -> nn.Module:
|
|
| 76 |
logging.warning(
|
| 77 |
f"Default model path '{model_path}' not found. Using untrained model."
|
| 78 |
)
|
| 79 |
-
#
|
|
|
|
| 80 |
model.eval()
|
| 81 |
return model
|
| 82 |
|
| 83 |
|
| 84 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
"""
|
| 86 |
-
Predict eye disease from an uploaded image.
|
| 87 |
|
| 88 |
Args:
|
| 89 |
image: Input image from Gradio
|
| 90 |
-
model_path: Path to the model state dict
|
| 91 |
model_type: Type of model architecture
|
| 92 |
|
| 93 |
Returns:
|
| 94 |
-
Dictionary of class probabilities
|
| 95 |
"""
|
| 96 |
try:
|
| 97 |
-
|
| 98 |
logging.info("Starting prediction...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
# Load model
|
| 100 |
model = load_model(model_type)
|
| 101 |
|
| 102 |
# Preprocess image
|
| 103 |
logging.info("Preprocessing image...")
|
| 104 |
-
if image is None:
|
| 105 |
-
logging.warning("No image provided.")
|
| 106 |
-
return {cls: 0.0 for cls in CLASSES}
|
| 107 |
transform = get_transform()
|
| 108 |
-
if image is None:
|
| 109 |
-
return {cls: 0.0 for cls in CLASSES}
|
| 110 |
|
| 111 |
-
# Convert numpy array to PIL Image
|
| 112 |
-
|
| 113 |
-
img_tensor = transform(
|
| 114 |
logging.info("Image preprocessed successfully.")
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
except Exception as e:
|
|
|
|
| 125 |
traceback.print_exc()
|
| 126 |
-
return {cls: 0.0 for cls in CLASSES}
|
| 127 |
|
| 128 |
|
| 129 |
def main():
|
|
@@ -159,12 +276,13 @@ def main():
|
|
| 159 |
|
| 160 |
with gr.Column():
|
| 161 |
output_chart = gr.Label(label="Prediction")
|
|
|
|
| 162 |
|
| 163 |
# Process the image when the button is clicked
|
| 164 |
submit_btn.click(
|
| 165 |
fn=predict_image,
|
| 166 |
inputs=[input_image, model_type],
|
| 167 |
-
outputs=output_chart,
|
| 168 |
)
|
| 169 |
|
| 170 |
# Examples section
|
|
@@ -172,7 +290,7 @@ def main():
|
|
| 172 |
gr.Examples(
|
| 173 |
examples=[], # Add example paths here
|
| 174 |
inputs=input_image,
|
| 175 |
-
outputs=[output_chart],
|
| 176 |
fn=predict_image,
|
| 177 |
cache_examples=True,
|
| 178 |
)
|
|
@@ -188,7 +306,15 @@ def main():
|
|
| 188 |
- Enter the path to your trained model file (.pth)
|
| 189 |
- Select the model architecture that was used for training
|
| 190 |
3. **Analyze**: Click the "Analyze Image" button to get results
|
| 191 |
-
4. **Interpret results**: The system will show the detected condition and
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
## Model Information:
|
| 194 |
|
|
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
import numpy as np
|
| 7 |
+
import cv2
|
| 8 |
import traceback
|
| 9 |
|
| 10 |
import torch
|
| 11 |
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
|
| 14 |
import gradio as gr
|
| 15 |
from PIL import Image
|
| 16 |
import logging
|
| 17 |
|
| 18 |
+
from pytorch_grad_cam import GradCAM
|
| 19 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
| 20 |
+
|
| 21 |
from main import get_transform
|
| 22 |
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 81 |
logging.warning(
|
| 82 |
f"Default model path '{model_path}' not found. Using untrained model."
|
| 83 |
)
|
| 84 |
+
# Move model to device and set to evaluation mode
|
| 85 |
+
model.to(device)
|
| 86 |
model.eval()
|
| 87 |
return model
|
| 88 |
|
| 89 |
|
| 90 |
+
def get_target_layers(model, model_type):
|
| 91 |
+
"""
|
| 92 |
+
Get the target layers for GradCAM based on model type.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
model: The model
|
| 96 |
+
model_type: Type of model
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
target_layers: List of layers to use for GradCAM
|
| 100 |
+
"""
|
| 101 |
+
try:
|
| 102 |
+
if model_type == "mobilenetv4":
|
| 103 |
+
# For MobileNetV4, use the last convolutional layer in features
|
| 104 |
+
return [model.features[-1]]
|
| 105 |
+
elif model_type == "levit":
|
| 106 |
+
# For LeViT (transformer), use the last block
|
| 107 |
+
return [model.blocks[-1]]
|
| 108 |
+
elif model_type == "efficientvit":
|
| 109 |
+
# For EfficientViT, use the last stage
|
| 110 |
+
return [model.stages[-1]]
|
| 111 |
+
elif model_type == "gernet":
|
| 112 |
+
# For GENet, use the last stage
|
| 113 |
+
return [model.stages[-1]]
|
| 114 |
+
elif model_type == "regnetx":
|
| 115 |
+
# For RegNetX, use the last trunk layer
|
| 116 |
+
return [model.trunk[-1]]
|
| 117 |
+
else:
|
| 118 |
+
# Default: try to get the last feature layer
|
| 119 |
+
if hasattr(model, "features"):
|
| 120 |
+
return [model.features[-1]]
|
| 121 |
+
elif hasattr(model, "stages"):
|
| 122 |
+
return [model.stages[-1]]
|
| 123 |
+
elif hasattr(model, "blocks"):
|
| 124 |
+
return [model.blocks[-1]]
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"Cannot determine target layer for model type: {model_type}"
|
| 128 |
+
)
|
| 129 |
+
except Exception as e:
|
| 130 |
+
logging.warning(f"Error getting target layer: {e}. Using fallback.")
|
| 131 |
+
# Fallback: try to get any reasonable last conv layer
|
| 132 |
+
for module in reversed(list(model.modules())):
|
| 133 |
+
if isinstance(module, nn.Conv2d):
|
| 134 |
+
return [module]
|
| 135 |
+
raise ValueError("Could not find suitable target layer for GradCAM")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def apply_heatmap_on_image(img, cam, alpha=0.4):
|
| 139 |
+
"""
|
| 140 |
+
Apply CAM heatmap overlay on the original image.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
img: Original image (PIL Image or numpy array)
|
| 144 |
+
cam: Class activation map (grayscale, values 0-1)
|
| 145 |
+
alpha: Overlay transparency (not used with show_cam_on_image, kept for compatibility)
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
Heatmap overlay image as numpy array
|
| 149 |
+
"""
|
| 150 |
+
# Convert PIL to numpy if needed
|
| 151 |
+
if isinstance(img, Image.Image):
|
| 152 |
+
img = np.array(img)
|
| 153 |
+
|
| 154 |
+
# Normalize image to 0-1 range for show_cam_on_image
|
| 155 |
+
img_float = img.astype(np.float32) / 255.0
|
| 156 |
+
|
| 157 |
+
# Resize CAM to match image size
|
| 158 |
+
h, w = img.shape[:2]
|
| 159 |
+
cam_resized = cv2.resize(cam, (w, h))
|
| 160 |
+
|
| 161 |
+
# Use pytorch_grad_cam utility to overlay
|
| 162 |
+
# This function expects img in 0-1 range and cam in 0-1 range
|
| 163 |
+
overlay = show_cam_on_image(img_float, cam_resized, use_rgb=True)
|
| 164 |
+
|
| 165 |
+
return overlay
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def predict_image(image: np.ndarray, model_type: str) -> tuple[dict, np.ndarray]:
|
| 169 |
"""
|
| 170 |
+
Predict eye disease from an uploaded image and generate attention heatmap.
|
| 171 |
|
| 172 |
Args:
|
| 173 |
image: Input image from Gradio
|
|
|
|
| 174 |
model_type: Type of model architecture
|
| 175 |
|
| 176 |
Returns:
|
| 177 |
+
Tuple of (Dictionary of class probabilities, Heatmap overlay image)
|
| 178 |
"""
|
| 179 |
try:
|
|
|
|
| 180 |
logging.info("Starting prediction...")
|
| 181 |
+
|
| 182 |
+
# Handle None image
|
| 183 |
+
if image is None:
|
| 184 |
+
logging.warning("No image provided.")
|
| 185 |
+
return {cls: 0.0 for cls in CLASSES}, None
|
| 186 |
+
|
| 187 |
# Load model
|
| 188 |
model = load_model(model_type)
|
| 189 |
|
| 190 |
# Preprocess image
|
| 191 |
logging.info("Preprocessing image...")
|
|
|
|
|
|
|
|
|
|
| 192 |
transform = get_transform()
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# Convert numpy array to PIL Image and keep original for heatmap
|
| 195 |
+
img_pil = Image.fromarray(image).convert("RGB")
|
| 196 |
+
img_tensor = transform(img_pil).unsqueeze(0).to(device)
|
| 197 |
logging.info("Image preprocessed successfully.")
|
| 198 |
|
| 199 |
+
# Get target layers for GradCAM
|
| 200 |
+
try:
|
| 201 |
+
target_layers = get_target_layers(model, model_type)
|
| 202 |
+
logging.info(f"Using target layers: {target_layers}")
|
| 203 |
+
|
| 204 |
+
# Initialize GradCAM from pytorch_grad_cam library
|
| 205 |
+
cam_extractor = GradCAM(model=model, target_layers=target_layers)
|
| 206 |
|
| 207 |
+
# Generate CAM - the library handles forward and backward passes
|
| 208 |
+
grayscale_cam = cam_extractor(input_tensor=img_tensor, targets=None)
|
| 209 |
+
|
| 210 |
+
# Get the CAM for the first image in batch
|
| 211 |
+
cam = grayscale_cam[0, :]
|
| 212 |
+
|
| 213 |
+
# Get model prediction
|
| 214 |
+
with torch.no_grad():
|
| 215 |
+
outputs = model(img_tensor)
|
| 216 |
+
|
| 217 |
+
# Generate heatmap overlay
|
| 218 |
+
heatmap_overlay = apply_heatmap_on_image(img_pil, cam)
|
| 219 |
+
|
| 220 |
+
# Clean up
|
| 221 |
+
del cam_extractor
|
| 222 |
+
|
| 223 |
+
except Exception as e:
|
| 224 |
+
logging.error(f"Error generating heatmap: {e}")
|
| 225 |
+
traceback.print_exc()
|
| 226 |
+
# Fallback: just do prediction without heatmap
|
| 227 |
+
with torch.no_grad():
|
| 228 |
+
outputs = model(img_tensor)
|
| 229 |
+
heatmap_overlay = np.array(img_pil) # Return original image
|
| 230 |
+
|
| 231 |
+
# Get probabilities
|
| 232 |
+
probabilities = F.softmax(outputs, dim=1)[0].cpu().detach().numpy()
|
| 233 |
+
|
| 234 |
+
# Return probabilities and heatmap
|
| 235 |
+
result_dict = {cls: float(prob) for cls, prob in zip(CLASSES, probabilities)}
|
| 236 |
+
|
| 237 |
+
logging.info("Prediction completed successfully.")
|
| 238 |
+
return result_dict, heatmap_overlay
|
| 239 |
|
| 240 |
except Exception as e:
|
| 241 |
+
logging.error(f"Error during prediction: {e}")
|
| 242 |
traceback.print_exc()
|
| 243 |
+
return {cls: 0.0 for cls in CLASSES}, None
|
| 244 |
|
| 245 |
|
| 246 |
def main():
|
|
|
|
| 276 |
|
| 277 |
with gr.Column():
|
| 278 |
output_chart = gr.Label(label="Prediction")
|
| 279 |
+
output_heatmap = gr.Image(label="Attention Heatmap")
|
| 280 |
|
| 281 |
# Process the image when the button is clicked
|
| 282 |
submit_btn.click(
|
| 283 |
fn=predict_image,
|
| 284 |
inputs=[input_image, model_type],
|
| 285 |
+
outputs=[output_chart, output_heatmap],
|
| 286 |
)
|
| 287 |
|
| 288 |
# Examples section
|
|
|
|
| 290 |
gr.Examples(
|
| 291 |
examples=[], # Add example paths here
|
| 292 |
inputs=input_image,
|
| 293 |
+
outputs=[output_chart, output_heatmap],
|
| 294 |
fn=predict_image,
|
| 295 |
cache_examples=True,
|
| 296 |
)
|
|
|
|
| 306 |
- Enter the path to your trained model file (.pth)
|
| 307 |
- Select the model architecture that was used for training
|
| 308 |
3. **Analyze**: Click the "Analyze Image" button to get results
|
| 309 |
+
4. **Interpret results**: The system will show the detected condition, probability distribution, and an attention heatmap
|
| 310 |
+
|
| 311 |
+
## Attention Heatmap:
|
| 312 |
+
|
| 313 |
+
The attention heatmap visualizes which regions of the fundus image the model is focusing on when making its prediction.
|
| 314 |
+
- **Red/Yellow areas**: Regions the model considers most important for the diagnosis
|
| 315 |
+
- **Blue/Green areas**: Regions with less influence on the prediction
|
| 316 |
+
|
| 317 |
+
This helps in understanding and validating the model's decision-making process.
|
| 318 |
|
| 319 |
## Model Information:
|
| 320 |
|
pyproject.toml
CHANGED
|
@@ -6,8 +6,11 @@ readme = "README.md"
|
|
| 6 |
requires-python = ">=3.12.9"
|
| 7 |
dependencies = [
|
| 8 |
"gradio>=5.29.0",
|
|
|
|
| 9 |
"matplotlib>=3.10.3",
|
|
|
|
| 10 |
"pandas>=2.2.3",
|
|
|
|
| 11 |
"scikit-learn>=1.6.1",
|
| 12 |
"seaborn>=0.13.2",
|
| 13 |
"timm>=1.0.15",
|
|
|
|
| 6 |
requires-python = ">=3.12.9"
|
| 7 |
dependencies = [
|
| 8 |
"gradio>=5.29.0",
|
| 9 |
+
"grad-cam>=1.5.0",
|
| 10 |
"matplotlib>=3.10.3",
|
| 11 |
+
"opencv-python>=4.8.0",
|
| 12 |
"pandas>=2.2.3",
|
| 13 |
+
"pillow>=10.0.0",
|
| 14 |
"scikit-learn>=1.6.1",
|
| 15 |
"seaborn>=0.13.2",
|
| 16 |
"timm>=1.0.15",
|