Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,7 @@ import base64
|
|
| 9 |
from PIL import Image
|
| 10 |
import os
|
| 11 |
import logging
|
|
|
|
| 12 |
|
| 13 |
# Configure logging
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -34,31 +35,31 @@ class CattleDiseaseClassifier:
|
|
| 34 |
self.model_loaded = True
|
| 35 |
logger.info("β
Model loaded successfully")
|
| 36 |
|
| 37 |
-
# Load dataset from
|
| 38 |
-
self.
|
| 39 |
|
| 40 |
except Exception as e:
|
| 41 |
logger.error(f"β Initialization failed: {e}")
|
| 42 |
self.error = str(e)
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
"""Load dataset from
|
| 46 |
-
# Look for
|
| 47 |
-
|
| 48 |
-
'
|
| 49 |
-
'
|
| 50 |
-
'
|
| 51 |
-
'
|
| 52 |
]
|
| 53 |
|
| 54 |
dataset_file = None
|
| 55 |
-
for filename in
|
| 56 |
if os.path.exists(filename):
|
| 57 |
dataset_file = filename
|
| 58 |
break
|
| 59 |
|
| 60 |
if not dataset_file:
|
| 61 |
-
logger.warning("β οΈ No
|
| 62 |
return
|
| 63 |
|
| 64 |
logger.info(f"π Loading dataset from: {dataset_file}")
|
|
@@ -68,61 +69,86 @@ class CattleDiseaseClassifier:
|
|
| 68 |
|
| 69 |
try:
|
| 70 |
with open(dataset_file, 'r', encoding='utf-8') as f:
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
continue
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 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:
|
|
@@ -130,14 +156,26 @@ class CattleDiseaseClassifier:
|
|
| 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)
|
|
@@ -252,12 +290,12 @@ class CattleDiseaseClassifier:
|
|
| 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 "
|
| 261 |
confidence = np.mean([item['similarity'] for item in similar_images[:3]])
|
| 262 |
|
| 263 |
# Format result as a single string
|
|
@@ -267,15 +305,19 @@ class CattleDiseaseClassifier:
|
|
| 267 |
**Disease Stage:** {best_stage}
|
| 268 |
**Confidence:** {confidence:.2%}
|
| 269 |
|
| 270 |
-
**Description:** {similar_images[0]['description']
|
| 271 |
|
| 272 |
### Top Similar Cases:
|
| 273 |
"""
|
| 274 |
|
| 275 |
-
for i, item in enumerate(similar_images[:
|
| 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 |
|
|
@@ -307,6 +349,8 @@ with gr.Blocks(title="π Cattle Disease Classifier", theme=gr.themes.Soft()) a
|
|
| 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():
|
|
@@ -331,11 +375,17 @@ with gr.Blocks(title="π Cattle Disease Classifier", theme=gr.themes.Soft()) a
|
|
| 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 |
|
|
|
|
| 9 |
from PIL import Image
|
| 10 |
import os
|
| 11 |
import logging
|
| 12 |
+
import json
|
| 13 |
|
| 14 |
# Configure logging
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 35 |
self.model_loaded = True
|
| 36 |
logger.info("β
Model loaded successfully")
|
| 37 |
|
| 38 |
+
# Load dataset from JSON file
|
| 39 |
+
self.load_json_dataset()
|
| 40 |
|
| 41 |
except Exception as e:
|
| 42 |
logger.error(f"β Initialization failed: {e}")
|
| 43 |
self.error = str(e)
|
| 44 |
|
| 45 |
+
def load_json_dataset(self):
|
| 46 |
+
"""Load dataset from JSON file"""
|
| 47 |
+
# Look for JSON dataset files
|
| 48 |
+
json_files = [
|
| 49 |
+
'cattle_disease_features.json',
|
| 50 |
+
'cattle_disease_dataset.json',
|
| 51 |
+
'dataset.json',
|
| 52 |
+
'data.json'
|
| 53 |
]
|
| 54 |
|
| 55 |
dataset_file = None
|
| 56 |
+
for filename in json_files:
|
| 57 |
if os.path.exists(filename):
|
| 58 |
dataset_file = filename
|
| 59 |
break
|
| 60 |
|
| 61 |
if not dataset_file:
|
| 62 |
+
logger.warning("β οΈ No JSON dataset file found")
|
| 63 |
return
|
| 64 |
|
| 65 |
logger.info(f"π Loading dataset from: {dataset_file}")
|
|
|
|
| 69 |
|
| 70 |
try:
|
| 71 |
with open(dataset_file, 'r', encoding='utf-8') as f:
|
| 72 |
+
data = json.load(f)
|
| 73 |
+
|
| 74 |
+
# Handle both list format and dict format
|
| 75 |
+
if isinstance(data, dict):
|
| 76 |
+
# If it's a dict, assume it has a key containing the list
|
| 77 |
+
for key in data:
|
| 78 |
+
if isinstance(data[key], list):
|
| 79 |
+
data = data[key]
|
| 80 |
+
break
|
| 81 |
+
else:
|
| 82 |
+
# If no list found, treat the dict itself as a single entry
|
| 83 |
+
data = [data]
|
| 84 |
+
|
| 85 |
+
total_entries = len(data)
|
| 86 |
+
logger.info(f"π Found {total_entries} entries in dataset")
|
| 87 |
+
|
| 88 |
+
for idx, entry in enumerate(data):
|
| 89 |
+
try:
|
| 90 |
+
# Extract required fields
|
| 91 |
+
if 'features' not in entry or 'class' not in entry:
|
| 92 |
+
logger.warning(f"β οΈ Entry {idx}: Missing required fields (features or class)")
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
# Get class name
|
| 96 |
+
class_name = entry['class'].strip() if entry['class'] else None
|
| 97 |
+
if not class_name:
|
| 98 |
+
logger.warning(f"β οΈ Entry {idx}: Empty class name")
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
# Get stage - handle missing stage with "no stage"
|
| 102 |
+
stage = entry.get('stage', 'no stage')
|
| 103 |
+
if not stage or stage.strip() == '':
|
| 104 |
+
stage = 'no stage'
|
| 105 |
+
else:
|
| 106 |
+
stage = stage.strip()
|
| 107 |
+
|
| 108 |
+
# Get description
|
| 109 |
+
description = entry.get('description', '').strip() if entry.get('description') else 'No description available'
|
| 110 |
|
| 111 |
+
# Get file path (optional)
|
| 112 |
+
file_path = entry.get('file_path', '').strip() if entry.get('file_path') else None
|
| 113 |
+
|
| 114 |
+
# Parse features
|
| 115 |
+
features = entry['features']
|
| 116 |
+
if isinstance(features, str):
|
| 117 |
+
# If features are stored as string, parse them
|
| 118 |
+
features = [float(x.strip()) for x in features.split(',')]
|
| 119 |
+
elif not isinstance(features, list):
|
| 120 |
+
logger.warning(f"β οΈ Entry {idx}: Features must be a list or comma-separated string")
|
| 121 |
continue
|
| 122 |
|
| 123 |
+
# Convert to numpy array
|
| 124 |
+
features_array = np.array(features, dtype=np.float32)
|
| 125 |
+
|
| 126 |
+
# Validate features
|
| 127 |
+
if len(features_array) == 0:
|
| 128 |
+
logger.warning(f"β οΈ Entry {idx}: Empty features array")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
continue
|
| 130 |
+
if np.any(np.isnan(features_array)) or np.any(np.isinf(features_array)):
|
| 131 |
+
logger.warning(f"β οΈ Entry {idx}: Invalid features (NaN/Inf)")
|
| 132 |
+
continue
|
| 133 |
+
|
| 134 |
+
# Store valid entry
|
| 135 |
+
features_list.append(features_array)
|
| 136 |
+
metadata_list.append({
|
| 137 |
+
'id': entry.get('id', idx),
|
| 138 |
+
'class': class_name,
|
| 139 |
+
'stage': stage,
|
| 140 |
+
'description': description,
|
| 141 |
+
'file_path': file_path,
|
| 142 |
+
'index': len(features_list) - 1
|
| 143 |
+
})
|
| 144 |
+
|
| 145 |
+
# Progress logging
|
| 146 |
+
if len(features_list) % 100 == 0:
|
| 147 |
+
logger.info(f" π Processed {len(features_list)}/{total_entries} entries...")
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.warning(f"β οΈ Error parsing entry {idx}: {e}")
|
| 151 |
+
continue
|
| 152 |
|
| 153 |
# Convert to numpy arrays
|
| 154 |
if features_list:
|
|
|
|
| 156 |
self.dataset_metadata = metadata_list
|
| 157 |
self.dataset_loaded = True
|
| 158 |
|
| 159 |
+
# Get unique classes and stages for statistics
|
| 160 |
+
unique_classes = set(item['class'] for item in self.dataset_metadata)
|
| 161 |
+
unique_stages = set(item['stage'] for item in self.dataset_metadata)
|
| 162 |
+
|
| 163 |
logger.info(f"β
Dataset loaded successfully:")
|
| 164 |
logger.info(f" π Total entries: {len(self.dataset_metadata)}")
|
| 165 |
logger.info(f" π Feature shape: {self.dataset_features.shape}")
|
| 166 |
+
logger.info(f" π Unique classes: {len(unique_classes)}")
|
| 167 |
+
logger.info(f" π Unique stages: {len(unique_stages)}")
|
| 168 |
logger.info(f" πΎ Memory usage: {self.dataset_features.nbytes / 1024 / 1024:.1f} MB")
|
| 169 |
|
| 170 |
+
# Log some class examples
|
| 171 |
+
logger.info(f" π·οΈ Sample classes: {sorted(list(unique_classes))[:10]}")
|
| 172 |
+
|
| 173 |
else:
|
| 174 |
logger.warning("β οΈ No valid entries found in dataset")
|
| 175 |
|
| 176 |
+
except json.JSONDecodeError as e:
|
| 177 |
+
logger.error(f"β Error parsing JSON: {e}")
|
| 178 |
+
self.error = f"JSON parsing error: {str(e)}"
|
| 179 |
except Exception as e:
|
| 180 |
logger.error(f"β Error loading dataset: {e}")
|
| 181 |
self.error = str(e)
|
|
|
|
| 290 |
for item in similar_images[:5]:
|
| 291 |
if item['class']:
|
| 292 |
class_votes[item['class']] = class_votes.get(item['class'], 0) + item['similarity']
|
| 293 |
+
if item['stage'] and item['stage'] != 'no stage':
|
| 294 |
stage_votes[item['stage']] = stage_votes.get(item['stage'], 0) + item['similarity']
|
| 295 |
|
| 296 |
# Get final prediction
|
| 297 |
best_class = max(class_votes.items(), key=lambda x: x[1])[0] if class_votes else "Unknown"
|
| 298 |
+
best_stage = max(stage_votes.items(), key=lambda x: x[1])[0] if stage_votes else "no stage"
|
| 299 |
confidence = np.mean([item['similarity'] for item in similar_images[:3]])
|
| 300 |
|
| 301 |
# Format result as a single string
|
|
|
|
| 305 |
**Disease Stage:** {best_stage}
|
| 306 |
**Confidence:** {confidence:.2%}
|
| 307 |
|
| 308 |
+
**Description:** {similar_images[0]['description']}
|
| 309 |
|
| 310 |
### Top Similar Cases:
|
| 311 |
"""
|
| 312 |
|
| 313 |
+
for i, item in enumerate(similar_images[:5], 1):
|
| 314 |
result_text += f"\n{i}. **{item['class']}** - Similarity: {item['similarity']:.2%}"
|
| 315 |
+
if item['stage'] and item['stage'] != 'no stage':
|
| 316 |
result_text += f" (Stage: {item['stage']})"
|
| 317 |
+
else:
|
| 318 |
+
result_text += f" (Stage: no stage)"
|
| 319 |
+
if item['file_path']:
|
| 320 |
+
result_text += f" - File: {item['file_path']}"
|
| 321 |
|
| 322 |
return result_text
|
| 323 |
|
|
|
|
| 349 |
1. Upload a clear image of the cattle
|
| 350 |
2. The AI analyzes the image using deep learning
|
| 351 |
3. Get classification results with confidence scores
|
| 352 |
+
|
| 353 |
+
**Now using JSON dataset with full feature support!**
|
| 354 |
""")
|
| 355 |
|
| 356 |
with gr.Row():
|
|
|
|
| 375 |
|
| 376 |
# Status information
|
| 377 |
with gr.Row():
|
| 378 |
+
# Get dataset statistics
|
| 379 |
+
unique_classes = len(set(item['class'] for item in classifier.dataset_metadata)) if classifier.dataset_metadata else 0
|
| 380 |
+
unique_stages = len(set(item['stage'] for item in classifier.dataset_metadata)) if classifier.dataset_metadata else 0
|
| 381 |
+
|
| 382 |
status_info = gr.Markdown(f"""
|
| 383 |
**System Status:**
|
| 384 |
- Model Loaded: {'β
' if classifier.model_loaded else 'β'}
|
| 385 |
- Dataset Loaded: {'β
' if classifier.dataset_loaded else 'β'}
|
| 386 |
- Dataset Size: {len(classifier.dataset_metadata)} entries
|
| 387 |
+
- Unique Classes: {unique_classes}
|
| 388 |
+
- Unique Stages: {unique_stages}
|
| 389 |
- Error: {classifier.error or 'None'}
|
| 390 |
""")
|
| 391 |
|