Ten7 commited on
Commit
800c083
·
verified ·
1 Parent(s): 7f9e82e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -92
app.py CHANGED
@@ -1,59 +1,26 @@
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/spaces/Ten7/Maize_and_Cassava_Crop_Disease_Classification/blob/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)
@@ -68,73 +35,83 @@ def home_page():
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,3 +127,4 @@ def main():
150
 
151
  if __name__ == "__main__":
152
  main()
 
 
 
1
  import streamlit as st
2
+ from tensorflow.keras.models import load_model
3
  from tensorflow.keras.preprocessing import image
4
  import numpy as np
5
  from PIL import Image
 
 
 
6
 
7
+ # Hugging Face model path for the filter model
8
+ FILTER_MODEL_PATH = "https://huggingface.co/your-repo-name/path/to/filter_model_folder/"
9
+
10
+ # Function to load the filter model directly
11
  @st.cache_resource
12
  def load_filter_model():
13
+ model = load_model(FILTER_MODEL_PATH)
14
+ return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # Load the filter model
17
  filter_model = load_filter_model()
18
 
19
+ # Load maize and cassava models
20
+ corn_model = load_model('corn_model_mobilenetv2.h5')
21
+ cassava_model = load_model('cassava_disease_model.h5')
 
 
 
 
 
22
 
23
+ # Function to predict an uploaded image
 
 
 
 
 
 
 
 
24
  def predict_image(img, model, class_names):
25
  img = image.img_to_array(img)
26
  img = np.expand_dims(img, axis=0)
 
35
  st.image("1093908406.jpg", use_column_width=True)
36
  st.write("""
37
  Welcome to the Crop Disease Identification App. This tool helps farmers identify diseases in maize and cassava crops by analyzing images of leaves.
38
+
39
  Use the navigation menu to explore the app:
40
  - **Home:** Overview of the app
41
  - **About:** Information about the app and its purpose
42
+ - **Prediction:** Upload an image and get a disease diagnosis along with recommendations.
43
  """)
44
 
45
  def about_page():
46
  st.title("About")
47
  st.image("IMG_20240727_143208_444.jpg", use_column_width=True)
48
  st.write("""
49
+ This application helps diagnose common diseases in maize and cassava crops. It uses deep learning models trained on thousands of leaf images to accurately identify diseases.
50
+
51
+ Diseases include:
52
+ - Maize: Blight, Common Rust, Gray Leaf Spot
53
+ - Cassava: Bacterial Blight, Green Mottle, Brown Streak, Mosaic
54
+
55
+ For questions or feedback, email: olorunnisholato7@gmail.com
56
  """)
57
 
58
  def prediction_page():
59
  st.title("Crop Disease Prediction")
60
+ crop_type = st.selectbox("Select the crop:", ["Maize", "Cassava"])
61
  uploaded_file = st.file_uploader("Upload an image of the leaf...", type=["jpg", "jpeg", "png"])
62
 
63
  if uploaded_file is not None:
64
+ img = Image.open(uploaded_file)
65
+
66
+ # Set image size for filtering and crop-specific models
67
+ img_resized = img.resize((128, 128)) # For the filter model
68
+ img_array = np.expand_dims(image.img_to_array(img_resized) / 255.0, axis=0)
69
+
70
+ # Apply the filter model
71
+ filter_prediction = filter_model.predict(img_array)
72
+ filter_class = np.argmax(filter_prediction)
73
+ if filter_class == 0: # Assuming 0 is "Non-Leaf"
74
+ st.warning("The uploaded image does not appear to contain a leaf. Please try again.")
75
+ return
76
+
77
+ # Resize for crop-specific models
78
+ target_size = (128, 128) if crop_type == "Maize" else (224, 224)
79
+ img = img.resize(target_size)
80
+
81
+ # Display the uploaded image
82
  st.image(img, caption='Uploaded Image', use_column_width=True)
83
 
84
  if st.button('Predict'):
85
+ st.write("Classifying...")
86
+ if crop_type == "Maize":
87
+ class_names = ['Blight', 'Common_Rust', 'Gray_Leaf_Spot', 'Healthy']
88
+ predicted_class, class_name = predict_image(img, corn_model, class_names)
 
 
89
  else:
90
+ class_names = [
91
+ 'Cassava_bacterial_blight',
92
+ 'Cassava_brown_streak_disease',
93
+ 'Cassava_green_mottle',
94
+ 'Cassava_healthy',
95
+ 'Cassava_mosaic_disease',
96
+ ]
97
+ predicted_class, class_name = predict_image(img, cassava_model, class_names)
98
+
99
+ st.write(f"Predicted Class: {class_name}")
100
+
101
+ # Recommendations based on predictions
102
+ if class_name in ['Healthy', 'Cassava_healthy']:
103
+ st.success("The leaf is healthy. No action needed.")
104
+ else:
105
+ recommendations = {
106
+ 'Blight': "Remove infected plants, apply fungicides, and rotate crops.",
107
+ 'Common_Rust': "Use resistant varieties and apply fungicides as needed.",
108
+ 'Gray_Leaf_Spot': "Ensure crop rotation, balanced nitrogen, and apply fungicides.",
109
+ 'Cassava_bacterial_blight': "Use disease-free planting material and remove affected plants.",
110
+ 'Cassava_brown_streak_disease': "Plant resistant varieties and manage whiteflies.",
111
+ 'Cassava_green_mottle': "Ensure good sanitation and use resistant varieties.",
112
+ 'Cassava_mosaic_disease': "Use resistant varieties and practice good field hygiene.",
113
+ }
114
+ st.warning(recommendations[class_name])
 
 
 
 
 
 
 
 
115
 
116
  # Main app
117
  def main():
 
127
 
128
  if __name__ == "__main__":
129
  main()
130
+