""" Malaria Detection - Streamlit App =================================== AI-powered blood smear analysis. Run with: streamlit run app.py """ import streamlit as st import tensorflow as tf import numpy as np from PIL import Image import time import datetime # ───────────────────────────────────────────── # PAGE CONFIG # ───────────────────────────────────────────── st.set_page_config( page_title="Malaria Detection System", page_icon="🦟", layout="centered" ) # ───────────────────────────────────────────── # CUSTOM CSS # ───────────────────────────────────────────── st.markdown(""" """, unsafe_allow_html=True) # ───────────────────────────────────────────── # SESSION STATE # ───────────────────────────────────────────── if "history" not in st.session_state: st.session_state.history = [] if "total_latency" not in st.session_state: st.session_state.total_latency = 0 # ───────────────────────────────────────────── # LOAD MODEL (cached so it only loads once) # ───────────────────────────────────────────── @st.cache_resource def load_model(): from keras.layers import Dense class PatchedDense(Dense): def __init__(self, *args, **kwargs): kwargs.pop('quantization_config', None) super().__init__(*args, **kwargs) model = tf.keras.models.load_model( 'malaria_model_final.h5', custom_objects={'Dense': PatchedDense}, compile=False ) return model IMG_SIZE = (128, 128) # ───────────────────────────────────────────── # HEADER # ───────────────────────────────────────────── st.markdown("""
⚡ 5G ENABLED
🦟 Malaria Detection System
AI-powered blood smear analysis · MobileNetV2
""", unsafe_allow_html=True) # ───────────────────────────────────────────── # STATS BAR # ───────────────────────────────────────────── total = len(st.session_state.history) avg_latency = round(st.session_state.total_latency / total) if total > 0 else 0 col1, col2, col3, col4 = st.columns(4) with col1: st.markdown('
94.3%
MODEL ACCURACY
', unsafe_allow_html=True) with col2: st.markdown('
0.9846
AUC-ROC SCORE
', unsafe_allow_html=True) with col3: st.markdown(f'
{total}
TOTAL PREDICTIONS
', unsafe_allow_html=True) with col4: latency_display = f"{avg_latency}ms" if total > 0 else "—" st.markdown(f'
{latency_display}
AVG LATENCY
', unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # ───────────────────────────────────────────── # UPLOAD + PREDICT # ───────────────────────────────────────────── st.markdown("#### 🔬 Upload Blood Smear Image") st.write("Uploader Test") uploaded_file = st.file_uploader( "Upload", type=["png", "jpg", "jpeg"] ) if uploaded_file: st.success("File received!") st.write(uploaded_file.name) if uploaded_file: col_img, col_info = st.columns([1, 2]) with col_img: img = Image.open(uploaded_file).convert("RGB") st.image(img, caption="Uploaded image", use_container_width=True) with col_info: st.markdown(f""" **File:** `{uploaded_file.name}` **Size:** `{img.size[0]} × {img.size[1]} px` **Format:** `{uploaded_file.type}` """) st.markdown(" ") analyze = st.button("🚀 Analyze via 5G Network") if analyze: model = load_model() with st.spinner("Transmitting over 5G network... Running AI analysis..."): start = time.time() img_resized = img.resize(IMG_SIZE) img_array = np.array(img_resized) / 255.0 img_array = np.expand_dims(img_array, axis=0) prob = float(model.predict(img_array, verbose=0)[0][0]) latency_ms = round((time.time() - start) * 1000) prediction = "Parasitized" if prob > 0.5 else "Uninfected" confidence = prob if prob > 0.5 else 1 - prob timestamp = datetime.datetime.now().strftime("%H:%M:%S") st.session_state.history.insert(0, { "prediction": prediction, "confidence": f"{confidence:.1%}", "latency_ms": latency_ms, "timestamp": timestamp, }) st.session_state.total_latency += latency_ms st.markdown('
', unsafe_allow_html=True) if prediction == "Parasitized": st.markdown(f"""
🦟
Malaria Detected — Parasitized
Confidence: {confidence:.1%}  ·  Latency: {latency_ms}ms  ·  {timestamp}
""", unsafe_allow_html=True) else: st.markdown(f"""
No Malaria — Uninfected
Confidence: {confidence:.1%}  ·  Latency: {latency_ms}ms  ·  {timestamp}
""", unsafe_allow_html=True) st.markdown(" ") st.progress(confidence, text=f"Confidence: {confidence:.1%}") st.rerun() # ───────────────────────────────────────────── # PREDICTION HISTORY # ───────────────────────────────────────────── st.markdown('
', unsafe_allow_html=True) st.markdown("#### 📋 Prediction History") if not st.session_state.history: st.markdown('

No predictions yet. Upload an image to begin.

', unsafe_allow_html=True) else: for entry in st.session_state.history: is_infected = entry["prediction"] == "Parasitized" dot_color = "#f85149" if is_infected else "#2ea043" label = "🦟 Parasitized" if is_infected else "✅ Uninfected" st.markdown(f"""
{label} {entry['confidence']} confidence {entry['latency_ms']}ms {entry['timestamp']}
""", unsafe_allow_html=True)