Spaces:
Runtime error

leafscan / src /streamlit_app.py
MRM5's picture
Update src/streamlit_app.py
dd68430 verified
Raw History Blame Contribute Delete
12.5 kB
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("""
<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;
}
/* SIDEBAR LOCK */
[data-testid="stSidebar"] {
background-color: #0f172a !important;
border-right: 1px solid #1e293b;
min-width: 260px !important;
max-width: 260px !important;
}
/* CRITICAL: Lock all containers to prevent layout shifts */
.stImage {
min-height: 280px !important;
max-height: 280px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
background-color: rgba(15, 23, 42, 0.4);
border-radius: 1rem;
border: 1px solid #1e293b;
overflow: hidden;
}
.stImage img {
max-height: 280px !important;
width: auto !important;
object-fit: contain;
}
/* Lock column heights to prevent vertical shifting */
[data-testid="column"] {
min-height: 350px;
}
/* Prevent spinner from causing layout shift */
.stSpinner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.metric-card {
background: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(16px);
border: 1px solid rgba(16, 185, 129, 0.2);
border-radius: 1rem;
padding: 1rem;
text-align: center;
min-height: 100px;
}
.metric-card h2 {
color: #10b981;
font-size: 1.8rem;
font-weight: 800;
margin: 0;
}
.metric-card h3 {
color: #94a3b8;
font-size: 0.8rem;
margin-bottom: 0.5rem;
font-weight: 600;
}
/* Sample grid buttons - consistent sizing */
.sample-grid-btn {
background: rgba(15, 23, 42, 0.8);
border: 1px solid #1e293b;
border-radius: 0.5rem;
padding: 0.5rem;
text-align: center;
transition: all 0.2s;
min-height: 180px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* PRIMARY ACTION BUTTON */
div[class="stButton"] > button {
background: linear-gradient(90deg, #10b981 0%, #059669 100%);
color: #ffffff !important;
border-radius: 0.8rem;
border: 1px solid rgba(255, 255, 255, 0.2);
padding: 1.2rem 2rem;
font-weight: 800;
width: 100%;
text-transform: uppercase;
letter-spacing: 0.1em;
box-shadow: 0 0 20px rgba(16, 185, 129, 0.4);
transition: all 0.3s ease;
}
div[class="stButton"] > button:hover {
background: linear-gradient(90deg, #059669 0%, #047857 100%);
box-shadow: 0 0 30px rgba(16, 185, 129, 0.6);
transform: translateY(-2px);
}
/* Result container - fixed height */
.result-container {
min-height: 280px;
display: flex;
align-items: center;
justify-content: center;
}
</style>
""", 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("""
<div style="padding-top: 1rem; margin-bottom: 2rem;">
<div style="color: #10b981; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.1em; margin-bottom: 0.5rem;">AI DIAGNOSTICS</div>
<h1 style="font-size: 2.5rem; font-weight: 800; color: #f8fafc; margin: 0; letter-spacing: -0.04em;">Precision Plant <span style="color: #10b981;">Pathology</span></h1>
<p style="color: #94a3b8; font-size: 0.9rem; margin-top: 0.5rem;">Diagnostic identification system for botanical pathogens.</p>
</div>
""", unsafe_allow_html=True)
m1, m2 = st.columns(2)
with m1:
st.markdown('<div class="metric-card"><h3>Species Library</h3><h2>38</h2></div>', unsafe_allow_html=True)
with m2:
st.markdown('<div class="metric-card"><h3>CNN Accuracy</h3><h2>96.5%</h2></div>', 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('''
<div style="
border: 2px dashed #1e293b;
border-radius: 1rem;
height: 280px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(15, 23, 42, 0.4);
color: #64748b;
text-align: center;
padding: 20px;
">
<div>
<p style="font-size: 1rem; font-weight: 600; margin-bottom: 0.5rem;">No Specimen Selected</p>
<p style="font-size: 0.8rem; opacity: 0.7;">Select a clinical specimen above to begin automated pathology assessment</p>
</div>
</div>
''', 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"""
<div class="result-container">
<div style="
background: #0f172a;
border: 1px solid #1e293b;
border-radius: 1rem;
padding: 1.5rem;
text-align: center;
width: 100%;
">
<h4 style="color: #10b981; margin-bottom: 1rem; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.1em;">Diagnostic Result</h4>
<div style="font-size: 2.8rem; font-weight: 800; color: #ffffff; margin-bottom: 0.5rem;">{st.session_state.confidence:.1f}%</div>
<div style="color: #94a3b8; font-size: 0.65rem; text-transform: uppercase; margin-bottom: 1.5rem; letter-spacing: 0.05em;">Confidence Score</div>
<div style="
border: 1px solid #1e293b;
padding: 1rem;
border-radius: 0.5rem;
font-weight: 700;
background: rgba(16, 185, 129, 0.05);
font-size: 0.95rem;
">{st.session_state.prediction}</div>
</div>
</div>
""", unsafe_allow_html=True)
else:
st.markdown('''
<div class="result-container">
<div style="
background: rgba(15, 23, 42, 0.4);
border: 1px dashed #1e293b;
border-radius: 1rem;
padding: 2rem;
text-align: center;
color: #64748b;
width: 100%;
">
<p style="font-size: 0.9rem;">Click the button above to start analysis</p>
</div>
</div>
''', unsafe_allow_html=True)
else:
st.markdown('''
<div class="result-container">
<div style="
background: rgba(15, 23, 42, 0.4);
border: 1px dashed #1e293b;
border-radius: 1rem;
padding: 2rem;
text-align: center;
color: #64748b;
width: 100%;
">
<p style="font-size: 0.9rem;">Results will appear here</p>
</div>
</div>
''', unsafe_allow_html=True)
# Footer
st.markdown("""
<div style="
margin-top: 3rem;
padding: 2rem;
border-top: 1px solid #1e293b;
text-align: center;
color: #475569;
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.1em;
">
SYSTEMS ENGINEER: RMUTUA | PRECISION AGRO-PATHOLOGY
</div>
""", unsafe_allow_html=True)