EnYa32 commited on
Commit
e51a9e2
Β·
verified Β·
1 Parent(s): 6ecdd4b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +79 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,81 @@
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 CNN (without Transfer Learning)
 
 
2
  import streamlit as st
3
+ import numpy as np
4
+ from PIL import Image
5
+ import tensorflow as tf
6
+ from tensorflow.keras.models import load_model
7
+ import warnings
8
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
9
+
10
+
11
+ # ------------------ SETTINGS ------------------
12
+ MODEL_PATH = "grape_cnn_final_optionA.keras" # CNN model (trained from scratch)
13
+ IMG_SIZE = (224, 224) # Based on your training setup
14
+
15
+ # Class labels (same order as during training)
16
+ CLASS_NAMES = [
17
+ "Black Rot",
18
+ "Esca (Black Measles)",
19
+ "Leaf Blight (Isariopsis Leaf Spot)",
20
+ "Healthy"
21
+ ]
22
+
23
+ # ------------------ LOAD MODEL ------------------
24
+ @st.cache_resource
25
+ def load_model_cached():
26
+ return load_model(MODEL_PATH)
27
+
28
+ model = load_model_cached()
29
+
30
+ # ------------------ IMAGE PREPROCESSING ------------------
31
+ def preprocess_image(image: Image.Image) -> np.ndarray:
32
+ image = image.convert("RGB")
33
+ image = image.resize(IMG_SIZE)
34
+ img_array = np.array(image) / 255.0 # Normalization (used during training)
35
+ return np.expand_dims(img_array, axis=0)
36
+
37
+ # ------------------ PREDICTION ------------------
38
+ def predict(image: Image.Image):
39
+ processed_img = preprocess_image(image)
40
+ preds = model.predict(processed_img)
41
+ probs = tf.nn.softmax(preds[0]).numpy() # In case final layer used raw logits
42
+ top_idx = np.argmax(probs)
43
+ return CLASS_NAMES[top_idx], probs[top_idx], probs
44
+
45
+ # ------------------ STREAMLIT UI ------------------
46
+ st.set_page_config(page_title="Grapevine CNN Classifier (No Transfer Learning)", layout="centered")
47
+
48
+ st.title("πŸ‡ Grapevine Leaf Disease Classifier (CNN – No Transfer Learning)")
49
+ st.write(
50
+ "This app uses your custom Convolutional Neural Network trained **from scratch** "
51
+ "to classify grapevine leaf images into disease categories."
52
+ )
53
+
54
+ # --- Model Info ---
55
+ st.sidebar.header("πŸ”§ Model Details")
56
+ st.sidebar.write(f"**Model file:** `{MODEL_PATH}`")
57
+ st.sidebar.write(f"**Input size:** {IMG_SIZE[0]} Γ— {IMG_SIZE[1]}")
58
+ st.sidebar.write("**Class labels:**")
59
+ for cls in CLASS_NAMES:
60
+ st.sidebar.write(f"- {cls}")
61
+
62
+ # --- File Upload ---
63
+ uploaded_file = st.file_uploader("πŸ“€ Upload a grapevine leaf image", type=["jpg", "jpeg", "png"])
64
+
65
+ if uploaded_file is not None:
66
+ image = Image.open(uploaded_file)
67
+ st.image(image, caption="πŸ“Έ Uploaded Image", use_container_width=True)
68
+
69
+ if st.button("πŸ” Predict Disease"):
70
+ with st.spinner("Analyzing image..."):
71
+ top_class, top_prob, probabilities = predict(image)
72
+
73
+ st.subheader("πŸ”Ž Prediction Result")
74
+ st.write(f"**Predicted Disease:** `{top_class}`")
75
+ st.write(f"**Confidence:** {top_prob:.2%}")
76
 
77
+ st.subheader("πŸ“Š Probability per Class")
78
+ for cls, prob in zip(CLASS_NAMES, probabilities):
79
+ st.write(f"- **{cls}** β†’ {prob:.2%}")
80
+ else:
81
+ st.info("Please upload a grapevine leaf image to start the prediction.")