bouthina commited on
Commit
7066b60
Β·
verified Β·
1 Parent(s): 9f59f80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +180 -37
app.py CHANGED
@@ -27,13 +27,15 @@ class CattleBodyConditionClassifier:
27
  self.error = str(e)
28
 
29
  def load_json_dataset(self):
30
- """Load dataset from JSON file"""
31
  json_files = [
 
 
 
32
  'cattle_disease_features.json',
33
  'cattle_disease_dataset.json',
34
  'dataset.json',
35
- 'data.json',
36
- 'cattle_bcs_dataset.json'
37
  ]
38
 
39
  dataset_file = None
@@ -68,23 +70,44 @@ class CattleBodyConditionClassifier:
68
 
69
  for idx, entry in enumerate(data):
70
  try:
71
- if 'class' not in entry:
72
- continue
 
 
 
 
73
 
74
- class_name = entry['class'].strip() if entry['class'] else None
75
  if not class_name:
76
  continue
77
 
78
  description = entry.get('description', 'No description available').strip()
79
  file_path = entry.get('file_path', '').strip() if entry.get('file_path') else None
80
- features = entry.get('features', [])
 
 
 
 
 
 
 
 
 
 
81
 
82
  metadata_list.append({
83
  'id': entry.get('id', idx),
84
  'class': class_name,
 
 
 
85
  'description': description,
86
  'file_path': file_path,
87
  'features': features,
 
 
 
 
 
88
  'index': len(metadata_list)
89
  })
90
 
@@ -96,8 +119,12 @@ class CattleBodyConditionClassifier:
96
  self.dataset_metadata = metadata_list
97
  self.dataset_loaded = True
98
 
99
- unique_classes = set(item['class'] for item in self.dataset_metadata)
100
- logger.info(f"βœ… Dataset loaded: {len(self.dataset_metadata)} entries, {len(unique_classes)} classes")
 
 
 
 
101
  else:
102
  logger.warning("⚠️ No valid entries found")
103
 
@@ -127,23 +154,49 @@ class CattleBodyConditionClassifier:
127
  return f"❌ Error during classification: {str(e)}"
128
 
129
  def simulate_classification(self):
130
- """Simulate classification results"""
131
  if not self.dataset_metadata:
132
  return None
133
 
134
- # Random selection for demo
135
  primary_idx = random.randint(0, len(self.dataset_metadata) - 1)
136
  primary_result = self.dataset_metadata[primary_idx]
137
  confidence = random.uniform(0.75, 0.98)
138
 
139
- # Get similar cases
140
  similar_cases = []
141
- num_similar = min(5, len(self.dataset_metadata))
142
- indices = random.sample(range(len(self.dataset_metadata)), num_similar)
143
 
144
- for i, idx in enumerate(indices):
145
- case = self.dataset_metadata[idx]
146
- similarity = confidence - (i * 0.05) + random.uniform(-0.02, 0.02)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  similarity = max(0.5, min(0.99, similarity))
148
 
