File size: 14,243 Bytes
c8df794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""
Grad-CAM Implementation for Crop Disease Detection using pytorch-grad-cam
Generates visual explanations showing which parts of the leaf image the model focuses on
"""

import torch
import torch.nn.functional as F
import cv2
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from pathlib import Path
import base64
import io
import os

try:
    from pytorch_grad_cam import GradCAM
    from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
    from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
    PYTORCH_GRAD_CAM_AVAILABLE = True
except ImportError:
    print("Warning: pytorch-grad-cam not available. Installing...")
    import subprocess
    import sys
    subprocess.check_call([sys.executable, "-m", "pip", "install", "grad-cam"])
    try:
        from pytorch_grad_cam import GradCAM
        from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
        from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
        PYTORCH_GRAD_CAM_AVAILABLE = True
    except ImportError:
        PYTORCH_GRAD_CAM_AVAILABLE = False
        print("Warning: Could not import pytorch-grad-cam after installation")

class CropDiseaseExplainer:
    """High-level interface for crop disease explanation using pytorch-grad-cam"""
    
    def __init__(self, model, class_names, device='cpu'):
        """
        Initialize explainer
        
        Args:
            model: Trained model
            class_names: List of class names
            device: Device to run on
        """
        self.model = model.to(device)
        self.class_names = class_names
        self.device = device
        
        # Define target layer for Grad-CAM (last convolutional layer)
        target_layers = []
        
        # Try different model architectures
        if hasattr(model, 'resnet') and hasattr(model.resnet, 'layer4'):
            # For our CropDiseaseResNet50 model
            target_layers = [model.resnet.layer4[-1]]
            print(f"Using target layer: model.resnet.layer4[-1]")
        elif hasattr(model, 'layer4'):
            # For standard ResNet
            target_layers = [model.layer4[-1]]
            print(f"Using target layer: model.layer4[-1]")
        else:
            # Try to find the last convolutional layer
            for name, module in model.named_modules():
                if isinstance(module, (torch.nn.Conv2d, torch.nn.modules.conv.Conv2d)):
                    target_layers = [module]
                    print(f"Using target layer: {name}")
        
        if not target_layers:
            print("Warning: Could not find suitable target layer for Grad-CAM")
            self.grad_cam = None
            return
        
        self.target_layers = target_layers
        
        # Initialize Grad-CAM with better error handling
        if PYTORCH_GRAD_CAM_AVAILABLE:
            try:
                # Ensure model is in eval mode
                self.model.eval()
                
                # Create a wrapper to fix potential issues
                class ModelWrapper(torch.nn.Module):
                    def __init__(self, model):
                        super().__init__()
                        self.model = model
                    
                    def forward(self, x):
                        return self.model(x)
                
                wrapped_model = ModelWrapper(self.model)
                
                self.grad_cam = GradCAM(
                    model=wrapped_model, 
                    target_layers=self.target_layers
                )
                print("✅ Grad-CAM initialized successfully")
            except Exception as e:
                print(f"Error initializing Grad-CAM: {e}")
                print("Falling back to alternative implementation...")
                self.grad_cam = None
        else:
            self.grad_cam = None
            print("Warning: pytorch-grad-cam not available, Grad-CAM disabled")
    
    def explain_prediction(self, image_path, save_dir='outputs/heatmaps', 
                          return_base64=False, target_class=None):
        """
        Generate complete explanation for an image with robust error handling
        
        Args:
            image_path: Path to input image
            save_dir: Directory to save explanations
            return_base64: Whether to return base64 encoded image
            target_class: Specific class to target (if None, uses predicted class)
            
        Returns:
            explanation: Dictionary with prediction and explanation
        """
        
        # Load and preprocess image
        original_image = Image.open(image_path).convert('RGB')
        original_np = np.array(original_image) / 255.0  # Normalize to [0,1]
        
        # Preprocessing transforms (should match training transforms)
        from torchvision import transforms
        transform = transforms.Compose([
            transforms.Resize((224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], 
                               std=[0.229, 0.224, 0.225])
        ])
        
        input_tensor = transform(original_image).unsqueeze(0).to(self.device)
        
        # Get prediction
        self.model.eval()
        with torch.no_grad():
            outputs = self.model(input_tensor)
            probabilities = F.softmax(outputs, dim=1)
            predicted_idx = torch.argmax(probabilities, dim=1).item()
            confidence = probabilities[0][predicted_idx].item()
        
        # Use target class if specified, otherwise use predicted class
        target_idx = target_class if target_class is not None else predicted_idx
        
        # Try to generate visual explanation
        try:
            if PYTORCH_GRAD_CAM_AVAILABLE and self.grad_cam is not None:
                # Try pytorch-grad-cam first
                cam_image = self._generate_pytorch_gradcam(
                    input_tensor, original_image, target_idx
                )
            else:
                # Use fallback method
                cam_image = self._generate_simple_attention(
                    input_tensor, original_image, target_idx
                )
            
            # Create save directory
            Path(save_dir).mkdir(parents=True, exist_ok=True)
            
            # Save visualization
            filename = Path(image_path).stem
            save_path = Path(save_dir) / f"{filename}_gradcam.jpg"
            cam_image.save(save_path)
            
            # Prepare return data
            result = {
                'predicted_class': self.class_names[predicted_idx],
                'predicted_idx': predicted_idx,
                'confidence': confidence,
                'target_class': self.class_names[target_idx],
                'target_idx': target_idx,
                'save_path': str(save_path),
                'cam_image': cam_image
            }
            
            # Add base64 encoding if requested
            if return_base64:
                buffer = io.BytesIO()
                cam_image.save(buffer, format='JPEG')
                buffer.seek(0)
                base64_str = base64.b64encode(buffer.getvalue()).decode()
                result['overlay_base64'] = base64_str
            
            return result
            
        except Exception as e:
            print(f"Error generating explanation: {e}")
            # Return basic prediction without visual explanation
            return {
                'predicted_class': self.class_names[predicted_idx],
                'predicted_idx': predicted_idx,
                'confidence': confidence,
                'target_class': self.class_names[target_idx],
                'target_idx': target_idx,
                'error': 'Visual explanation not available',
                'save_path': '',
                'cam_image': original_image
            }
    
    def _generate_pytorch_gradcam(self, input_tensor, original_image, target_idx):
        """Generate Grad-CAM using pytorch-grad-cam library"""
        targets = [ClassifierOutputTarget(target_idx)]
        
        # Resize original image for overlay
        original_resized = cv2.resize(np.array(original_image), (224, 224))
        original_resized = original_resized / 255.0
        
        # Ensure input tensor requires grad
        input_tensor.requires_grad_(True)
        
        # Generate CAM
        grayscale_cam = self.grad_cam(input_tensor=input_tensor, targets=targets)
        
        if grayscale_cam is None:
            raise Exception("Grad-CAM returned None")
        
        # Ensure we have the right shape
        if len(grayscale_cam.shape) == 3 and grayscale_cam.shape[0] == 1:
            grayscale_cam = grayscale_cam[0, :]
        elif len(grayscale_cam.shape) != 2:
            grayscale_cam = grayscale_cam.reshape(224, 224)
        
        # Create visualization
        cam_image = show_cam_on_image(original_resized, grayscale_cam, use_rgb=True)
        
        # Convert to PIL Image
        return Image.fromarray((cam_image * 255).astype(np.uint8))
    
    def _generate_simple_attention(self, input_tensor, original_image, target_idx):
        """Generate simple attention map as fallback"""
        print("Using simple attention fallback method...")
        
        # Enable gradients
        input_tensor.requires_grad_(True)
        
        # Forward pass
        output = self.model(input_tensor)
        
        # Get gradient of target class score with respect to input
        self.model.zero_grad()
        target_score = output[0, target_idx]
        target_score.backward()
        
        # Get gradients
        gradients = input_tensor.grad.data
        
        # Create simple attention map (average across channels)
        attention = torch.mean(torch.abs(gradients), dim=1).squeeze()
        
        # Normalize to [0, 1]
        attention = (attention - attention.min()) / (attention.max() - attention.min())
        
        # Convert to numpy
        attention_np = attention.cpu().numpy()
        
        # Resize original image
        original_resized = cv2.resize(np.array(original_image), (224, 224)) / 255.0
        
        # Create simple overlay
        heatmap = cm.jet(attention_np)[:, :, :3]  # Remove alpha channel
        overlay = 0.7 * original_resized + 0.3 * heatmap
        
        # Convert to PIL Image
        return Image.fromarray((overlay * 255).astype(np.uint8))

def load_model_and_generate_gradcam(model_path, image_path, output_path=None, target_class=None):
    """
    Complete example function that loads a model and generates Grad-CAM visualization
    
    Args:
        model_path: Path to the saved model file
        image_path: Path to input image
        output_path: Path to save the output (optional)
        target_class: Target class index (optional, uses prediction if None)
    
    Returns:
        Dictionary with results
    """
    # Import model
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__)))
    from model import CropDiseaseResNet50
    
    # Define class names
    class_names = [
        'Corn___Cercospora_leaf_spot_Gray_leaf_spot',
        'Corn___Common_rust',
        'Corn___healthy',
        'Corn___Northern_Leaf_Blight',
        'Potato___Early_Blight',
        'Potato___healthy',
        'Potato___Late_Blight',
        'Tomato___Bacterial_spot',
        'Tomato___Early_blight',
        'Tomato___healthy',
        'Tomato___Late_blight',
        'Tomato___Leaf_Mold',
        'Tomato___Septoria_leaf_spot',
        'Tomato___Spider_mites_Two_spotted_spider_mite',
        'Tomato___Target_Spot',
        'Tomato___Tomato_mosaic_virus',
        'Tomato___Tomato_Yellow_Leaf_Curl_Virus'
    ]
    
    # Step 1: Load the trained model
    print(f"Loading model from {model_path}...")
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    model = CropDiseaseResNet50(num_classes=len(class_names), pretrained=False)
    checkpoint = torch.load(model_path, map_location=device)
    
    # Handle checkpoint format
    if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
        state_dict = checkpoint['model_state_dict']
        if 'class_names' in checkpoint:
            class_names = checkpoint['class_names']
    else:
        state_dict = checkpoint
    
    model.load_state_dict(state_dict, strict=True)
    model.to(device)
    model.eval()
    print(f"✅ Model loaded successfully!")
    
    # Step 2: Initialize Grad-CAM explainer
    print("Initializing Grad-CAM explainer...")
    explainer = CropDiseaseExplainer(model, class_names, device)
    
    # Step 3: Generate Grad-CAM visualization
    print(f"Generating Grad-CAM for {image_path}...")
    result = explainer.explain_prediction(
        image_path=image_path,
        save_dir='outputs/heatmaps',
        return_base64=True,
        target_class=target_class
    )
    
    if 'error' in result:
        print(f"❌ Error: {result['error']}")
        return result
    
    # Step 4: Save output if path specified
    if output_path:
        result['cam_image'].save(output_path)
        print(f"✅ Saved Grad-CAM visualization to {output_path}")
    
    # Print results
    print(f"✅ Grad-CAM generated successfully!")
    print(f"   Predicted: {result['predicted_class']} ({result['confidence']:.1%})")
    print(f"   Target: {result['target_class']}")
    print(f"   Saved to: {result['save_path']}")
    
    return result

# Example usage
if __name__ == "__main__":
    # Example usage
    model_path = "../models/crop_disease_v3_model.pth"
    image_path = "../test_leaf_sample.jpg"
    output_path = "../outputs/gradcam_example.jpg"
    
    if os.path.exists(model_path) and os.path.exists(image_path):
        result = load_model_and_generate_gradcam(
            model_path=model_path,
            image_path=image_path,
            output_path=output_path
        )
    else:
        print("Model or image file not found!")
        print(f"Model path: {model_path}")
        print(f"Image path: {image_path}")