Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +61 -29
src/streamlit_app.py
CHANGED
|
@@ -1,17 +1,23 @@
|
|
| 1 |
-
# --- Fish Classifier (CNN from scratch) ---
|
| 2 |
import streamlit as st
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
import tensorflow as tf
|
| 6 |
from tensorflow.keras.models import load_model
|
| 7 |
|
|
|
|
|
|
|
|
|
|
| 8 |
st.set_page_config(
|
| 9 |
-
page_title="Fish Classifier (CNN β
|
| 10 |
layout="centered"
|
| 11 |
)
|
| 12 |
|
| 13 |
-
# ------------------
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
IMG_SIZE = (224, 224)
|
| 16 |
|
| 17 |
CLASS_NAMES = [
|
|
@@ -26,73 +32,99 @@ CLASS_NAMES = [
|
|
| 26 |
"Trout"
|
| 27 |
]
|
| 28 |
|
| 29 |
-
# ------------------
|
|
|
|
|
|
|
| 30 |
@st.cache_resource
|
| 31 |
def load_model_cached():
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
model = load_model_cached()
|
| 35 |
|
| 36 |
-
# ------------------
|
|
|
|
|
|
|
| 37 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 38 |
"""Resize and normalize image for the CNN model."""
|
| 39 |
image = image.convert("RGB")
|
| 40 |
image = image.resize(IMG_SIZE)
|
| 41 |
-
img_array = np.array(image).astype("float32") / 255.0
|
| 42 |
-
img_array = np.expand_dims(img_array, axis=0)
|
| 43 |
return img_array
|
| 44 |
|
| 45 |
def predict_image(image: Image.Image):
|
| 46 |
-
"""Run model prediction and return class
|
| 47 |
img_batch = preprocess_image(image)
|
| 48 |
preds = model.predict(img_batch)
|
| 49 |
-
probs = preds[0]
|
| 50 |
pred_index = int(np.argmax(probs))
|
| 51 |
pred_class = CLASS_NAMES[pred_index]
|
| 52 |
return pred_class, probs
|
| 53 |
|
| 54 |
-
# ------------------
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
layout="centered"
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
st.title("π Fish Species Classifier (CNN From Scratch)")
|
|
|
|
| 61 |
st.write(
|
| 62 |
"Upload a fish image and the model will predict one of **9 fish species**. "
|
| 63 |
-
"This model is a custom Convolutional Neural Network
|
|
|
|
| 64 |
)
|
| 65 |
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
| 67 |
st.sidebar.markdown(
|
| 68 |
"""
|
| 69 |
-
**Model:** CNN
|
| 70 |
-
**Input size:** 224Γ224
|
| 71 |
**Classes:** 9 fish species
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
**Author:** Enes Yamac
|
| 73 |
"""
|
| 74 |
)
|
| 75 |
|
|
|
|
|
|
|
|
|
|
| 76 |
uploaded_file = st.file_uploader(
|
| 77 |
-
"Upload a fish image (JPG/PNG)",
|
| 78 |
type=["jpg", "jpeg", "png"]
|
| 79 |
)
|
| 80 |
|
|
|
|
|
|
|
|
|
|
| 81 |
if uploaded_file is not None:
|
| 82 |
image = Image.open(uploaded_file)
|
| 83 |
-
st.image(image, caption="Uploaded image",
|
| 84 |
|
| 85 |
-
with st.spinner("Predicting..."):
|
| 86 |
pred_class, probs = predict_image(image)
|
| 87 |
|
| 88 |
-
st.subheader("Prediction")
|
| 89 |
-
st.write(f"**Predicted class:** {pred_class}")
|
| 90 |
|
| 91 |
-
#
|
| 92 |
-
st.subheader("Class probabilities")
|
| 93 |
prob_dict = {cls: float(p) for cls, p in zip(CLASS_NAMES, probs)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
st.
|
|
|
|
| 96 |
|
| 97 |
else:
|
| 98 |
st.info("Please upload an image to start.")
|
|
|
|
| 1 |
+
# --- Fish Classifier (CNN from scratch) ---------------------------------------
|
| 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.models import load_model
|
| 8 |
|
| 9 |
+
# -----------------------------------------------------------------------------
|
| 10 |
+
# PAGE CONFIG
|
| 11 |
+
# -----------------------------------------------------------------------------
|
| 12 |
st.set_page_config(
|
| 13 |
+
page_title="Fish Classifier (CNN β From Scratch)",
|
| 14 |
layout="centered"
|
| 15 |
)
|
| 16 |
|
| 17 |
+
# -----------------------------------------------------------------------------
|
| 18 |
+
# SETTINGS
|
| 19 |
+
# -----------------------------------------------------------------------------
|
| 20 |
+
MODEL_PATH = "src/best_fish_cnn.keras"
|
| 21 |
IMG_SIZE = (224, 224)
|
| 22 |
|
| 23 |
CLASS_NAMES = [
|
|
|
|
| 32 |
"Trout"
|
| 33 |
]
|
| 34 |
|
| 35 |
+
# -----------------------------------------------------------------------------
|
| 36 |
+
# MODEL LOADING (CACHED)
|
| 37 |
+
# -----------------------------------------------------------------------------
|
| 38 |
@st.cache_resource
|
| 39 |
def load_model_cached():
|
| 40 |
+
# compile=False reicht fΓΌr reine Vorhersage
|
| 41 |
+
model = load_model(MODEL_PATH, compile=False)
|
| 42 |
+
return model
|
| 43 |
|
| 44 |
model = load_model_cached()
|
| 45 |
|
| 46 |
+
# -----------------------------------------------------------------------------
|
| 47 |
+
# HELPER FUNCTIONS
|
| 48 |
+
# -----------------------------------------------------------------------------
|
| 49 |
def preprocess_image(image: Image.Image) -> np.ndarray:
|
| 50 |
"""Resize and normalize image for the CNN model."""
|
| 51 |
image = image.convert("RGB")
|
| 52 |
image = image.resize(IMG_SIZE)
|
| 53 |
+
img_array = np.array(image).astype("float32") / 255.0
|
| 54 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 55 |
return img_array
|
| 56 |
|
| 57 |
def predict_image(image: Image.Image):
|
| 58 |
+
"""Run model prediction and return class label and probability vector."""
|
| 59 |
img_batch = preprocess_image(image)
|
| 60 |
preds = model.predict(img_batch)
|
| 61 |
+
probs = preds[0]
|
| 62 |
pred_index = int(np.argmax(probs))
|
| 63 |
pred_class = CLASS_NAMES[pred_index]
|
| 64 |
return pred_class, probs
|
| 65 |
|
| 66 |
+
# -----------------------------------------------------------------------------
|
| 67 |
+
# UI β HEADER
|
| 68 |
+
# -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 69 |
st.title("π Fish Species Classifier (CNN From Scratch)")
|
| 70 |
+
|
| 71 |
st.write(
|
| 72 |
"Upload a fish image and the model will predict one of **9 fish species**. "
|
| 73 |
+
"This model is a custom Convolutional Neural Network (**no transfer learning**) "
|
| 74 |
+
"trained on the Kaggle fish dataset."
|
| 75 |
)
|
| 76 |
|
| 77 |
+
# -----------------------------------------------------------------------------
|
| 78 |
+
# SIDEBAR INFO
|
| 79 |
+
# -----------------------------------------------------------------------------
|
| 80 |
+
st.sidebar.header("βΉοΈ About this app")
|
| 81 |
st.sidebar.markdown(
|
| 82 |
"""
|
| 83 |
+
**Model:** Custom CNN (no transfer learning)
|
| 84 |
+
**Input size:** 224 Γ 224
|
| 85 |
**Classes:** 9 fish species
|
| 86 |
+
|
| 87 |
+
**Validation performance:**
|
| 88 |
+
- Accuracy: ~84%
|
| 89 |
+
- Top-3 accuracy: ~95%
|
| 90 |
+
|
| 91 |
**Author:** Enes Yamac
|
| 92 |
"""
|
| 93 |
)
|
| 94 |
|
| 95 |
+
# -----------------------------------------------------------------------------
|
| 96 |
+
# FILE UPLOAD
|
| 97 |
+
# -----------------------------------------------------------------------------
|
| 98 |
uploaded_file = st.file_uploader(
|
| 99 |
+
"π€ Upload a fish image (JPG/PNG)",
|
| 100 |
type=["jpg", "jpeg", "png"]
|
| 101 |
)
|
| 102 |
|
| 103 |
+
# -----------------------------------------------------------------------------
|
| 104 |
+
# PREDICTION + OUTPUT
|
| 105 |
+
# -----------------------------------------------------------------------------
|
| 106 |
if uploaded_file is not None:
|
| 107 |
image = Image.open(uploaded_file)
|
| 108 |
+
st.image(image, caption="Uploaded image", use_container_width=True)
|
| 109 |
|
| 110 |
+
with st.spinner("π Predicting..."):
|
| 111 |
pred_class, probs = predict_image(image)
|
| 112 |
|
| 113 |
+
st.subheader("π Prediction")
|
| 114 |
+
st.write(f"**Predicted class:** `{pred_class}`")
|
| 115 |
|
| 116 |
+
# Wahrscheinlichkeiten vorbereiten
|
|
|
|
| 117 |
prob_dict = {cls: float(p) for cls, p in zip(CLASS_NAMES, probs)}
|
| 118 |
+
prob_df = (
|
| 119 |
+
pd.DataFrame.from_dict(prob_dict, orient="index", columns=["Probability"])
|
| 120 |
+
.sort_values("Probability", ascending=False)
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
st.subheader("π Class probabilities")
|
| 124 |
+
st.bar_chart(prob_df)
|
| 125 |
|
| 126 |
+
with st.expander("Show numeric probabilities"):
|
| 127 |
+
st.dataframe(prob_df.style.format("{:.2%}"))
|
| 128 |
|
| 129 |
else:
|
| 130 |
st.info("Please upload an image to start.")
|