Spaces:
Sleeping
Sleeping
Basak Tamer commited on
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +66 -45
src/streamlit_app.py
CHANGED
|
@@ -1,65 +1,86 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import tensorflow as tf
|
| 3 |
-
from tensorflow.keras.preprocessing import image
|
| 4 |
-
import numpy as np
|
| 5 |
from PIL import Image
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
@st.cache_resource
|
| 10 |
def load_my_model():
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
| 13 |
model = load_my_model()
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
# This MUST match the alphabetical order or the folder order from training.
|
| 17 |
-
# Based on your notebook cells, use this exact order:
|
| 18 |
labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
st.title("🌾 Rice Variety
|
| 22 |
-
st.
|
| 23 |
|
| 24 |
-
uploaded_file = st.file_uploader("
|
| 25 |
|
| 26 |
-
if uploaded_file is not None:
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
st.image(
|
| 30 |
|
| 31 |
-
with st.spinner('
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
img_array = np.array(img_resized).astype('float32')
|
| 37 |
-
|
| 38 |
-
# If the image has an Alpha channel (RGBA), remove it
|
| 39 |
if img_array.shape[-1] == 4:
|
| 40 |
-
img_array = img_array[:,
|
| 41 |
|
| 42 |
-
# C. Add batch dimension (1, 224, 224, 3)
|
| 43 |
img_array = np.expand_dims(img_array, axis=0)
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
result_index = np.argmax(predictions[0])
|
| 53 |
-
confidence = predictions[0][result_index] * 100
|
| 54 |
-
|
| 55 |
-
# F. Output Results
|
| 56 |
-
predicted_label = labels[result_index]
|
| 57 |
-
|
| 58 |
-
st.subheader(f"Prediction: **{predicted_label}**")
|
| 59 |
-
st.progress(int(confidence))
|
| 60 |
-
st.write(f"Confidence: **{confidence:.2f}%**")
|
| 61 |
|
| 62 |
-
#
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
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 LOADING ---
|
| 11 |
@st.cache_resource
|
| 12 |
def load_my_model():
|
| 13 |
+
# Check multiple possible locations for the model file
|
| 14 |
+
model_path = 'rice_transfer_model.h5'
|
| 15 |
+
|
| 16 |
+
if not os.path.exists(model_path):
|
| 17 |
+
# If it's not in the root, check the 'src' folder as a backup
|
| 18 |
+
model_path = os.path.join('src', 'rice_transfer_model.h5')
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
# 1. Recreate the exact architecture from your Kaggle Notebook
|
| 22 |
+
base_model = tf.keras.applications.MobileNetV2(
|
| 23 |
+
input_shape=(224, 224, 3),
|
| 24 |
+
include_top=False,
|
| 25 |
+
weights=None
|
| 26 |
+
)
|
| 27 |
+
base_model.trainable = False
|
| 28 |
+
|
| 29 |
+
model = tf.keras.Sequential([
|
| 30 |
+
base_model,
|
| 31 |
+
tf.keras.layers.GlobalAveragePooling2D(),
|
| 32 |
+
tf.keras.layers.Dense(512, activation='relu'),
|
| 33 |
+
tf.keras.layers.Dense(5, activation='softmax')
|
| 34 |
+
])
|
| 35 |
+
|
| 36 |
+
# 2. Load the weights from the verified path
|
| 37 |
+
model.load_weights(model_path)
|
| 38 |
+
return model
|
| 39 |
+
except Exception as e:
|
| 40 |
+
st.error(f"Error: Could not find or load {model_path}. Please ensure the file is uploaded to your Hugging Face Space.")
|
| 41 |
+
st.info(f"System Error Message: {e}")
|
| 42 |
+
return None
|
| 43 |
|
| 44 |
+
# Initialize Model
|
| 45 |
model = load_my_model()
|
| 46 |
|
| 47 |
+
# Labels must match your training dictionary exactly
|
|
|
|
|
|
|
| 48 |
labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
|
| 49 |
|
| 50 |
+
# --- USER INTERFACE ---
|
| 51 |
+
st.title("🌾 Rice Variety Classification")
|
| 52 |
+
st.markdown("### **Deployment for Data Science Assignment**")
|
| 53 |
|
| 54 |
+
uploaded_file = st.file_uploader("Upload a rice grain image (JPG/PNG)", type=["jpg", "jpeg", "png"])
|
| 55 |
|
| 56 |
+
if uploaded_file is not None and model is not None:
|
| 57 |
+
# 1. Process Image
|
| 58 |
+
image = Image.open(uploaded_file)
|
| 59 |
+
st.image(image, caption='Uploaded Sample', use_container_width=True)
|
| 60 |
|
| 61 |
+
with st.spinner('AI is classifying...'):
|
| 62 |
+
# 2. Preprocessing
|
| 63 |
+
img = image.resize((224, 224))
|
| 64 |
+
img_array = np.array(img).astype('float32')
|
| 65 |
|
| 66 |
+
# Handle transparency (RGBA to RGB)
|
|
|
|
|
|
|
|
|
|
| 67 |
if img_array.shape[-1] == 4:
|
| 68 |
+
img_array = img_array[:,:,:3]
|
| 69 |
|
|
|
|
| 70 |
img_array = np.expand_dims(img_array, axis=0)
|
| 71 |
|
| 72 |
+
# MobileNetV2 scaling (-1 to 1)
|
| 73 |
+
img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
|
| 74 |
+
|
| 75 |
+
# 3. Prediction
|
| 76 |
+
predictions = model.predict(img_array)
|
| 77 |
+
result_idx = np.argmax(predictions[0])
|
| 78 |
+
confidence = predictions[0][result_idx] * 100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# 4. Results
|
| 81 |
+
st.success(f"Prediction: **{labels[result_idx]}**")
|
| 82 |
+
st.metric(label="Model Confidence", value=f"{confidence:.2f}%")
|
| 83 |
+
|
| 84 |
+
with st.expander("Show Probability Distribution"):
|
| 85 |
+
for i, name in enumerate(labels):
|
| 86 |
+
st.write(f"{name}: {predictions[0][i]*100:.2f}%")
|