Basak Tamer commited on
Commit
5959ea0
·
verified ·
1 Parent(s): 666045b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +52 -39
src/streamlit_app.py CHANGED
@@ -1,55 +1,68 @@
1
- import os
2
- # CRITICAL: This flag must be set BEFORE importing tensorflow
3
- os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
-
5
  import streamlit as st
6
  import tensorflow as tf
7
  import numpy as np
8
  from PIL import Image
9
 
10
- # Use tf_keras specifically to bridge the 3.10 -> 3.13 gap
11
- try:
12
- import tf_keras as keras
13
- except ImportError:
14
- from tensorflow import keras
15
 
16
  @st.cache_resource
17
- def load_model_legacy():
18
- # We use the standard load_model because the environment variable
19
- # above tells it to use the old Keras 2 loading logic.
20
- model_path = 'src/malaria_cnnmodel.keras'
21
- return keras.models.load_model(model_path)
22
-
23
- def predict(image, model):
24
- # Standard preprocessing for VGG16/ResNet
25
- img = image.resize((224, 224))
26
- img_array = np.array(img)
27
- if img_array.shape[-1] == 4: img_array = img_array[:,:,:3]
28
- img_array = img_array / 255.0
29
- img_array = np.expand_dims(img_array, axis=0)
30
 
31
- prediction = model.predict(img_array)[0][0]
32
- return prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  # --- UI ---
35
- st.title("🩸 Malaria Cell Detection")
36
 
37
  try:
38
- model = load_model_legacy()
39
- st.sidebar.success("Legacy Keras Engine Loaded")
40
  except Exception as e:
41
- st.error(f"Load Error: {e}")
42
- st.info("Try checking if 'tf-keras' is in your requirements.txt")
43
  st.stop()
44
 
45
- file = st.file_uploader("Upload Cell Image", type=['jpg', 'png', 'jpeg'])
46
 
47
- if file:
48
- img = Image.open(file)
49
- st.image(img, width=300)
50
- if st.button("Classify"):
51
- res = predict(img, model)
52
- if res > 0.5:
53
- st.error(f"PARASITIZED ({res:.2%})")
54
- else:
55
- st.success(f"UNINFECTED ({1-res:.2%})")
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
 
6
+ # --- CONFIG ---
7
+ # Your error config was [None, 64, 64, 3], so we use 64 here
8
+ IMG_SIZE = (64, 64)
9
+ MODEL_PATH = 'src/malaria_cnnmodel.keras'
 
10
 
11
  @st.cache_resource
12
+ def load_model_by_weights():
13
+ """
14
+ Manual rebuild to bypass the 'batch_shape' deserialization error.
15
+ """
16
+ # 1. Define the Input exactly as the error showed
17
+ inputs = tf.keras.Input(shape=(IMG_SIZE[0], IMG_SIZE[1], 3))
18
+
19
+ # 2. Build the Base (Assuming VGG16 based on previous errors)
20
+ base_model = tf.keras.applications.VGG16(
21
+ weights=None,
22
+ include_top=False,
23
+ input_tensor=inputs
24
+ )
25
 
26
+ # 3. Add the classification head
27
+ x = tf.keras.layers.Flatten()(base_model.output)
28
+ x = tf.keras.layers.Dense(256, activation='relu')(x)
29
+ outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)
30
+
31
+ model = tf.keras.Model(inputs=inputs, outputs=outputs)
32
+
33
+ # 4. LOAD WEIGHTS ONLY
34
+ # This bypasses the broken 'InputLayer' config in the file
35
+ try:
36
+ model.load_weights(MODEL_PATH)
37
+ except Exception:
38
+ # If 'dense_2' name mismatch occurs, load by topology
39
+ model.load_weights(MODEL_PATH, by_name=False)
40
+
41
+ return model
42
 
43
  # --- UI ---
44
+ st.title("🩸 Malaria Detection (Version Bridge)")
45
 
46
  try:
47
+ model = load_model_by_weights()
48
+ st.sidebar.success("Model Shell Rebuilt & Weights Loaded")
49
  except Exception as e:
50
+ st.error(f"Final Attempt Failed: {e}")
 
51
  st.stop()
52
 
53
+ uploaded_file = st.file_uploader("Upload Cell Image", type=["png", "jpg", "jpeg"])
54
 
55
+ if uploaded_file:
56
+ image = Image.open(uploaded_file).convert("RGB")
57
+ st.image(image, width=250)
58
+
59
+ # Preprocess
60
+ img = image.resize(IMG_SIZE)
61
+ img_array = np.array(img) / 255.0
62
+ img_array = np.expand_dims(img_array, axis=0)
63
+
64
+ if st.button("Run Prediction"):
65
+ pred = model.predict(img_array)[0][0]
66
+ label = "Parasitized" if pred > 0.5 else "Uninfected"
67
+ color = "red" if pred > 0.5 else "green"
68
+ st.markdown(f"Result: :{color}[**{label}**] ({pred:.2%})")