Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +81 -61
src/streamlit_app.py
CHANGED
|
@@ -1,101 +1,121 @@
|
|
| 1 |
-
import json
|
| 2 |
import os
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
import streamlit as st
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
CLASS_NAMES_PATH = "src/class_names3.json"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
with st.expander("π Debug info (HuggingFace check)"):
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
st.write("
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
with open(path, "r", encoding="utf-8") as f:
|
| 31 |
names = json.load(f)
|
| 32 |
if not isinstance(names, list) or len(names) == 0:
|
| 33 |
-
raise ValueError("
|
| 34 |
return names
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
include_top=False,
|
| 42 |
-
input_shape=(224, 224, 3),
|
| 43 |
-
)
|
| 44 |
base_model.trainable = False
|
| 45 |
|
| 46 |
-
model =
|
| 47 |
base_model,
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
model.
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
try:
|
| 63 |
-
class_names =
|
| 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 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
x = np.array(img, dtype=np.float32)
|
| 76 |
-
x = np.expand_dims(x, axis=0)
|
| 77 |
-
x = tf.keras.applications.resnet50.preprocess_input(x)
|
| 78 |
-
return x
|
| 79 |
|
| 80 |
if uploaded_file is None:
|
| 81 |
-
st.info("π
|
| 82 |
else:
|
| 83 |
-
img = Image.open(uploaded_file)
|
| 84 |
-
st.image(img, use_container_width=True)
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
| 88 |
|
|
|
|
| 89 |
idx = int(np.argmax(preds))
|
| 90 |
-
conf = float(preds
|
| 91 |
-
name = class_names[idx] if idx < len(class_names) else f"Class {idx}"
|
| 92 |
|
| 93 |
st.subheader("β
Prediction")
|
| 94 |
-
st.write(f"**
|
| 95 |
-
st.write(f"Confidence:
|
| 96 |
-
|
| 97 |
-
st.subheader("π
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
st.write(f"{
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import numpy as np
|
| 4 |
import streamlit as st
|
| 5 |
from PIL import Image
|
| 6 |
+
|
| 7 |
import tensorflow as tf
|
| 8 |
+
from tensorflow.keras.applications import ResNet50
|
| 9 |
+
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
|
| 10 |
+
from tensorflow.keras.models import Sequential
|
| 11 |
|
| 12 |
+
# -----------------------------
|
| 13 |
+
# Page config
|
| 14 |
+
# -----------------------------
|
| 15 |
st.set_page_config(page_title="ResNet50 Image Predictor", page_icon="π§ ", layout="centered")
|
| 16 |
st.title("π§ ResNet50 Image Predictor")
|
| 17 |
st.write("Loads ResNet50 architecture and then loads trained weights (HF-safe).")
|
| 18 |
|
| 19 |
+
# -----------------------------
|
| 20 |
+
# Paths (FIXED)
|
| 21 |
+
# -----------------------------
|
| 22 |
+
WEIGHTS_PATH = "src/resnet50_weights_noBN3.h5"
|
| 23 |
CLASS_NAMES_PATH = "src/class_names3.json"
|
| 24 |
|
| 25 |
+
# -----------------------------
|
| 26 |
+
# Debug info
|
| 27 |
+
# -----------------------------
|
| 28 |
with st.expander("π Debug info (HuggingFace check)"):
|
| 29 |
+
try:
|
| 30 |
+
st.write("Files in src/:")
|
| 31 |
+
st.write(os.listdir("src"))
|
| 32 |
+
st.write("Weights exists:", os.path.exists(WEIGHTS_PATH))
|
| 33 |
+
st.write("Class names exists:", os.path.exists(CLASS_NAMES_PATH))
|
| 34 |
+
st.write("TF:", tf.__version__)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
st.error(e)
|
| 37 |
+
|
| 38 |
+
# -----------------------------
|
| 39 |
+
# Load class names
|
| 40 |
+
# -----------------------------
|
| 41 |
+
def load_class_names(path: str) -> list:
|
| 42 |
+
with open(path, "r") as f:
|
|
|
|
| 43 |
names = json.load(f)
|
| 44 |
if not isinstance(names, list) or len(names) == 0:
|
| 45 |
+
raise ValueError("class_names3.json must be a non-empty list of class names.")
|
| 46 |
return names
|
| 47 |
|
| 48 |
+
# -----------------------------
|
| 49 |
+
# Build architecture (MUST match training!)
|
| 50 |
+
# -----------------------------
|
| 51 |
+
def build_model(num_classes: int) -> tf.keras.Model:
|
| 52 |
+
base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
|
|
|
|
|
|
|
|
|
|
| 53 |
base_model.trainable = False
|
| 54 |
|
| 55 |
+
model = Sequential([
|
| 56 |
base_model,
|
| 57 |
+
GlobalAveragePooling2D(),
|
| 58 |
+
Dense(256, activation="relu"),
|
| 59 |
+
Dropout(0.5),
|
| 60 |
+
Dense(num_classes, activation="softmax"),
|
| 61 |
])
|
| 62 |
+
return model
|
| 63 |
+
|
| 64 |
+
# -----------------------------
|
| 65 |
+
# Load model + weights
|
| 66 |
+
# -----------------------------
|
| 67 |
+
@st.cache_resource
|
| 68 |
+
def load_trained_model(weights_path: str, class_names_path: str):
|
| 69 |
+
if not os.path.exists(weights_path):
|
| 70 |
+
raise FileNotFoundError(f"Missing weights file: {weights_path}")
|
| 71 |
+
if not os.path.exists(class_names_path):
|
| 72 |
+
raise FileNotFoundError(f"Missing class names file: {class_names_path}")
|
| 73 |
|
| 74 |
+
class_names = load_class_names(class_names_path)
|
| 75 |
+
model = build_model(num_classes=len(class_names))
|
| 76 |
|
| 77 |
+
# IMPORTANT: build the model by calling it once (creates weights shapes)
|
| 78 |
+
_ = model(np.zeros((1, 224, 224, 3), dtype=np.float32), training=False)
|
| 79 |
|
| 80 |
+
# Load weights from your file name EXACTLY
|
| 81 |
+
model.load_weights(weights_path)
|
| 82 |
+
|
| 83 |
+
return model, class_names
|
| 84 |
|
| 85 |
try:
|
| 86 |
+
model, class_names = load_trained_model(WEIGHTS_PATH, CLASS_NAMES_PATH)
|
|
|
|
| 87 |
st.success("β
Model + weights loaded successfully!")
|
| 88 |
except Exception as e:
|
| 89 |
st.error("β Model could not be loaded.")
|
| 90 |
st.exception(e)
|
| 91 |
st.stop()
|
| 92 |
|
| 93 |
+
# -----------------------------
|
| 94 |
+
# Image upload & prediction
|
| 95 |
+
# -----------------------------
|
| 96 |
+
uploaded_file = st.file_uploader("Upload a mushroom image", type=["jpg", "jpeg", "png", "webp"])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
if uploaded_file is None:
|
| 99 |
+
st.info("π Please upload an image to start prediction.")
|
| 100 |
else:
|
| 101 |
+
img = Image.open(uploaded_file).convert("RGB")
|
| 102 |
+
st.image(img, caption="Uploaded image", use_container_width=True)
|
| 103 |
|
| 104 |
+
img_resized = img.resize((224, 224))
|
| 105 |
+
x = np.array(img_resized, dtype=np.float32)
|
| 106 |
+
x = np.expand_dims(x, axis=0)
|
| 107 |
+
x = tf.keras.applications.resnet50.preprocess_input(x)
|
| 108 |
|
| 109 |
+
preds = model.predict(x, verbose=0)[0]
|
| 110 |
idx = int(np.argmax(preds))
|
| 111 |
+
conf = float(np.max(preds))
|
|
|
|
| 112 |
|
| 113 |
st.subheader("β
Prediction")
|
| 114 |
+
st.write(f"**Predicted class:** {class_names[idx]}")
|
| 115 |
+
st.write(f"**Confidence:** {conf:.4f}")
|
| 116 |
+
|
| 117 |
+
st.subheader("π Class probabilities")
|
| 118 |
+
# Show top 5
|
| 119 |
+
topk = np.argsort(preds)[::-1][:5]
|
| 120 |
+
for i in topk:
|
| 121 |
+
st.write(f"{class_names[i]}: {preds[i]:.4f}")
|