Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import jsonimport osimport numpy as npimport streamlit as stfrom PIL import Imageimport tensorflow as tfst.set_page_config(page_title="ResNet50 Image Predictor", page_icon="π§ ", layout="centered")st.title("π§ ResNet50 Image Predictor")st.write("Loads ResNet50 architecture and then loads trained weights (HF-safe).")WEIGHTS_PATH = "src/resnet50_weights_noBN3.weights.h5"CLASS_NAMES_PATH = "src/class_names3.json"with st.expander("π Debug info (HuggingFace check)"):st.write("cwd:", os.getcwd())st.write("src exists:", os.path.isdir("src"))if os.path.isdir("src"):st.write("files in src:", os.listdir("src"))st.write("TF version:", tf.__version__)st.write("weights exists:", os.path.exists(WEIGHTS_PATH), WEIGHTS_PATH)st.write("class_names exists:", os.path.exists(CLASS_NAMES_PATH), CLASS_NAMES_PATH)if os.path.exists(WEIGHTS_PATH):st.write("weights size (MB):", round(os.path.getsize(WEIGHTS_PATH) / (1024**2), 2))@st.cache_datadef load_class_names(path: str):if not os.path.exists(path):raise FileNotFoundError(f"Missing file: {path}")with open(path, "r", encoding="utf-8") as f:names = json.load(f)if not isinstance(names, list) or len(names) == 0:raise ValueError("class_names JSON must be a non-empty list.")return names@st.cache_resourcedef build_and_load_model(num_classes: int):# Build the SAME model you trained (NO BatchNorm)base_model = tf.keras.applications.ResNet50(weights="imagenet",include_top=False,input_shape=(224, 224, 3),)base_model.trainable = Falsemodel = tf.keras.Sequential([base_model,tf.keras.layers.GlobalAveragePooling2D(),tf.keras.layers.Dense(256, activation="relu"),tf.keras.layers.Dropout(0.5),tf.keras.layers.Dense(num_classes, activation="softmax"),])if not os.path.exists(WEIGHTS_PATH):raise FileNotFoundError(f"Missing weights file: {WEIGHTS_PATH}")# Load weightsmodel.load_weights(WEIGHTS_PATH)return modeltry:class_names = load_class_names(CLASS_NAMES_PATH)model = build_and_load_model(num_classes=len(class_names))st.success("β Model + weights loaded successfully!")except Exception as e:st.error("β Model could not be loaded.")st.exception(e)st.stop()uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png", "webp"])def preprocess(img: Image.Image) -> np.ndarray:img = img.convert("RGB").resize((224, 224))x = np.array(img, dtype=np.float32)x = np.expand_dims(x, axis=0)x = tf.keras.applications.resnet50.preprocess_input(x)return xif uploaded_file is None:st.info("π Upload an image to get a prediction.")else:img = Image.open(uploaded_file)st.image(img, use_container_width=True)x = preprocess(img)preds = model.predict(x, verbose=0)[0]idx = int(np.argmax(preds))conf = float(preds[idx])name = class_names[idx] if idx < len(class_names) else f"Class {idx}"st.subheader("β Prediction")st.write(f"**{name}** (index {idx})")st.write(f"Confidence: **{conf:.4f}**")st.subheader("π Probabilities (top 5)")top = np.argsort(preds)[::-1][:5]for i in top:n = class_names[i] if i < len(class_names) else f"Class {i}"st.write(f"{n}: {float(preds[i]):.4f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import osimport jsonimport numpy as npimport streamlit as stfrom PIL import Imageimport tensorflow as tffrom tensorflow.keras.applications import ResNet50from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropoutfrom tensorflow.keras.models import Sequential# -----------------------------# Page config# -----------------------------st.set_page_config(page_title="ResNet50 Image Predictor", page_icon="π§ ", layout="centered")st.title("π§ ResNet50 Image Predictor")st.write("Loads ResNet50 architecture and then loads trained weights (HF-safe).")# -----------------------------# Paths (FIXED)# -----------------------------WEIGHTS_PATH = "src/resnet50_weights_noBN3.h5"CLASS_NAMES_PATH = "src/class_names3.json"# -----------------------------# Debug info# -----------------------------with st.expander("π Debug info (HuggingFace check)"):try:st.write("Files in src/:")st.write(os.listdir("src"))st.write("Weights exists:", os.path.exists(WEIGHTS_PATH))st.write("Class names exists:", os.path.exists(CLASS_NAMES_PATH))st.write("TF:", tf.__version__)except Exception as e:st.error(e)# -----------------------------# Load class names# -----------------------------def load_class_names(path: str) -> list:with open(path, "r") as f:names = json.load(f)if not isinstance(names, list) or len(names) == 0:raise ValueError("class_names3.json must be a non-empty list of class names.")return names# -----------------------------# Build architecture (MUST match training!)# -----------------------------def build_model(num_classes: int) -> tf.keras.Model:base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3))base_model.trainable = Falsemodel = Sequential([base_model,GlobalAveragePooling2D(),Dense(256, activation="relu"),Dropout(0.5),Dense(num_classes, activation="softmax"),])return model# -----------------------------# Load model + weights# -----------------------------@st.cache_resourcedef load_trained_model(weights_path: str, class_names_path: str):if not os.path.exists(weights_path):raise FileNotFoundError(f"Missing weights file: {weights_path}")if not os.path.exists(class_names_path):raise FileNotFoundError(f"Missing class names file: {class_names_path}")class_names = load_class_names(class_names_path)model = build_model(num_classes=len(class_names))# IMPORTANT: build the model by calling it once (creates weights shapes)_ = model(np.zeros((1, 224, 224, 3), dtype=np.float32), training=False)# Load weights from your file name EXACTLYmodel.load_weights(weights_path)return model, class_namestry:model, class_names = load_trained_model(WEIGHTS_PATH, CLASS_NAMES_PATH)st.success("β Model + weights loaded successfully!")except Exception as e:st.error("β Model could not be loaded.")st.exception(e)st.stop()# -----------------------------# Image upload & prediction# -----------------------------uploaded_file = st.file_uploader("Upload a mushroom image", type=["jpg", "jpeg", "png", "webp"])if uploaded_file is None:st.info("π Please upload an image to start prediction.")else:img = Image.open(uploaded_file).convert("RGB")st.image(img, caption="Uploaded image", use_container_width=True)img_resized = img.resize((224, 224))x = np.array(img_resized, dtype=np.float32)x = np.expand_dims(x, axis=0)x = tf.keras.applications.resnet50.preprocess_input(x)preds = model.predict(x, verbose=0)[0]idx = int(np.argmax(preds))conf = float(np.max(preds))st.subheader("β Prediction")st.write(f"**Predicted class:** {class_names[idx]}")st.write(f"**Confidence:** {conf:.4f}")st.subheader("π Class probabilities")# Show top 5topk = np.argsort(preds)[::-1][:5]for i in topk:st.write(f"{class_names[i]}: {preds[i]:.4f}")
src/streamlit_app.py+81-61