EnYa32 commited on
Commit
a5aa4b2
Β·
verified Β·
1 Parent(s): 834c379

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. 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("Classifies mushroom images using a trained ResNet50 model.")
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
- try:
31
- st.write("Working dir:", os.getcwd())
32
- st.write("Files in src/:", os.listdir("src") if os.path.isdir("src") else "src/ not found")
33
- st.write("Model exists:", os.path.exists(MODEL_PATH), "β†’", MODEL_PATH)
34
- st.write("class_names exists:", os.path.exists(CLASS_NAMES_PATH), "β†’", CLASS_NAMES_PATH)
35
- st.write("TF version:", tf.__version__)
36
- except Exception as e:
37
- st.error(e)
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 load_trained_model(path: str):
57
- if not os.path.exists(path):
58
- raise FileNotFoundError(f"Missing model file: {path}")
59
- # compile=False = safer for deployment (no optimizer/loss needed)
60
- model = tf.keras.models.load_model(path, compile=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  return model
62
 
63
  try:
64
  class_names = load_class_names(CLASS_NAMES_PATH)
65
- model = load_trained_model(MODEL_PATH)
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
- # Upload
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("πŸ‘† Please upload an image to start prediction.")
92
  else:
93
  img = Image.open(uploaded_file)
94
- st.image(img, caption="Uploaded image", use_container_width=True)
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
- pred_idx = int(np.argmax(preds))
102
- confidence = float(preds[pred_idx])
103
 
104
- # Safety: if JSON has fewer/more names than model outputs
105
- if pred_idx < len(class_names):
106
- pred_name = class_names[pred_idx]
107
- else:
108
- pred_name = f"Class {pred_idx}"
109
 
110
  st.subheader("βœ… Prediction")
111
- st.write(f"**Predicted class:** {pred_name} (index {pred_idx})")
112
- st.write(f"**Confidence:** {confidence:.4f}")
113
-
114
- st.subheader("πŸ“Š Class probabilities")
115
- # Show sorted probabilities (highest first)
116
- sorted_idx = np.argsort(preds)[::-1]
117
- for i in sorted_idx:
118
- name = class_names[i] if i < len(class_names) else f"Class {i}"
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}")