YonaniCodes commited on
Commit
c058f53
ยท
1 Parent(s): cf51d59
Files changed (1) hide show
  1. app.py +25 -17
app.py CHANGED
@@ -4,11 +4,14 @@ import json
4
  import tensorflow_hub as hub
5
  from PIL import Image
6
 
 
7
  tf.keras.utils.get_custom_objects().update({'KerasLayer': hub.KerasLayer})
8
 
 
9
  class_file_path = './labels.json'
10
  model_file_path = './model.h5'
11
 
 
12
  model = tf.keras.models.load_model(model_file_path)
13
 
14
  def load_breeds(file_path=class_file_path):
@@ -17,14 +20,14 @@ def load_breeds(file_path=class_file_path):
17
 
18
  labels = load_breeds()
19
 
20
- # Disease list as one space-separated string (title case, spaces not underscores)
21
- disease_list_str = " ".join([label.replace(' ', '_').title() for label in labels])
22
 
23
- # Example organic treatments per disease (fill with your actual treatments)
24
  organic_treatments = {
25
  "Maize Rust": "Use neem oil spray weekly and rotate crops to prevent rust spread.",
26
  "Maize Fall Armyworm": "Introduce natural predators like Trichogramma wasps and use Bacillus thuringiensis (Bt) sprays.",
27
- "Maize Grasshoper": "Manual removal and natural bird repellents recommended.",
28
  "Maize Healthy": "No treatment needed. Maintain good crop hygiene.",
29
  "Maize Leaf Beetle": "Apply insecticidal soap and promote beneficial insects like ladybugs.",
30
  "Maize Leaf Blight": "Use resistant varieties and apply copper-based fungicides organically.",
@@ -37,8 +40,8 @@ organic_treatments = {
37
  "Tomato Septoria Leaf Spot": "Mulch soil and use biofungicides such as Bacillus subtilis.",
38
  "Tomato Spider Mites Two Spotted Spider Mite": "Introduce predatory mites and spray insecticidal soap.",
39
  "Tomato Target Spot": "Crop rotation and neem oil sprays are effective.",
40
- "Tomato Tomato YellowLeaf Curl Virus": "Control whitefly vectors and use resistant varieties.",
41
- "Tomato Tomato Mosaic Virus": "Remove infected plants and sanitize tools regularly.",
42
  "Tomato Healthy": "No treatment needed. Keep plants healthy with regular watering and nutrients."
43
  }
44
 
@@ -58,22 +61,28 @@ def predict_breed(image):
58
  predictions = model.predict(img_array)[0]
59
  top3_indices = predictions.argsort()[-3:][::-1]
60
 
61
- top_pred_class = labels[top3_indices[0]]
62
- if "maize" not in top_pred_class.lower() and "tomato" not in top_pred_class.lower():
 
 
 
63
  return "โŒ This model only supports Maize and Tomato leaf images.", {}, ""
64
 
 
65
  output_lines = ["๐ŸŒฟ **Top 3 Predictions:**"]
66
  confidence_scores = {}
67
 
68
  for i in top3_indices:
69
  class_name = labels[i].replace('_', ' ').title()
70
  confidence = predictions[i] * 100
71
- output_lines.append(f"{class_name}: {confidence:.2f}%")
72
  confidence_scores[class_name] = float(f"{confidence:.2f}")
73
 
74
- treatment = organic_treatments.get(top_pred_class.replace('_', ' ').title(), "No organic treatment available.")
 
 
75
 
76
- return "\n".join(output_lines), confidence_scores, f"๐ŸŒฑ **Organic Treatment for {top_pred_class.replace('_', ' ').title()}:**\n{treatment}"
77
 
78
  except Exception as e:
79
  print("Prediction Error:", e)
@@ -81,13 +90,12 @@ def predict_breed(image):
81
 
82
  with gr.Blocks() as demo:
83
  gr.Markdown("# ๐ŸŒฟ Hares: Maize & Tomato Disease Classifier")
84
- gr.Markdown("## Supported Diseases:")
85
- gr.Markdown(disease_list_str)
86
-
87
  image_input = gr.Image(type="pil", label="Upload Maize or Tomato Leaf Image")
88
- prediction_text = gr.Text(label="Prediction")
89
- confidence_bar = gr.Label(label="Confidence Scores")
90
- treatment_text = gr.Textbox(label="Organic Treatment", lines=4)
91
 
92
  image_input.change(fn=predict_breed, inputs=image_input, outputs=[prediction_text, confidence_bar, treatment_text])
93
 
 
4
  import tensorflow_hub as hub
5
  from PIL import Image
6
 
7
+ # Ensure KerasLayer is recognized when loading the model
8
  tf.keras.utils.get_custom_objects().update({'KerasLayer': hub.KerasLayer})
9
 
10
+ # Paths to your model and label files
11
  class_file_path = './labels.json'
12
  model_file_path = './model.h5'
13
 
14
+ # Load the model
15
  model = tf.keras.models.load_model(model_file_path)
16
 
17
  def load_breeds(file_path=class_file_path):
 
20
 
21
  labels = load_breeds()
22
 
23
+ # Format disease list as comma-separated string, nice readable format
24
+ disease_list_str = ", ".join([label.replace('_', ' ').title() for label in labels])
25
 
26
+ # Organic treatments dictionary with keys matching formatted labels exactly
27
  organic_treatments = {
28
  "Maize Rust": "Use neem oil spray weekly and rotate crops to prevent rust spread.",
29
  "Maize Fall Armyworm": "Introduce natural predators like Trichogramma wasps and use Bacillus thuringiensis (Bt) sprays.",
30
+ "Maize Grasshopper": "Manual removal and natural bird repellents recommended.",
31
  "Maize Healthy": "No treatment needed. Maintain good crop hygiene.",
32
  "Maize Leaf Beetle": "Apply insecticidal soap and promote beneficial insects like ladybugs.",
33
  "Maize Leaf Blight": "Use resistant varieties and apply copper-based fungicides organically.",
 
40
  "Tomato Septoria Leaf Spot": "Mulch soil and use biofungicides such as Bacillus subtilis.",
41
  "Tomato Spider Mites Two Spotted Spider Mite": "Introduce predatory mites and spray insecticidal soap.",
42
  "Tomato Target Spot": "Crop rotation and neem oil sprays are effective.",
43
+ "Tomato Yellowleaf Curl Virus": "Control whitefly vectors and use resistant varieties.",
44
+ "Tomato Mosaic Virus": "Remove infected plants and sanitize tools regularly.",
45
  "Tomato Healthy": "No treatment needed. Keep plants healthy with regular watering and nutrients."
46
  }
47
 
 
61
  predictions = model.predict(img_array)[0]
62
  top3_indices = predictions.argsort()[-3:][::-1]
63
 
64
+ top_pred_class_raw = labels[top3_indices[0]]
65
+ top_pred_class = top_pred_class_raw.replace('_', ' ').title()
66
+
67
+ # Check for valid crops
68
+ if "Maize" not in top_pred_class and "Tomato" not in top_pred_class:
69
  return "โŒ This model only supports Maize and Tomato leaf images.", {}, ""
70
 
71
+ # Build prediction text with markdown formatting
72
  output_lines = ["๐ŸŒฟ **Top 3 Predictions:**"]
73
  confidence_scores = {}
74
 
75
  for i in top3_indices:
76
  class_name = labels[i].replace('_', ' ').title()
77
  confidence = predictions[i] * 100
78
+ output_lines.append(f"- **{class_name}**: {confidence:.2f}%")
79
  confidence_scores[class_name] = float(f"{confidence:.2f}")
80
 
81
+ treatment = organic_treatments.get(top_pred_class, "No organic treatment available.")
82
+
83
+ treatment_text = f"๐ŸŒฑ **Organic Treatment for {top_pred_class}:**\n\n{treatment}"
84
 
85
+ return "\n".join(output_lines), confidence_scores, treatment_text
86
 
87
  except Exception as e:
88
  print("Prediction Error:", e)
 
90
 
91
  with gr.Blocks() as demo:
92
  gr.Markdown("# ๐ŸŒฟ Hares: Maize & Tomato Disease Classifier")
93
+ gr.Markdown(f"### Supported Diseases:\n\n{disease_list_str}")
94
+
 
95
  image_input = gr.Image(type="pil", label="Upload Maize or Tomato Leaf Image")
96
+ prediction_text = gr.Markdown(label="Prediction")
97
+ confidence_bar = gr.JSON(label="Confidence Scores")
98
+ treatment_text = gr.Markdown(label="Organic Treatment")
99
 
100
  image_input.change(fn=predict_breed, inputs=image_input, outputs=[prediction_text, confidence_bar, treatment_text])
101