File size: 6,725 Bytes
eb03e62
7ae96e1
 
 
 
eb03e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c39af0a
eb03e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2182d48
eb03e62
2182d48
eb03e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2182d48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb03e62
 
 
7ae96e1
 
eb03e62
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import torch
import torchvision.transforms as transforms
from PIL import Image
from torchvision.models import resnet50
import os
import logging
from typing import Optional, Union
import numpy as np
from pathlib import Path

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Directory Configuration
BASE_DIR = Path(__file__).resolve().parent
MODELS_DIR = BASE_DIR / "models"
EXAMPLES_DIR = BASE_DIR / "examples"
STATIC_DIR = BASE_DIR / "static" / "uploaded"

# Ensure directories exist
STATIC_DIR.mkdir(parents=True, exist_ok=True)

# Global variables
MODEL_PATH = MODELS_DIR / "model_10.pth"
CLASSES_PATH = BASE_DIR / "classes.txt"
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

def load_class_labels() -> Optional[list]:
    """
    Load class labels from the classes.txt file
    """
    try:
        if not CLASSES_PATH.exists():
            raise FileNotFoundError(f"Classes file not found at {CLASSES_PATH}")
            
        with open(CLASSES_PATH, 'r') as f:
            return [line.strip() for line in f.readlines()]
    except Exception as e:
        logger.error(f"Error loading class labels: {str(e)}")
        return None

# Load class labels
CLASS_NAMES = load_class_labels()
if CLASS_NAMES is None:
    raise RuntimeError("Failed to load class labels from classes.txt")

# Cache the model to avoid reloading for each prediction
model = None

def load_model() -> Optional[torch.nn.Module]:
    """
    Load the ResNet50 model with error handling
    """
    global model
    
    try:
        if model is not None:
            return model
            
        if not MODEL_PATH.exists():
            raise FileNotFoundError(f"Model file not found at {MODEL_PATH}")
        
        logger.info(f"Loading model on {DEVICE}")
        model = resnet50(pretrained=False)
        model.fc = torch.nn.Linear(model.fc.in_features, len(CLASS_NAMES))
        
        # Load the model weights
        state_dict = torch.load(MODEL_PATH, map_location=DEVICE)
        
        if 'state_dict' in state_dict:
            state_dict = state_dict['state_dict']
        
        model.load_state_dict(state_dict)
        model.to(DEVICE)
        model.eval()
        
        logger.info("Model loaded successfully")
        return model
        
    except Exception as e:
        logger.error(f"Error loading model: {str(e)}")
        return None

def preprocess_image(image: Union[np.ndarray, Image.Image]) -> Optional[torch.Tensor]:
    """
    Preprocess the input image with error handling
    """
    try:
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)
        
        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]
            )
        ])
        
        return transform(image).unsqueeze(0).to(DEVICE)
        
    except Exception as e:
        logger.error(f"Error preprocessing image: {str(e)}")
        return None

def predict(image: Union[np.ndarray, None]) -> tuple[str, dict]:
    """
    Make predictions on the input image with comprehensive error handling
    Returns the predicted class and top 5 confidence scores
    """
    try:
        if image is None:
            return "Error: No image provided", {}
        
        model = load_model()
        if model is None:
            return "Error: Failed to load model", {}
            
        # Ensure model is in eval mode
        model.eval()
        
        input_tensor = preprocess_image(image)
        if input_tensor is None:
            return "Error: Failed to preprocess image", {}
            
        with torch.no_grad():
            input_tensor = input_tensor.to(DEVICE)
            output = model(input_tensor)
            probabilities = torch.nn.functional.softmax(output[0], dim=0)
            
        # Get predictions and confidences
        top_5_probs, top_5_indices = torch.topk(probabilities, k=5)
        
        # Format confidences with exactly 2 decimal places
        confidences = {
            CLASS_NAMES[idx.item()]: "{:.2f}".format(float(prob.item() * 100))
            for prob, idx in zip(top_5_probs, top_5_indices)
        }
        
        predicted_class = CLASS_NAMES[top_5_indices[0].item()]
        
        return predicted_class, confidences
                
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        return f"Error during prediction: {str(e)}", {}

def get_example_list() -> list:
    """
    Get list of example images from the examples directory
    """
    try:
        examples = []
        for ext in ['.jpg', '.jpeg', '.png']:
            examples.extend(list(EXAMPLES_DIR.glob(f'*{ext}')))
        return [[str(ex)] for ex in sorted(examples)]
    except Exception as e:
        logger.error(f"Error loading examples: {str(e)}")
        return []

# Create Gradio interface with error handling
try:
    with gr.Blocks(theme=gr.themes.Base()) as iface:
        gr.Markdown("# Image Classification with ResNet50")
        gr.Markdown("Upload an image to classify. The model will predict the class and show top 5 confidence scores.")
        
        with gr.Row():
            with gr.Column(scale=1):
                input_image = gr.Image(type="numpy", label="Upload Image")
                predict_btn = gr.Button("Predict")
            
            with gr.Column(scale=1):
                output_label = gr.Label(label="Predicted Class", num_top_classes=1)
                confidence_label = gr.Label(label="Top 5 Predictions", num_top_classes=5)

        # Add examples
        gr.Examples(
            examples=get_example_list(),
            inputs=input_image,
            outputs=[output_label, confidence_label],
            fn=predict,
            cache_examples=True
        )

        # Set up prediction event
        predict_btn.click(
            fn=predict,
            inputs=input_image,
            outputs=[output_label, confidence_label]
        )
        input_image.change(
            fn=predict,
            inputs=input_image,
            outputs=[output_label, confidence_label]
        )

except Exception as e:
    logger.error(f"Error creating Gradio interface: {str(e)}")
    raise

if __name__ == "__main__":
    try:
        load_model()  # Pre-load the model
        iface.launch(
            share=False,
            server_name="0.0.0.0",
            server_port=7860,
            debug=False
        )
    except Exception as e:
        logger.error(f"Error launching application: {str(e)}")