EnYa32 commited on
Commit
d68bcd7
Β·
verified Β·
1 Parent(s): 8b56483

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +115 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,117 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ # app.py --- Grapevine Leaf Disease Classifier using Transfer Learning (ResNet50)
 
 
2
  import streamlit as st
3
+ import numpy as np
4
+ from PIL import Image
5
+ import tensorflow as tf
6
+
7
+ from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
8
+ from tensorflow.keras.models import Sequential
9
+ from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
10
+
11
+ st.set_page_config(
12
+ page_title="Grapevine Leaf Disease Classifier (Transfer Learning)",
13
+ layout="centered"
14
+ )
15
+
16
+ # ------------------ SETTINGS ------------------
17
+ MODEL_PATH = "grape_cnn_TL_ResNet50.weights.h5" # Weights file
18
+ IMG_SIZE = (224, 224) # Same as used during training
19
+
20
+ # Class labels (same order as during training)
21
+ CLASS_NAMES = [
22
+ "Black Rot",
23
+ "Esca (Black Measles)",
24
+ "Leaf Blight (Isariopsis Leaf Spot)",
25
+ "Healthy"
26
+ ]
27
+
28
+ # ------------------ BUILD MODEL + LOAD WEIGHTS ------------------
29
+ @st.cache_resource
30
+ def build_and_load_model():
31
+ # 1) Base ResNet50 (same setup as in training)
32
+ base_model = ResNet50(
33
+ weights="imagenet",
34
+ include_top=False,
35
+ input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)
36
+ )
37
+
38
+ # Freeze backbone (as in training)
39
+ for layer in base_model.layers:
40
+ layer.trainable = False
41
+
42
+ # 2) Classification head (same as in your notebook)
43
+ model = Sequential([
44
+ base_model,
45
+ GlobalAveragePooling2D(),
46
+ Dense(256, activation="relu"),
47
+ Dropout(0.5),
48
+ Dense(len(CLASS_NAMES), activation="softmax")
49
+ ])
50
+
51
+ # 3) Load trained weights
52
+ model.load_weights(MODEL_PATH)
53
+
54
+ return model
55
+
56
+ model = build_and_load_model()
57
+
58
+ # ------------------ IMAGE PREPROCESSING ------------------
59
+ def preprocess_image(image: Image.Image) -> np.ndarray:
60
+ """Prepare image for ResNet50-based Transfer Learning model."""
61
+ image = image.convert("RGB")
62
+ image = image.resize(IMG_SIZE)
63
+ img_array = np.array(image)
64
+ img_array = np.expand_dims(img_array, axis=0)
65
+ img_array = preprocess_input(img_array) # ResNet50-specific preprocessing
66
+ return img_array
67
+
68
+ # ------------------ PREDICTION ------------------
69
+ def predict(image: Image.Image):
70
+ processed_img = preprocess_image(image)
71
+ preds = model.predict(processed_img)
72
+ probs = tf.nn.softmax(preds[0]).numpy()
73
+ top_idx = np.argmax(probs)
74
+ return CLASS_NAMES[top_idx], probs[top_idx], probs
75
+
76
+ # ------------------ STREAMLIT UI ------------------
77
+ st.title("πŸ‡ Grapevine Leaf Disease Classifier (CNN – Transfer Learning with ResNet50)")
78
+ st.write(
79
+ "This app uses a Convolutional Neural Network with **Transfer Learning (ResNet50)** "
80
+ "to classify grapevine leaf images into disease categories."
81
+ )
82
+
83
+ # --- Sidebar: Model Info ---
84
+ st.sidebar.header("πŸ”§ Model Details")
85
+ st.sidebar.write(f"**Weights file:** `{MODEL_PATH}`")
86
+ st.sidebar.write(f"**Input size:** {IMG_SIZE[0]} Γ— {IMG_SIZE[1]}")
87
+ st.sidebar.write("**Class labels:**")
88
+ for cls in CLASS_NAMES:
89
+ st.sidebar.write(f"- {cls}")
90
+
91
+ # --- File Upload ---
92
+ uploaded_file = st.file_uploader(
93
+ "πŸ“€ Upload a grapevine leaf image",
94
+ type=["jpg", "jpeg", "png"]
95
+ )
96
+
97
+ if uploaded_file is not None:
98
+ image = Image.open(uploaded_file)
99
+ st.image(
100
+ image,
101
+ caption="πŸ“Έ Uploaded Image",
102
+ use_container_width=True
103
+ )
104
+
105
+ if st.button("πŸ” Predict Disease"):
106
+ with st.spinner("Analyzing image..."):
107
+ top_class, top_prob, probabilities = predict(image)
108
+
109
+ st.subheader("πŸ”Ž Prediction Result")
110
+ st.write(f"**Predicted Disease:** `{top_class}`")
111
+ st.write(f"**Confidence:** {top_prob:.2%}")
112
 
113
+ st.subheader("πŸ“Š Probability per Class")
114
+ for cls, prob in zip(CLASS_NAMES, probabilities):
115
+ st.write(f"- **{cls}** β†’ {prob:.2%}")
116
+ else:
117
+ st.info("Please upload a grapevine leaf image to start the prediction.")