Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import timm
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
import requests
|
6 |
+
from io import BytesIO
|
7 |
+
import numpy as np
|
8 |
+
from pytorch_grad_cam import GradCAM, HiResCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad
|
9 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget, get_target_layer
|
10 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
11 |
+
from timm.data import create_transform
|
12 |
+
|
13 |
+
# List of available timm models
|
14 |
+
MODELS = timm.list_models()
|
15 |
+
|
16 |
+
# List of available GradCAM methods
|
17 |
+
CAM_METHODS = {
|
18 |
+
"GradCAM": GradCAM,
|
19 |
+
"HiResCAM": HiResCAM,
|
20 |
+
"ScoreCAM": ScoreCAM,
|
21 |
+
"GradCAM++": GradCAMPlusPlus,
|
22 |
+
"AblationCAM": AblationCAM,
|
23 |
+
"XGradCAM": XGradCAM,
|
24 |
+
"EigenCAM": EigenCAM,
|
25 |
+
"FullGrad": FullGrad
|
26 |
+
}
|
27 |
+
|
28 |
+
def load_model(model_name):
|
29 |
+
model = timm.create_model(model_name, pretrained=True)
|
30 |
+
model.eval()
|
31 |
+
return model
|
32 |
+
|
33 |
+
def process_image(image_path, model):
|
34 |
+
if image_path.startswith('http'):
|
35 |
+
response = requests.get(image_path)
|
36 |
+
image = Image.open(BytesIO(response.content))
|
37 |
+
else:
|
38 |
+
image = Image.open(image_path)
|
39 |
+
|
40 |
+
config = model.pretrained_cfg
|
41 |
+
transform = create_transform(
|
42 |
+
input_size=config['input_size'],
|
43 |
+
crop_pct=config['crop_pct'],
|
44 |
+
mean=config['mean'],
|
45 |
+
std=config['std'],
|
46 |
+
interpolation=config['interpolation'],
|
47 |
+
is_training=False
|
48 |
+
)
|
49 |
+
|
50 |
+
tensor = transform(image).unsqueeze(0)
|
51 |
+
return tensor
|
52 |
+
|
53 |
+
def get_cam_image(model, image, target_layer, cam_method):
|
54 |
+
cam = CAM_METHODS[cam_method](model=model, target_layers=[target_layer], use_cuda=torch.cuda.is_available())
|
55 |
+
grayscale_cam = cam(input_tensor=image)
|
56 |
+
|
57 |
+
config = model.pretrained_cfg
|
58 |
+
mean = torch.tensor(config['mean']).view(3, 1, 1)
|
59 |
+
std = torch.tensor(config['std']).view(3, 1, 1)
|
60 |
+
rgb_img = (image.squeeze(0) * std + mean).permute(1, 2, 0).cpu().numpy()
|
61 |
+
rgb_img = np.clip(rgb_img, 0, 1)
|
62 |
+
|
63 |
+
cam_image = show_cam_on_image(rgb_img, grayscale_cam[0, :], use_rgb=True)
|
64 |
+
return Image.fromarray(cam_image)
|
65 |
+
|
66 |
+
def get_feature_info(model):
|
67 |
+
if hasattr(model, 'feature_info'):
|
68 |
+
return [f['module'] for f in model.feature_info]
|
69 |
+
else:
|
70 |
+
return []
|
71 |
+
|
72 |
+
def explain_image(model_name, image_path, cam_method, feature_module):
|
73 |
+
model = load_model(model_name)
|
74 |
+
image = process_image(image_path, model)
|
75 |
+
|
76 |
+
if feature_module:
|
77 |
+
target_layer = get_target_layer(model, feature_module)
|
78 |
+
print(f"Using feature module: {feature_module}")
|
79 |
+
else:
|
80 |
+
# Fallback to the last feature module or last convolutional layer
|
81 |
+
feature_info = get_feature_info(model)
|
82 |
+
if feature_info:
|
83 |
+
target_layer = get_target_layer(model, feature_info[-1])
|
84 |
+
print(f"Using last feature module: {feature_info[-1]}")
|
85 |
+
else:
|
86 |
+
# Fallback to finding last convolutional layer
|
87 |
+
for name, module in reversed(list(model.named_modules())):
|
88 |
+
if isinstance(module, torch.nn.Conv2d):
|
89 |
+
target_layer = module
|
90 |
+
print(f"Fallback: Using last convolutional layer: {name}")
|
91 |
+
break
|
92 |
+
|
93 |
+
if target_layer is None:
|
94 |
+
raise ValueError("Could not find a suitable target layer.")
|
95 |
+
|
96 |
+
cam_image = get_cam_image(model, image, target_layer, cam_method)
|
97 |
+
return cam_image
|
98 |
+
|
99 |
+
def update_feature_modules(model_name):
|
100 |
+
model = load_model(model_name)
|
101 |
+
feature_modules = get_feature_info(model)
|
102 |
+
return gr.Dropdown.update(choices=feature_modules, value=feature_modules[-1] if feature_modules else None)
|
103 |
+
|
104 |
+
iface = gr.Interface(
|
105 |
+
fn=explain_image,
|
106 |
+
inputs=[
|
107 |
+
gr.Dropdown(choices=MODELS, label="Select Model"),
|
108 |
+
gr.Image(type="filepath", label="Upload Image"),
|
109 |
+
gr.Dropdown(choices=list(CAM_METHODS.keys()), label="Select CAM Method"),
|
110 |
+
gr.Dropdown(label="Select Feature Module (optional)")
|
111 |
+
],
|
112 |
+
outputs=gr.Image(type="pil", label="Explained Image"),
|
113 |
+
title="Explainable AI with timm models",
|
114 |
+
description="Upload an image, select a model, CAM method, and optionally a specific feature module to visualize the explanation.",
|
115 |
+
allow_flagging="never"
|
116 |
+
)
|
117 |
+
|
118 |
+
iface.load(update_feature_modules, inputs=[iface.inputs[0]], outputs=[iface.inputs[3]])
|
119 |
+
|
120 |
+
iface.launch()
|