shaheer-data commited on
Commit
0953fe9
·
verified ·
1 Parent(s): d7c73c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -102
app.py CHANGED
@@ -1,115 +1,78 @@
1
  import streamlit as st
2
  import numpy as np
3
- import tensorflow as tf # "tf" is not accessed
4
- from PIL import Image, ImageDraw
5
- import gdown
6
  from tensorflow.keras.models import load_model
 
 
 
7
  import os
8
 
9
- # Set page configuration (must be the first Streamlit command)
10
- st.set_page_config(
11
- page_title="Yellow Rust Disease Classification",
12
- layout="wide",
13
- initial_sidebar_state="expanded"
14
- )
15
-
16
- # Function to download the model
17
- def download_model_from_drive(file_id, output_path):
18
- try:
19
- if not os.path.exists(output_path):
20
- gdown.download(f"https://drive.google.com/uc?id={file_id}", output_path, quiet=False)
21
- else:
22
- st.info("Model already downloaded.")
23
- except Exception as e:
24
- st.error(f"Error downloading model: {e}")
25
-
26
- # Define Google Drive file ID and local model path
27
- file_id = "1EnokggrC6ymrSibtj2t7IHWb9QVtrehS" # Replace with your Google Drive file ID
28
- model_path = "my_model.keras"
29
-
30
- # Streamlit app
31
- st.title("Streamlit App with Pretrained Model")
32
-
33
- # Download model from Google Drive
34
- st.write("Downloading model from Google Drive...")
35
- download_model_from_drive(file_id, model_path)
36
-
37
- # Load the model
38
- if os.path.exists(model_path):
39
- st.write("Loading model...")
40
- try:
41
- model = load_model(model_path, compile=False)
42
- st.success("Model loaded successfully!")
43
- st.write(model.summary())
44
- except Exception as e:
45
- st.error(f"Error loading model: {e}")
46
- else:
47
- st.error("Model file not found.")
48
-
49
- # Theme selection
50
- st.sidebar.title("Settings and Preferences")
51
- theme = st.sidebar.selectbox("Select Theme", ["Light", "Dark"])
52
- if theme == "Dark":
53
- st.markdown(
54
- "<style>body { background-color: #0e1117; color: white; }</style>",
55
- unsafe_allow_html=True,
56
- )
57
-
58
- # Title
59
- st.title("Yellow Rust Disease Classification Dashboard")
60
-
61
- # User Input Section
62
- st.sidebar.header("Upload Image of Plant Leaf")
63
- image_file = st.sidebar.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
64
-
65
- if image_file:
66
- st.subheader("Uploaded Image")
67
- image = Image.open(image_file)
68
- st.image(image, caption="Uploaded Image", use_column_width=True)
69
-
70
- # Preprocess the image for prediction
71
- def preprocess_image(img):
72
- img = img.resize((224, 224)) # Adjust to model input size
73
- img_array = np.array(img) / 255.0 # Normalize
74
- return np.expand_dims(img_array, axis=0) # Add batch dimension
75
-
76
- processed_image = preprocess_image(image)
77
-
78
- # Prediction Results
79
- predictions = model.predict(processed_image, batch_size=1)
80
- class_names = ["0", "MR", "MRMS", "MS", "R", "S"] # Replace with actual class labels from dataset
81
  predicted_class = class_names[np.argmax(predictions)]
82
- confidence = np.max(predictions) * 100
83
 
84
- st.header("Prediction Results")
85
- st.write(f"**Predicted Status:** {predicted_class}")
86
- st.write(f"**Confidence Level:** {confidence:.2f}%")
87
 
88
- # Severity Level
89
- severity = "High" if confidence > 80 else "Moderate" if confidence > 50 else "Low"
90
- st.write(f"**Severity Level:** {severity}")
91
 
92
- # Highlighting a region (Example: bounding box)
93
- st.subheader("Highlighted Regions")
94
- draw = ImageDraw.Draw(image)
95
- # Example bounding box coordinates, adjust as necessary
96
- draw.rectangle([50, 50, 150, 150], outline="red", width=3) # Example bounding box
97
- st.image(image, caption="Highlighted Regions", use_column_width=True)
98
 
