import streamlit as st import tensorflow as tf from PIL import Image import numpy as np # --- PAGE CONFIG --- st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered") # --- MODEL RECONSTRUCTION (Fixed Shape) --- @st.cache_resource def load_my_model(): try: # 1. Recreate the Base (MobileNetV2) base_model = tf.keras.applications.MobileNetV2( input_shape=(224, 224, 3), include_top=False, weights=None ) base_model.trainable = False # 2. Rebuild the Top Layers (MATCHING YOUR WEIGHTS: 512 neurons) model = tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(512, activation='relu'), # Changed from 128 to 512 tf.keras.layers.Dense(5, activation='softmax') ]) # 3. Load the weights model.load_weights('src/rice_transfer_model.h5') return model except Exception as e: st.error(f"Shape Mismatch or Loading Error: {e}") return None # Initialize Model model = load_my_model() class_names = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag'] # --- USER INTERFACE --- st.title("🌾 Rice Variety Classification") st.markdown("### **Transfer Learning Edition (MobileNetV2)**") uploaded_file = st.file_uploader("Upload a rice grain image...", type=["jpg", "jpeg", "png"]) if uploaded_file is not None and model is not None: image = Image.open(uploaded_file) st.image(image, caption='Uploaded Sample', use_container_width=True) with st.spinner('Calculating probabilities...'): # Preprocessing img = image.resize((224, 224)) img_array = np.array(img) if img_array.shape[-1] == 4: img_array = img_array[:,:,:3] img_array = np.expand_dims(img_array, axis=0) img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array) # Prediction predictions = model.predict(img_array) result_idx = np.argmax(predictions[0]) confidence = predictions[0][result_idx] * 100 # Results st.success(f"Prediction: **{class_names[result_idx]}**") st.metric(label="Confidence Level", value=f"{confidence:.2f}%")