import streamlit as st import tensorflow as tf import numpy as np from PIL import Image # --- SETTINGS --- # Use 64 because your previous error specifically mentioned (None, 64, 64, 3) IMG_SIZE = (64, 64) MODEL_PATH = 'src/malaria_cnnmodel.h5' @st.cache_resource def load_malaria_model(): """ Loads the model using the standard Keras loader. If you get a 'ValueError' about layers, we use the weights-only fallback. """ try: # Standard load for .h5 files model = tf.keras.models.load_model(MODEL_PATH, compile=False) return model except Exception as e: st.warning("Standard load failed. Rebuilding model shell to load weights...") # MANUAL REBUILD (Matching your specific CNN architecture) # Based on your error: Input(64,64,3) -> VGG-style base -> Dense inputs = tf.keras.Input(shape=(IMG_SIZE[0], IMG_SIZE[1], 3)) # This assumes your model used VGG16 as a base. # If it was a custom CNN, this part would need to match your layers. base = tf.keras.applications.VGG16(weights=None, include_top=False, input_tensor=inputs) x = tf.keras.layers.Flatten()(base.output) x = tf.keras.layers.Dense(256, activation='relu')(x) outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.Model(inputs=inputs, outputs=outputs) model.load_weights(MODEL_PATH) return model def preprocess(image): # Resize to the 64x64 expected by your model img = image.resize(IMG_SIZE) img_array = np.array(img) # Handle PNGs with alpha channels (transparency) if img_array.shape[-1] == 4: img_array = img_array[:, :, :3] # Scale pixels to [0, 1] img_array = img_array / 255.0 return np.expand_dims(img_array, axis=0) # --- UI --- st.set_page_config(page_title="Malaria Detector") st.title("🩸 Malaria Parasite Detector") st.write(f"Loading model: `{MODEL_PATH}`") try: model = load_malaria_model() st.success("Model ready!") except Exception as e: st.error(f"Could not load model file: {e}") st.stop() uploaded_file = st.file_uploader("Upload a blood smear cell image", type=["png", "jpg", "jpeg"]) if uploaded_file: image = Image.open(uploaded_file).convert("RGB") st.image(image, caption="Uploaded Cell", width=250) if st.button("Predict"): with st.spinner("Analyzing..."): processed_img = preprocess(image) prediction = model.predict(processed_img)[0][0] # Binary classification threshold if prediction > 0.5: st.error(f"RESULT: PARASITIZED ({prediction:.2%})") else: st.success(f"RESULT: UNINFECTED ({1 - prediction:.2%})")