import os
import json
import numpy as np
import streamlit as st
import tensorflow as tf
from PIL import Image
from tensorflow import keras
# 1. System Configuration
st.set_page_config(
page_title="LeafScan AI | Precision Diagnostics",
layout="wide",
initial_sidebar_state="expanded"
)
# Absolute path handling for Docker/HF environment
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 2. Enhanced CSS: Eliminate All Layout Shifts
st.markdown("""
""", unsafe_allow_html=True)
# 3. Backend Asset Loading
@st.cache_resource
def load_assets():
model_path = os.path.join(BASE_DIR, "plant_disease_pred.h5")
class_indices_path = os.path.join(BASE_DIR, "class_indices.json")
try:
model = keras.models.load_model(model_path)
if os.path.exists(class_indices_path):
with open(class_indices_path, 'r') as f:
indices = json.load(f)
indices = {str(k): v for k, v in indices.items()}
else:
indices = {str(i): f"Pathogen {i}" for i in range(38)}
return model, indices
except Exception as e:
st.error(f"Model loading failed: {e}")
return None, None
model, class_indices = load_assets()
def predict_disease(image):
img = image.convert("RGB")
img = img.resize((224, 224))
img_array = np.array(img).astype('float32') / 255.
predictions = model.predict(np.expand_dims(img_array, axis=0), verbose=0)
idx = np.argmax(predictions[0])
confidence = float(np.max(predictions[0]) * 100)
if confidence < 75:
return "Unidentified Specimen", confidence
return class_indices.get(str(idx), f"Unknown {idx}"), confidence
# 4. Header Section
st.markdown("""
AI DIAGNOSTICS
Precision Plant Pathology
Diagnostic identification system for botanical pathogens.
""", unsafe_allow_html=True)
m1, m2 = st.columns(2)
with m1:
st.markdown('Species Library
38
', unsafe_allow_html=True)
with m2:
st.markdown('CNN Accuracy
96.5%
', unsafe_allow_html=True)
st.divider()
# 5. Initialize session state
if 'active_img' not in st.session_state:
st.session_state.active_img = None
if 'show_result' not in st.session_state:
st.session_state.show_result = False
if 'prediction' not in st.session_state:
st.session_state.prediction = None
if 'confidence' not in st.session_state:
st.session_state.confidence = None
# 6. Sample Selection Grid
st.markdown("### Clinical Specimen Selection")
samples = [
("Apple Rot", "apple_black rot.jpeg"),
("Healthy Apple", "apple_healthy.jpeg"),
("Corn Blight", "corn(maize)_leaf_blight.jpg"),
("Tomato Spot", "tomato_bacterial_spot.jpeg")
]
# 2x2 Grid with consistent layout
r1_c1, r1_c2 = st.columns(2)
with r1_c1:
sample_path = os.path.join(BASE_DIR, samples[0][1])
if os.path.exists(sample_path):
st.image(Image.open(sample_path), width=110)
if st.button(f"Analyze {samples[0][0]}", key="btn_0"):
st.session_state.active_img = Image.open(sample_path)
st.session_state.show_result = False
st.rerun()
with r1_c2:
sample_path = os.path.join(BASE_DIR, samples[1][1])
if os.path.exists(sample_path):
st.image(Image.open(sample_path), width=110)
if st.button(f"Analyze {samples[1][0]}", key="btn_1"):
st.session_state.active_img = Image.open(sample_path)
st.session_state.show_result = False
st.rerun()
r2_c1, r2_c2 = st.columns(2)
with r2_c1:
sample_path = os.path.join(BASE_DIR, samples[2][1])
if os.path.exists(sample_path):
st.image(Image.open(sample_path), width=110)
if st.button(f"Analyze {samples[2][0]}", key="btn_2"):
st.session_state.active_img = Image.open(sample_path)
st.session_state.show_result = False
st.rerun()
with r2_c2:
sample_path = os.path.join(BASE_DIR, samples[3][1])
if os.path.exists(sample_path):
st.image(Image.open(sample_path), width=110)
if st.button(f"Analyze {samples[3][0]}", key="btn_3"):
st.session_state.active_img = Image.open(sample_path)
st.session_state.show_result = False
st.rerun()
st.divider()
# 7. Analysis Hub - Fixed Height Layout
col_up, col_res = st.columns([1.2, 1])
with col_up:
if st.session_state.active_img:
st.image(st.session_state.active_img, use_container_width=True)
else:
st.markdown('''
No Specimen Selected
Select a clinical specimen above to begin automated pathology assessment
''', unsafe_allow_html=True)
with col_res:
# Always render container with fixed height
if st.session_state.active_img and model:
if st.button("🔬 RUN INTELLIGENT ANALYSIS", key="analyze_btn"):
with st.spinner("Analyzing feature maps..."):
prediction, confidence = predict_disease(st.session_state.active_img)
st.session_state.prediction = prediction
st.session_state.confidence = confidence
st.session_state.show_result = True
# Display result if available
if st.session_state.show_result and st.session_state.prediction:
st.markdown(f"""
Diagnostic Result
{st.session_state.confidence:.1f}%
Confidence Score
{st.session_state.prediction}
""", unsafe_allow_html=True)
else:
st.markdown('''
Click the button above to start analysis
''', unsafe_allow_html=True)
else:
st.markdown('''
''', unsafe_allow_html=True)
# Footer
st.markdown("""
SYSTEMS ENGINEER: RMUTUA | PRECISION AGRO-PATHOLOGY
""", unsafe_allow_html=True)