saakshigupta commited on
Commit
d742a0e
·
verified ·
1 Parent(s): e84eb9a

Upload gradcam_xception.py

Browse files
Files changed (1) hide show
  1. gradcam_xception.py +460 -0
gradcam_xception.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchvision import transforms
5
+ from torchvision.transforms.functional import to_pil_image
6
+ import matplotlib.pyplot as plt
7
+ from PIL import Image
8
+ import numpy as np
9
+ import cv2
10
+ from timm import create_model
11
+ from huggingface_hub import hf_hub_download
12
+ import io
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore", category=UserWarning)
16
+
17
+ # Advanced Grad-CAM Implementation
18
+ class AdvancedGradCAM:
19
+ def __init__(self, model, target_layer, method="gradcam"):
20
+ self.model = model
21
+ self.target_layer = target_layer
22
+ self.method = method
23
+ self.gradients = None
24
+ self.activations = None
25
+ self.forward_hook_handle = None
26
+ self.backward_hook_handle = None
27
+ self._register_hooks()
28
+
29
+ def _register_hooks(self):
30
+ layer = dict([*self.model.named_modules()])[self.target_layer]
31
+
32
+ def forward_hook(module, input, output):
33
+ if isinstance(output, tuple):
34
+ for item in output:
35
+ if isinstance(item, torch.Tensor):
36
+ self.activations = item.detach()
37
+ break
38
+ else:
39
+ self.activations = output.detach()
40
+
41
+ def backward_hook(module, grad_in, grad_out):
42
+ self.gradients = grad_out[0].detach()
43
+
44
+ self.forward_hook_handle = layer.register_forward_hook(forward_hook)
45
+ self.backward_hook_handle = layer.register_backward_hook(backward_hook)
46
+
47
+ def remove_hooks(self):
48
+ if self.forward_hook_handle:
49
+ self.forward_hook_handle.remove()
50
+ if self.backward_hook_handle:
51
+ self.backward_hook_handle.remove()
52
+ self.forward_hook_handle = None
53
+ self.backward_hook_handle = None
54
+ self.gradients = None
55
+ self.activations = None
56
+
57
+ def generate(self, input_tensor, class_idx, num_samples=5, stdev_spread=0.15):
58
+ if self.forward_hook_handle is None or self.backward_hook_handle is None:
59
+ self._register_hooks()
60
+
61
+ self.model.zero_grad()
62
+
63
+ try:
64
+ input_tensor.requires_grad_(True)
65
+ output = self.model(input_tensor)
66
+ class_score = output[:, class_idx]
67
+ class_score.backward()
68
+
69
+ if self.gradients is None or self.activations is None:
70
+ print(f"Warning: Gradients or activations are None for layer {self.target_layer}. Using fallback CAM.")
71
+ h, w = input_tensor.shape[-2:]
72
+ fallback_h, fallback_w = h // 16, w // 16
73
+ return np.ones((fallback_h, fallback_w), dtype=np.float32) * 0.5
74
+
75
+ if self.method == "gradcam":
76
+ cam_result = self._standard_gradcam()
77
+ else:
78
+ raise ValueError(f"Unsupported CAM method: {self.method}")
79
+
80
+ self.gradients = None
81
+ self.activations = None
82
+ input_tensor.requires_grad_(False)
83
+ self.model.zero_grad()
84
+
85
+ return cam_result
86
+
87
+ except Exception as e:
88
+ print(f"Error in AdvancedGradCAM.generate: {str(e)}")
89
+ import traceback
90
+ traceback.print_exc()
91
+ h, w = input_tensor.shape[-2:]
92
+ fallback_h, fallback_w = h // 16, w // 16
93
+ return np.ones((fallback_h, fallback_w), dtype=np.float32) * 0.5
94
+
95
+ def _standard_gradcam(self):
96
+ gradients = self.gradients.cpu().numpy()
97
+ activations = self.activations.cpu().numpy()
98
+
99
+ if len(gradients.shape) != 4 or len(activations.shape) != 4:
100
+ print(f"Warning: Unexpected shape in GradCAM++. Gradients: {gradients.shape}, Activations: {activations.shape}. Using fallback.")
101
+ fallback_h, fallback_w = activations.shape[-2:] if len(activations.shape) >= 2 else (14, 14)
102
+ return np.ones((fallback_h, fallback_w), dtype=np.float32) * 0.5
103
+
104
+ grad_2 = gradients ** 2
105
+ grad_3 = gradients ** 3
106
+ epsilon = 1e-10
107
+ alpha_denom = 2 * grad_2 + np.sum(activations * grad_3, axis=(2, 3), keepdims=True)
108
+ alpha = grad_2 / (alpha_denom + epsilon)
109
+ positive_activations_gradients = np.maximum(gradients, 0)
110
+ weights = np.sum(alpha * positive_activations_gradients, axis=(2, 3))
111
+
112
+ cam = np.zeros(activations.shape[2:], dtype=np.float32)
113
+ for i, w in enumerate(weights[0]):
114
+ cam += w * activations[0, i, :, :]
115
+
116
+ cam = np.maximum(cam, 0)
117
+ if np.max(cam) > 0:
118
+ cam = cam / np.max(cam)
119
+ return cam
120
+
121
+ # Utility Functions
122
+ def overlay_cam_on_image(image, cam, face_box=None, alpha=0.5):
123
+ img_np = np.array(image.convert('RGB'))
124
+ h, w = img_np.shape[:2]
125
+
126
+ if face_box is not None:
127
+ x, y, fw, fh = map(int, face_box)
128
+ if fw <= 0 or fh <= 0:
129
+ print(f"Warning: Invalid face box dimensions {fw}x{fh}. Applying CAM to full image.")
130
+ face_box = None
131
+ else:
132
+ try:
133
+ face_cam_resized = cv2.resize(cam, (fw, fh))
134
+ except cv2.error as e:
135
+ print(f"Error resizing CAM to face box {fw}x{fh}: {e}. Applying CAM to full image.")
136
+ face_box = None
137
+
138
+ if face_box is not None:
139
+ x, y, fw, fh = map(int, face_box)
140
+ full_cam_heatmap = np.zeros((h, w), dtype=np.float32)
141
+ y_end = min(y + fh, h)
142
+ x_end = min(x + fw, w)
143
+ fh_clipped = y_end - y
144
+ fw_clipped = x_end - x
145
+ if fh_clipped > 0 and fw_clipped > 0:
146
+ full_cam_heatmap[y:y_end, x:x_end] = face_cam_resized[:fh_clipped, :fw_clipped]
147
+ else:
148
+ print("Warning: Face box calculation resulted in zero area for heatmap placement.")
149
+ heatmap_colored = cv2.applyColorMap(np.uint8(255 * full_cam_heatmap), cv2.COLORMAP_JET)
150
+ heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)
151
+ else:
152
+ try:
153
+ cam_resized = cv2.resize(cam, (w, h))
154
+ except cv2.error as e:
155
+ print(f"Error resizing CAM to full image size {w}x{h}: {e}. Skipping overlay.")
156
+ return image
157
+ heatmap_colored = cv2.applyColorMap(np.uint8(255 * cam_resized), cv2.COLORMAP_JET)
158
+ heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB)
159
+
160
+ overlayed_img = cv2.addWeighted(img_np, 1 - alpha, heatmap_colored, alpha, 0)
161
+ return Image.fromarray(overlayed_img)
162
+
163
+ def save_comparison(image, cam, overlay, face_box=None):
164
+ fig, axes = plt.subplots(1, 3, figsize=(15, 5))
165
+
166
+ axes[0].imshow(image)
167
+ axes[0].set_title("Original")
168
+ if face_box is not None:
169
+ x, y, w, h = map(int, face_box)
170
+ if w > 0 and h > 0:
171
+ rect = plt.Rectangle((x, y), w, h, edgecolor='lime', linewidth=2, fill=False)
172
+ axes[0].add_patch(rect)
173
+ axes[0].axis("off")
174
+
175
+ if face_box is not None:
176
+ x, y, w, h = map(int, face_box)
177
+ if w > 0 and h > 0:
178
+ try:
179
+ cam_display = cv2.resize(cam, (w, h))
180
+ img_h, img_w = np.array(image).shape[:2]
181
+ full_cam_display = np.zeros((img_h, img_w))
182
+ y_end = min(y + h, img_h)
183
+ x_end = min(x + w, img_w)
184
+ h_clipped = y_end - y
185
+ w_clipped = x_end - x
186
+ if h_clipped > 0 and w_clipped > 0:
187
+ full_cam_display[y:y_end, x:x_end] = cam_display[:h_clipped, :w_clipped]
188
+ axes[1].imshow(full_cam_display, cmap="jet")
189
+ except cv2.error:
190
+ axes[1].imshow(cam, cmap="jet")
191
+ else:
192
+ axes[1].imshow(cam, cmap="jet")
193
+ else:
194
+ axes[1].imshow(cam, cmap="jet")
195
+
196
+ axes[1].set_title("CAM")
197
+ axes[1].axis("off")
198
+
199
+ axes[2].imshow(overlay)
200
+ axes[2].set_title("Overlay")
201
+ axes[2].axis("off")
202
+
203
+ plt.tight_layout()
204
+
205
+ buf = io.BytesIO()
206
+ plt.savefig(buf, format="png", bbox_inches="tight")
207
+ plt.close()
208
+ buf.seek(0)
209
+ return Image.open(buf)
210
+ #load xception model
211
+ def load_xception_model(model_repo="drg31/xception", model_filename="final_xception_model.pth", num_classes=2):
212
+ try:
213
+ model_path = hf_hub_download(repo_id=model_repo, filename=model_filename)
214
+ print(f"Model downloaded to: {model_path}")
215
+ except Exception as e:
216
+ print(f"Error downloading model from Hugging Face Hub ({model_repo}/{model_filename}): {e}")
217
+ raise
218
+
219
+ model = create_model("xception", pretrained=False, num_classes=num_classes)
220
+ print(f"Created Xception model with {num_classes} output classes.")
221
+
222
+ try:
223
+ checkpoint = torch.load(model_path, map_location=torch.device('cpu'), weights_only=False)
224
+ print(f"Checkpoint loaded successfully from {model_path} (with weights_only=False).")
225
+ except Exception as e:
226
+ print(f"Error loading checkpoint from {model_path}: {e}")
227
+ raise
228
+
229
+ if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
230
+ checkpoint_state_dict = checkpoint['state_dict']
231
+ print("Extracted state_dict from checkpoint dictionary.")
232
+ else:
233
+ checkpoint_state_dict = checkpoint
234
+ print("Using checkpoint directly as state_dict.")
235
+
236
+ cleaned_state_dict = {}
237
+ for k, v in checkpoint_state_dict.items():
238
+ name = k.replace('module.', '')
239
+ cleaned_state_dict[name] = v
240
+ print(f"Cleaned state_dict contains {len(cleaned_state_dict)} keys (after removing 'module.' prefix).")
241
+
242
+ print("Loading state_dict with strict=False...")
243
+ report = model.load_state_dict(cleaned_state_dict, strict=False)
244
+ print(f"Load report - Missing keys: {report.missing_keys}")
245
+ print(f"Load report - Unexpected keys: {report.unexpected_keys}")
246
+
247
+ print("Model state loaded.")
248
+ model.eval()
249
+ return model
250
+
251
+ def get_target_layer_xception(model):
252
+ target_layer_name = "block12.rep.6" # Deeper layer for semantic features
253
+ if target_layer_name not in dict([*model.named_modules()]):
254
+ print(f"Warning: Target layer '{target_layer_name}' not found. Trying 'block11.rep.2'.")
255
+ target_layer_name = "block11.rep.2"
256
+ if target_layer_name not in dict([*model.named_modules()]):
257
+ print(f"Warning: Fallback layer '{target_layer_name}' not found. Trying 'act4'.")
258
+ target_layer_name = "act4"
259
+ if target_layer_name not in dict([*model.named_modules()]):
260
+ raise ValueError("Could not find suitable target layer for GradCAM in Xception model.")
261
+ print(f"Using target layer: {target_layer_name}")
262
+ return target_layer_name
263
+
264
+ # Main Visualization Function
265
+ def generate_smoothgrad_visualizations_xception(model, image, target_class=None, face_only=True, num_samples=5, stdev_spread=0.15):
266
+ print("\n--- Starting Prediction and Grad-CAM ---")
267
+ try:
268
+ predicted_class_idx, confidence = predict_image(model, image, face_only)
269
+ except Exception as pred_e:
270
+ print(f"Error during prediction: {pred_e}")
271
+ import traceback
272
+ traceback.print_exc()
273
+ return None, None, None, None
274
+
275
+ if target_class is None:
276
+ cam_target_class = predicted_class_idx
277
+ print(f"CAM Target Class: Using predicted class index {cam_target_class} ({'real' if cam_target_class == 0 else 'fake'})")
278
+ elif target_class in [0, 1]:
279
+ cam_target_class = target_class
280
+ print(f"CAM Target Class: Using specified class index {cam_target_class} ({'real' if cam_target_class == 0 else 'fake'})")
281
+ else:
282
+ print(f"Warning: Invalid target_class specified ({target_class}). Defaulting to predicted class index {predicted_class_idx}.")
283
+ cam_target_class = predicted_class_idx
284
+
285
+ device = next(model.parameters()).device
286
+ model.eval()
287
+
288
+ IMAGE_SIZE = 299
289
+ transform = transforms.Compose([
290
+ transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
291
+ transforms.ToTensor(),
292
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
293
+ ])
294
+
295
+ dataset = ImageDataset(image, transform=transform, face_only=face_only)
296
+ input_tensor, original_image, face_box = dataset[0]
297
+ input_tensor = input_tensor.unsqueeze(0).to(device)
298
+ print(f"Input tensor for CAM shape: {input_tensor.shape}, Face box: {face_box}")
299
+
300
+ raw_cam = None
301
+ try:
302
+ target_layer = get_target_layer_xception(model)
303
+ print(f"Using target layer for CAM: {target_layer}")
304
+ cam_extractor = AdvancedGradCAM(model, target_layer, method="gradcam")
305
+ raw_cam = cam_extractor.generate(input_tensor, cam_target_class, num_samples=num_samples, stdev_spread=stdev_spread)
306
+ except Exception as cam_e:
307
+ print(f"Error during CAM generation: {cam_e}")
308
+ import traceback
309
+ traceback.print_exc()
310
+
311
+ cam_heatmap_img, overlay_img, comparison_img = None, None, None
312
+ if raw_cam is None or not isinstance(raw_cam, np.ndarray) or raw_cam.size == 0:
313
+ print("CAM generation failed or produced invalid result. Skipping visualization.")
314
+ else:
315
+ try:
316
+ print("Generating visualizations...")
317
+ img_h, img_w = np.array(original_image).shape[:2]
318
+ heatmap_display_np = np.zeros((img_h, img_w), dtype=np.float32)
319
+ if face_box:
320
+ x, y, w_fb, h_fb = map(int, face_box)
321
+ if w_fb > 0 and h_fb > 0:
322
+ cam_resized_face = cv2.resize(raw_cam, (w_fb, h_fb), interpolation=cv2.INTER_LINEAR)
323
+ y_end, x_end = min(y + h_fb, img_h), min(x + w_fb, img_w)
324
+ h_clip, w_clip = y_end - y, x_end - x
325
+ if h_clip > 0 and w_clip > 0:
326
+ heatmap_display_np[y:y_end, x:x_end] = cam_resized_face[:h_clip, :w_clip]
327
+ else:
328
+ heatmap_display_np = cv2.resize(raw_cam, (img_w, img_h), interpolation=cv2.INTER_LINEAR)
329
+ else:
330
+ heatmap_display_np = cv2.resize(raw_cam, (img_w, img_h), interpolation=cv2.INTER_LINEAR)
331
+
332
+ min_h, max_h = np.min(heatmap_display_np), np.max(heatmap_display_np)
333
+ if max_h > min_h:
334
+ heatmap_norm = (heatmap_display_np - min_h) / (max_h - min_h)
335
+ else:
336
+ heatmap_norm = np.zeros_like(heatmap_display_np)
337
+ heatmap_rgb = (plt.cm.jet(heatmap_norm)[:, :, :3] * 255).astype(np.uint8)
338
+ cam_heatmap_img = Image.fromarray(heatmap_rgb)
339
+ print(" Heatmap generated.")
340
+
341
+ overlay_img = overlay_cam_on_image(original_image, raw_cam, face_box)
342
+ print(" Overlay generated.")
343
+
344
+ if overlay_img:
345
+ comparison_img = save_comparison(original_image, raw_cam, overlay_img, face_box)
346
+ print(" Comparison generated.")
347
+ else:
348
+ print(" Skipping comparison image because overlay failed.")
349
+
350
+ except Exception as vis_e:
351
+ print(f"Error during visualization generation: {vis_e}")
352
+ import traceback
353
+ traceback.print_exc()
354
+
355
+ print("--- Prediction and Grad-CAM Finished ---")
356
+ return raw_cam, cam_heatmap_img, overlay_img, comparison_img
357
+
358
+ # Face Detection Dataset
359
+ class ImageDataset(torch.utils.data.Dataset):
360
+ def __init__(self, image, transform=None, face_only=True):
361
+ self.image = image
362
+ self.transform = transform
363
+ self.face_only = face_only
364
+ try:
365
+ self.face_detector = cv2.CascadeClassifier(
366
+ cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
367
+ )
368
+ if self.face_detector.empty():
369
+ raise IOError("Failed to load cascade file")
370
+ except Exception as e:
371
+ print(f"Error loading Haar Cascade: {e}. Face detection might fail.")
372
+ class DummyDetector:
373
+ def detectMultiScale(self, *args, **kwargs): return []
374
+ self.face_detector = DummyDetector()
375
+
376
+ def __len__(self):
377
+ return 1
378
+
379
+ def detect_face(self, image_np):
380
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
381
+ faces = self.face_detector.detectMultiScale(gray, 1.1, 5)
382
+ if len(faces) == 0:
383
+ print("No face detected, using full image as fallback.")
384
+ h, w = image_np.shape[:2]
385
+ return (0, 0, w, h), image_np
386
+ areas = [w * h for (x, y, w, h) in faces]
387
+ idx = np.argmax(areas) # Select largest face
388
+ x, y, w, h = faces[idx]
389
+ pad_x, pad_y = int(w * 0.05), int(h * 0.05)
390
+ x1, y1 = max(0, x - pad_x), max(0, y - pad_y)
391
+ x2, y2 = min(image_np.shape[1], x + w + pad_x), min(image_np.shape[0], y + h + pad_y)
392
+ face_img = image_np[y1:y2, x1:x2]
393
+ return (x1, y1, x2 - x1, y2 - y1), face_img
394
+
395
+ def __getitem__(self, idx):
396
+ image_np = np.array(self.image)
397
+ original_image = self.image.copy()
398
+ face_box_final = None
399
+ processed_image = original_image
400
+
401
+ if self.face_only:
402
+ try:
403
+ face_box, face_img_np = self.detect_face(image_np)
404
+ if face_img_np.size == 0 or face_box[2] <= 0 or face_box[3] <= 0:
405
+ print("Warning: Face detection returned empty or invalid region. Using full image.")
406
+ face_box_final = None
407
+ processed_image = original_image
408
+ else:
409
+ processed_image = Image.fromarray(face_img_np)
410
+ face_box_final = face_box
411
+ except Exception as e:
412
+ print(f"Error during face detection: {e}. Using full image.")
413
+ face_box_final = None
414
+ processed_image = original_image
415
+ else:
416
+ face_box_final = None
417
+ processed_image = original_image
418
+
419
+ if self.transform:
420
+ tensor = self.transform(processed_image)
421
+ else:
422
+ tensor = transforms.ToTensor()(processed_image)
423
+
424
+ return tensor, original_image, face_box_final
425
+
426
+ def predict_image(model, image, face_only=True):
427
+ device = next(model.parameters()).device
428
+ model.eval()
429
+
430
+ IMAGE_SIZE = 299
431
+ transform = transforms.Compose([
432
+ transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
433
+ transforms.ToTensor(),
434
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
435
+ ])
436
+
437
+ dataset = ImageDataset(image, transform=transform, face_only=face_only)
438
+ input_tensor, _, _ = dataset[0]
439
+ input_tensor = input_tensor.unsqueeze(0).to(device)
440
+
441
+ with torch.no_grad():
442
+ logits = model(input_tensor)
443
+ probabilities = F.softmax(logits, dim=1)
444
+
445
+ pred_prob = probabilities[0].max().item()
446
+ pred_class_idx = probabilities[0].argmax().item()
447
+ pred_label = "real" if pred_class_idx == 0 else "fake"
448
+
449
+ if pred_prob < 0.7: # Example threshold
450
+ print(f"Warning: Low confidence ({pred_prob:.4f}) detected. Model may need fine-tuning.")
451
+
452
+ print(f"--- Prediction ---")
453
+ print(f"Input Tensor Shape: {input_tensor.shape}")
454
+ print(f"Logits: {logits.cpu().numpy()}")
455
+ print(f"Probabilities: {probabilities.cpu().numpy()}")
456
+ print(f"Predicted Class: {pred_label} (Index: {pred_class_idx})")
457
+ print(f"Confidence: {pred_prob:.4f}")
458
+ print(f"--------------------")
459
+
460
+ return pred_class_idx, pred_prob