Spaces:
Sleeping
Sleeping
Basak Tamer commited on
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +17 -42
src/streamlit_app.py
CHANGED
|
@@ -2,29 +2,15 @@ import streamlit as st
|
|
| 2 |
import tensorflow as tf
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
-
import os
|
| 6 |
|
| 7 |
# --- PAGE CONFIG ---
|
| 8 |
st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered")
|
| 9 |
|
| 10 |
-
# --- MODEL
|
| 11 |
@st.cache_resource
|
| 12 |
def load_my_model():
|
| 13 |
-
# 1. FIND THE FILE: Check for common names and locations
|
| 14 |
-
possible_names = ['rice_model.h5', 'rice_transfer_model.h5', 'src/rice_transfer_model.h5']
|
| 15 |
-
model_path = None
|
| 16 |
-
|
| 17 |
-
for name in possible_names:
|
| 18 |
-
if os.path.exists(name):
|
| 19 |
-
model_path = name
|
| 20 |
-
break
|
| 21 |
-
|
| 22 |
-
if model_path is None:
|
| 23 |
-
st.error("Model file not found! Please ensure your .h5 file is uploaded to the Hugging Face Space.")
|
| 24 |
-
return None
|
| 25 |
-
|
| 26 |
try:
|
| 27 |
-
#
|
| 28 |
base_model = tf.keras.applications.MobileNetV2(
|
| 29 |
input_shape=(224, 224, 3),
|
| 30 |
include_top=False,
|
|
@@ -32,62 +18,51 @@ def load_my_model():
|
|
| 32 |
)
|
| 33 |
base_model.trainable = False
|
| 34 |
|
|
|
|
| 35 |
model = tf.keras.Sequential([
|
| 36 |
base_model,
|
| 37 |
tf.keras.layers.GlobalAveragePooling2D(),
|
| 38 |
-
#
|
| 39 |
-
tf.keras.layers.Dense(512, activation='relu'),
|
| 40 |
tf.keras.layers.Dense(5, activation='softmax')
|
| 41 |
])
|
| 42 |
|
| 43 |
-
# 3.
|
| 44 |
-
model.load_weights(
|
| 45 |
return model
|
| 46 |
except Exception as e:
|
| 47 |
-
st.error(f"
|
| 48 |
return None
|
| 49 |
|
| 50 |
# Initialize Model
|
| 51 |
model = load_my_model()
|
| 52 |
-
|
| 53 |
-
# Alphabetical order based on folder names (Standard for Keras)
|
| 54 |
-
labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
|
| 55 |
|
| 56 |
# --- USER INTERFACE ---
|
| 57 |
st.title("🌾 Rice Variety Classification")
|
| 58 |
-
st.
|
| 59 |
|
| 60 |
-
uploaded_file = st.file_uploader("Upload
|
| 61 |
|
| 62 |
if uploaded_file is not None and model is not None:
|
| 63 |
-
# 1. Display Image
|
| 64 |
image = Image.open(uploaded_file)
|
| 65 |
st.image(image, caption='Uploaded Sample', use_container_width=True)
|
| 66 |
|
| 67 |
-
with st.spinner('
|
| 68 |
-
#
|
| 69 |
img = image.resize((224, 224))
|
| 70 |
-
img_array = np.array(img)
|
| 71 |
|
| 72 |
-
# Remove Alpha channel if it exists
|
| 73 |
if img_array.shape[-1] == 4:
|
| 74 |
img_array = img_array[:,:,:3]
|
| 75 |
|
| 76 |
img_array = np.expand_dims(img_array, axis=0)
|
| 77 |
-
|
| 78 |
-
# Scaling between -1 and 1 (Required for MobileNetV2)
|
| 79 |
img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
|
| 80 |
|
| 81 |
-
#
|
| 82 |
predictions = model.predict(img_array)
|
| 83 |
result_idx = np.argmax(predictions[0])
|
| 84 |
confidence = predictions[0][result_idx] * 100
|
| 85 |
|
| 86 |
-
#
|
| 87 |
-
st.success(f"Prediction: **{
|
| 88 |
-
st.metric(label="Confidence Level", value=f"{confidence:.2f}%")
|
| 89 |
-
|
| 90 |
-
# Show all probabilities to help debug "Jasmine vs Ipsala"
|
| 91 |
-
with st.expander("Show detailed breakdown"):
|
| 92 |
-
for i, name in enumerate(labels):
|
| 93 |
-
st.write(f"{name}: {predictions[0][i]*100:.2f}%")
|
|
|
|
| 2 |
import tensorflow as tf
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
|
|
|
| 5 |
|
| 6 |
# --- PAGE CONFIG ---
|
| 7 |
st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered")
|
| 8 |
|
| 9 |
+
# --- MODEL RECONSTRUCTION (Fixed Shape) ---
|
| 10 |
@st.cache_resource
|
| 11 |
def load_my_model():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
+
# 1. Recreate the Base (MobileNetV2)
|
| 14 |
base_model = tf.keras.applications.MobileNetV2(
|
| 15 |
input_shape=(224, 224, 3),
|
| 16 |
include_top=False,
|
|
|
|
| 18 |
)
|
| 19 |
base_model.trainable = False
|
| 20 |
|
| 21 |
+
# 2. Rebuild the Top Layers (MATCHING YOUR WEIGHTS: 512 neurons)
|
| 22 |
model = tf.keras.Sequential([
|
| 23 |
base_model,
|
| 24 |
tf.keras.layers.GlobalAveragePooling2D(),
|
| 25 |
+
tf.keras.layers.Dense(512, activation='relu'), # Changed from 128 to 512
|
|
|
|
| 26 |
tf.keras.layers.Dense(5, activation='softmax')
|
| 27 |
])
|
| 28 |
|
| 29 |
+
# 3. Load the weights
|
| 30 |
+
model.load_weights('src/rice_transfer_model.h5')
|
| 31 |
return model
|
| 32 |
except Exception as e:
|
| 33 |
+
st.error(f"Shape Mismatch or Loading Error: {e}")
|
| 34 |
return None
|
| 35 |
|
| 36 |
# Initialize Model
|
| 37 |
model = load_my_model()
|
| 38 |
+
class_names = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
|
|
|
|
|
|
|
| 39 |
|
| 40 |
# --- USER INTERFACE ---
|
| 41 |
st.title("🌾 Rice Variety Classification")
|
| 42 |
+
st.markdown("### **Transfer Learning Edition (MobileNetV2)**")
|
| 43 |
|
| 44 |
+
uploaded_file = st.file_uploader("Upload a rice grain image...", type=["jpg", "jpeg", "png"])
|
| 45 |
|
| 46 |
if uploaded_file is not None and model is not None:
|
|
|
|
| 47 |
image = Image.open(uploaded_file)
|
| 48 |
st.image(image, caption='Uploaded Sample', use_container_width=True)
|
| 49 |
|
| 50 |
+
with st.spinner('Calculating probabilities...'):
|
| 51 |
+
# Preprocessing
|
| 52 |
img = image.resize((224, 224))
|
| 53 |
+
img_array = np.array(img)
|
| 54 |
|
|
|
|
| 55 |
if img_array.shape[-1] == 4:
|
| 56 |
img_array = img_array[:,:,:3]
|
| 57 |
|
| 58 |
img_array = np.expand_dims(img_array, axis=0)
|
|
|
|
|
|
|
| 59 |
img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
|
| 60 |
|
| 61 |
+
# Prediction
|
| 62 |
predictions = model.predict(img_array)
|
| 63 |
result_idx = np.argmax(predictions[0])
|
| 64 |
confidence = predictions[0][result_idx] * 100
|
| 65 |
|
| 66 |
+
# Results
|
| 67 |
+
st.success(f"Prediction: **{class_names[result_idx]}**")
|
| 68 |
+
st.metric(label="Confidence Level", value=f"{confidence:.2f}%")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|