Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +56 -74
src/streamlit_app.py
CHANGED
|
@@ -5,40 +5,24 @@ import streamlit as st
|
|
| 5 |
from PIL import Image
|
| 6 |
import tensorflow as tf
|
| 7 |
|
| 8 |
-
|
| 9 |
-
# Page config
|
| 10 |
-
# -----------------------------
|
| 11 |
-
st.set_page_config(
|
| 12 |
-
page_title="ResNet50 Image Predictor",
|
| 13 |
-
page_icon="π§ ",
|
| 14 |
-
layout="centered"
|
| 15 |
-
)
|
| 16 |
-
|
| 17 |
st.title("π§ ResNet50 Image Predictor")
|
| 18 |
-
st.write("
|
| 19 |
|
| 20 |
-
|
| 21 |
-
# Fixed paths (as requested)
|
| 22 |
-
# -----------------------------
|
| 23 |
-
MODEL_PATH = "src/new_best3_resnet50.keras"
|
| 24 |
CLASS_NAMES_PATH = "src/class_names3.json"
|
| 25 |
|
| 26 |
-
# -----------------------------
|
| 27 |
-
# Debug panel (helps on HuggingFace)
|
| 28 |
-
# -----------------------------
|
| 29 |
with st.expander("π Debug info (HuggingFace check)"):
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
st.write("
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
# Load class names
|
| 41 |
-
# -----------------------------
|
| 42 |
@st.cache_data
|
| 43 |
def load_class_names(path: str):
|
| 44 |
if not os.path.exists(path):
|
|
@@ -49,38 +33,44 @@ def load_class_names(path: str):
|
|
| 49 |
raise ValueError("class_names JSON must be a non-empty list.")
|
| 50 |
return names
|
| 51 |
|
| 52 |
-
# -----------------------------
|
| 53 |
-
# Load model
|
| 54 |
-
# -----------------------------
|
| 55 |
@st.cache_resource
|
| 56 |
-
def
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return model
|
| 62 |
|
| 63 |
try:
|
| 64 |
class_names = load_class_names(CLASS_NAMES_PATH)
|
| 65 |
-
model =
|
| 66 |
-
st.success("β
Model loaded successfully!")
|
| 67 |
except Exception as e:
|
| 68 |
st.error("β Model could not be loaded.")
|
| 69 |
st.exception(e)
|
| 70 |
st.stop()
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
uploaded_file = st.file_uploader(
|
| 76 |
-
"Upload a mushroom image",
|
| 77 |
-
type=["jpg", "jpeg", "png", "webp"]
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
# -----------------------------
|
| 81 |
-
# Predict
|
| 82 |
-
# -----------------------------
|
| 83 |
-
def preprocess_pil_for_resnet50(img: Image.Image) -> np.ndarray:
|
| 84 |
img = img.convert("RGB").resize((224, 224))
|
| 85 |
x = np.array(img, dtype=np.float32)
|
| 86 |
x = np.expand_dims(x, axis=0)
|
|
@@ -88,32 +78,24 @@ def preprocess_pil_for_resnet50(img: Image.Image) -> np.ndarray:
|
|
| 88 |
return x
|
| 89 |
|
| 90 |
if uploaded_file is None:
|
| 91 |
-
st.info("π
|
| 92 |
else:
|
| 93 |
img = Image.open(uploaded_file)
|
| 94 |
-
st.image(img,
|
| 95 |
-
|
| 96 |
-
x = preprocess_pil_for_resnet50(img)
|
| 97 |
-
|
| 98 |
-
with st.spinner("Predicting..."):
|
| 99 |
-
preds = model.predict(x, verbose=0)[0] # shape: (num_classes,)
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
else:
|
| 108 |
-
pred_name = f"Class {pred_idx}"
|
| 109 |
|
| 110 |
st.subheader("β
Prediction")
|
| 111 |
-
st.write(f"**
|
| 112 |
-
st.write(f"
|
| 113 |
-
|
| 114 |
-
st.subheader("π
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
st.write(f"**{name}**: {float(preds[i]):.4f}")
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
import tensorflow as tf
|
| 7 |
|
| 8 |
+
st.set_page_config(page_title="ResNet50 Image Predictor", page_icon="π§ ", layout="centered")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
st.title("π§ ResNet50 Image Predictor")
|
| 10 |
+
st.write("Loads ResNet50 architecture and then loads trained weights (HF-safe).")
|
| 11 |
|
| 12 |
+
WEIGHTS_PATH = "src/resnet50_weights_noBN3.weights.h5"
|
|
|
|
|
|
|
|
|
|
| 13 |
CLASS_NAMES_PATH = "src/class_names3.json"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
with st.expander("π Debug info (HuggingFace check)"):
|
| 16 |
+
st.write("cwd:", os.getcwd())
|
| 17 |
+
st.write("src exists:", os.path.isdir("src"))
|
| 18 |
+
if os.path.isdir("src"):
|
| 19 |
+
st.write("files in src:", os.listdir("src"))
|
| 20 |
+
st.write("TF version:", tf.__version__)
|
| 21 |
+
st.write("weights exists:", os.path.exists(WEIGHTS_PATH), WEIGHTS_PATH)
|
| 22 |
+
st.write("class_names exists:", os.path.exists(CLASS_NAMES_PATH), CLASS_NAMES_PATH)
|
| 23 |
+
if os.path.exists(WEIGHTS_PATH):
|
| 24 |
+
st.write("weights size (MB):", round(os.path.getsize(WEIGHTS_PATH) / (1024**2), 2))
|
| 25 |
+
|
|
|
|
|
|
|
| 26 |
@st.cache_data
|
| 27 |
def load_class_names(path: str):
|
| 28 |
if not os.path.exists(path):
|
|
|
|
| 33 |
raise ValueError("class_names JSON must be a non-empty list.")
|
| 34 |
return names
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
@st.cache_resource
|
| 37 |
+
def build_and_load_model(num_classes: int):
|
| 38 |
+
# Build the SAME model you trained (NO BatchNorm)
|
| 39 |
+
base_model = tf.keras.applications.ResNet50(
|
| 40 |
+
weights="imagenet",
|
| 41 |
+
include_top=False,
|
| 42 |
+
input_shape=(224, 224, 3),
|
| 43 |
+
)
|
| 44 |
+
base_model.trainable = False
|
| 45 |
+
|
| 46 |
+
model = tf.keras.Sequential([
|
| 47 |
+
base_model,
|
| 48 |
+
tf.keras.layers.GlobalAveragePooling2D(),
|
| 49 |
+
tf.keras.layers.Dense(256, activation="relu"),
|
| 50 |
+
tf.keras.layers.Dropout(0.5),
|
| 51 |
+
tf.keras.layers.Dense(num_classes, activation="softmax"),
|
| 52 |
+
])
|
| 53 |
+
|
| 54 |
+
if not os.path.exists(WEIGHTS_PATH):
|
| 55 |
+
raise FileNotFoundError(f"Missing weights file: {WEIGHTS_PATH}")
|
| 56 |
+
|
| 57 |
+
# Load weights
|
| 58 |
+
model.load_weights(WEIGHTS_PATH)
|
| 59 |
+
|
| 60 |
return model
|
| 61 |
|
| 62 |
try:
|
| 63 |
class_names = load_class_names(CLASS_NAMES_PATH)
|
| 64 |
+
model = build_and_load_model(num_classes=len(class_names))
|
| 65 |
+
st.success("β
Model + weights loaded successfully!")
|
| 66 |
except Exception as e:
|
| 67 |
st.error("β Model could not be loaded.")
|
| 68 |
st.exception(e)
|
| 69 |
st.stop()
|
| 70 |
|
| 71 |
+
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png", "webp"])
|
| 72 |
+
|
| 73 |
+
def preprocess(img: Image.Image) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
img = img.convert("RGB").resize((224, 224))
|
| 75 |
x = np.array(img, dtype=np.float32)
|
| 76 |
x = np.expand_dims(x, axis=0)
|
|
|
|
| 78 |
return x
|
| 79 |
|
| 80 |
if uploaded_file is None:
|
| 81 |
+
st.info("π Upload an image to get a prediction.")
|
| 82 |
else:
|
| 83 |
img = Image.open(uploaded_file)
|
| 84 |
+
st.image(img, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
x = preprocess(img)
|
| 87 |
+
preds = model.predict(x, verbose=0)[0]
|
| 88 |
|
| 89 |
+
idx = int(np.argmax(preds))
|
| 90 |
+
conf = float(preds[idx])
|
| 91 |
+
name = class_names[idx] if idx < len(class_names) else f"Class {idx}"
|
|
|
|
|
|
|
| 92 |
|
| 93 |
st.subheader("β
Prediction")
|
| 94 |
+
st.write(f"**{name}** (index {idx})")
|
| 95 |
+
st.write(f"Confidence: **{conf:.4f}**")
|
| 96 |
+
|
| 97 |
+
st.subheader("π Probabilities (top 5)")
|
| 98 |
+
top = np.argsort(preds)[::-1][:5]
|
| 99 |
+
for i in top:
|
| 100 |
+
n = class_names[i] if i < len(class_names) else f"Class {i}"
|
| 101 |
+
st.write(f"{n}: {float(preds[i]):.4f}")
|
|
|