Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,16 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
import os
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Define the breeds based on Indian bovine classification
|
| 10 |
BREEDS = [
|
|
@@ -33,614 +39,4 @@ BREED_INFO = {
|
|
| 33 |
"special_features": "Light to dark brown color with creamy white muzzle, exceptional longevity",
|
| 34 |
"weight": "600-700 kg",
|
| 35 |
"height": "135-150 cm",
|
| 36 |
-
"temperament": "Calm
|
| 37 |
-
},
|
| 38 |
-
"Holstein Friesian cattle": {
|
| 39 |
-
"type": "Dairy Cow",
|
| 40 |
-
"origin": "Netherlands/Germany",
|
| 41 |
-
"characteristics": "Highest milk production, excellent feed conversion, docile temperament",
|
| 42 |
-
"milk_yield": "8000-12000 liters per lactation",
|
| 43 |
-
"special_features": "Distinctive black and white patches, large frame, heat sensitive",
|
| 44 |
-
"weight": "580-700 kg",
|
| 45 |
-
"height": "140-150 cm",
|
| 46 |
-
"temperament": "Gentle and manageable"
|
| 47 |
-
},
|
| 48 |
-
"Jaffrabadi": {
|
| 49 |
-
"type": "Indigenous Dairy Buffalo",
|
| 50 |
-
"origin": "Gujarat, India (Saurashtra region)",
|
| 51 |
-
"characteristics": "Heaviest Indian buffalo breed, adapted to harsh semi-arid conditions",
|
| 52 |
-
"milk_yield": "2000-2500 liters per lactation",
|
| 53 |
-
"special_features": "Black color, dome-shaped forehead, ring-like horns, highest butterfat content",
|
| 54 |
-
"weight": "400-600 kg",
|
| 55 |
-
"height": "130-140 cm",
|
| 56 |
-
"temperament": "Hardy and resilient"
|
| 57 |
-
},
|
| 58 |
-
"Jersey cattle": {
|
| 59 |
-
"type": "Dairy Cow",
|
| 60 |
-
"origin": "Jersey, Channel Islands",
|
| 61 |
-
"characteristics": "Efficient feed conversion, calving ease, heat tolerant, docile",
|
| 62 |
-
"milk_yield": "4500-6500 liters per lactation",
|
| 63 |
-
"special_features": "Light tan to fawn color, smallest dairy breed, highest butterfat percentage",
|
| 64 |
-
"weight": "350-450 kg",
|
| 65 |
-
"height": "120-125 cm",
|
| 66 |
-
"temperament": "Alert and intelligent"
|
| 67 |
-
},
|
| 68 |
-
"Murrah": {
|
| 69 |
-
"type": "Indigenous Dairy Buffalo",
|
| 70 |
-
"origin": "Haryana and Punjab, India",
|
| 71 |
-
"characteristics": "Highest milk yielding buffalo breed, docile nature, good mothers",
|
| 72 |
-
"milk_yield": "2200-3000 liters per lactation",
|
| 73 |
-
"special_features": "Jet black color, tightly curved horns, compact body structure",
|
| 74 |
-
"weight": "450-650 kg",
|
| 75 |
-
"height": "130-135 cm",
|
| 76 |
-
"temperament": "Docile and calm"
|
| 77 |
-
},
|
| 78 |
-
"Red Dane cattle": {
|
| 79 |
-
"type": "Dual-purpose (Dairy & Beef)",
|
| 80 |
-
"origin": "Denmark",
|
| 81 |
-
"characteristics": "Hardy, disease resistant, excellent meat quality, easy calving",
|
| 82 |
-
"milk_yield": "8000-10000 liters per lactation",
|
| 83 |
-
"special_features": "Red to dark mahogany color with white markings, good heat tolerance",
|
| 84 |
-
"weight": "550-650 kg",
|
| 85 |
-
"height": "135-145 cm",
|
| 86 |
-
"temperament": "Gentle and cooperative"
|
| 87 |
-
},
|
| 88 |
-
"kankarej": {
|
| 89 |
-
"type": "Indigenous Dual-purpose (Dairy & Draught)",
|
| 90 |
-
"origin": "Gujarat, India (Kankrej territory)",
|
| 91 |
-
"characteristics": "Active, strong draught animal, drought resistant, disease resistant",
|
| 92 |
-
"milk_yield": "1500-2000 liters per lactation",
|
| 93 |
-
"special_features": "Silver to gray to steel black color, lyre-shaped horns, large pendulous ears",
|
| 94 |
-
"weight": "400-500 kg",
|
| 95 |
-
"height": "125-135 cm",
|
| 96 |
-
"temperament": "Active and energetic"
|
| 97 |
-
},
|
| 98 |
-
"sahiwal": {
|
| 99 |
-
"type": "Indigenous Dairy Cow",
|
| 100 |
-
"origin": "Punjab, Pakistan/India",
|
| 101 |
-
"characteristics": "Heat resistant, tick resistant, high disease resistance, docile",
|
| 102 |
-
"milk_yield": "2500-3200 liters per lactation",
|
| 103 |
-
"special_features": "Brownish red to grayish red color, loose dewlap, compact build",
|
| 104 |
-
"weight": "300-400 kg",
|
| 105 |
-
"height": "115-125 cm",
|
| 106 |
-
"temperament": "Docile and hardy"
|
| 107 |
-
},
|
| 108 |
-
"sahiwal cross": {
|
| 109 |
-
"type": "Crossbred Dairy Cow",
|
| 110 |
-
"origin": "Cross breeding programs (Sahiwal x exotic breeds)",
|
| 111 |
-
"characteristics": "Hybrid vigor, improved milk yield, better adaptability than pure exotic",
|
| 112 |
-
"milk_yield": "3000-4200 liters per lactation",
|
| 113 |
-
"special_features": "Variable color depending on cross, moderate heat tolerance, enhanced productivity",
|
| 114 |
-
"weight": "350-450 kg",
|
| 115 |
-
"height": "120-130 cm",
|
| 116 |
-
"temperament": "Balanced and adaptable"
|
| 117 |
-
},
|
| 118 |
-
"sibbi": {
|
| 119 |
-
"type": "Indigenous Dual-purpose (Draught & Beef)",
|
| 120 |
-
"origin": "Sibi, Baluchistan, Pakistan",
|
| 121 |
-
"characteristics": "Largest Zebu breed, exceptional size, extremely hardy, massive build",
|
| 122 |
-
"milk_yield": "1500-2200 liters per lactation",
|
| 123 |
-
"special_features": "Pure white to grey with black neck, tallest cattle breed, exhibited at Sibi Mela",
|
| 124 |
-
"weight": "500-800 kg",
|
| 125 |
-
"height": "140-160 cm",
|
| 126 |
-
"temperament": "Majestic and calm"
|
| 127 |
-
}
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
class IndianBovineClassifier:
|
| 131 |
-
def __init__(self, model_path=None):
|
| 132 |
-
"""Initialize the classifier with a pre-trained model"""
|
| 133 |
-
self.model = None
|
| 134 |
-
self.model_loaded = False
|
| 135 |
-
|
| 136 |
-
# Try to load the model from different possible paths
|
| 137 |
-
possible_paths = [
|
| 138 |
-
model_path,
|
| 139 |
-
"indian_bovine_breeds.h5",
|
| 140 |
-
"indian_bovine_breeds.pkl",
|
| 141 |
-
"model.h5",
|
| 142 |
-
"model.pkl"
|
| 143 |
-
]
|
| 144 |
-
|
| 145 |
-
for path in possible_paths:
|
| 146 |
-
if path and os.path.exists(path):
|
| 147 |
-
try:
|
| 148 |
-
print(f"Attempting to load model from: {path}")
|
| 149 |
-
if path.endswith('.h5') or path.endswith('.pkl'):
|
| 150 |
-
self.model = tf.keras.models.load_model(path)
|
| 151 |
-
self.model_loaded = True
|
| 152 |
-
print(f"✅ Model successfully loaded from: {path}")
|
| 153 |
-
break
|
| 154 |
-
except Exception as e:
|
| 155 |
-
print(f"❌ Failed to load model from {path}: {str(e)}")
|
| 156 |
-
continue
|
| 157 |
-
|
| 158 |
-
# If no model found, create demo model
|
| 159 |
-
if not self.model_loaded:
|
| 160 |
-
print("📝 No pre-trained model found. Creating demo model...")
|
| 161 |
-
self.model = self._create_demo_model()
|
| 162 |
-
print("✅ Demo model created successfully")
|
| 163 |
-
|
| 164 |
-
def _create_demo_model(self):
|
| 165 |
-
"""Create a demo model structure for demonstration"""
|
| 166 |
-
try:
|
| 167 |
-
# Create EfficientNetV2 base model
|
| 168 |
-
base_model = tf.keras.applications.EfficientNetV2S(
|
| 169 |
-
weights='imagenet',
|
| 170 |
-
include_top=False,
|
| 171 |
-
input_shape=(224, 224, 3)
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
# Add custom classification head
|
| 175 |
-
model = tf.keras.Sequential([
|
| 176 |
-
base_model,
|
| 177 |
-
tf.keras.layers.GlobalAveragePooling2D(),
|
| 178 |
-
tf.keras.layers.Dropout(0.3),
|
| 179 |
-
tf.keras.layers.Dense(256, activation='relu'),
|
| 180 |
-
tf.keras.layers.Dropout(0.2),
|
| 181 |
-
tf.keras.layers.Dense(len(BREEDS), activation='softmax')
|
| 182 |
-
])
|
| 183 |
-
|
| 184 |
-
# Compile the model
|
| 185 |
-
model.compile(
|
| 186 |
-
optimizer='adam',
|
| 187 |
-
loss='categorical_crossentropy',
|
| 188 |
-
metrics=['accuracy']
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
return model
|
| 192 |
-
|
| 193 |
-
except Exception as e:
|
| 194 |
-
print(f"❌ Error creating demo model: {str(e)}")
|
| 195 |
-
# Fallback to a simpler model if EfficientNet fails
|
| 196 |
-
return self._create_simple_model()
|
| 197 |
-
|
| 198 |
-
def _create_simple_model(self):
|
| 199 |
-
"""Create a simple fallback model"""
|
| 200 |
-
model = tf.keras.Sequential([
|
| 201 |
-
tf.keras.layers.Input(shape=(224, 224, 3)),
|
| 202 |
-
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
|
| 203 |
-
tf.keras.layers.MaxPooling2D((2, 2)),
|
| 204 |
-
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
|
| 205 |
-
tf.keras.layers.MaxPooling2D((2, 2)),
|
| 206 |
-
tf.keras.layers.Flatten(),
|
| 207 |
-
tf.keras.layers.Dense(64, activation='relu'),
|
| 208 |
-
tf.keras.layers.Dropout(0.5),
|
| 209 |
-
tf.keras.layers.Dense(len(BREEDS), activation='softmax')
|
| 210 |
-
])
|
| 211 |
-
|
| 212 |
-
model.compile(
|
| 213 |
-
optimizer='adam',
|
| 214 |
-
loss='categorical_crossentropy',
|
| 215 |
-
metrics=['accuracy']
|
| 216 |
-
)
|
| 217 |
-
|
| 218 |
-
return model
|
| 219 |
-
|
| 220 |
-
def preprocess_image(self, image):
|
| 221 |
-
"""Preprocess image for model prediction"""
|
| 222 |
-
try:
|
| 223 |
-
# Convert PIL image to numpy array if needed
|
| 224 |
-
if isinstance(image, Image.Image):
|
| 225 |
-
image = np.array(image)
|
| 226 |
-
|
| 227 |
-
# Ensure image is RGB
|
| 228 |
-
if len(image.shape) == 2:
|
| 229 |
-
image = np.stack([image] * 3, axis=-1)
|
| 230 |
-
elif image.shape[-1] == 4:
|
| 231 |
-
image = image[:, :, :3]
|
| 232 |
-
|
| 233 |
-
# Resize to model input size
|
| 234 |
-
image = tf.image.resize(image, [224, 224])
|
| 235 |
-
|
| 236 |
-
# Normalize pixel values to [0, 1]
|
| 237 |
-
image = tf.cast(image, tf.float32) / 255.0
|
| 238 |
-
|
| 239 |
-
# Add batch dimension
|
| 240 |
-
image = tf.expand_dims(image, 0)
|
| 241 |
-
|
| 242 |
-
return image
|
| 243 |
-
|
| 244 |
-
except Exception as e:
|
| 245 |
-
print(f"❌ Error in image preprocessing: {str(e)}")
|
| 246 |
-
raise
|
| 247 |
-
|
| 248 |
-
def predict(self, image):
|
| 249 |
-
"""Make prediction on input image"""
|
| 250 |
-
try:
|
| 251 |
-
if self.model is None:
|
| 252 |
-
return {"Error": "Model not loaded"}, "Unknown"
|
| 253 |
-
|
| 254 |
-
# Preprocess image
|
| 255 |
-
processed_image = self.preprocess_image(image)
|
| 256 |
-
|
| 257 |
-
# Make prediction
|
| 258 |
-
predictions = self.model.predict(processed_image, verbose=0)
|
| 259 |
-
|
| 260 |
-
# Get top 3 predictions
|
| 261 |
-
top_indices = np.argsort(predictions[0])[::-1][:3]
|
| 262 |
-
|
| 263 |
-
results = {}
|
| 264 |
-
for i, idx in enumerate(top_indices):
|
| 265 |
-
breed_name = BREEDS[idx]
|
| 266 |
-
confidence = float(predictions[0][idx])
|
| 267 |
-
results[f"Top {i+1}: {breed_name}"] = confidence
|
| 268 |
-
|
| 269 |
-
top_breed = BREEDS[top_indices[0]]
|
| 270 |
-
return results, top_breed
|
| 271 |
-
|
| 272 |
-
except Exception as e:
|
| 273 |
-
error_msg = f"Prediction error: {str(e)}"
|
| 274 |
-
print(f"❌ {error_msg}")
|
| 275 |
-
return {"Error": error_msg}, "Unknown"
|
| 276 |
-
|
| 277 |
-
# Initialize classifier
|
| 278 |
-
print("🚀 Initializing Indian Bovine Classifier...")
|
| 279 |
-
classifier = IndianBovineClassifier()
|
| 280 |
-
|
| 281 |
-
def classify_image_with_progress(image):
|
| 282 |
-
"""Classification function with enhanced error handling"""
|
| 283 |
-
if image is None:
|
| 284 |
-
return "Please upload an image", "Upload an image to see breed details", "| Status | Awaiting image upload |"
|
| 285 |
-
|
| 286 |
-
try:
|
| 287 |
-
# Get predictions
|
| 288 |
-
predictions, top_breed = classifier.predict(image)
|
| 289 |
-
|
| 290 |
-
# Check for errors
|
| 291 |
-
if "Error" in predictions:
|
| 292 |
-
error_msg = predictions["Error"]
|
| 293 |
-
return f"❌ {error_msg}", "Error occurred during classification", f"| Status | Error: {error_msg} |"
|
| 294 |
-
|
| 295 |
-
# Format predictions for display
|
| 296 |
-
prediction_text = "🎯 **Classification Results:**\n\n"
|
| 297 |
-
for breed, conf in predictions.items():
|
| 298 |
-
prediction_text += f"• **{breed}**: {conf:.2%}\n"
|
| 299 |
-
|
| 300 |
-
# Get breed information
|
| 301 |
-
breed_info = ""
|
| 302 |
-
breed_stats = ""
|
| 303 |
-
|
| 304 |
-
if top_breed in BREED_INFO:
|
| 305 |
-
info = BREED_INFO[top_breed]
|
| 306 |
-
breed_info = f"""
|
| 307 |
-
## 🐄 {top_breed}
|
| 308 |
-
|
| 309 |
-
🏷️ **Type:** {info['type']}
|
| 310 |
-
🌍 **Origin:** {info['origin']}
|
| 311 |
-
📊 **Characteristics:** {info['characteristics']}
|
| 312 |
-
🥛 **Milk Yield:** {info['milk_yield']}
|
| 313 |
-
⭐ **Special Features:** {info['special_features']}
|
| 314 |
-
⚖️ **Weight:** {info['weight']}
|
| 315 |
-
📏 **Height:** {info['height']}
|
| 316 |
-
😊 **Temperament:** {info['temperament']}
|
| 317 |
-
"""
|
| 318 |
-
|
| 319 |
-
breed_stats = f"""
|
| 320 |
-
| Attribute | Value |
|
| 321 |
-
|-----------|-------|
|
| 322 |
-
| **Type** | {info['type']} |
|
| 323 |
-
| **Origin** | {info['origin']} |
|
| 324 |
-
| **Weight** | {info['weight']} |
|
| 325 |
-
| **Height** | {info['height']} |
|
| 326 |
-
| **Milk Yield** | {info['milk_yield']} |
|
| 327 |
-
| **Temperament** | {info['temperament']} |
|
| 328 |
-
"""
|
| 329 |
-
else:
|
| 330 |
-
breed_info = "ℹ️ Detailed information not available for this breed."
|
| 331 |
-
breed_stats = "| Status | Information not available |"
|
| 332 |
-
|
| 333 |
-
return prediction_text, breed_info, breed_stats
|
| 334 |
-
|
| 335 |
-
except Exception as e:
|
| 336 |
-
error_msg = f"Unexpected error: {str(e)}"
|
| 337 |
-
print(f"❌ {error_msg}")
|
| 338 |
-
return f"❌ {error_msg}", "Error in classification process", f"| Status | Error: {error_msg} |"
|
| 339 |
-
|
| 340 |
-
# Enhanced CSS with modern styling and animations
|
| 341 |
-
enhanced_css = """
|
| 342 |
-
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
|
| 343 |
-
|
| 344 |
-
.gradio-container {
|
| 345 |
-
font-family: 'Poppins', sans-serif !important;
|
| 346 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 347 |
-
min-height: 100vh;
|
| 348 |
-
}
|
| 349 |
-
|
| 350 |
-
.main-header {
|
| 351 |
-
text-align: center;
|
| 352 |
-
background: linear-gradient(45deg, #FF6B6B, #4ECDC4, #45B7D1, #96CEB4);
|
| 353 |
-
background-size: 400% 400%;
|
| 354 |
-
animation: gradientShift 8s ease infinite;
|
| 355 |
-
color: white;
|
| 356 |
-
padding: 2rem;
|
| 357 |
-
border-radius: 20px;
|
| 358 |
-
margin-bottom: 2rem;
|
| 359 |
-
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
|
| 360 |
-
transition: all 0.3s ease;
|
| 361 |
-
}
|
| 362 |
-
|
| 363 |
-
.main-header:hover {
|
| 364 |
-
transform: translateY(-5px);
|
| 365 |
-
box-shadow: 0 15px 40px rgba(0,0,0,0.4);
|
| 366 |
-
}
|
| 367 |
-
|
| 368 |
-
@keyframes gradientShift {
|
| 369 |
-
0% { background-position: 0% 50%; }
|
| 370 |
-
50% { background-position: 100% 50%; }
|
| 371 |
-
100% { background-position: 0% 50%; }
|
| 372 |
-
}
|
| 373 |
-
|
| 374 |
-
.title {
|
| 375 |
-
font-size: 3.5em;
|
| 376 |
-
font-weight: 700;
|
| 377 |
-
margin-bottom: 0.5em;
|
| 378 |
-
text-shadow: 2px 2px 8px rgba(0,0,0,0.3);
|
| 379 |
-
}
|
| 380 |
-
|
| 381 |
-
.subtitle {
|
| 382 |
-
font-size: 1.3em;
|
| 383 |
-
font-weight: 300;
|
| 384 |
-
opacity: 0.9;
|
| 385 |
-
}
|
| 386 |
-
|
| 387 |
-
.feature-card {
|
| 388 |
-
background: rgba(255, 255, 255, 0.95);
|
| 389 |
-
backdrop-filter: blur(10px);
|
| 390 |
-
border-radius: 20px;
|
| 391 |
-
padding: 2rem;
|
| 392 |
-
margin: 1rem 0;
|
| 393 |
-
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
|
| 394 |
-
transition: all 0.3s ease;
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
.feature-card:hover {
|
| 398 |
-
transform: translateY(-5px);
|
| 399 |
-
box-shadow: 0 15px 40px rgba(0,0,0,0.2);
|
| 400 |
-
}
|
| 401 |
-
|
| 402 |
-
.classify-btn {
|
| 403 |
-
background: linear-gradient(45deg, #FF6B6B, #4ECDC4) !important;
|
| 404 |
-
border: none !important;
|
| 405 |
-
color: white !important;
|
| 406 |
-
font-weight: 600 !important;
|
| 407 |
-
font-size: 1.1em !important;
|
| 408 |
-
padding: 0.8rem 2rem !important;
|
| 409 |
-
border-radius: 50px !important;
|
| 410 |
-
box-shadow: 0 5px 15px rgba(0,0,0,0.2) !important;
|
| 411 |
-
transition: all 0.3s ease !important;
|
| 412 |
-
}
|
| 413 |
-
|
| 414 |
-
.classify-btn:hover {
|
| 415 |
-
transform: translateY(-3px) !important;
|
| 416 |
-
box-shadow: 0 8px 20px rgba(0,0,0,0.3) !important;
|
| 417 |
-
}
|
| 418 |
-
|
| 419 |
-
.prediction-box {
|
| 420 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 421 |
-
color: white;
|
| 422 |
-
padding: 1.5rem;
|
| 423 |
-
border-radius: 15px;
|
| 424 |
-
font-weight: 500;
|
| 425 |
-
box-shadow: 0 5px 20px rgba(0,0,0,0.2);
|
| 426 |
-
}
|
| 427 |
-
|
| 428 |
-
.breed-info-card {
|
| 429 |
-
background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
|
| 430 |
-
color: #333;
|
| 431 |
-
padding: 2rem;
|
| 432 |
-
border-radius: 20px;
|
| 433 |
-
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
|
| 434 |
-
line-height: 1.6;
|
| 435 |
-
}
|
| 436 |
-
|
| 437 |
-
.stats-table {
|
| 438 |
-
background: rgba(255, 255, 255, 0.95);
|
| 439 |
-
border-radius: 15px;
|
| 440 |
-
overflow: hidden;
|
| 441 |
-
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
|
| 442 |
-
}
|
| 443 |
-
|
| 444 |
-
.footer-stats {
|
| 445 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 446 |
-
color: white;
|
| 447 |
-
text-align: center;
|
| 448 |
-
margin-top: 3rem;
|
| 449 |
-
padding: 2rem;
|
| 450 |
-
border-radius: 20px;
|
| 451 |
-
box-shadow: 0 8px 25px rgba(0,0,0,0.2);
|
| 452 |
-
}
|
| 453 |
-
"""
|
| 454 |
-
|
| 455 |
-
def create_enhanced_interface():
|
| 456 |
-
"""Create the main Gradio interface"""
|
| 457 |
-
with gr.Blocks(css=enhanced_css, theme=gr.themes.Soft(), title="🐄 Indian Bovine Classifier") as demo:
|
| 458 |
-
|
| 459 |
-
# Header
|
| 460 |
-
gr.HTML("""
|
| 461 |
-
<div class="main-header">
|
| 462 |
-
<div class="title">🐄 Indian Bovine Breeds Classifier 🐃</div>
|
| 463 |
-
<div class="subtitle">
|
| 464 |
-
AI-Powered Recognition of Indian Cattle & Buffalo Breeds<br>
|
| 465 |
-
<em>🚀 Powered by TensorFlow EfficientNetV2 | 🎯 11 Breed Classifications</em>
|
| 466 |
-
</div>
|
| 467 |
-
</div>
|
| 468 |
-
""")
|
| 469 |
-
|
| 470 |
-
# Main content area with two columns
|
| 471 |
-
with gr.Row(equal_height=False):
|
| 472 |
-
# Left Column - Image Upload Section
|
| 473 |
-
with gr.Column(scale=1, elem_classes=["feature-card"]):
|
| 474 |
-
gr.HTML("<h2 style='text-align: center; color: #333; margin-bottom: 1rem;'>📸 Upload Your Image</h2>")
|
| 475 |
-
|
| 476 |
-
image_input = gr.Image(
|
| 477 |
-
type="pil",
|
| 478 |
-
label="🖼️ Select Cattle/Buffalo Image",
|
| 479 |
-
height=350,
|
| 480 |
-
interactive=True
|
| 481 |
-
)
|
| 482 |
-
|
| 483 |
-
classify_btn = gr.Button(
|
| 484 |
-
"🔍 Classify Breed",
|
| 485 |
-
variant="primary",
|
| 486 |
-
size="lg",
|
| 487 |
-
elem_classes=["classify-btn"]
|
| 488 |
-
)
|
| 489 |
-
|
| 490 |
-
# Example images section (if you have sample images)
|
| 491 |
-
gr.HTML("<h4 style='text-align: center; color: #666; margin-top: 1rem;'>📋 Sample Images</h4>")
|
| 492 |
-
gr.Examples(
|
| 493 |
-
examples=[
|
| 494 |
-
# Add paths to your example images here when available
|
| 495 |
-
# ["examples/sahiwal.jpg"],
|
| 496 |
-
# ["examples/murrah.jpg"],
|
| 497 |
-
# ["examples/jersey.jpg"]
|
| 498 |
-
],
|
| 499 |
-
inputs=image_input,
|
| 500 |
-
label="Click examples to test (add image paths when available)"
|
| 501 |
-
)
|
| 502 |
-
|
| 503 |
-
# Right Column - Results Section
|
| 504 |
-
with gr.Column(scale=1, elem_classes=["feature-card"]):
|
| 505 |
-
gr.HTML("<h2 style='text-align: center; color: #333; margin-bottom: 1rem;'>🎯 Classification Results</h2>")
|
| 506 |
-
|
| 507 |
-
prediction_output = gr.Markdown(
|
| 508 |
-
value="🔄 Upload an image to see classification results...",
|
| 509 |
-
elem_classes=["prediction-box"],
|
| 510 |
-
label="Prediction Confidence"
|
| 511 |
-
)
|
| 512 |
-
|
| 513 |
-
detected_breed = gr.Textbox(
|
| 514 |
-
label="🏆 Top Predicted Breed",
|
| 515 |
-
interactive=False,
|
| 516 |
-
placeholder="Detected breed will appear here..."
|
| 517 |
-
)
|
| 518 |
-
|
| 519 |
-
# Breed Information Section
|
| 520 |
-
with gr.Row():
|
| 521 |
-
with gr.Column(elem_classes=["feature-card"]):
|
| 522 |
-
gr.HTML("<h2 style='text-align: center; color: #333; margin: 1rem 0;'>📖 Detailed Breed Information</h2>")
|
| 523 |
-
|
| 524 |
-
breed_info_output = gr.Markdown(
|
| 525 |
-
value="🔄 Upload an image to see detailed breed information...",
|
| 526 |
-
elem_classes=["breed-info-card"],
|
| 527 |
-
label="Breed Details"
|
| 528 |
-
)
|
| 529 |
-
|
| 530 |
-
# Statistics Table Section
|
| 531 |
-
with gr.Row():
|
| 532 |
-
with gr.Column(elem_classes=["feature-card"]):
|
| 533 |
-
gr.HTML("<h3 style='text-align: center; color: #333; margin: 1rem 0;'>📊 Breed Statistics</h3>")
|
| 534 |
-
|
| 535 |
-
breed_stats_table = gr.Markdown(
|
| 536 |
-
value="| Attribute | Value |\n|-----------|-------|\n| Status | Awaiting classification... |",
|
| 537 |
-
elem_classes=["stats-table"],
|
| 538 |
-
label="Statistical Information"
|
| 539 |
-
)
|
| 540 |
-
|
| 541 |
-
# Additional Information Section
|
| 542 |
-
with gr.Row():
|
| 543 |
-
with gr.Column(scale=1, elem_classes=["feature-card"]):
|
| 544 |
-
gr.HTML("<h3 style='text-align: center; color: #333;'>🌟 About This Classifier</h3>")
|
| 545 |
-
gr.Markdown("""
|
| 546 |
-
### Features:
|
| 547 |
-
- **11 Breed Classifications**: Covers major Indian and international bovine breeds
|
| 548 |
-
- **High Accuracy**: 95%+ accuracy on test datasets
|
| 549 |
-
- **Real-time Processing**: Instant classification results
|
| 550 |
-
- **Detailed Information**: Comprehensive breed characteristics and statistics
|
| 551 |
-
|
| 552 |
-
### Supported Breeds:
|
| 553 |
-
- **Dairy Cows**: Holstein Friesian, Jersey, Ayrshire, Brown Swiss, Sahiwal
|
| 554 |
-
- **Indigenous Breeds**: Sahiwal, Kankarej, Sibbi
|
| 555 |
-
- **Buffalo Breeds**: Murrah, Jaffrabadi
|
| 556 |
-
- **Crossbreeds**: Sahiwal Cross
|
| 557 |
-
- **Dual-purpose**: Red Dane, Brown Swiss, Kankarej, Sibbi
|
| 558 |
-
""")
|
| 559 |
-
|
| 560 |
-
with gr.Column(scale=1, elem_classes=["feature-card"]):
|
| 561 |
-
gr.HTML("<h3 style='text-align: center; color: #333;'>📱 How to Use</h3>")
|
| 562 |
-
gr.Markdown("""
|
| 563 |
-
### Step-by-step Guide:
|
| 564 |
-
1. **Upload Image**: Click on the image area and select a clear photo of cattle/buffalo
|
| 565 |
-
2. **Automatic Classification**: The model will process your image automatically
|
| 566 |
-
3. **View Results**: Check the confidence scores for top 3 predictions
|
| 567 |
-
4. **Explore Details**: Read comprehensive information about the detected breed
|
| 568 |
-
5. **Check Statistics**: View physical characteristics and performance metrics
|
| 569 |
-
|
| 570 |
-
### Tips for Best Results:
|
| 571 |
-
- Use **clear, high-quality images**
|
| 572 |
-
- Ensure the **animal is clearly visible**
|
| 573 |
-
- **Good lighting** improves accuracy
|
| 574 |
-
- **Side or front view** works best
|
| 575 |
-
""")
|
| 576 |
-
|
| 577 |
-
# Model Performance and Statistics Footer
|
| 578 |
-
gr.HTML(f"""
|
| 579 |
-
<div class="footer-stats">
|
| 580 |
-
<h3>🏆 Model Performance & Statistics</h3>
|
| 581 |
-
<div style="display: flex; justify-content: space-around; flex-wrap: wrap; margin: 1rem 0;">
|
| 582 |
-
<div style="margin: 0.5rem; text-align: center;">
|
| 583 |
-
<div style="font-size: 2.5em; font-weight: bold;">95%+</div>
|
| 584 |
-
<div style="font-size: 0.9em;">Model Accuracy</div>
|
| 585 |
-
</div>
|
| 586 |
-
<div style="margin: 0.5rem; text-align: center;">
|
| 587 |
-
<div style="font-size: 2.5em; font-weight: bold;">{len(BREEDS)}</div>
|
| 588 |
-
<div style="font-size: 0.9em;">Breed Classes</div>
|
| 589 |
-
</div>
|
| 590 |
-
<div style="margin: 0.5rem; text-align: center;">
|
| 591 |
-
<div style="font-size: 2.5em; font-weight: bold;">EfficientNetV2</div>
|
| 592 |
-
<div style="font-size: 0.9em;">Neural Network</div>
|
| 593 |
-
</div>
|
| 594 |
-
<div style="margin: 0.5rem; text-align: center;">
|
| 595 |
-
<div style="font-size: 2.5em; font-weight: bold;">🇮🇳</div>
|
| 596 |
-
<div style="font-size: 0.9em;">Indian Focus</div>
|
| 597 |
-
</div>
|
| 598 |
-
</div>
|
| 599 |
-
|
| 600 |
-
<div style="margin-top: 2rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.3);">
|
| 601 |
-
<p style="font-style: italic; margin: 0.5rem 0;">
|
| 602 |
-
🌱 <strong>Mission:</strong> Preserving Indigenous Knowledge through AI Technology
|
| 603 |
-
</p>
|
| 604 |
-
<p style="font-style: italic; margin: 0.5rem 0;">
|
| 605 |
-
🤖 <strong>Purpose:</strong> Empowering Farmers and Researchers with Advanced Classification
|
| 606 |
-
</p>
|
| 607 |
-
<p style="font-size: 0.9em; margin-top: 1rem; opacity: 0.8;">
|
| 608 |
-
Built with ❤️ for the farming community | Powered by TensorFlow & Gradio
|
| 609 |
-
</p>
|
| 610 |
-
</div>
|
| 611 |
-
</div>
|
| 612 |
-
""")
|
| 613 |
-
|
| 614 |
-
# Connect event handlers
|
| 615 |
-
classify_btn.click(
|
| 616 |
-
fn=classify_image_with_progress,
|
| 617 |
-
inputs=[image_input],
|
| 618 |
-
outputs=[prediction_output, breed_info_output, breed_stats_table],
|
| 619 |
-
show_progress=True
|
| 620 |
-
)
|
| 621 |
-
|
| 622 |
-
# Auto-classify when image is uploaded
|
| 623 |
-
image_input.change(
|
| 624 |
-
fn=classify_image_with_progress,
|
| 625 |
-
inputs=[image_input],
|
| 626 |
-
outputs=[prediction_output, breed_info_output, breed_stats_table],
|
| 627 |
-
show_progress=True
|
| 628 |
-
)
|
| 629 |
-
|
| 630 |
-
# Update detected breed field
|
| 631 |
-
def update_detected_breed(image):
|
| 632 |
-
if image is None:
|
| 633 |
-
return ""
|
| 634 |
-
try:
|
| 635 |
-
predictions, top_breed = classifier.predict(image)
|
| 636 |
-
return top_breed if "Error" not in predictions else "Classification Error"
|
| 637 |
-
except:
|
| 638 |
-
return "Error"
|
| 639 |
-
|
| 640 |
-
image_input.change(
|
| 641 |
-
fn=update_detected_breed,
|
| 642 |
-
inputs=[image_input],
|
| 643 |
-
outputs=[detected_breed]
|
| 644 |
-
)
|
| 645 |
-
|
| 646 |
-
return demo
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torchvision.models as models
|
| 6 |
+
import torchvision.transforms as transforms
|
| 7 |
import numpy as np
|
| 8 |
from PIL import Image
|
| 9 |
+
import pickle
|
| 10 |
+
import joblib
|
| 11 |
import os
|
| 12 |
+
import warnings
|
| 13 |
+
warnings.filterwarnings("ignore")
|
| 14 |
|
| 15 |
# Define the breeds based on Indian bovine classification
|
| 16 |
BREEDS = [
|
|
|
|
| 39 |
"special_features": "Light to dark brown color with creamy white muzzle, exceptional longevity",
|
| 40 |
"weight": "600-700 kg",
|
| 41 |
"height": "135-150 cm",
|
| 42 |
+
"temperament": "Calm an
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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