Ten7 commited on
Commit
964aba1
·
verified ·
1 Parent(s): 0161257

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -68
app.py CHANGED
@@ -1,15 +1,59 @@
1
 
2
  import streamlit as st
3
- from tensorflow.keras.models import load_model
4
  from tensorflow.keras.preprocessing import image
5
  import numpy as np
6
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Load the models
9
- corn_model = load_model('corn_model_mobilenetv2.h5')
10
- cassava_model = load_model('cassava_disease_model.h5')
11
-
12
- # Function to predict an uploaded image
13
  def predict_image(img, model, class_names):
14
  img = image.img_to_array(img)
15
  img = np.expand_dims(img, axis=0)
@@ -21,93 +65,76 @@ def predict_image(img, model, class_names):
21
  # Define pages
22
  def home_page():
23
  st.title("Maize and Cassava Crop Disease Identification")
24
- # Add an image to the home page
25
  st.image("1093908406.jpg", use_column_width=True)
26
  st.write("""
27
- Welcome to the Crop Disease Identification App. This tool aims at helping local farmers
28
- identify diseases in maize and cassava crops by analyzing images of leaves.
29
-
30
  Use the navigation menu to explore the app:
31
  - **Home:** Overview of the app
32
  - **About:** Information about the app and its purpose
33
  - **Prediction:** Upload an image and get a disease diagnosis along with recommendations
34
  """)
35
-
36
 
37
  def about_page():
38
  st.title("About")
39
- # Add an image to the about page
40
  st.image("IMG_20240727_143208_444.jpg", use_column_width=True)
41
  st.write("""
42
- This application is designed to assist farmers in diagnosing common diseases in maize and cassava crops.
43
- By utilizing deep learning models trained on thousands of leaf images, the app can accurately identify
44
- diseases such as "blight, common rust and gray leaf spot" in maize and "Bacterial blight, green mottle, brown streak and mosaic" in cassava.
45
-
46
- The models were built using Convolutional Neural Networks (CNNs), trained on publicly available datasets and tested on locally obtained images..
47
- The goal is to provide quick and accurate disease identification to help mitigate crop losses and improve yields.
48
-
49
- If you have any questions or feedback, please reach out to the developer.
50
-
51
-
52
  E-mail: olorunnisholato7@gmail.com
53
-
54
- Thank you for using the Crop Disease Identification App!
55
  """)
56
-
57
 
58
  def prediction_page():
59
  st.title("Crop Disease Prediction")
60
 
61
- # Model selection
62
- crop_type = st.selectbox("Select the crop:", ["Maize", "Cassava"])
63
-
64
- # File uploader for image input
65
  uploaded_file = st.file_uploader("Upload an image of the leaf...", type=["jpg", "jpeg", "png"])
66
 
67
  if uploaded_file is not None:
68
- # Load the uploaded image
69
- img = Image.open(uploaded_file)
70
- # Set image size based on crop type
71
- if crop_type == "Maize":
72
- img = img.resize((128, 128)) # Resize for Maize
73
- target_size = (128, 128)
74
- else:
75
- img = img.resize((224, 224)) # Resize for Cassava
76
- target_size = (224, 224)
77
-
78
- # Display the uploaded image
79
  st.image(img, caption='Uploaded Image', use_column_width=True)
80
- st.write("")
81
 
82
- # Predict button
83
  if st.button('Predict'):
84
- st.write("Classifying...")
85
-
86
- # Predict based on the selected crop type
87
- if crop_type == "Maize":
88
- class_names = ['Blight', 'Common_Rust', 'Gray_Leaf_Spot', 'Healthy']
89
- predicted_class, class_name = predict_image(img, corn_model, class_names)
90
- else:
91
- class_names = ['Cassava_bacterial_blight','Cassava_brown_streak_disease','Cassava_green_mottle','Cassava_healthy','Cassava_mosaic_disease']
92
- predicted_class, class_name = predict_image(img, cassava_model, class_names)
93
-
94
- # Display prediction
95
- st.write(f"Predicted Class: {class_name}")
96
 
97
- # Recommendation based on the predicted class
98
- if class_name == 'Healthy' or class_name == 'Cassava_healthy':
99
- st.success("The leaf is healthy. No action needed.")
 
100
  else:
