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

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. 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
- 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):
29
- raise FileNotFoundError(f"Missing file: {path}")
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("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)
77
- x = tf.keras.applications.resnet50.preprocess_input(x)
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}")
 
 
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}")