Spaces:
Runtime error

File size: 12,538 Bytes
6f9bd22
 
30f6772
 
6f9bd22
 
 
30f6772
8248837
6f9bd22
 
 
 
 
 
e6b86c7
6f9bd22
 
dd68430
6f9bd22
 
 
 
 
 
 
 
 
c0e6f50
dd68430
0bbfe64
6f9bd22
 
e6b86c7
 
6f9bd22
 
dd68430
acef378
dd68430
 
 
 
 
8610087
acef378
8610087
 
 
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8610087
6f9bd22
 
 
 
c0e6f50
8610087
6f9bd22
c31cc48
6f9bd22
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9bd22
dd68430
6f9bd22
 
 
8248837
1142967
acef378
6f9bd22
 
 
8610087
c0e6f50
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ba4097
6f9bd22
 
 
1142967
6f9bd22
 
 
 
 
 
 
 
 
 
 
 
 
dd68430
 
6f9bd22
 
 
 
 
dd68430
6f9bd22
 
dd68430
6f9bd22
 
 
 
ea3242f
6f9bd22
 
7da92c9
6f9bd22
8248837
1142967
d527889
dd68430
6f9bd22
 
 
 
dd68430
 
 
 
6f9bd22
d527889
3ba4097
dd68430
 
 
 
 
 
 
 
 
 
 
acef378
dd68430
c31cc48
 
 
 
 
 
 
dd68430
8610087
acef378
dd68430
 
 
acef378
dd68430
 
 
 
acef378
dd68430
 
 
acef378
dd68430
 
 
acef378
8610087
acef378
dd68430
 
 
acef378
dd68430
 
 
 
acef378
dd68430
 
 
acef378
dd68430
 
 
6f9bd22
c0e6f50
6f9bd22
dd68430
c0e6f50
dd68430
6f9bd22
 
dd68430
6f9bd22
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9bd22
 
dd68430
6f9bd22
dd68430
9eecc41
6f9bd22
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9bd22
dd68430
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9bd22
 
 
dd68430
 
 
 
 
 
 
 
 
 
1142967
6f9bd22
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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)