101
- recommendations = {
102
- 'Blight': "Recommendation: Immediately remove and destroy infected plants to prevent the spread of the disease. Implement a rotation plan that avoids planting corn for at least two years in affected fields. Apply a fungicide that is effective against blight, such as those containing chlorothalonil or mancozeb, at the early signs of disease.Consider planting blight-resistant corn varieties in future planting seasons.",
103
- 'Common_Rust': "Recommendation: Use resistant varieties and apply fungicides if necessary. If rust is detected early, apply a fungicide like azoxystrobin or tebuconazole to control the spread. Clear out any crop debris from previous seasons, as rust spores can survive in old plant material. Avoid overhead irrigation to reduce leaf wetness, which can promote rust development.",
104
- 'Gray_Leaf_Spot': "Recommendation: Ensure proper crop rotation and apply fungicides. Regularly monitor fields during humid conditions, as Gray Leaf Spot thrives in such environments. Use fungicides like pyraclostrobin or propiconazole at the onset of symptoms. Ensure balanced nitrogen levels; excessive nitrogen can exacerbate Gray Leaf Spot. Consider tillage practices that bury crop residues, reducing the amount of fungal spores in the soil.",
105
- 'Cassava_bacterial_blight': "Recommendation: Use disease-free planting material and remove affected plants. Remove and destroy infected plants to prevent the spread. Avoid excessive irrigation and ensure proper drainage to reduce waterlogging, which can exacerbate CBB. Sterilize tools and equipment to avoid spreading bacteria from infected plants.",
106
- 'Cassava_brown_streak_disease': "Recommendation: Plant CBSD-resistant cassava varieties, such as those developed through breeding programs. Consider harvesting earlier than usual to reduce yield loss if CBSD symptoms are present. Manage whiteflies, the primary vector for CBSD, by using insecticides or planting barrier crops. Isolate infected fields from healthy ones to prevent the spread of the virus",
107
- 'Cassava_green_mottle': "Recommendation: Ensure good field sanitation and use resistant varieties. Select varieties known for resistance to CGM. Control weeds that may serve as hosts for the CGM virus.",
108
- 'Cassava_mosaic_disease': "Recommendation: Use resistant varieties and practice good field hygiene."
109
- }
110
- st.warning(recommendations[class_name])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  # Main app
113
  def main():
@@ -123,4 +150,3 @@ def main():
123
 
124
  if __name__ == "__main__":
125
  main()
126
-
 
1
 
2
  import streamlit as st
3
+ from tensorflow.keras.models import load_model, model_from_json
4
  from tensorflow.keras.preprocessing import image
5
  import numpy as np
6
  from PIL import Image
7
+ import requests
8
+ import zipfile
9
+ import os
10
+
11
+ # Download and extract the filter model files
12
+ @st.cache_resource
13
+ def load_filter_model():
14
+ # URL of the zipped filter model folder
15
+ filter_model_url = "https://huggingface.co/username/path-to-folder/resolve/main/model_checkpoint.zip"
16
+
17
+ # Download the zipped folder
18
+ zip_path = "model_checkpoint.zip"
19
+ with open(zip_path, "wb") as f:
20
+ f.write(requests.get(filter_model_url).content)
21
+
22
+ # Extract the zipped folder
23
+ extract_dir = "filter_model"
24
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
25
+ zip_ref.extractall(extract_dir)
26
+
27
+ # Load the filter model
28
+ config_path = os.path.join(extract_dir, "config.json")
29
+ weights_path = os.path.join(extract_dir, "model.weights.h5")
30
+
31
+ with open(config_path, "r") as f:
32
+ config_json = f.read()
33
+ filter_model = model_from_json(config_json)
34
+ filter_model.load_weights(weights_path)
35
+ return filter_model
36
+
37
+ filter_model = load_filter_model()
38
+
39
+ # Load the disease models
40
+ @st.cache_resource
41
+ def load_disease_models():
42
+ corn_model = load_model('corn_model_mobilenetv2.h5')
43
+ cassava_model = load_model('cassava_disease_model.h5')
44
+ return corn_model, cassava_model
45
+
46
+ corn_model, cassava_model = load_disease_models()
47
+
48
+ # Function to predict using the filter model
49
+ def filter_prediction(img, model):
50
+ img = image.img_to_array(img)
51
+ img = np.expand_dims(img, axis=0)
52
+ img = img / 255.0 # Normalize image
53
+ prediction = model.predict(img)
54
+ return np.argmax(prediction)
55
 
