MuhammmadRizwanRizwan commited on
Commit
2c8c7ef
·
verified ·
1 Parent(s): 3e0d3bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -190
app.py CHANGED
@@ -1,124 +1,17 @@
1
- # from ultralytics import YOLO
2
- # import gradio as gr
3
- # import os
4
- # import numpy as np
5
- # from PIL import Image
6
-
7
- # # Load the trained model
8
- # model_path = "best.pt" # Update this path to your best model
9
- # model = YOLO(model_path)
10
-
11
- # # Define class names
12
- # class_names = {
13
- # 0: "bacterial_leaf_blight",
14
- # 1: "brown_spot",
15
- # 2: "healthy",
16
- # 3: "leaf_blast",
17
- # 4: "leaf_scald",
18
- # 5: "narrow_brown_spot"
19
- # }
20
-
21
- # # Description for each disease
22
- # disease_info = {
23
- # "bacterial_leaf_blight": "Bacterial Leaf Blight is caused by Xanthomonas oryzae. Water-soaked lesions along leaf margins that turn yellow and eventually grey as they expand.",
24
- # "brown_spot": "Brown Spot is caused by Cochliobolus miyabeanus. Oval or round brown lesions with grey or whitish centers and a yellow halo.",
25
- # "healthy": "This leaf shows no signs of disease and appears to be healthy.",
26
- # "leaf_blast": "Leaf Blast is caused by Magnaporthe oryzae. Diamond-shaped lesions with a grey center and brown to red-brown borders.",
27
- # "leaf_scald": "Leaf Scald is caused by Microdochium oryzae. Zonate lesions with alternating light and dark brown bands that run across the leaf.",
28
- # "narrow_brown_spot": "Narrow Brown Spot is caused by Cercospora janseana. Narrow, long brown lesions parallel to the leaf veins."
29
- # }
30
-
31
- # # Treatment recommendations
32
- # treatment_recommendations = {
33
- # "bacterial_leaf_blight": "• Use disease-free seeds\n• Apply copper-based bactericides\n• Maintain proper field drainage\n• Rotate crops with non-host plants",
34
- # "brown_spot": "• Use fungicides containing azoxystrobin or propiconazole\n• Ensure balanced fertilization\n• Use resistant rice varieties\n• Proper water management",
35
- # "healthy": "• Continue regular monitoring\n• Maintain balanced fertilization\n• Follow proper irrigation practices",
36
- # "leaf_blast": "• Apply fungicides containing tricyclazole or azoxystrobin\n• Avoid excessive nitrogen fertilization\n• Use resistant rice varieties\n• Maintain proper spacing between plants",
37
- # "leaf_scald": "• Apply fungicides containing propiconazole\n• Ensure adequate drainage\n• Use resistant varieties\n• Apply balanced fertilization",
38
- # "narrow_brown_spot": "• Apply fungicides containing propiconazole or azoxystrobin\n• Maintain proper field sanitation\n• Use resistant varieties\n• Balanced fertilization"
39
- # }
40
-
41
- # def predict_image(image):
42
- # if image is None:
43
- # return {class_name: 0 for class_name in class_names.values()}, "", "", ""
44
-
45
- # # Convert to RGB if the image has an alpha channel
46
- # if image.shape[2] == 4:
47
- # image_rgb = Image.fromarray(image).convert('RGB')
48
- # image = np.array(image_rgb)
49
-
50
- # # Run inference
51
- # results = model(image)[0]
52
-
53
- # # Get probabilities for all classes
54
- # probs = results.probs.data.tolist()
55
-
56
- # # Create a dictionary of class names and their probabilities
57
- # class_probs = {class_names[i]: float(prob) for i, prob in enumerate(probs)}
58
-
59
- # # Get the top prediction
60
- # top_class_idx = results.probs.top1
61
- # top_class_name = class_names[top_class_idx]
62
- # confidence = results.probs.top1conf.item()
63
-
64
- # # Get disease info and treatment
65
- # info = disease_info[top_class_name]
66
- # treatment = treatment_recommendations[top_class_name]
67
-
68
- # # Create result text
69
- # result_text = f"Prediction: {top_class_name}\nConfidence: {confidence:.2f}"
70
-
71
- # return class_probs, result_text, info, treatment
72
-
73
- # # Create the Gradio interface
74
- # with gr.Blocks(title="Rice Leaf Disease Classifier") as app:
75
- # gr.Markdown("# Rice Leaf Disease Classification")
76
- # gr.Markdown("Upload an image of a rice leaf to identify potential diseases.")
77
-
78
- # with gr.Row():
79
- # with gr.Column():
80
- # input_image = gr.Image(label="Upload Image", type="numpy")
81
- # submit_btn = gr.Button("Analyze Leaf", variant="primary")
82
-
83
- # with gr.Column():
84
- # result_text = gr.Textbox(label="Prediction Result")
85
- # label_probs = gr.Label(label="Disease Probabilities")
86
- # disease_description = gr.Textbox(label="Disease Information", lines=4)
87
- # treatment_info = gr.Textbox(label="Treatment Recommendations", lines=6)
88
-
89
- # gr.Markdown("### Disease Categories")
90
- # gr.Markdown("• Bacterial Leaf Blight\n• Brown Spot\n• Healthy\n• Leaf Blast\n• Leaf Scald\n• Narrow Brown Spot")
91
-
92
- # gr.Markdown("### How to Use")
93
- # gr.Markdown("1. Upload a clear image of a rice leaf\n2. Click 'Analyze Leaf'\n3. View the prediction results, disease information, and treatment recommendations")
94
-
95
- # submit_btn.click(
96
- # predict_image,
97
- # inputs=[input_image],
98
- # outputs=[label_probs, result_text, disease_description, treatment_info]
99
- # )
100
-
101
- # # Launch the app
102
- # app.launch(share=True)
103
-
104
-
105
-
106
-
107
  from ultralytics import YOLO
