yasyn14 commited on
Commit
46f1618
·
1 Parent(s): 40547f7

made new changes

Browse files
Files changed (1) hide show
  1. main.py +56 -32
main.py CHANGED
@@ -188,21 +188,33 @@ def sanitize_search_query(query: str) -> str:
188
  def safe_create_disease_info(class_index: str, disease_data: Optional[Dict[str, Any]] = None) -> DiseaseInfo:
189
  """Safely create DiseaseInfo object with proper validation and defaults"""
190
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  if not disease_data:
192
- # This is likely a healthy plant or unknown disease
193
- return DiseaseInfo(
194
- disease_name=None,
195
- crop="Unknown",
196
- description=f"This appears to be a healthy plant or an unrecognized condition for class {class_index}",
197
- is_healthy=True,
198
- type="Healthy/Unknown"
199
- )
200
-
201
- # Create a copy of the data to avoid modifying the original
202
  safe_data = disease_data.copy()
203
-
204
- # Ensure all required fields have proper defaults
205
- defaults = {
206
  'disease_name': safe_data.get('disease_name'),
207
  'common_names': safe_data.get('common_names', []),
208
  'crop': safe_data.get('crop', 'Unknown'),
@@ -217,36 +229,48 @@ def safe_create_disease_info(class_index: str, disease_data: Optional[Dict[str,
217
  'sprayer_intervals': safe_data.get('sprayer_intervals', ''),
218
  'localized_tips': safe_data.get('localized_tips', ''),
219
  'type': safe_data.get('type', 'Unknown'),
220
- 'external_resources': safe_data.get('external_resources', []),
221
  'is_healthy': False
222
  }
223
-
224
- # Validate and clean external_resources
225
- if defaults['external_resources']:
226
- validated_resources = []
227
- for resource in defaults['external_resources']:
228
- if isinstance(resource, dict):
229
- validated_resources.append({
230
- 'title': str(resource.get('title', '')),
231
- 'url': str(resource.get('url', ''))
232
- })
233
- defaults['external_resources'] = validated_resources
234
-
235
- return DiseaseInfo(**defaults)
236
-
237
  except Exception as e:
238
  logger.error(f"Error creating DiseaseInfo for class {class_index}: {str(e)}")
239
  logger.error(f"Data causing error: {disease_data}")
240
-
241
- # Return a minimal valid DiseaseInfo object
242
  return DiseaseInfo(
243
  disease_name="Unknown",
 
244
  crop="Unknown",
245
  description=f"Error loading disease information for class {class_index}",
 
246
  cause="Unknown",
 
 
 
 
 
 
 
 
 
247
  is_healthy=False
248
  )
249
 
 
250
  def get_recommendations(class_index: str, confidence: float, disease_info: DiseaseInfo) -> List[str]:
251
  """Generate actionable recommendations based on prediction using treatment and prevention from JSON"""
252
  recommendations = []
@@ -451,9 +475,9 @@ def predict_image(image_bytes: bytes) -> PredictionResponse:
451
  # Final structured response
452
  return PredictionResponse(
453
  success=True,
454
- predicted_class=disease_info['disease_name'] if disease_info.disease_name else "Unknown",
455
  predicted_class_index=predicted_class_idx,
456
- clean_class_name=disease_info['disease_name'] if disease_info.disease_name else "Unknown",
457
  message="Prediction successful",
458
  all_predictions=all_predictions,
459
  class_id=class_id,
 
188
  def safe_create_disease_info(class_index: str, disease_data: Optional[Dict[str, Any]] = None) -> DiseaseInfo:
189
  """Safely create DiseaseInfo object with proper validation and defaults"""
190
  try:
191
+ # Set up base defaults to always match DiseaseInfo model
192
+ base_defaults = {
193
+ 'disease_name': None,
194
+ 'common_names': [],
195
+ 'crop': "Unknown",
196
+ 'description': f"This appears to be a healthy plant or an unrecognized condition for class {class_index}",
197
+ 'symptoms': [],
198
+ 'cause': None,
199
+ 'treatment': [],
200
+ 'image_urls': [],
201
+ 'prevention': [],
202
+ 'management_tips': "",
203
+ 'risk_level': "Unknown",
204
+ 'sprayer_intervals': "",
205
+ 'localized_tips': "",
206
+ 'type': "Healthy/Unknown",
207
+ 'external_resources': [],
208
+ 'is_healthy': True
209
+ }
210
+
211
  if not disease_data:
212
+ return DiseaseInfo(**base_defaults)
213
+
214
+ # Use defaults but override with any provided disease data
 
 
 
 
 
 
 
215
  safe_data = disease_data.copy()
216
+
217
+ final_data = {
 
218
  'disease_name': safe_data.get('disease_name'),
219
  'common_names': safe_data.get('common_names', []),
220
  'crop': safe_data.get('crop', 'Unknown'),
 
229
  'sprayer_intervals': safe_data.get('sprayer_intervals', ''),
230
  'localized_tips': safe_data.get('localized_tips', ''),
231
  'type': safe_data.get('type', 'Unknown'),
232
+ 'external_resources': [],
233
  'is_healthy': False
234
  }
235
+
236
+ # Validate and normalize external_resources
237
+ external_resources = safe_data.get('external_resources', [])
238
+ if isinstance(external_resources, list):
239
+ final_data['external_resources'] = [
240
+ {
241
+ 'title': str(res.get('title', '')),
242
+ 'url': str(res.get('url', ''))
243
+ }
244
+ for res in external_resources if isinstance(res, dict)
245
+ ]
246
+
247
+ return DiseaseInfo(**final_data)
248
+
249
  except Exception as e:
250
  logger.error(f"Error creating DiseaseInfo for class {class_index}: {str(e)}")
251
  logger.error(f"Data causing error: {disease_data}")
252
+
253
+ # Return a safe fallback object with all required fields
254
  return DiseaseInfo(
255
  disease_name="Unknown",
256
+ common_names=[],
257
  crop="Unknown",
258
  description=f"Error loading disease information for class {class_index}",
259
+ symptoms=[],
260
  cause="Unknown",
261
+ treatment=[],
262
+ image_urls=[],
263
+ prevention=[],
264
+ management_tips="",
265
+ risk_level="Unknown",
266
+ sprayer_intervals="",
267
+ localized_tips="",
268
+ type="Unknown",
269
+ external_resources=[],
270
  is_healthy=False
271
  )
272
 
273
+
274
  def get_recommendations(class_index: str, confidence: float, disease_info: DiseaseInfo) -> List[str]:
275
  """Generate actionable recommendations based on prediction using treatment and prevention from JSON"""
276
  recommendations = []
 
475
  # Final structured response
476
  return PredictionResponse(
477
  success=True,
478
+ predicted_class=clean_name,
479
  predicted_class_index=predicted_class_idx,
480
+ clean_class_name= clean_name,
481
  message="Prediction successful",
482
  all_predictions=all_predictions,
483
  class_id=class_id,