149
  similar_cases.append({
@@ -160,34 +213,62 @@ class CattleBodyConditionClassifier:
160
  }
161
 
162
  def format_results(self, results):
163
- """Format results as markdown"""
164
  primary = results['primary_result']
165
  confidence = results['confidence']
166
  similar_cases = results['similar_cases']
167
 
 
 
 
 
 
 
 
 
 
168
  result_text = f"""## πŸ„ Cattle Body Condition Classification Results
169
 
170
- **Body Condition Class:** {primary['class']}
 
 
171
  **Confidence Score:** {confidence:.1%}
172
 
173
- **Description:** {primary['description']}
174
 
175
- ### πŸ” Top Similar Cases:
176
  """
 
 
 
 
 
 
 
177
 
178
  for i, case in enumerate(similar_cases[:5], 1):
179
- result_text += f"\n**{i}.** {case['class']} - Similarity: {case['similarity']:.1%}"
 
 
 
 
180
  if case['file_path']:
181
- result_text += f" \n πŸ“ *Source: {case['file_path']}*"
182
 
183
  if self.dataset_metadata:
184
- unique_classes = len(set(item['class'] for item in self.dataset_metadata))
 
 
 
 
185
  result_text += f"""
186
 
187
  ### πŸ“Š Dataset Information:
188
  - **Total Cases:** {len(self.dataset_metadata)}
189
- - **Unique Classes:** {unique_classes}
190
- - **Classification Method:** Feature-based similarity matching
 
 
191
  """
192
 
193
  return result_text
@@ -202,23 +283,75 @@ def classify_cattle_image(image):
202
  return classifier.classify_image(image)
203
 
204
  def get_system_status():
205
- """Get system status"""
206
  if classifier.dataset_loaded:
207
- unique_classes = len(set(item['class'] for item in classifier.dataset_metadata))
 
 
 
 
 
208
  return f"""### System Status βœ…
209
 
210
  - **Dataset Status:** Loaded Successfully
211
  - **Total Entries:** {len(classifier.dataset_metadata)}
212
- - **Unique Classes:** {unique_classes}
 
 
 
213
  - **Error Status:** None
214
 
215
- **Sample Classes:** {', '.join(sorted(list(set(item['class'] for item in classifier.dataset_metadata)))[:5])}"""
 
 
216
  else:
217
  return f"""### System Status ❌
218
 
219
  - **Dataset Status:** Failed to Load
220
  - **Error:** {classifier.error or 'Unknown error'}
221
- - **Solution:** Ensure your JSON dataset file is in the correct location"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
  # Create Gradio interface
224
  with gr.Blocks(
@@ -232,12 +365,12 @@ with gr.Blocks(
232
  gr.Markdown("""
233
  # πŸ„ Cattle Body Condition Classification System
234
 
235
- Upload an image of cattle to analyze body condition score and get detailed assessment.
236
 
237
  **How it works:**
238
  1. πŸ“€ Upload a clear image of cattle
239
  2. πŸ€– AI analyzes the image for body condition indicators
240
- 3. πŸ“Š Get classification results with confidence scores
241
  """)
242
 
243
  with gr.Row():
@@ -261,8 +394,12 @@ with gr.Blocks(
261
  height=400
262
  )
263
 
264
- with gr.Row():
265
- status_output = gr.Markdown(value=get_system_status())
 
 
 
 
266
 
267
  # Event handlers
268
  classify_btn.click(
@@ -280,9 +417,15 @@ with gr.Blocks(
280
  gr.Markdown("""
281
  ### πŸ’‘ Tips for Best Results:
282
  - Use clear, well-lit images of cattle
283
- - Ensure the cattle's body condition is visible
284
- - Side-view images work best for assessment
285
  - Higher resolution images provide better analysis
 
 
 
 
 
 
286
  """)
287
 
288
  if __name__ == "__main__":
 
27
  self.error = str(e)
28
 
29
  def load_json_dataset(self):
30
+ """Load dataset from JSON file - Updated for new structure"""
31
  json_files = [
32
+ 'cattle_bcs_complete_dataset.json',
33
+ 'cattle_bcs_with_features.json',
34
+ 'cattle_bcs_metadata_only.json',
35
  'cattle_disease_features.json',
36
  'cattle_disease_dataset.json',
37
  'dataset.json',
38
+ 'data.json'
 
39
  ]
40
 
41
  dataset_file = None
 
70
 
71
  for idx, entry in enumerate(data):
72
  try:
73
+ # Updated to use new JSON structure
74
+ bcs_category = entry.get('bcs_category', '').strip() if entry.get('bcs_category') else None
75
+ main_category = entry.get('main_category', '').strip() if entry.get('main_category') else None
76
+
77
+ # Use bcs_category as primary class, fallback to main_category or old 'class' field
78
+ class_name = bcs_category or main_category or entry.get('class', '').strip()
79
 
 
80
  if not class_name:
81
  continue
82
 
83
  description = entry.get('description', 'No description available').strip()
84
  file_path = entry.get('file_path', '').strip() if entry.get('file_path') else None
85
+
86
+ # Handle both old 'features' and new 'image_features'
87
+ features = entry.get('image_features', entry.get('features', []))
88
+
89
+ # Extract additional metadata from new structure
90
+ breed = entry.get('breed', 'Unknown breed')
91
+ cattle_type = entry.get('cattle_type', 'Unknown type')
92
+ weight_kg = entry.get('weight_kg', None)
93
+ thoracic_perimeter = entry.get('thoracic_perimeter_cm', None)
94
+ body_length = entry.get('body_length_cm', None)
95
+ specific_characteristics = entry.get('specific_characteristics', [])
96
 
97
  metadata_list.append({
98
  'id': entry.get('id', idx),
99
  'class': class_name,
100
+ 'bcs_category': bcs_category or class_name,
101
+ 'breed': breed,
102
+ 'cattle_type': cattle_type,
103
  'description': description,
104
  'file_path': file_path,
105
  'features': features,
106
+ 'weight_kg': weight_kg,
107
+ 'thoracic_perimeter_cm': thoracic_perimeter,
108
+ 'body_length_cm': body_length,
109
+ 'specific_characteristics': specific_characteristics,
110
+ 'has_measurements': entry.get('has_measurements', False),
111
  'index': len(metadata_list)
112
  })
113
 
 
119
  self.dataset_metadata = metadata_list
120
  self.dataset_loaded = True
121
 
122
+ unique_classes = set(item['bcs_category'] for item in self.dataset_metadata)
123
+ unique_breeds = set(item['breed'] for item in self.dataset_metadata)
124
+ unique_types = set(item['cattle_type'] for item in self.dataset_metadata)
125
+
126
+ logger.info(f"βœ… Dataset loaded: {len(self.dataset_metadata)} entries")
127
+ logger.info(f"πŸ“Š {len(unique_classes)} BCS categories, {len(unique_breeds)} breeds, {len(unique_types)} cattle types")
128
  else:
129
  logger.warning("⚠️ No valid entries found")
130
 
 
154
  return f"❌ Error during classification: {str(e)}"
155
 
156
  def simulate_classification(self):
157
+ """Simulate classification results with improved logic"""
158
  if not self.dataset_metadata:
159
  return None
160
 
161
+ # Random selection for demo - can be replaced with actual ML inference
162
  primary_idx = random.randint(0, len(self.dataset_metadata) - 1)
163
  primary_result = self.dataset_metadata[primary_idx]
164
  confidence = random.uniform(0.75, 0.98)
165
 
166
+ # Get similar cases from same BCS category and breed
167
  similar_cases = []
 
 
168
 
169
+ # First, try to find cases from same BCS category
170
+ same_bcs_cases = [item for item in self.dataset_metadata
171
+ if item['bcs_category'] == primary_result['bcs_category']]
172
+
173
+ # Then, try to find cases from same breed
174
+ same_breed_cases = [item for item in self.dataset_metadata
175
+ if item['breed'] == primary_result['breed']]
176
+
177
+ # Combine and deduplicate
178
+ candidate_cases = list({item['id']: item for item in (same_bcs_cases + same_breed_cases)}.values())
179
+
180
+ # If not enough candidates, use random selection
181
+ if len(candidate_cases) < 5:
182
+ num_random = 5 - len(candidate_cases)
183
+ random_cases = random.sample(self.dataset_metadata, min(num_random, len(self.dataset_metadata)))
184
+ candidate_cases.extend(random_cases)
185
+
186
+ # Select top cases and calculate similarity
187
+ num_similar = min(5, len(candidate_cases))
188
+ selected_cases = random.sample(candidate_cases, num_similar)
189
+
190
+ for i, case in enumerate(selected_cases):
191
+ # Higher similarity for same BCS category and breed
192
+ base_similarity = confidence - (i * 0.05)
193
+
194
+ if case['bcs_category'] == primary_result['bcs_category']:
195
+ base_similarity += 0.1
196
+ if case['breed'] == primary_result['breed']:
197
+ base_similarity += 0.05
198
+
199
+ similarity = base_similarity + random.uniform(-0.02, 0.02)
200
  similarity = max(0.5, min(0.99, similarity))
201
 
202
  similar_cases.append({
 
213
  }
214
 
215
  def format_results(self, results):
216
+ """Format results as markdown with enhanced information"""
217
  primary = results['primary_result']
218
  confidence = results['confidence']
219
  similar_cases = results['similar_cases']
220
 
221
+ # Format weight information
222
+ weight_info = ""
223
+ if primary.get('weight_kg') and isinstance(primary['weight_kg'], (int, float)):
224
+ weight_info = f"**Estimated Weight:** {primary['weight_kg']} kg"
225
+ if primary.get('thoracic_perimeter_cm') and primary.get('body_length_cm'):
226
+ weight_info += f" (calculated from {primary['thoracic_perimeter_cm']}Γ—{primary['body_length_cm']} cm)"
227
+ elif primary.get('weight_kg'):
228
+ weight_info = f"**Weight Status:** {primary['weight_kg']}"
229
+
230
  result_text = f"""## πŸ„ Cattle Body Condition Classification Results
231
 
232
+ **Body Condition Score:** {primary['bcs_category']}
233
+ **Breed:** {primary['breed']}
234
+ **Cattle Type:** {primary['cattle_type']}
235
  **Confidence Score:** {confidence:.1%}
236
 
237
+ {weight_info}
238
 
239
+ **Description:** {primary['description']}
240
  """
241
+
242
+ # Add specific characteristics if available
243
+ if primary.get('specific_characteristics') and primary['specific_characteristics']:
244
+ characteristics = ', '.join(primary['specific_characteristics'])
245
+ result_text += f"\n**Specific Characteristics:** {characteristics}"
246
+
247
+ result_text += "\n\n### πŸ” Top Similar Cases:"
248
 
249
  for i, case in enumerate(similar_cases[:5], 1):
250
+ case_weight = ""
251
+ if case.get('weight_kg') and isinstance(case['weight_kg'], (int, float)):
252
+ case_weight = f" ({case['weight_kg']} kg)"
253
+
254
+ result_text += f"\n**{i}.** {case['bcs_category']} - {case['breed']} - Similarity: {case['similarity']:.1%}{case_weight}"
255
  if case['file_path']:
256
+ result_text += f" \n πŸ“ *{case['file_path']}*"
257
 
258
  if self.dataset_metadata:
259
+ unique_bcs = len(set(item['bcs_category'] for item in self.dataset_metadata))
260
+ unique_breeds = len(set(item['breed'] for item in self.dataset_metadata))
261
+ with_weights = sum(1 for item in self.dataset_metadata
262
+ if item.get('weight_kg') and isinstance(item['weight_kg'], (int, float)))
263
+
264
  result_text += f"""
265
 
266
  ### πŸ“Š Dataset Information:
267
  - **Total Cases:** {len(self.dataset_metadata)}
268
+ - **BCS Categories:** {unique_bcs}
269
+ - **Unique Breeds:** {unique_breeds}
270
+ - **Cases with Weight Data:** {with_weights}
271
+ - **Classification Method:** Feature-based similarity matching with BCS and breed weighting
272
  """
273
 
274
  return result_text
 
283
  return classifier.classify_image(image)
284
 
285
  def get_system_status():
286
+ """Get system status with enhanced information"""
287
  if classifier.dataset_loaded:
288
+ unique_bcs = sorted(list(set(item['bcs_category'] for item in classifier.dataset_metadata)))
289
+ unique_breeds = sorted(list(set(item['breed'] for item in classifier.dataset_metadata)))
290
+ unique_types = sorted(list(set(item['cattle_type'] for item in classifier.dataset_metadata)))
291
+ with_weights = sum(1 for item in classifier.dataset_metadata
292
+ if item.get('weight_kg') and isinstance(item['weight_kg'], (int, float)))
293
+
294
  return f"""### System Status βœ…
295
 
296
  - **Dataset Status:** Loaded Successfully
297
  - **Total Entries:** {len(classifier.dataset_metadata)}
298
+ - **BCS Categories:** {len(unique_bcs)}
299
+ - **Unique Breeds:** {len(unique_breeds)}
300
+ - **Cattle Types:** {len(unique_types)}
301
+ - **Entries with Weight Data:** {with_weights}
302
  - **Error Status:** None
303
 
304
+ **BCS Categories:** {', '.join(unique_bcs[:3])}{'...' if len(unique_bcs) > 3 else ''}
305
+ **Sample Breeds:** {', '.join(unique_breeds[:5])}{'...' if len(unique_breeds) > 5 else ''}
306
+ **Cattle Types:** {', '.join(unique_types)}"""
307
  else:
308
  return f"""### System Status ❌
309
 
310
  - **Dataset Status:** Failed to Load
311
  - **Error:** {classifier.error or 'Unknown error'}
312
+ - **Solution:** Ensure your cattle BCS JSON dataset file is in the correct location
313
+ - **Expected Files:** cattle_bcs_complete_dataset.json, cattle_bcs_with_features.json, or cattle_bcs_metadata_only.json"""
314
+
315
+ def get_dataset_statistics():
316
+ """Get detailed dataset statistics"""
317
+ if not classifier.dataset_loaded:
318
+ return "Dataset not loaded"
319
+
320
+ # BCS distribution
321
+ bcs_counts = {}
322
+ breed_counts = {}
323
+ type_counts = {}
324
+
325
+ for item in classifier.dataset_metadata:
326
+ bcs = item['bcs_category']
327
+ breed = item['breed']
328
+ cattle_type = item['cattle_type']
329
+
330
+ bcs_counts[bcs] = bcs_counts.get(bcs, 0) + 1
331
+ breed_counts[breed] = breed_counts.get(breed, 0) + 1
332
+ type_counts[cattle_type] = type_counts.get(cattle_type, 0) + 1
333
+
334
+ stats_text = "### πŸ“Š Detailed Dataset Statistics\n\n"
335
+
336
+ # BCS distribution
337
+ stats_text += "**BCS Distribution:**\n"
338
+ for bcs, count in sorted(bcs_counts.items()):
339
+ percentage = (count / len(classifier.dataset_metadata)) * 100
340
+ stats_text += f"- {bcs}: {count} ({percentage:.1f}%)\n"
341
+
342
+ # Breed distribution
343
+ stats_text += "\n**Breed Distribution:**\n"
344
+ for breed, count in sorted(breed_counts.items(), key=lambda x: x[1], reverse=True)[:10]:
345
+ percentage = (count / len(classifier.dataset_metadata)) * 100
346
+ stats_text += f"- {breed}: {count} ({percentage:.1f}%)\n"
347
+
348
+ # Type distribution
349
+ stats_text += "\n**Cattle Type Distribution:**\n"
350
+ for cattle_type, count in sorted(type_counts.items()):
351
+ percentage = (count / len(classifier.dataset_metadata)) * 100
352
+ stats_text += f"- {cattle_type}: {count} ({percentage:.1f}%)\n"
353
+
354
+ return stats_text
355
 
356
  # Create Gradio interface
357
  with gr.Blocks(
 
365
  gr.Markdown("""
366
  # πŸ„ Cattle Body Condition Classification System
367
 
368
+ Upload an image of cattle to analyze body condition score (BCS) and get detailed assessment including breed identification and weight estimation.
369
 
370
  **How it works:**
371
  1. πŸ“€ Upload a clear image of cattle
372
  2. πŸ€– AI analyzes the image for body condition indicators
373
+ 3. πŸ“Š Get comprehensive classification results with BCS, breed, weight, and confidence scores
374
  """)
375
 
376
  with gr.Row():
 
394
  height=400
395
  )
396
 
397
+ with gr.Tabs():
398
+ with gr.TabItem("System Status"):
399
+ status_output = gr.Markdown(value=get_system_status())
400
+
401
+ with gr.TabItem("Dataset Statistics"):
402
+ stats_output = gr.Markdown(value=get_dataset_statistics())
403
 
404
  # Event handlers
405
  classify_btn.click(
 
417
  gr.Markdown("""
418
  ### πŸ’‘ Tips for Best Results:
419
  - Use clear, well-lit images of cattle
420
+ - Ensure the cattle's body condition is visible from the side
421
+ - Include visible body parts: ribs, spine, hip bones, tail head
422
  - Higher resolution images provide better analysis
423
+ - Different breeds may have different ideal body condition scores
424
+
425
+ ### πŸ“ Body Condition Scoring:
426
+ - **BCS 1-2 (Thin):** Ribs easily visible, minimal fat cover
427
+ - **BCS 3-3.5 (Ideal):** Optimal body condition, ribs covered with thin fat layer
428
+ - **BCS 4-5 (Obese):** Excessive fat deposits, ribs difficult to feel
429
  """)
430
 
431
  if __name__ == "__main__":