Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +116 -37
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,119 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
""
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 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_rice_resnet50.py
|
| 2 |
+
import streamlit as st
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.applications.resnet50 import preprocess_input
|
| 8 |
+
|
| 9 |
+
# ----------------- SETTINGS -----------------
|
| 10 |
+
MODEL_PATH = "src/best_rice_resnet50.keras"
|
| 11 |
+
IMG_SIZE = (224, 224)
|
| 12 |
+
|
| 13 |
+
CLASS_NAMES = [
|
| 14 |
+
"Arborio",
|
| 15 |
+
"Basmati",
|
| 16 |
+
"Ipsala",
|
| 17 |
+
"Jasmine",
|
| 18 |
+
"Karacadag",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# ----------------- MODEL LOADING -----------------
|
| 22 |
+
@st.cache_resource
|
| 23 |
+
def load_resnet_model():
|
| 24 |
+
try:
|
| 25 |
+
model = tf.keras.models.load_model(MODEL_PATH, compile=False)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
st.error(f"Error loading model: {e}")
|
| 28 |
+
model = None
|
| 29 |
+
return model
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 33 |
+
"""Resize image and apply ResNet50 preprocessing."""
|
| 34 |
+
img = image.convert("RGB")
|
| 35 |
+
img = img.resize(IMG_SIZE)
|
| 36 |
+
img_array = np.array(img).astype("float32")
|
| 37 |
+
img_array = preprocess_input(img_array)
|
| 38 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 39 |
+
return img_array
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def predict_image(model, image_array: np.ndarray):
|
| 43 |
+
preds = model.predict(image_array, verbose=0)[0]
|
| 44 |
+
probs = tf.nn.softmax(preds).numpy()
|
| 45 |
+
pred_idx = int(np.argmax(probs))
|
| 46 |
+
pred_class = CLASS_NAMES[pred_idx]
|
| 47 |
+
pred_conf = float(probs[pred_idx])
|
| 48 |
+
|
| 49 |
+
top3_idx = np.argsort(probs)[-3:][::-1]
|
| 50 |
+
top3 = [(CLASS_NAMES[i], float(probs[i])) for i in top3_idx]
|
| 51 |
+
|
| 52 |
+
return pred_class, pred_conf, probs, top3
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ----------------- PAGE CONFIG -----------------
|
| 56 |
+
st.set_page_config(
|
| 57 |
+
page_title="Rice Classifier – ResNet50 (Transfer Learning)",
|
| 58 |
+
page_icon="🌾",
|
| 59 |
+
layout="wide",
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# ----------------- SIDEBAR -----------------
|
| 63 |
+
st.sidebar.title("🌾 Rice ResNet50 Classifier")
|
| 64 |
+
st.sidebar.write(
|
| 65 |
+
"This app uses a ResNet50 transfer learning model to classify rice grains."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
st.sidebar.subheader("Rice classes")
|
| 69 |
+
for idx, name in enumerate(CLASS_NAMES):
|
| 70 |
+
st.sidebar.write(f"- **{idx}** → {name}")
|
| 71 |
+
|
| 72 |
+
st.sidebar.markdown("---")
|
| 73 |
+
st.sidebar.caption("Author: Enes Yamac")
|
| 74 |
+
|
| 75 |
+
# ----------------- MAIN PAGE -----------------
|
| 76 |
+
st.title("🌾 Rice Classifier – ResNet50 (Transfer Learning)")
|
| 77 |
+
st.write("Upload a rice grain image. The model will predict the rice type and show top-3 results.")
|
| 78 |
+
|
| 79 |
+
uploaded_file = st.file_uploader(
|
| 80 |
+
"Upload a rice image (JPG or PNG)",
|
| 81 |
+
type=["jpg", "jpeg", "png"],
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
if uploaded_file is not None:
|
| 85 |
+
image = Image.open(uploaded_file)
|
| 86 |
+
|
| 87 |
+
col1, col2 = st.columns([1, 1])
|
| 88 |
+
|
| 89 |
+
with col1:
|
| 90 |
+
st.subheader("Uploaded image")
|
| 91 |
+
st.image(image, width=500)
|
| 92 |
+
|
| 93 |
+
with st.spinner("Loading ResNet50 model and making prediction..."):
|
| 94 |
+
model = load_resnet_model()
|
| 95 |
+
|
| 96 |
+
if model is not None:
|
| 97 |
+
img_array = preprocess_image(image)
|
| 98 |
+
pred_class, pred_conf, probs, top3 = predict_image(model, img_array)
|
| 99 |
+
|
| 100 |
+
with col2:
|
| 101 |
+
st.subheader("Prediction")
|
| 102 |
+
st.markdown(f"**Predicted class:** `{pred_class}`")
|
| 103 |
+
st.markdown(f"**Confidence:** `{pred_conf:.2%}`")
|
| 104 |
+
|
| 105 |
+
st.subheader("Top-3 predictions")
|
| 106 |
+
for name, p in top3:
|
| 107 |
+
st.write(f"- {name}: {p:.2%}")
|
| 108 |
+
|
| 109 |
+
st.subheader("Class probabilities")
|
| 110 |
+
df = pd.DataFrame(
|
| 111 |
+
{"class": CLASS_NAMES, "probability": probs}
|
| 112 |
+
).set_index("class")
|
| 113 |
+
st.bar_chart(df)
|
| 114 |
|
| 115 |
+
with st.expander("Show probabilities as text"):
|
| 116 |
+
for name, p in zip(CLASS_NAMES, probs):
|
| 117 |
+
st.write(f"- {name}: {p:.2%}")
|
| 118 |
+
else:
|
| 119 |
+
st.info("Please upload a rice image to get a prediction.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|