Download src/streamlit_app.py from MRM5/pneumo_ai: direct link, hf CLI and curl.
- Browser
- Download file 6.12 kB
-
https://huggingface.co/spaces/MRM5/pneumo_ai/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/MRM5/pneumo_ai/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/MRM5/pneumo_ai/resolve/main/src/streamlit_app.py
6.12 kB
| import os | |
| import numpy as np | |
| import tensorflow as tf | |
| import streamlit as st | |
| from PIL import Image | |
| # Use standardized Keras 3 imports | |
| from tensorflow.keras.models import load_model | |
| from tensorflow.keras.preprocessing import image | |
| # 1. System Configuration & Total Layout Locking | |
| st.set_page_config( | |
| page_title="Pneumo AI | Clinical Diagnostics", | |
| layout="wide", | |
| initial_sidebar_state="collapsed" | |
| ) | |
| # Rigid CSS to prevent "shaking" on Hugging Face | |
| st.markdown(""" | |
| <style> | |
| @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap'); | |
| .main { background-color: #020617; color: #f8fafc; font-family: 'Plus Jakarta Sans', sans-serif; } | |
| [data-testid="stImage"] { | |
| background-color: rgba(15, 23, 42, 0.4); | |
| border-radius: 1rem; border: 1px solid #1e293b; | |
| min-height: 450px; max-height: 450px; | |
| overflow: hidden; display: flex; justify-content: center; align-items: center; | |
| } | |
| div[class="stButton"] > button { | |
| background: linear-gradient(90deg, #3b82f6 0%, #2563eb 100%); | |
| color: white !important; border-radius: 0.8rem; padding: 1.2rem; | |
| font-weight: 800; width: 100%; text-transform: uppercase; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # 2. Asset Management & Absolute Path Resolution | |
| # This ensures files are found inside the /src directory on GitHub | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| MODEL_NAME = 'custom_cnn_pneumo_ai_best_baseline.keras' | |
| MODEL_PATH = os.path.join(BASE_DIR, MODEL_NAME) | |
| CLASS_LABELS = ['NORMAL', 'BACTERIAL', 'VIRAL'] | |
| # Debug: Print paths for troubleshooting | |
| print(f"BASE_DIR: {BASE_DIR}") | |
| print(f"MODEL_PATH: {MODEL_PATH}") | |
| print(f"Model exists: {os.path.exists(MODEL_PATH)}") | |
| # Initialize variable to None to prevent NameError | |
| pneumo_model = None | |
| def load_pneumo_engine(): | |
| if not os.path.exists(MODEL_PATH): | |
| return None | |
| # Load model and explicitly build the graph for Keras 3 | |
| model = load_model(MODEL_PATH, compile=False) | |
| model.build((None, 128, 128, 3)) | |
| return model | |
| # Global Load Attempt | |
| pneumo_model = load_pneumo_engine() | |
| # 3. Header Section | |
| st.markdown(""" | |
| <div style="padding-top: 1rem; margin-bottom: 2rem;"> | |
| <div style="color: #3b82f6; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.1em; margin-bottom: 0.5rem;">AI PATHOLOGY HUB</div> | |
| <h1 style="font-size: 2.5rem; font-weight: 800; color: #f8fafc; margin: 0; letter-spacing: -0.04em;">Pneumo AI <span style="color: #3b82f6;">Pathology</span></h1> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Safety check for Model Loading | |
| if pneumo_model is None: | |
| st.error(f"⚠️ MODEL NOT FOUND: System looked in {MODEL_PATH}") | |
| st.info("Check your folder structure: the .keras file must be in the same folder as this script.") | |
| st.stop() # Prevents NameError at prediction time | |
| # 4. Clinical Specimen Selection (180px Thumbnails) | |
| st.markdown("### Clinical Specimen Selection") | |
| samples = [ | |
| ("Normal Specimen", "normal_sample.jpg"), | |
| ("Bacterial Specimen", "bacterial_sample.jpg"), | |
| ("Viral Specimen", "viral_sample.jpg"), | |
| ("Review Case", "unidentified_sample.jpg") | |
| ] | |
| if 'active_specimen' not in st.session_state: | |
| st.session_state.active_specimen = None | |
| # Stable 2x2 Selection Grid | |
| c1, c2 = st.columns(2) | |
| for i in range(2): | |
| path = os.path.join(BASE_DIR, samples[i][1]) | |
| with [c1, c2][i]: | |
| if os.path.exists(path): | |
| st.image(Image.open(path), width=180) | |
| if st.button(f"Load {samples[i][0]}", key=f"btn_{i}"): | |
| st.session_state.active_specimen = Image.open(path) | |
| c3, c4 = st.columns(2) | |
| for i in range(2, 4): | |
| path = os.path.join(BASE_DIR, samples[i][1]) | |
| with [c3, c4][i-2]: | |
| if os.path.exists(path): | |
| st.image(Image.open(path), width=180) | |
| if st.button(f"Load {samples[i][0]}", key=f"btn_{i}"): | |
| st.session_state.active_specimen = Image.open(path) | |
| st.divider() | |
| # 5. Analysis Hub (450px Main Display) | |
| col_img, col_res = st.columns([1.4, 1]) | |
| with col_img: | |
| if st.session_state.active_specimen: | |
| st.image(st.session_state.active_specimen, width=450) | |
| else: | |
| st.markdown('<div style="border: 1px solid #1e293b; border-radius: 1rem; height: 450px; display: flex; align-items: center; justify-content: center; background: rgba(15, 23, 42, 0.4); color: #64748b; text-align: center; padding: 20px;">Select a clinical specimen above</div>', unsafe_allow_html=True) | |
| with col_res: | |
| if st.session_state.active_specimen: | |
| if st.button("RUN INTELLIGENT ANALYSIS"): | |
| # Additional safety check before prediction | |
| if pneumo_model is None: | |
| st.error("⚠️ Model not loaded. Cannot perform analysis.") | |
| else: | |
| with st.spinner("Classifying pathology..."): | |
| img = st.session_state.active_specimen.convert("RGB").resize((128, 128)) | |
| img_array = image.img_to_array(img) / 255.0 | |
| img_array = np.expand_dims(img_array, axis=0) | |
| # Perform Inference | |
| preds = pneumo_model.predict(img_array)[0] | |
| idx = np.argmax(preds) | |
| conf = preds[idx] * 100 | |
| st.markdown(f""" | |
| <div style="background: #0f172a; border: 1px solid #3b82f6; border-radius: 1rem; padding: 2rem; text-align: center; margin-top: 2rem;"> | |
| <h2 style="color: #3b82f6; margin: 0; font-size: 2.2rem;">{CLASS_LABELS[idx]}</h2> | |
| <div style="font-size: 3rem; font-weight: 800; color: #ffffff;">{conf:.1f}%</div> | |
| <p style="color: #94a3b8; font-size: 0.75rem; text-transform: uppercase;">AI Confidence Score</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<div style='margin-top: 5rem; text-align: center; color: #475569; font-size: 0.65rem;'>SYSTEMS ENGINEER: RMUTUA | STRATHMORE UNIVERSITY</div>", unsafe_allow_html=True) |