Spaces:
Runtime error

MRM5 commited on
Commit
6f9bd22
·
verified ·
1 Parent(s): d2eb14a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +207 -37
src/streamlit_app.py CHANGED
@@ -1,40 +1,210 @@
1
- import altair as alt
 
2
  import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
  import numpy as np
 
4
  import streamlit as st
5
+ import tensorflow as tf
6
+ from PIL import Image
7
+ from tensorflow import keras
8
+ from datetime import datetime
9
 
10
+ # 1. Professional Configuration
11
+ st.set_page_config(
12
+ page_title="LeafScan AI | Precision Diagnostics",
13
+ layout="wide",
14
+ initial_sidebar_state="expanded"
15
+ )
16
+
17
+ # Absolute path handling for Hugging Face
18
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
19
+
20
+ # High-Visibility Professional Theme
21
+ st.markdown("""
22
+ <style>
23
+ @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
24
+
25
+ .main {
26
+ background-color: #020617;
27
+ color: #f8fafc;
28
+ font-family: 'Plus Jakarta Sans', sans-serif;
29
+ }
30
+
31
+ section[data-testid="stSidebar"] {
32
+ background-color: #0f172a !important;
33
+ border-right: 1px solid #1e293b;
34
+ }
35
+
36
+ /* Professional Metric Cards */
37
+ .metric-card {
38
+ background: rgba(15, 23, 42, 0.6);
39
+ backdrop-filter: blur(16px);
40
+ border: 1px solid rgba(16, 185, 129, 0.2);
41
+ border-radius: 1.5rem;
42
+ padding: 2rem;
43
+ text-align: center;
44
+ box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5);
45
+ }
46
+ .metric-card h2 { color: #10b981; font-size: 2.5rem; font-weight: 800; margin: 0; }
47
+
48
+ /* HIGH-VISIBILITY COMMAND BUTTON */
49
+ div[class="stButton"] > button {
50
+ background: linear-gradient(90deg, #10b981 0%, #059669 100%);
51
+ color: #ffffff !important;
52
+ border-radius: 1rem;
53
+ border: 2px solid rgba(255, 255, 255, 0.2);
54
+ padding: 1.5rem 2rem;
55
+ font-weight: 800;
56
+ width: 100%;
57
+ text-transform: uppercase;
58
+ letter-spacing: 0.15em;
59
+ font-size: 1.1rem;
60
+ box-shadow: 0 0 30px rgba(16, 185, 129, 0.4);
61
+ transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
62
+ }
63
+
64
+ div[class="stButton"] > button:hover {
65
+ transform: scale(1.03);
66
+ background: linear-gradient(90deg, #059669 0%, #10b981 100%);
67
+ border-color: #ffffff;
68
+ box-shadow: 0 0 50px rgba(16, 185, 129, 0.6);
69
+ }
70
+
71
+ .result-panel {
72
+ background: linear-gradient(145deg, #0f172a, #020617);
73
+ border: 1px solid #1e293b;
74
+ border-radius: 2rem;
75
+ padding: 2.5rem;
76
+ }
77
+
78
+ .emerald-badge {
79
+ background: rgba(16, 185, 129, 0.1);
80
+ color: #10b981;
81
+ padding: 0.5rem 1.25rem;
82
+ border-radius: 9999px;
83
+ font-size: 0.75rem;
84
+ font-weight: 700;
85
+ border: 1px solid rgba(16, 185, 129, 0.3);
86
+ display: inline-flex;
87
+ margin-bottom: 1.5rem;
88
+ }
89
+ </style>
90
+ """, unsafe_allow_html=True)
91
+
92
+ # 2. Asset Management
93
+ @st.cache_resource
94
+ def load_assets():
95
+ model_path = os.path.join(BASE_DIR, "plant_disease_pred.h5")
96
+ class_indices_path = os.path.join(BASE_DIR, "class_indices.json")
97
+ try:
98
+ model = keras.models.load_model(model_path)
99
+ if os.path.exists(class_indices_path):
100
+ with open(class_indices_path, 'r') as f:
101
+ indices = json.load(f)
102
+ indices = {str(k): v for k, v in indices.items()}
103
+ else:
104
+ indices = {str(i): f"Pathogen {i}" for i in range(38)}
105
+ return model, indices
106
+ except Exception as e:
107
+ st.error(f"System Load Error: {e}")
108
+ return None, None
109
+
110
+ model, class_indices = load_assets()
111
+
112
+ def predict_disease(image):
113
+ # Standardize to RGB
114
+ img = image.convert("RGB")
115
+ img = img.resize((224, 224))
116
+ img_array = np.array(img).astype('float32') / 255.
117
+ predictions = model.predict(np.expand_dims(img_array, axis=0))
118
+ idx = np.argmax(predictions[0])
119
+ confidence = float(np.max(predictions[0]) * 100)
120
+
121
+ # Reliability Guardrail
122
+ if confidence < 75:
123
+ return "Non-Botanical / Unidentified", confidence
124
+ return class_indices.get(str(idx), f"Unknown {idx}"), confidence
125
+
126
+ # 3. Main Interface
127
+ st.markdown("""
128
+ <div style="padding-top: 1rem; margin-bottom: 3rem;">
129
+ <div class="emerald-badge">AI-POWERED DIAGNOSTICS</div>
130
+ <h1 style="font-size: 3.5rem; font-weight: 800; color: #f8fafc; margin: 0; letter-spacing: -0.05em;">Precision Plant <span style="color: #10b981;">Pathology</span></h1>
131
+ <p style="color: #94a3b8; font-size: 1.1rem; margin-top: 0.5rem;">Diagnostic identification of botanical pathogens.</p>
132
+ </div>
133
+ """, unsafe_allow_html=True)
134
+
135
+ # Metrics Section
136
+ m1, m2 = st.columns(2)
137
+ with m1: st.markdown('<div class="metric-card"><h3>Species Library</h3><h2>38</h2></div>', unsafe_allow_html=True)
138
+ with m2: st.markdown('<div class="metric-card"><h3>CNN Accuracy</h3><h2>96.5%</h2></div>', unsafe_allow_html=True)
139
+
140
+ st.markdown("<br>", unsafe_allow_html=True)
141
+
142
+ # 4. Gallery
143
+ st.markdown("### Clinical Specimen Gallery")
144
+ samples = {
145
+ "Apple Rot": "apple_black rot.jpeg",
146
+ "Healthy Apple": "apple_healthy.jpeg",
147
+ "Corn Blight": "corn(maize)_leaf_blight.jpg",
148
+ "Tomato Spot": "tomato_bacterial_spot.jpeg"
149
+ }
150
+ sample_cols = st.columns(4)
151
+ if 'active_img' not in st.session_state:
152
+ st.session_state.active_img = None
153
+
154
+ for i, (name, filename) in enumerate(samples.items()):
155
+ img_path = os.path.join(BASE_DIR, filename)
156
+ with sample_cols[i]:
157
+ if os.path.exists(img_path):
158
+ img_disp = Image.open(img_path)
159
+ st.image(img_disp, use_container_width=True, caption=name)
160
+ if st.button(f"Load {name}", key=f"btn_{i}"):
161
+ st.session_state.active_img = img_disp
162
+
163
+ st.markdown("---")
164
+
165
+ col_up, col_res = st.columns([1.4, 1])
166
+ with col_up:
167
+ uploaded_file = st.file_uploader("Upload Specimen", type=["jpg", "jpeg", "png"], label_visibility="collapsed")
168
+ if uploaded_file:
169
+ st.session_state.active_img = Image.open(uploaded_file)
170
+
171
+ if st.session_state.active_img:
172
+ st.image(st.session_state.active_img, use_container_width=True, caption="Active Specimen")
173
+ else:
174
+ st.markdown('<div style="border: 2px dashed #1e293b; border-radius: 2rem; padding: 6rem; text-align: center; background: rgba(15, 23, 42, 0.4); color: #64748b;">Load a sample or upload a specimen</div>', unsafe_allow_html=True)
175
+
176
+ with col_res:
177
+ if st.session_state.active_img and model:
178
+ # High-Impact identifiable button
179
+ if st.button("RUN INTELLIGENT ANALYSIS"):
180
+ with st.spinner("Processing feature maps..."):
181
+ prediction, confidence = predict_disease(st.session_state.active_img)
182
+ st.markdown(f"""
183
+ <div class="result-panel">
184
+ <h4 style="margin: 0 0 2rem 0; color: #10b981; font-weight: 700;">Diagnostic Assessment</h4>
185
+ <div style="display: flex; justify-content: center; margin-bottom: 2.5rem;">
186
+ <div style="position: relative; width: 150px; height: 150px;">
187
+ <svg viewBox="0 0 100 100" style="transform: rotate(-90deg); width: 100%; height: 100%;">
188
+ <circle cx="50" cy="50" r="45" fill="none" stroke="#1e293b" stroke-width="6" />
189
+ <circle cx="50" cy="50" r="45" fill="none" stroke="#10b981" stroke-width="6"
190
+ stroke-dasharray="{2.83 * confidence} 283" stroke-linecap="round" />
191
+ </svg>
192
+ <div style="position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; transform: rotate(0deg);">
193
+ <span style="font-size: 2.25rem; font-weight: 800; color: #ffffff;">{confidence:.0f}%</span>
194
+ </div>
195
+ </div>
196
+ </div>
197
+ <div style="border: 1px solid #1e293b; padding: 1rem; border-radius: 1rem; text-align: center;">
198
+ <p style="font-size: 1.5rem; font-weight: 800; color: #ffffff; margin: 0;">{prediction}</p>
199
+ </div>
200
+ </div>
201
+ """, unsafe_allow_html=True)
202
+
203
+ # Footer
204
+ st.markdown("""
205
+ <div style="margin-top: 6rem; padding: 2rem; border-top: 1px solid #1e293b; text-align: center;">
206
+ <p style="color: #475569; font-size: 0.75rem; letter-spacing: 0.1em; text-transform: uppercase;">
207
+ SYSTEMS ENGINEER: RMUTUA | BUILT FOR PRECISION AGRO-PATHOLOGY
208
+ </p>
209
+ </div>
210
+ """, unsafe_allow_html=True)