99
- # Disease Insights
100
- st.header("Disease Insights")
101
- for i, class_name in enumerate(class_names):
102
- st.write(f"{class_name}: {predictions[0][i] * 100:.2f}%")
103
 
104
- # Model Performance Metrics (Admin Only)
105
- if st.checkbox("Show Model Performance Metrics (Admin Only)"):
106
- st.write("**Accuracy:** 95.6%") # Replace with actual metric
107
- st.write("**Precision:** 94.7%") # Replace with actual metric
108
- st.write("**Recall:** 93.5%") # Replace with actual metric
109
 
110
- # User Notifications
111
- if severity == "High":
112
- st.warning("High severity detected! Immediate action is recommended.")
113
 
114
- # Footer
115
- st.sidebar.info("Powered by Streamlit and TensorFlow")
 
 
 
 
1
  import streamlit as st
2
  import numpy as np
3
+ import tensorflow as tf
 
 
4
  from tensorflow.keras.models import load_model
5
+ from PIL import Image
6
+ import requests
7
+ import tempfile
8
  import os
9
 
10
+ def download_model_from_gdrive():
11
+ """Downloads the model from Google Drive."""
12
+ gdrive_url = "https://drive.google.com/uc?id=1EnokggrC6ymrSibtj2t7IHWb9QVtrehS"
13
+ output_path = "final_meta_model.keras"
14
+
15
+ with requests.get(gdrive_url, stream=True) as r:
16
+ r.raise_for_status()
17
+ with open(output_path, "wb") as f:
18
+ for chunk in r.iter_content(chunk_size=8192):
19
+ f.write(chunk)
20
+
21
+ return output_path
22
+
23
+ def load_or_download_model():
24
+ """Loads the model from Hugging Face or Google Drive."""
25
+ hf_model_path = "final_meta_model.keras"
26
+
27
+ # Check if model exists locally (from Hugging Face Space storage)
28
+ if os.path.exists(hf_model_path):
29
+ model = load_model(hf_model_path)
30
+ else:
31
+ st.write("Model not found locally. Downloading from Google Drive...")
32
+ model_path = download_model_from_gdrive()
33
+ model = load_model(model_path)
34
+
35
+ return model
36
+
37
+ def preprocess_image(image):
38
+ """Preprocesses the uploaded image for model prediction."""
39
+ image = image.resize((224, 224)) # Assuming input size of 224x224 for the model
40
+ image_array = np.array(image)
41
+ image_array = image_array / 255.0 # Normalize pixel values to [0, 1]
42
+ image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
43
+ return image_array
44
+
45
+ def predict_severity(model, image):
46
+ """Predicts the severity using the model."""
47
+ predictions = model.predict(image)
48
+ class_names = ['0', 'MR', 'MRMS', 'MS', 'R', 'S']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  predicted_class = class_names[np.argmax(predictions)]
50
+ return predicted_class, predictions
51
 
52
+ # Streamlit App
53
+ st.title("Disease Severity Prediction App")
54
+ st.write("Upload an image to predict the severity of the disease.")
55
 
56
+ # Image Upload
57
+ uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
 
58
 
59
+ if uploaded_image:
60
+ st.image(uploaded_image, caption="Uploaded Image", use_column_width=True)
 
 
 
 
61
 
62
+ # Load model
63
+ with st.spinner("Loading model..."):
64
+ model = load_or_download_model()
 
65
 
66
+ # Preprocess image
67
+ image = Image.open(uploaded_image)
68
+ preprocessed_image = preprocess_image(image)
 
 
69
 
70
+ # Predict severity
71
+ with st.spinner("Predicting severity..."):
72
+ predicted_class, prediction_scores = predict_severity(model, preprocessed_image)
73
 
74
+ # Display results
75
+ st.success(f"Predicted Class: {predicted_class}")
76
+ st.write("Prediction Scores:")
77
+ for class_name, score in zip(['0', 'MR', 'MRMS', 'MS', 'R', 'S'], prediction_scores[0]):
78
+ st.write(f"{class_name}: {score:.4f}")