# app.py --- Grapevine Leaf Disease Classifier using Transfer Learning (ResNet50) import streamlit as st import numpy as np from PIL import Image import tensorflow as tf from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input from tensorflow.keras.models import Sequential from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout st.set_page_config( page_title="Grapevine Leaf Disease Classifier (Transfer Learning)", layout="centered" ) # ------------------ SETTINGS ------------------ MODEL_PATH = "src/grape_cnn_TL_ResNet50.weights.h5" # Weights file IMG_SIZE = (224, 224) # Same as used during training # Class labels (same order as during training) CLASS_NAMES = [ "Black Rot", "Esca (Black Measles)", "Leaf Blight (Isariopsis Leaf Spot)", "Healthy" ] # ------------------ BUILD MODEL + LOAD WEIGHTS ------------------ @st.cache_resource def build_and_load_model(): # 1) Base ResNet50 (same setup as in training) base_model = ResNet50( weights="imagenet", include_top=False, input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3) ) # Freeze backbone (as in training) for layer in base_model.layers: layer.trainable = False # 2) Classification head (same as in your notebook) model = Sequential([ base_model, GlobalAveragePooling2D(), Dense(256, activation="relu"), Dropout(0.5), Dense(len(CLASS_NAMES), activation="softmax") ]) # 3) Load trained weights model.load_weights(MODEL_PATH) return model model = build_and_load_model() # ------------------ IMAGE PREPROCESSING ------------------ def preprocess_image(image: Image.Image) -> np.ndarray: """Prepare image for ResNet50-based Transfer Learning model.""" image = image.convert("RGB") image = image.resize(IMG_SIZE) img_array = np.array(image) img_array = np.expand_dims(img_array, axis=0) img_array = preprocess_input(img_array) # ResNet50-specific preprocessing return img_array # ------------------ PREDICTION ------------------ def predict(image: Image.Image): processed_img = preprocess_image(image) preds = model.predict(processed_img) probs = tf.nn.softmax(preds[0]).numpy() top_idx = np.argmax(probs) return CLASS_NAMES[top_idx], probs[top_idx], probs # ------------------ STREAMLIT UI ------------------ st.title("🍇 Grapevine Leaf Disease Classifier (CNN – Transfer Learning with ResNet50)") st.write( "This app uses a Convolutional Neural Network with **Transfer Learning (ResNet50)** " "to classify grapevine leaf images into disease categories." ) # --- Sidebar: Model Info --- st.sidebar.header("🔧 Model Details") st.sidebar.write(f"**Weights file:** `{MODEL_PATH}`") st.sidebar.write(f"**Input size:** {IMG_SIZE[0]} × {IMG_SIZE[1]}") st.sidebar.write("**Class labels:**") for cls in CLASS_NAMES: st.sidebar.write(f"- {cls}") # --- File Upload --- uploaded_file = st.file_uploader( "📤 Upload a grapevine leaf image", type=["jpg", "jpeg", "png"] ) if uploaded_file is not None: image = Image.open(uploaded_file) st.image( image, caption="📸 Uploaded Image", use_container_width=True ) if st.button("🔍 Predict Disease"): with st.spinner("Analyzing image..."): top_class, top_prob, probabilities = predict(image) st.subheader("🔎 Prediction Result") st.write(f"**Predicted Disease:** `{top_class}`") st.write(f"**Confidence:** {top_prob:.2%}") st.subheader("📊 Probability per Class") for cls, prob in zip(CLASS_NAMES, probabilities): st.write(f"- **{cls}** → {prob:.2%}") else: st.info("Please upload a grapevine leaf image to start the prediction.")