Update app.py
Browse files
app.py
CHANGED
|
@@ -1,356 +1,356 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import numpy as np
|
| 3 |
-
import tensorflow as tf
|
| 4 |
-
from tensorflow.keras.applications import MobileNetV2
|
| 5 |
-
from tensorflow.keras.preprocessing import image
|
| 6 |
-
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
|
| 7 |
-
import io
|
| 8 |
-
import base64
|
| 9 |
-
from PIL import Image
|
| 10 |
-
import os
|
| 11 |
-
import logging
|
| 12 |
-
|
| 13 |
-
# Configure logging
|
| 14 |
-
logging.basicConfig(level=logging.INFO)
|
| 15 |
-
logger = logging.getLogger(__name__)
|
| 16 |
-
|
| 17 |
-
class CattleDiseaseClassifier:
|
| 18 |
-
def __init__(self):
|
| 19 |
-
self.model = None
|
| 20 |
-
self.dataset_features = None
|
| 21 |
-
self.dataset_metadata = []
|
| 22 |
-
self.model_loaded = False
|
| 23 |
-
self.dataset_loaded = False
|
| 24 |
-
self.error = None
|
| 25 |
-
|
| 26 |
-
self.initialize()
|
| 27 |
-
|
| 28 |
-
def initialize(self):
|
| 29 |
-
"""Initialize model and dataset"""
|
| 30 |
-
try:
|
| 31 |
-
# Load TensorFlow model
|
| 32 |
-
logger.info("π Loading MobileNetV2 model...")
|
| 33 |
-
self.model = MobileNetV2(weights='imagenet', include_top=False, pooling='avg')
|
| 34 |
-
self.model_loaded = True
|
| 35 |
-
logger.info("β
Model loaded successfully")
|
| 36 |
-
|
| 37 |
-
# Load dataset from text file
|
| 38 |
-
self.load_txt_dataset()
|
| 39 |
-
|
| 40 |
-
except Exception as e:
|
| 41 |
-
logger.error(f"β Initialization failed: {e}")
|
| 42 |
-
self.error = str(e)
|
| 43 |
-
|
| 44 |
-
def load_txt_dataset(self):
|
| 45 |
-
"""Load dataset from text file"""
|
| 46 |
-
# Look for text dataset file
|
| 47 |
-
txt_files = [
|
| 48 |
-
'cattle_disease_dataset.txt',
|
| 49 |
-
'dataset.txt',
|
| 50 |
-
'data.txt',
|
| 51 |
-
'cattle_disease_features.txt'
|
| 52 |
-
]
|
| 53 |
-
|
| 54 |
-
dataset_file = None
|
| 55 |
-
for filename in txt_files:
|
| 56 |
-
if os.path.exists(filename):
|
| 57 |
-
dataset_file = filename
|
| 58 |
-
break
|
| 59 |
-
|
| 60 |
-
if not dataset_file:
|
| 61 |
-
logger.warning("β οΈ No TXT dataset file found")
|
| 62 |
-
return
|
| 63 |
-
|
| 64 |
-
logger.info(f"π Loading dataset from: {dataset_file}")
|
| 65 |
-
|
| 66 |
-
features_list = []
|
| 67 |
-
metadata_list = []
|
| 68 |
-
|
| 69 |
-
try:
|
| 70 |
-
with open(dataset_file, 'r', encoding='utf-8') as f:
|
| 71 |
-
for line_num, line in enumerate(f, 1):
|
| 72 |
-
line = line.strip()
|
| 73 |
-
|
| 74 |
-
# Skip comments and empty lines
|
| 75 |
-
if not line or line.startswith('#'):
|
| 76 |
-
continue
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
# Parse line: class|stage|description|features
|
| 80 |
-
parts = line.split('|', 3)
|
| 81 |
-
if len(parts) != 4:
|
| 82 |
-
logger.warning(f"β οΈ Line {line_num}: Expected 4 parts, got {len(parts)}")
|
| 83 |
-
continue
|
| 84 |
-
|
| 85 |
-
class_name = parts[0].strip()
|
| 86 |
-
stage = parts[1].strip() if parts[1].strip() else None
|
| 87 |
-
description = parts[2].strip() if parts[2].strip() else None
|
| 88 |
-
features_str = parts[3].strip()
|
| 89 |
-
|
| 90 |
-
# Skip if no class or features
|
| 91 |
-
if not class_name or not features_str:
|
| 92 |
-
continue
|
| 93 |
-
|
| 94 |
-
# Parse features (comma-separated numbers)
|
| 95 |
-
try:
|
| 96 |
-
features = [float(x.strip()) for x in features_str.split(',')]
|
| 97 |
-
features_array = np.array(features, dtype=np.float32)
|
| 98 |
-
|
| 99 |
-
# Validate features
|
| 100 |
-
if len(features) == 0:
|
| 101 |
-
continue
|
| 102 |
-
if np.any(np.isnan(features_array)) or np.any(np.isinf(features_array)):
|
| 103 |
-
logger.warning(f"β οΈ Line {line_num}: Invalid features (NaN/Inf)")
|
| 104 |
-
continue
|
| 105 |
-
|
| 106 |
-
except ValueError as e:
|
| 107 |
-
logger.warning(f"β οΈ Line {line_num}: Error parsing features - {e}")
|
| 108 |
-
continue
|
| 109 |
-
|
| 110 |
-
# Store valid entry
|
| 111 |
-
features_list.append(features_array)
|
| 112 |
-
metadata_list.append({
|
| 113 |
-
'class': class_name,
|
| 114 |
-
'stage': stage,
|
| 115 |
-
'description': description,
|
| 116 |
-
'index': len(features_list) - 1
|
| 117 |
-
})
|
| 118 |
-
|
| 119 |
-
# Progress logging
|
| 120 |
-
if len(features_list) % 50 == 0:
|
| 121 |
-
logger.info(f" π Loaded {len(features_list)} entries...")
|
| 122 |
-
|
| 123 |
-
except Exception as e:
|
| 124 |
-
logger.warning(f"β οΈ Error parsing line {line_num}: {e}")
|
| 125 |
-
continue
|
| 126 |
-
|
| 127 |
-
# Convert to numpy arrays
|
| 128 |
-
if features_list:
|
| 129 |
-
self.dataset_features = np.array(features_list, dtype=np.float32)
|
| 130 |
-
self.dataset_metadata = metadata_list
|
| 131 |
-
self.dataset_loaded = True
|
| 132 |
-
|
| 133 |
-
logger.info(f"β
Dataset loaded successfully:")
|
| 134 |
-
logger.info(f" π Total entries: {len(self.dataset_metadata)}")
|
| 135 |
-
logger.info(f" π Feature shape: {self.dataset_features.shape}")
|
| 136 |
-
logger.info(f" πΎ Memory usage: {self.dataset_features.nbytes / 1024 / 1024:.1f} MB")
|
| 137 |
-
|
| 138 |
-
else:
|
| 139 |
-
logger.warning("β οΈ No valid entries found in dataset")
|
| 140 |
-
|
| 141 |
-
except Exception as e:
|
| 142 |
-
logger.error(f"β Error loading dataset: {e}")
|
| 143 |
-
self.error = str(e)
|
| 144 |
-
|
| 145 |
-
def preprocess_image(self, image_pil):
|
| 146 |
-
"""Preprocess PIL image for feature extraction"""
|
| 147 |
-
try:
|
| 148 |
-
# Convert to RGB if needed
|
| 149 |
-
if image_pil.mode != 'RGB':
|
| 150 |
-
image_pil = image_pil.convert('RGB')
|
| 151 |
-
|
| 152 |
-
# Resize to 224x224 (MobileNetV2 input size)
|
| 153 |
-
img = image_pil.resize((224, 224), Image.Resampling.LANCZOS)
|
| 154 |
-
|
| 155 |
-
# Convert to array and preprocess
|
| 156 |
-
img_array = np.array(img, dtype=np.float32)
|
| 157 |
-
img_array = np.expand_dims(img_array, axis=0)
|
| 158 |
-
img_array = preprocess_input(img_array)
|
| 159 |
-
|
| 160 |
-
return img_array
|
| 161 |
-
|
| 162 |
-
except Exception as e:
|
| 163 |
-
logger.error(f"β Error preprocessing image: {e}")
|
| 164 |
-
return None
|
| 165 |
-
|
| 166 |
-
def extract_features(self, img_array):
|
| 167 |
-
"""Extract features from preprocessed image"""
|
| 168 |
-
if not self.model_loaded:
|
| 169 |
-
return None
|
| 170 |
-
try:
|
| 171 |
-
features = self.model.predict(img_array, verbose=0)
|
| 172 |
-
return features.flatten().astype(np.float32)
|
| 173 |
-
except Exception as e:
|
| 174 |
-
logger.error(f"β Error extracting features: {e}")
|
| 175 |
-
return None
|
| 176 |
-
|
| 177 |
-
def find_similar_images(self, query_features, top_k=10):
|
| 178 |
-
"""Find similar images using cosine similarity"""
|
| 179 |
-
if self.dataset_features is None or len(self.dataset_features) == 0:
|
| 180 |
-
return []
|
| 181 |
-
|
| 182 |
-
try:
|
| 183 |
-
# Normalize query features
|
| 184 |
-
query_norm = np.linalg.norm(query_features)
|
| 185 |
-
if query_norm == 0:
|
| 186 |
-
return []
|
| 187 |
-
query_normalized = query_features / query_norm
|
| 188 |
-
|
| 189 |
-
# Normalize dataset features
|
| 190 |
-
dataset_norms = np.linalg.norm(self.dataset_features, axis=1)
|
| 191 |
-
valid_indices = dataset_norms > 0
|
| 192 |
-
|
| 193 |
-
if not np.any(valid_indices):
|
| 194 |
-
return []
|
| 195 |
-
|
| 196 |
-
dataset_normalized = self.dataset_features[valid_indices]
|
| 197 |
-
dataset_normalized = dataset_normalized / dataset_norms[valid_indices].reshape(-1, 1)
|
| 198 |
-
|
| 199 |
-
# Compute cosine similarities
|
| 200 |
-
similarities = np.dot(dataset_normalized, query_normalized)
|
| 201 |
-
|
| 202 |
-
# Get top-k results
|
| 203 |
-
top_indices = np.argsort(similarities)[::-1][:top_k]
|
| 204 |
-
|
| 205 |
-
# Build results
|
| 206 |
-
results = []
|
| 207 |
-
valid_metadata = [self.dataset_metadata[i] for i in range(len(self.dataset_metadata)) if valid_indices[i]]
|
| 208 |
-
|
| 209 |
-
for idx in top_indices:
|
| 210 |
-
if idx < len(valid_metadata):
|
| 211 |
-
metadata = valid_metadata[idx]
|
| 212 |
-
results.append({
|
| 213 |
-
**metadata,
|
| 214 |
-
'similarity': float(similarities[idx])
|
| 215 |
-
})
|
| 216 |
-
|
| 217 |
-
return results
|
| 218 |
-
|
| 219 |
-
except Exception as e:
|
| 220 |
-
logger.error(f"β Error finding similar images: {e}")
|
| 221 |
-
return []
|
| 222 |
-
|
| 223 |
-
def classify_image(self, image_pil):
|
| 224 |
-
"""Main classification function for Gradio"""
|
| 225 |
-
try:
|
| 226 |
-
if not self.model_loaded:
|
| 227 |
-
return "β Model not loaded"
|
| 228 |
-
|
| 229 |
-
if not self.dataset_loaded:
|
| 230 |
-
return "β Dataset not loaded"
|
| 231 |
-
|
| 232 |
-
# Preprocess image
|
| 233 |
-
img_array = self.preprocess_image(image_pil)
|
| 234 |
-
if img_array is None:
|
| 235 |
-
return "β Failed to preprocess image"
|
| 236 |
-
|
| 237 |
-
# Extract features
|
| 238 |
-
features = self.extract_features(img_array)
|
| 239 |
-
if features is None:
|
| 240 |
-
return "β Failed to extract features"
|
| 241 |
-
|
| 242 |
-
# Find similar images
|
| 243 |
-
similar_images = self.find_similar_images(features, top_k=10)
|
| 244 |
-
|
| 245 |
-
if not similar_images:
|
| 246 |
-
return "β No similar images found"
|
| 247 |
-
|
| 248 |
-
# Classification by voting (top 5 similar images)
|
| 249 |
-
class_votes = {}
|
| 250 |
-
stage_votes = {}
|
| 251 |
-
|
| 252 |
-
for item in similar_images[:5]:
|
| 253 |
-
if item['class']:
|
| 254 |
-
class_votes[item['class']] = class_votes.get(item['class'], 0) + item['similarity']
|
| 255 |
-
if item['stage']:
|
| 256 |
-
stage_votes[item['stage']] = stage_votes.get(item['stage'], 0) + item['similarity']
|
| 257 |
-
|
| 258 |
-
# Get final prediction
|
| 259 |
-
best_class = max(class_votes.items(), key=lambda x: x[1])[0] if class_votes else "Unknown"
|
| 260 |
-
best_stage = max(stage_votes.items(), key=lambda x: x[1])[0] if stage_votes else "N/A"
|
| 261 |
-
confidence = np.mean([item['similarity'] for item in similar_images[:3]])
|
| 262 |
-
|
| 263 |
-
# Format result
|
| 264 |
-
result_text = f"""
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
**Disease
|
| 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 |
-
return
|
| 298 |
-
|
| 299 |
-
# Create Gradio interface
|
| 300 |
-
with gr.Blocks(title="π Cattle Disease Classifier", theme=gr.themes.Soft()) as demo:
|
| 301 |
-
gr.Markdown("""
|
| 302 |
-
# π Cattle Disease Classification System
|
| 303 |
-
|
| 304 |
-
Upload an image of cattle to identify potential diseases and get detailed analysis.
|
| 305 |
-
|
| 306 |
-
**How it works:**
|
| 307 |
-
1. Upload a clear image of the cattle
|
| 308 |
-
2. The AI analyzes the image using deep learning
|
| 309 |
-
3. Get classification results with confidence scores
|
| 310 |
-
""")
|
| 311 |
-
|
| 312 |
-
with gr.Row():
|
| 313 |
-
with gr.Column():
|
| 314 |
-
image_input = gr.Image(
|
| 315 |
-
label="Upload Cattle Image",
|
| 316 |
-
type="pil",
|
| 317 |
-
height=400
|
| 318 |
-
)
|
| 319 |
-
|
| 320 |
-
classify_btn = gr.Button(
|
| 321 |
-
"π Analyze Image",
|
| 322 |
-
variant="primary",
|
| 323 |
-
size="lg"
|
| 324 |
-
)
|
| 325 |
-
|
| 326 |
-
with gr.Column():
|
| 327 |
-
result_output = gr.Markdown(
|
| 328 |
-
label="Classification Results",
|
| 329 |
-
value="Upload an image and click 'Analyze Image' to get results."
|
| 330 |
-
)
|
| 331 |
-
|
| 332 |
-
# Status information
|
| 333 |
-
with gr.Row():
|
| 334 |
-
status_info = gr.Markdown(f"""
|
| 335 |
-
**System Status:**
|
| 336 |
-
- Model Loaded: {'β
' if classifier.model_loaded else 'β'}
|
| 337 |
-
- Dataset Loaded: {'β
' if classifier.dataset_loaded else 'β'}
|
| 338 |
-
- Dataset Size: {len(classifier.dataset_metadata)} entries
|
| 339 |
-
- Error: {classifier.error or 'None'}
|
| 340 |
-
""")
|
| 341 |
-
|
| 342 |
-
# Event handlers
|
| 343 |
-
classify_btn.click(
|
| 344 |
-
fn=classify_cattle_image,
|
| 345 |
-
inputs=[image_input],
|
| 346 |
-
outputs=[result_output]
|
| 347 |
-
)
|
| 348 |
-
|
| 349 |
-
image_input.change(
|
| 350 |
-
fn=classify_cattle_image,
|
| 351 |
-
inputs=[image_input],
|
| 352 |
-
outputs=[result_output]
|
| 353 |
-
)
|
| 354 |
-
|
| 355 |
-
if __name__ == "__main__":
|
| 356 |
demo.launch(share=True)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from tensorflow.keras.applications import MobileNetV2
|
| 5 |
+
from tensorflow.keras.preprocessing import image
|
| 6 |
+
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import os
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
# Configure logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
class CattleDiseaseClassifier:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.model = None
|
| 20 |
+
self.dataset_features = None
|
| 21 |
+
self.dataset_metadata = []
|
| 22 |
+
self.model_loaded = False
|
| 23 |
+
self.dataset_loaded = False
|
| 24 |
+
self.error = None
|
| 25 |
+
|
| 26 |
+
self.initialize()
|
| 27 |
+
|
| 28 |
+
def initialize(self):
|
| 29 |
+
"""Initialize model and dataset"""
|
| 30 |
+
try:
|
| 31 |
+
# Load TensorFlow model
|
| 32 |
+
logger.info("π Loading MobileNetV2 model...")
|
| 33 |
+
self.model = MobileNetV2(weights='imagenet', include_top=False, pooling='avg')
|
| 34 |
+
self.model_loaded = True
|
| 35 |
+
logger.info("β
Model loaded successfully")
|
| 36 |
+
|
| 37 |
+
# Load dataset from text file
|
| 38 |
+
self.load_txt_dataset()
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
logger.error(f"β Initialization failed: {e}")
|
| 42 |
+
self.error = str(e)
|
| 43 |
+
|
| 44 |
+
def load_txt_dataset(self):
|
| 45 |
+
"""Load dataset from text file"""
|
| 46 |
+
# Look for text dataset file
|
| 47 |
+
txt_files = [
|
| 48 |
+
'cattle_disease_dataset.txt',
|
| 49 |
+
'dataset.txt',
|
| 50 |
+
'data.txt',
|
| 51 |
+
'cattle_disease_features.txt'
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
dataset_file = None
|
| 55 |
+
for filename in txt_files:
|
| 56 |
+
if os.path.exists(filename):
|
| 57 |
+
dataset_file = filename
|
| 58 |
+
break
|
| 59 |
+
|
| 60 |
+
if not dataset_file:
|
| 61 |
+
logger.warning("β οΈ No TXT dataset file found")
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
logger.info(f"π Loading dataset from: {dataset_file}")
|
| 65 |
+
|
| 66 |
+
features_list = []
|
| 67 |
+
metadata_list = []
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
with open(dataset_file, 'r', encoding='utf-8') as f:
|
| 71 |
+
for line_num, line in enumerate(f, 1):
|
| 72 |
+
line = line.strip()
|
| 73 |
+
|
| 74 |
+
# Skip comments and empty lines
|
| 75 |
+
if not line or line.startswith('#'):
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
# Parse line: class|stage|description|features
|
| 80 |
+
parts = line.split('|', 3)
|
| 81 |
+
if len(parts) != 4:
|
| 82 |
+
logger.warning(f"β οΈ Line {line_num}: Expected 4 parts, got {len(parts)}")
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
class_name = parts[0].strip()
|
| 86 |
+
stage = parts[1].strip() if parts[1].strip() else None
|
| 87 |
+
description = parts[2].strip() if parts[2].strip() else None
|
| 88 |
+
features_str = parts[3].strip()
|
| 89 |
+
|
| 90 |
+
# Skip if no class or features
|
| 91 |
+
if not class_name or not features_str:
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
# Parse features (comma-separated numbers)
|
| 95 |
+
try:
|
| 96 |
+
features = [float(x.strip()) for x in features_str.split(',')]
|
| 97 |
+
features_array = np.array(features, dtype=np.float32)
|
| 98 |
+
|
| 99 |
+
# Validate features
|
| 100 |
+
if len(features) == 0:
|
| 101 |
+
continue
|
| 102 |
+
if np.any(np.isnan(features_array)) or np.any(np.isinf(features_array)):
|
| 103 |
+
logger.warning(f"β οΈ Line {line_num}: Invalid features (NaN/Inf)")
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
except ValueError as e:
|
| 107 |
+
logger.warning(f"β οΈ Line {line_num}: Error parsing features - {e}")
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
# Store valid entry
|
| 111 |
+
features_list.append(features_array)
|
| 112 |
+
metadata_list.append({
|
| 113 |
+
'class': class_name,
|
| 114 |
+
'stage': stage,
|
| 115 |
+
'description': description,
|
| 116 |
+
'index': len(features_list) - 1
|
| 117 |
+
})
|
| 118 |
+
|
| 119 |
+
# Progress logging
|
| 120 |
+
if len(features_list) % 50 == 0:
|
| 121 |
+
logger.info(f" π Loaded {len(features_list)} entries...")
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.warning(f"β οΈ Error parsing line {line_num}: {e}")
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
+
# Convert to numpy arrays
|
| 128 |
+
if features_list:
|
| 129 |
+
self.dataset_features = np.array(features_list, dtype=np.float32)
|
| 130 |
+
self.dataset_metadata = metadata_list
|
| 131 |
+
self.dataset_loaded = True
|
| 132 |
+
|
| 133 |
+
logger.info(f"β
Dataset loaded successfully:")
|
| 134 |
+
logger.info(f" π Total entries: {len(self.dataset_metadata)}")
|
| 135 |
+
logger.info(f" π Feature shape: {self.dataset_features.shape}")
|
| 136 |
+
logger.info(f" πΎ Memory usage: {self.dataset_features.nbytes / 1024 / 1024:.1f} MB")
|
| 137 |
+
|
| 138 |
+
else:
|
| 139 |
+
logger.warning("β οΈ No valid entries found in dataset")
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
logger.error(f"β Error loading dataset: {e}")
|
| 143 |
+
self.error = str(e)
|
| 144 |
+
|
| 145 |
+
def preprocess_image(self, image_pil):
|
| 146 |
+
"""Preprocess PIL image for feature extraction"""
|
| 147 |
+
try:
|
| 148 |
+
# Convert to RGB if needed
|
| 149 |
+
if image_pil.mode != 'RGB':
|
| 150 |
+
image_pil = image_pil.convert('RGB')
|
| 151 |
+
|
| 152 |
+
# Resize to 224x224 (MobileNetV2 input size)
|
| 153 |
+
img = image_pil.resize((224, 224), Image.Resampling.LANCZOS)
|
| 154 |
+
|
| 155 |
+
# Convert to array and preprocess
|
| 156 |
+
img_array = np.array(img, dtype=np.float32)
|
| 157 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 158 |
+
img_array = preprocess_input(img_array)
|
| 159 |
+
|
| 160 |
+
return img_array
|
| 161 |
+
|
| 162 |
+
except Exception as e:
|
| 163 |
+
logger.error(f"β Error preprocessing image: {e}")
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
def extract_features(self, img_array):
|
| 167 |
+
"""Extract features from preprocessed image"""
|
| 168 |
+
if not self.model_loaded:
|
| 169 |
+
return None
|
| 170 |
+
try:
|
| 171 |
+
features = self.model.predict(img_array, verbose=0)
|
| 172 |
+
return features.flatten().astype(np.float32)
|
| 173 |
+
except Exception as e:
|
| 174 |
+
logger.error(f"β Error extracting features: {e}")
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
def find_similar_images(self, query_features, top_k=10):
|
| 178 |
+
"""Find similar images using cosine similarity"""
|
| 179 |
+
if self.dataset_features is None or len(self.dataset_features) == 0:
|
| 180 |
+
return []
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
# Normalize query features
|
| 184 |
+
query_norm = np.linalg.norm(query_features)
|
| 185 |
+
if query_norm == 0:
|
| 186 |
+
return []
|
| 187 |
+
query_normalized = query_features / query_norm
|
| 188 |
+
|
| 189 |
+
# Normalize dataset features
|
| 190 |
+
dataset_norms = np.linalg.norm(self.dataset_features, axis=1)
|
| 191 |
+
valid_indices = dataset_norms > 0
|
| 192 |
+
|
| 193 |
+
if not np.any(valid_indices):
|
| 194 |
+
return []
|
| 195 |
+
|
| 196 |
+
dataset_normalized = self.dataset_features[valid_indices]
|
| 197 |
+
dataset_normalized = dataset_normalized / dataset_norms[valid_indices].reshape(-1, 1)
|
| 198 |
+
|
| 199 |
+
# Compute cosine similarities
|
| 200 |
+
similarities = np.dot(dataset_normalized, query_normalized)
|
| 201 |
+
|
| 202 |
+
# Get top-k results
|
| 203 |
+
top_indices = np.argsort(similarities)[::-1][:top_k]
|
| 204 |
+
|
| 205 |
+
# Build results
|
| 206 |
+
results = []
|
| 207 |
+
valid_metadata = [self.dataset_metadata[i] for i in range(len(self.dataset_metadata)) if valid_indices[i]]
|
| 208 |
+
|
| 209 |
+
for idx in top_indices:
|
| 210 |
+
if idx < len(valid_metadata):
|
| 211 |
+
metadata = valid_metadata[idx]
|
| 212 |
+
results.append({
|
| 213 |
+
**metadata,
|
| 214 |
+
'similarity': float(similarities[idx])
|
| 215 |
+
})
|
| 216 |
+
|
| 217 |
+
return results
|
| 218 |
+
|
| 219 |
+
except Exception as e:
|
| 220 |
+
logger.error(f"β Error finding similar images: {e}")
|
| 221 |
+
return []
|
| 222 |
+
|
| 223 |
+
def classify_image(self, image_pil):
|
| 224 |
+
"""Main classification function for Gradio - returns only a string"""
|
| 225 |
+
try:
|
| 226 |
+
if not self.model_loaded:
|
| 227 |
+
return "β Model not loaded"
|
| 228 |
+
|
| 229 |
+
if not self.dataset_loaded:
|
| 230 |
+
return "β Dataset not loaded"
|
| 231 |
+
|
| 232 |
+
# Preprocess image
|
| 233 |
+
img_array = self.preprocess_image(image_pil)
|
| 234 |
+
if img_array is None:
|
| 235 |
+
return "β Failed to preprocess image"
|
| 236 |
+
|
| 237 |
+
# Extract features
|
| 238 |
+
features = self.extract_features(img_array)
|
| 239 |
+
if features is None:
|
| 240 |
+
return "β Failed to extract features"
|
| 241 |
+
|
| 242 |
+
# Find similar images
|
| 243 |
+
similar_images = self.find_similar_images(features, top_k=10)
|
| 244 |
+
|
| 245 |
+
if not similar_images:
|
| 246 |
+
return "β No similar images found"
|
| 247 |
+
|
| 248 |
+
# Classification by voting (top 5 similar images)
|
| 249 |
+
class_votes = {}
|
| 250 |
+
stage_votes = {}
|
| 251 |
+
|
| 252 |
+
for item in similar_images[:5]:
|
| 253 |
+
if item['class']:
|
| 254 |
+
class_votes[item['class']] = class_votes.get(item['class'], 0) + item['similarity']
|
| 255 |
+
if item['stage']:
|
| 256 |
+
stage_votes[item['stage']] = stage_votes.get(item['stage'], 0) + item['similarity']
|
| 257 |
+
|
| 258 |
+
# Get final prediction
|
| 259 |
+
best_class = max(class_votes.items(), key=lambda x: x[1])[0] if class_votes else "Unknown"
|
| 260 |
+
best_stage = max(stage_votes.items(), key=lambda x: x[1])[0] if stage_votes else "N/A"
|
| 261 |
+
confidence = np.mean([item['similarity'] for item in similar_images[:3]])
|
| 262 |
+
|
| 263 |
+
# Format result as a single string
|
| 264 |
+
result_text = f"""## π Cattle Disease Classification Results
|
| 265 |
+
|
| 266 |
+
**Disease Class:** {best_class}
|
| 267 |
+
**Disease Stage:** {best_stage}
|
| 268 |
+
**Confidence:** {confidence:.2%}
|
| 269 |
+
|
| 270 |
+
**Description:** {similar_images[0]['description'] or 'No description available'}
|
| 271 |
+
|
| 272 |
+
### Top Similar Cases:
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
for i, item in enumerate(similar_images[:3], 1):
|
| 276 |
+
result_text += f"\n{i}. **{item['class']}** - Similarity: {item['similarity']:.2%}"
|
| 277 |
+
if item['stage']:
|
| 278 |
+
result_text += f" (Stage: {item['stage']})"
|
| 279 |
+
|
| 280 |
+
return result_text
|
| 281 |
+
|
| 282 |
+
except Exception as e:
|
| 283 |
+
logger.error(f"β Error in classification: {e}")
|
| 284 |
+
return f"β Error: {str(e)}"
|
| 285 |
+
|
| 286 |
+
# Initialize classifier
|
| 287 |
+
print("Initializing Cattle Disease Classifier...")
|
| 288 |
+
classifier = CattleDiseaseClassifier()
|
| 289 |
+
|
| 290 |
+
def classify_cattle_image(image):
|
| 291 |
+
"""Gradio interface function - returns only string"""
|
| 292 |
+
if image is None:
|
| 293 |
+
return "Please upload an image"
|
| 294 |
+
|
| 295 |
+
# Call the classification function and return only the string result
|
| 296 |
+
result = classifier.classify_image(image)
|
| 297 |
+
return result
|
| 298 |
+
|
| 299 |
+
# Create Gradio interface
|
| 300 |
+
with gr.Blocks(title="π Cattle Disease Classifier", theme=gr.themes.Soft()) as demo:
|
| 301 |
+
gr.Markdown("""
|
| 302 |
+
# π Cattle Disease Classification System
|
| 303 |
+
|
| 304 |
+
Upload an image of cattle to identify potential diseases and get detailed analysis.
|
| 305 |
+
|
| 306 |
+
**How it works:**
|
| 307 |
+
1. Upload a clear image of the cattle
|
| 308 |
+
2. The AI analyzes the image using deep learning
|
| 309 |
+
3. Get classification results with confidence scores
|
| 310 |
+
""")
|
| 311 |
+
|
| 312 |
+
with gr.Row():
|
| 313 |
+
with gr.Column():
|
| 314 |
+
image_input = gr.Image(
|
| 315 |
+
label="Upload Cattle Image",
|
| 316 |
+
type="pil",
|
| 317 |
+
height=400
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
classify_btn = gr.Button(
|
| 321 |
+
"π Analyze Image",
|
| 322 |
+
variant="primary",
|
| 323 |
+
size="lg"
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
with gr.Column():
|
| 327 |
+
result_output = gr.Markdown(
|
| 328 |
+
label="Classification Results",
|
| 329 |
+
value="Upload an image and click 'Analyze Image' to get results."
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# Status information
|
| 333 |
+
with gr.Row():
|
| 334 |
+
status_info = gr.Markdown(f"""
|
| 335 |
+
**System Status:**
|
| 336 |
+
- Model Loaded: {'β
' if classifier.model_loaded else 'β'}
|
| 337 |
+
- Dataset Loaded: {'β
' if classifier.dataset_loaded else 'β'}
|
| 338 |
+
- Dataset Size: {len(classifier.dataset_metadata)} entries
|
| 339 |
+
- Error: {classifier.error or 'None'}
|
| 340 |
+
""")
|
| 341 |
+
|
| 342 |
+
# Event handlers - Fixed to return only string
|
| 343 |
+
classify_btn.click(
|
| 344 |
+
fn=classify_cattle_image,
|
| 345 |
+
inputs=[image_input],
|
| 346 |
+
outputs=[result_output]
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
image_input.change(
|
| 350 |
+
fn=classify_cattle_image,
|
| 351 |
+
inputs=[image_input],
|
| 352 |
+
outputs=[result_output]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
if __name__ == "__main__":
|
| 356 |
demo.launch(share=True)
|