Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,159 +1,207 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Gradio App for Bird Classification - Hugging Face Deployment
|
| 3 |
-
Enhanced model with
|
| 4 |
-
"""
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import torch
|
| 7 |
-
import torch.nn.functional as F
|
| 8 |
-
from PIL import Image
|
| 9 |
-
import json
|
| 10 |
-
import numpy as np
|
| 11 |
-
from torchvision import transforms
|
| 12 |
-
import os
|
| 13 |
-
|
| 14 |
-
# Import our model architecture
|
| 15 |
-
from models import create_model
|
| 16 |
-
|
| 17 |
-
# Configuration
|
| 18 |
-
MODEL_PATH = "best_model.pth"
|
| 19 |
-
CLASS_NAMES_PATH = "class_names.json"
|
| 20 |
-
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 21 |
-
|
| 22 |
-
# Load class names
|
| 23 |
-
with open(CLASS_NAMES_PATH, 'r') as f:
|
| 24 |
-
class_names = json.load(f)
|
| 25 |
-
|
| 26 |
-
NUM_CLASSES = len(class_names)
|
| 27 |
-
|
| 28 |
-
# Load model
|
| 29 |
-
print("Loading model...")
|
| 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 |
iface.launch(debug=True)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gradio App for Bird Classification - Hugging Face Deployment
|
| 3 |
+
Enhanced model with architecture auto-detection and error handling.
|
| 4 |
+
"""
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import json
|
| 10 |
+
import numpy as np
|
| 11 |
+
from torchvision import transforms
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
# Import our model architecture
|
| 15 |
+
from models import create_model
|
| 16 |
+
|
| 17 |
+
# Configuration
|
| 18 |
+
MODEL_PATH = "best_model.pth"
|
| 19 |
+
CLASS_NAMES_PATH = "class_names.json"
|
| 20 |
+
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 21 |
+
|
| 22 |
+
# Load class names
|
| 23 |
+
with open(CLASS_NAMES_PATH, 'r') as f:
|
| 24 |
+
class_names = json.load(f)
|
| 25 |
+
|
| 26 |
+
NUM_CLASSES = len(class_names)
|
| 27 |
+
|
| 28 |
+
# Load model - detect architecture from checkpoint
|
| 29 |
+
print("Loading model...")
|
| 30 |
+
|
| 31 |
+
# First, try to detect the correct architecture from the model file
|
| 32 |
+
if os.path.exists(MODEL_PATH):
|
| 33 |
+
checkpoint = torch.load(MODEL_PATH, map_location='cpu')
|
| 34 |
+
|
| 35 |
+
# Detect EfficientNet variant based on feature dimensions
|
| 36 |
+
if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
|
| 37 |
+
state_dict = checkpoint['model_state_dict']
|
| 38 |
+
else:
|
| 39 |
+
state_dict = checkpoint
|
| 40 |
+
|
| 41 |
+
# Check backbone head feature size to determine EfficientNet variant
|
| 42 |
+
if 'backbone._conv_head.weight' in state_dict:
|
| 43 |
+
conv_head_shape = state_dict['backbone._conv_head.weight'].shape
|
| 44 |
+
if conv_head_shape[0] == 1536: # EfficientNet-B3
|
| 45 |
+
model_type = 'efficientnet_b3'
|
| 46 |
+
elif conv_head_shape[0] == 1408: # EfficientNet-B2
|
| 47 |
+
model_type = 'efficientnet_b2'
|
| 48 |
+
elif conv_head_shape[0] == 1280: # EfficientNet-B0/B1
|
| 49 |
+
model_type = 'efficientnet_b1'
|
| 50 |
+
else:
|
| 51 |
+
model_type = 'efficientnet_b2' # Default fallback
|
| 52 |
+
else:
|
| 53 |
+
model_type = 'efficientnet_b2' # Default fallback
|
| 54 |
+
|
| 55 |
+
# Check actual number of classes from classifier
|
| 56 |
+
if 'classifier.9.weight' in state_dict:
|
| 57 |
+
actual_classes = state_dict['classifier.9.weight'].shape[0]
|
| 58 |
+
else:
|
| 59 |
+
actual_classes = NUM_CLASSES
|
| 60 |
+
|
| 61 |
+
print("Detected model: {} with {} classes".format(model_type, actual_classes))
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
model_type = 'efficientnet_b2'
|
| 65 |
+
actual_classes = NUM_CLASSES
|
| 66 |
+
print("Model file not found, using default: {}".format(model_type))
|
| 67 |
+
|
| 68 |
+
model = create_model(
|
| 69 |
+
num_classes=actual_classes,
|
| 70 |
+
model_type=model_type,
|
| 71 |
+
pretrained=False, # We're loading trained weights
|
| 72 |
+
dropout_rate=0.3
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Load trained weights
|
| 76 |
+
if os.path.exists(MODEL_PATH):
|
| 77 |
+
try:
|
| 78 |
+
checkpoint = torch.load(MODEL_PATH, map_location=DEVICE)
|
| 79 |
+
if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
|
| 80 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
| 81 |
+
print("✅ Model loaded successfully! ({}, {} classes)".format(model_type, actual_classes))
|
| 82 |
+
else:
|
| 83 |
+
model.load_state_dict(checkpoint)
|
| 84 |
+
print("✅ Model loaded successfully! ({}, {} classes)".format(model_type, actual_classes))
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print("❌ Error loading model: {}".format(str(e)))
|
| 87 |
+
print("Please ensure the model architecture matches the saved weights.")
|
| 88 |
+
else:
|
| 89 |
+
print("⚠️ Model file not found. Please ensure best_model.pth is in the repository.")
|
| 90 |
+
|
| 91 |
+
model.to(DEVICE)
|
| 92 |
+
model.eval()
|
| 93 |
+
|
| 94 |
+
def predict_bird(image):
|
| 95 |
+
"""
|
| 96 |
+
Predict bird species from uploaded image.
|
| 97 |
+
"""
|
| 98 |
+
try:
|
| 99 |
+
# Preprocess image
|
| 100 |
+
if isinstance(image, np.ndarray):
|
| 101 |
+
image = Image.fromarray(image.astype('uint8'))
|
| 102 |
+
|
| 103 |
+
# Convert to RGB if needed
|
| 104 |
+
if image.mode != 'RGB':
|
| 105 |
+
image = image.convert('RGB')
|
| 106 |
+
|
| 107 |
+
# Define preprocessing step by step to avoid namespace issues
|
| 108 |
+
resize = transforms.Resize((320, 320))
|
| 109 |
+
to_tensor = transforms.ToTensor()
|
| 110 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 111 |
+
|
| 112 |
+
# Apply transformations step by step
|
| 113 |
+
resized_image = resize(image)
|
| 114 |
+
tensor_image = to_tensor(resized_image)
|
| 115 |
+
normalized_tensor = normalize(tensor_image)
|
| 116 |
+
input_tensor = normalized_tensor.unsqueeze(0).to(DEVICE)
|
| 117 |
+
|
| 118 |
+
# Prediction
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
outputs = model(input_tensor)
|
| 121 |
+
probabilities = F.softmax(outputs, dim=1)
|
| 122 |
+
confidence, predicted = torch.max(probabilities, 1)
|
| 123 |
+
|
| 124 |
+
# Get top 5 predictions
|
| 125 |
+
top5_prob, top5_indices = torch.topk(probabilities, 5)
|
| 126 |
+
|
| 127 |
+
# Format results
|
| 128 |
+
results = {}
|
| 129 |
+
for i in range(5):
|
| 130 |
+
class_idx = top5_indices[0][i].item()
|
| 131 |
+
prob = top5_prob[0][i].item()
|
| 132 |
+
# Handle potential class index mismatch
|
| 133 |
+
if class_idx < len(class_names):
|
| 134 |
+
class_name = class_names[class_idx].replace('_', ' ')
|
| 135 |
+
else:
|
| 136 |
+
class_name = "Class_" + str(class_idx)
|
| 137 |
+
results[class_name] = float(prob)
|
| 138 |
+
|
| 139 |
+
return results
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return {"Error": "Prediction failed: " + str(e)}
|
| 143 |
+
|
| 144 |
+
# Create Gradio interface
|
| 145 |
+
title = "🐦 Bird Species Classifier"
|
| 146 |
+
description = """
|
| 147 |
+
## Advanced Bird Classification Model
|
| 148 |
+
|
| 149 |
+
This model can classify **199 different bird species** using advanced deep learning techniques:
|
| 150 |
+
|
| 151 |
+
### Model Details:
|
| 152 |
+
- **Architecture**: Auto-detected EfficientNet (B2/B3) with enhanced regularization
|
| 153 |
+
- **Training Strategy**: Progressive training with advanced augmentation
|
| 154 |
+
- **Performance**: Optimized for accuracy and reliability
|
| 155 |
+
- **Dataset**: CUB-200-2011 (199 bird species)
|
| 156 |
+
|
| 157 |
+
### How to use:
|
| 158 |
+
1. Upload a clear image of a bird
|
| 159 |
+
2. The model will predict the top 5 most likely species
|
| 160 |
+
3. Confidence scores show the model's certainty
|
| 161 |
+
|
| 162 |
+
### Best Results Tips:
|
| 163 |
+
- Use high-quality, well-lit images
|
| 164 |
+
- Ensure the bird is clearly visible
|
| 165 |
+
- Close-up shots work better than distant ones
|
| 166 |
+
- Natural lighting produces better results
|
| 167 |
+
|
| 168 |
+
**Note**: This model was trained on the CUB-200-2011 dataset and works best with North American bird species.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
article = """
|
| 172 |
+
### Technical Implementation:
|
| 173 |
+
- **Framework**: PyTorch with auto-detected EfficientNet backbone
|
| 174 |
+
- **Training**: Progressive training with advanced augmentation strategies
|
| 175 |
+
- **Regularization**: Optimized dropout rates and comprehensive validation
|
| 176 |
+
- **Image Size**: 320x320 pixels for optimal detail capture
|
| 177 |
+
|
| 178 |
+
### About the Model:
|
| 179 |
+
This bird classifier was developed using advanced machine learning techniques including:
|
| 180 |
+
- Transfer learning from ImageNet-pretrained EfficientNet
|
| 181 |
+
- Progressive training strategy across multiple stages
|
| 182 |
+
- Advanced data augmentation for improved generalization
|
| 183 |
+
- Comprehensive evaluation and optimization
|
| 184 |
+
|
| 185 |
+
The model automatically detects the correct architecture (EfficientNet-B2 or B3) from the saved weights,
|
| 186 |
+
ensuring compatibility and optimal performance.
|
| 187 |
+
|
| 188 |
+
For more details about the training process and methodology, please refer to the repository documentation.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
# Create the interface
|
| 192 |
+
iface = gr.Interface(
|
| 193 |
+
fn=predict_bird,
|
| 194 |
+
inputs=gr.Image(type="pil", label="Upload Bird Image"),
|
| 195 |
+
outputs=gr.Label(num_top_classes=5, label="Predictions"),
|
| 196 |
+
title=title,
|
| 197 |
+
description=description,
|
| 198 |
+
article=article,
|
| 199 |
+
examples=[
|
| 200 |
+
# You can add example images here if you have them
|
| 201 |
+
],
|
| 202 |
+
allow_flagging="never",
|
| 203 |
+
theme=gr.themes.Soft()
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
iface.launch(debug=True)
|