108
  import gradio as gr
109
  import os
110
  import numpy as np
111
  from PIL import Image
112
- import torch
113
 
114
  # Load the trained model
115
- model_path = "best.pt" # Update this path to your best model
116
  model = YOLO(model_path)
117
 
118
  # Define class names
119
  class_names = {
120
  0: "bacterial_leaf_blight",
121
- 1: "brown_spot",
122
  2: "healthy",
123
  3: "leaf_blast",
124
  4: "leaf_scald",
@@ -127,97 +20,57 @@ class_names = {
127
 
128
  # Description for each disease
129
  disease_info = {
130
- "bacterial_leaf_blight": "Bacterial Leaf Blight is caused by Xanthomonas oryzae. Water-soaked lesions along leaf margins that turn yellow and eventually grey as they expand.",
131
- "brown_spot": "Brown Spot is caused by Cochliobolus miyabeanus. Oval or round brown lesions with grey or whitish centers and a yellow halo.",
132
  "healthy": "This leaf shows no signs of disease and appears to be healthy.",
133
- "leaf_blast": "Leaf Blast is caused by Magnaporthe oryzae. Diamond-shaped lesions with a grey center and brown to red-brown borders.",
134
- "leaf_scald": "Leaf Scald is caused by Microdochium oryzae. Zonate lesions with alternating light and dark brown bands that run across the leaf.",
135
- "narrow_brown_spot": "Narrow Brown Spot is caused by Cercospora janseana. Narrow, long brown lesions parallel to the leaf veins."
136
  }
137
 
138
  # Treatment recommendations
139
  treatment_recommendations = {
140
- "bacterial_leaf_blight": "• Use disease-free seeds\n• Apply copper-based bactericides\n• Maintain proper field drainage\n• Rotate crops with non-host plants",
141
- "brown_spot": "• Use fungicides containing azoxystrobin or propiconazole\n• Ensure balanced fertilization\n• Use resistant rice varieties\n• Proper water management",
142
- "healthy": "• Continue regular monitoring\n• Maintain balanced fertilization\n• Follow proper irrigation practices",
143
- "leaf_blast": "• Apply fungicides containing tricyclazole or azoxystrobin\n• Avoid excessive nitrogen fertilization\n• Use resistant rice varieties\n• Maintain proper spacing between plants",
144
- "leaf_scald": "• Apply fungicides containing propiconazole\n• Ensure adequate drainage\n• Use resistant varieties\n• Apply balanced fertilization",
145
- "narrow_brown_spot": "• Apply fungicides containing propiconazole or azoxystrobin\n• Maintain proper field sanitation\n• Use resistant varieties\n• Balanced fertilization"
146
  }
147
 
148
  def predict_image(image):
149
- # Default response for no image
150
- default_response = {
151
- 'class_probs': {class_name: 0 for class_name in class_names.values()},
152
- 'result_text': "No image uploaded",
153
- 'info': "",
154
- 'treatment': ""
155
- }
156
-
157
  if image is None:
158
- return default_response['class_probs'], default_response['result_text'], default_response['info'], default_response['treatment']
159
-
160
- try:
161
- # Convert to RGB if the image has an alpha channel
162
- if image.shape[2] == 4:
163
- image_rgb = Image.fromarray(image).convert('RGB')
164
- image = np.array(image_rgb)
165
-
166
- # Ensure image is in the right format for YOLO
167
- # Typically, YOLO expects images in RGB format and normalized
168
- if not isinstance(image, torch.Tensor):
169
- # Convert numpy array to torch tensor if needed
170
- image = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
171
- image = image.unsqueeze(0) # Add batch dimension
172
-
173
- # Run inference
174
- results = model(image)
175
-
176
- # Validate results
177
- if not results:
178
- return default_response['class_probs'], "No results from model", default_response['info'], default_response['treatment']
179
-
180
- # Get results based on the model's output
181
- if hasattr(results[0], 'probs'):
182
- # Classification model
183
- probs = results[0].probs.data.tolist()
184
- class_probs = {class_names[i]: float(prob) for i, prob in enumerate(probs)}
185
-
186
- # Get top prediction
187
- top_class_idx = results[0].probs.top1
188
- top_class_name = class_names[top_class_idx]
189
- confidence = results[0].probs.top1conf.item()
190
-
191
- elif hasattr(results[0], 'boxes'):
192
- # Detection model (fallback)
193
- class_probs = {class_name: 0 for class_name in class_names.values()}
194
- top_class_name = "Unable to classify"
195
- confidence = 0
196
- else:
197
- return default_response['class_probs'], "Unexpected model output", default_response['info'], default_response['treatment']
198
-
199
- # Get disease info and treatment
200
- info = disease_info.get(top_class_name, "No information available")
201
- treatment = treatment_recommendations.get(top_class_name, "No treatment recommendations")
202
-
203
- # Create result text
204
- result_text = f"Prediction: {top_class_name}\nConfidence: {confidence:.2f}"
205
-
206
- return class_probs, result_text, info, treatment
207
-
208
- except Exception as e:
209
- # Comprehensive error handling
210
- error_msg = f"Error in prediction: {str(e)}"
211
- return (
212
- default_response['class_probs'],
213
- error_msg,
214
- default_response['info'],
215
- default_response['treatment']
216
- )
217
 
218
  # Create the Gradio interface
219
  with gr.Blocks(title="Rice Leaf Disease Classifier") as app:
220
- gr.Markdown("# Rice Leaf Disease Classification")
221
  gr.Markdown("Upload an image of a rice leaf to identify potential diseases.")
222
 
223
  with gr.Row():
@@ -244,5 +97,4 @@ with gr.Blocks(title="Rice Leaf Disease Classifier") as app:
244
  )
245
 
246
  # Launch the app
247
- if __name__ == "__main__":
248
- app.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from ultralytics import YOLO
2
  import gradio as gr
3
  import os
4
  import numpy as np
5
  from PIL import Image
 
6
 
7
  # Load the trained model
8
+ model_path = "best.pt" # Ensure this file is uploaded to your Hugging Face Space
9
  model = YOLO(model_path)
10
 
11
  # Define class names
12
  class_names = {
13
  0: "bacterial_leaf_blight",
14
+ 1: "brown_spot",
15
  2: "healthy",
16
  3: "leaf_blast",
17
  4: "leaf_scald",
 
20
 
21
  # Description for each disease
22
  disease_info = {
23
+ "bacterial_leaf_blight": "Bacterial Leaf Blight is caused by Xanthomonas oryzae...",
24
+ "brown_spot": "Brown Spot is caused by Cochliobolus miyabeanus...",
25
  "healthy": "This leaf shows no signs of disease and appears to be healthy.",
26
+ "leaf_blast": "Leaf Blast is caused by Magnaporthe oryzae...",
27
+ "leaf_scald": "Leaf Scald is caused by Microdochium oryzae...",
28
+ "narrow_brown_spot": "Narrow Brown Spot is caused by Cercospora janseana..."
29
  }
30
 
31
  # Treatment recommendations
32
  treatment_recommendations = {
33
+ "bacterial_leaf_blight": "• Use disease-free seeds\n• Apply copper-based bactericides...",
34
+ "brown_spot": "• Use fungicides containing azoxystrobin or propiconazole...",
35
+ "healthy": "• Continue regular monitoring...",
36
+ "leaf_blast": "• Apply fungicides containing tricyclazole or azoxystrobin...",
37
+ "leaf_scald": "• Apply fungicides containing propiconazole...",
38
+ "narrow_brown_spot": "• Apply fungicides containing propiconazole or azoxystrobin..."
39
  }
40
 
41
  def predict_image(image):
 
 
 
 
 
 
 
 
42
  if image is None:
43
+ return {class_name: 0 for class_name in class_names.values()}, "", "", ""
44
+
45
+ # Convert to RGB if needed
46
+ if image.shape[2] == 4:
47
+ image_rgb = Image.fromarray(image).convert('RGB')
48
+ image = np.array(image_rgb)
49
+
50
+ # Run inference
51
+ results = model(image)[0]
52
+
53
+ # Get probabilities
54
+ probs = results.probs.data.tolist()
55
+ class_probs = {class_names[i]: float(prob) for i, prob in enumerate(probs)}
56
+
57
+ # Get top prediction
58
+ top_class_idx = results.probs.top1
59
+ top_class_name = class_names[top_class_idx]
60
+ confidence = results.probs.top1conf.item()
61
+
62
+ # Get disease info and treatment
63
+ info = disease_info[top_class_name]
64
+ treatment = treatment_recommendations[top_class_name]
65
+
66
+ # Create result text
67
+ result_text = f"Prediction: {top_class_name}\nConfidence: {confidence:.2f}"
68
+
69
+ return class_probs, result_text, info, treatment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  # Create the Gradio interface
72
  with gr.Blocks(title="Rice Leaf Disease Classifier") as app:
73
+ gr.Markdown("# 🌱 Rice Leaf Disease Classification")
74
  gr.Markdown("Upload an image of a rice leaf to identify potential diseases.")
75
 
76
  with gr.Row():
 
97
  )
98
 
99
  # Launch the app
100
+ app.launch(server_name="0.0.0.0")