56
+ # Function to predict crop disease
 
 
 
 
57
  def predict_image(img, model, class_names):
58
  img = image.img_to_array(img)
59
  img = np.expand_dims(img, axis=0)
 
65
  # Define pages
66
  def home_page():
67
  st.title("Maize and Cassava Crop Disease Identification")
 
68
  st.image("1093908406.jpg", use_column_width=True)
69
  st.write("""
70
+ Welcome to the Crop Disease Identification App. This tool helps farmers identify diseases in maize and cassava crops by analyzing images of leaves.
 
 
71
  Use the navigation menu to explore the app:
72
  - **Home:** Overview of the app
73
  - **About:** Information about the app and its purpose
74
  - **Prediction:** Upload an image and get a disease diagnosis along with recommendations
75
  """)
 
76
 
77
  def about_page():
78
  st.title("About")
 
79
  st.image("IMG_20240727_143208_444.jpg", use_column_width=True)
80
  st.write("""
81
+ This application assists farmers in diagnosing common diseases in maize and cassava crops.
82
+ It uses deep learning models trained on leaf images to identify diseases like blight, common rust, gray leaf spot (maize),
83
+ bacterial blight, green mottle, brown streak, and mosaic (cassava).
84
+ If you have questions or feedback, reach out to the developer at:
 
 
 
 
 
 
85
  E-mail: olorunnisholato7@gmail.com
 
 
86
  """)
 
87
 
88
  def prediction_page():
89
  st.title("Crop Disease Prediction")
90
 
 
 
 
 
91
  uploaded_file = st.file_uploader("Upload an image of the leaf...", type=["jpg", "jpeg", "png"])
92
 
93
  if uploaded_file is not None:
94
+ img = Image.open(uploaded_file).resize((128, 128))
 
 
 
 
 
 
 
 
 
 
95
  st.image(img, caption='Uploaded Image', use_column_width=True)
 
96
 
 
97
  if st.button('Predict'):
98
+ st.write("Classifying with the filter model...")
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ # Use the filter model to determine if the image is a leaf
101
+ filter_result = filter_prediction(img, filter_model)
102
+ if filter_result == 0:
103
+ st.error("The uploaded image is not a leaf. Please upload a valid leaf image.")
104
  else:
105
+ st.success("The uploaded image is a leaf. Proceeding with disease detection.")
106
+
107
+ # Select the crop type
108
+ crop_type = st.selectbox("Select the crop:", ["Maize", "Cassava"])
109
+
110
+ # Predict disease
111
+ if crop_type == "Maize":
112
+ img = img.resize((128, 128))
113
+ class_names = ['Blight', 'Common_Rust', 'Gray_Leaf_Spot', 'Healthy']
114
+ predicted_class, class_name = predict_image(img, corn_model, class_names)
115
+ else:
116
+ img = img.resize((224, 224))
117
+ class_names = ['Cassava_bacterial_blight', 'Cassava_brown_streak_disease',
118
+ 'Cassava_green_mottle', 'Cassava_healthy', 'Cassava_mosaic_disease']
119
+ predicted_class, class_name = predict_image(img, cassava_model, class_names)
120
+
121
+ # Display prediction
122
+ st.write(f"Predicted Class: {class_name}")
123
+
124
+ # Recommendation
125
+ if class_name == 'Healthy' or class_name == 'Cassava_healthy':
126
+ st.success("The leaf is healthy. No action needed.")
127
+ else:
128
+ recommendations = {
129
+ 'Blight': "Remove infected plants and apply fungicide.",
130
+ 'Common_Rust': "Use resistant varieties and fungicides.",
131
+ 'Gray_Leaf_Spot': "Ensure crop rotation and apply fungicides.",
132
+ 'Cassava_bacterial_blight': "Use disease-free planting material.",
133
+ 'Cassava_brown_streak_disease': "Plant resistant cassava varieties.",
134
+ 'Cassava_green_mottle': "Ensure good field sanitation.",
135
+ 'Cassava_mosaic_disease': "Use resistant varieties and good field hygiene."
136
+ }
137
+ st.warning(recommendations[class_name])
138
 
139
  # Main app
140
  def main():
 
150
 
151
  if __name__ == "__main__":
152
  main()