File size: 6,928 Bytes
03d5bce
 
 
aca7c2f
03d5bce
 
 
 
 
 
 
aca7c2f
 
03d5bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca7c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03d5bce
 
 
 
 
21859e7
e340399
21859e7
 
03d5bce
 
 
 
 
21859e7
 
 
 
 
 
 
 
e340399
21859e7
 
 
 
 
 
 
 
 
e340399
 
03d5bce
 
e340399
03d5bce
 
 
e340399
03d5bce
782ebb5
03d5bce
 
 
 
 
 
 
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
"""
Simple Demo for Pest and Disease Classification
For Hugging Face Space Deployment
Supports both single model and ensemble prediction
"""

import torch
from PIL import Image
import json
import gradio as gr
from torchvision import transforms
import numpy as np
from pathlib import Path

from model import create_model


class PestDiseasePredictor:
    """Simple predictor class"""

    def __init__(self, checkpoint_path, label_mapping_path, backbone='resnet50', device='cuda'):
        self.device = torch.device(device if torch.cuda.is_available() else 'cpu')

        # Load label mapping
        with open(label_mapping_path, 'r', encoding='utf-8') as f:
            mapping = json.load(f)
            self.id_to_label = {int(k): v for k, v in mapping['id_to_label'].items()}
            self.num_classes = mapping['num_classes']

        # Load model
        self.model = create_model(
            num_classes=self.num_classes,
            backbone=backbone,
            pretrained=False
        )

        # Load checkpoint
        checkpoint = torch.load(checkpoint_path, map_location=self.device)
        self.model.load_state_dict(checkpoint['model_state_dict'])
        self.model = self.model.to(self.device)
        self.model.eval()

        # Image transforms
        self.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])
        ])

        print(f"βœ… Model loaded from {checkpoint_path}")
        print(f"πŸ’» Device: {self.device}")
        print(f"πŸ“š Classes: {self.num_classes}")

    def predict(self, image):
        if image.mode != 'RGB':
            image = image.convert('RGB')

        img_tensor = self.transform(image).unsqueeze(0).to(self.device)
        with torch.no_grad():
            outputs = self.model(img_tensor)
            probs = torch.nn.functional.softmax(outputs, dim=1)[0].cpu().numpy()

        results = {self.id_to_label[i]: float(p) for i, p in enumerate(probs)}
        return dict(sorted(results.items(), key=lambda x: x[1], reverse=True))


class EnsemblePredictor:
    """Ensemble predictor using weighted soft voting"""

    def __init__(self, checkpoint_paths, weights, label_mapping_path, backbone='efficientnet_b3', device='cuda'):
        self.device = torch.device(device if torch.cuda.is_available() else 'cpu')

        # Normalize weights to sum to 1
        weights = np.array(weights)
        self.weights = weights / weights.sum()

        # Load label mapping
        with open(label_mapping_path, 'r', encoding='utf-8') as f:
            mapping = json.load(f)
            self.id_to_label = {int(k): v for k, v in mapping['id_to_label'].items()}
            self.num_classes = mapping['num_classes']

        # Load all models
        self.models = []
        print(f"\n{'='*80}")
        print("Loading Ensemble Models")
        print(f"{'='*80}")

        for i, checkpoint_path in enumerate(checkpoint_paths):
            print(f"\nModel {i+1}/{len(checkpoint_paths)}")
            print(f"  Checkpoint: {checkpoint_path}")
            print(f"  Weight: {self.weights[i]:.4f}")

            # Create model
            model = create_model(
                num_classes=self.num_classes,
                backbone=backbone,
                pretrained=False
            )

            # Load checkpoint
            if Path(checkpoint_path).exists():
                checkpoint = torch.load(checkpoint_path, map_location=self.device)
                model.load_state_dict(checkpoint['model_state_dict'])
                model = model.to(self.device)
                model.eval()
                self.models.append(model)
                print(f"  βœ… Loaded successfully")
            else:
                print(f"  ❌ Checkpoint not found: {checkpoint_path}")
                raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")

        print(f"\n{'='*80}")
        print(f"βœ… Ensemble loaded: {len(self.models)} models")
        print(f"πŸ’» Device: {self.device}")
        print(f"πŸ“š Classes: {self.num_classes}")
        print(f"{'='*80}\n")

        # Image transforms
        self.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])
        ])

    def predict(self, image):
        """Predict using weighted soft voting"""
        if image.mode != 'RGB':
            image = image.convert('RGB')

        img_tensor = self.transform(image).unsqueeze(0).to(self.device)

        # Get predictions from all models
        ensemble_probs = np.zeros(self.num_classes)

        with torch.no_grad():
            for model, weight in zip(self.models, self.weights):
                outputs = model(img_tensor)
                probabilities = torch.nn.functional.softmax(outputs, dim=1)
                probs = probabilities[0].cpu().numpy()
                ensemble_probs += weight * probs

        # Create results dictionary
        results = {}
        for idx, prob in enumerate(ensemble_probs):
            class_name = self.id_to_label[idx]
            results[class_name] = float(prob)

        return dict(sorted(results.items(), key=lambda x: x[1], reverse=True))


# ========== For Hugging Face Space ==========
label_mapping_path = "label_mapping.json"
backbone = 'efficientnet_b3'
device = "cuda"

# Load single model predictor
single_checkpoint = "checkpoints/best_model_fold1.pth"
single_predictor = PestDiseasePredictor(
    checkpoint_path=single_checkpoint,
    label_mapping_path=label_mapping_path,
    backbone=backbone,
    device=device
)

# Load ensemble predictor
ensemble_checkpoints = [
    "checkpoints/best_model_fold1.pth",
    "checkpoints/best_model_fold2.pth",
    "checkpoints/best_model_fold3.pth",
    "checkpoints/best_model_fold4.pth",
    "checkpoints/best_model_fold5.pth"
]
ensemble_weights = [1.0, 1.0, 1.0, 1.0, 1.0]

ensemble_predictor = EnsemblePredictor(
    checkpoint_paths=ensemble_checkpoints,
    weights=ensemble_weights,
    label_mapping_path=label_mapping_path,
    backbone=backbone,
    device=device
)

def predict_image(image):
    """Predict with ensemble model"""
    if image is None:
        return None
    return ensemble_predictor.predict(image) # return single_predictor.predict(image)

demo = gr.Interface(
    fn=predict_image,
    inputs=gr.Image(type="pil", label="Upload Image"),
    outputs=gr.Label(num_top_classes=10, label="Predictions"),
    title="<center>🌿 Pest and Disease Classification</center>",
    description="Upload an image of a citrus leaf to classify its pest or disease type.",
    theme=gr.themes.Soft(),
    allow_flagging="never"
)

if __name__ == "__main__":
    demo.launch()