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("""
""", 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
@st.cache_resource
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("""
AI PATHOLOGY HUB
Pneumo AI Pathology
""", 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('Select a clinical specimen above
', 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"""
{CLASS_LABELS[idx]}
{conf:.1f}%
AI Confidence Score
""", unsafe_allow_html=True)
st.markdown("SYSTEMS ENGINEER: RMUTUA | STRATHMORE UNIVERSITY
", unsafe_allow_html=True)