Repository navigation
Expand file tree
/
Copy pathappsoilvision.py
More file actions
535 lines (486 loc) Β· 17.8 KB
/
Copy pathappsoilvision.py
File metadata and controls
535 lines (486 loc) Β· 17.8 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import streamlit as st
import pandas as pd
import plotly.express as px
from PIL import Image
import os
import re
import requests
from streamlit_lottie import st_lottie
from streamlit_js_eval import streamlit_js_eval
# Import the logic functions
import backend_logic as backend
def load_lottie_url(url: str):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return response.json()
except requests.RequestException:
pass
return None
def parse_recommendation(reco_text: str):
"""Return intro sentence and list of (label, value) tuples from markdown bullets."""
if not reco_text:
return "", []
lines = [line.strip() for line in reco_text.splitlines() if line.strip()]
intro = lines[0] if lines else ""
items = []
for line in lines[1:]:
match = re.match(r"\*\s+\*\*(.+?)\*\*:\s*(.+)", line)
if match:
label, value = match.groups()
items.append((label, value))
return intro, items
def stylize_value(text: str) -> str:
"""Wrap key terms in neon accent spans for holographic display."""
if not text:
return ""
cleaned = text.strip()
trailing_period = ""
if cleaned.endswith("."):
cleaned = cleaned[:-1]
trailing_period = "."
if "," in cleaned:
parts = [part.strip() for part in cleaned.split(",") if part.strip()]
highlighted = ", ".join(f"<span class='holo-accent'>{part}</span>" for part in parts)
else:
highlighted = f"<span class='holo-accent'>{cleaned}</span>"
return highlighted + trailing_period
# --- PAGE CONFIGURATION ---
st.set_page_config(
page_title="SoilVision - The Debug Dynasty",
page_icon="π±",
layout="wide"
)
# --- CSS STYLING ---
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;600;800&display=swap');
html, body, .main, [data-testid="stAppViewContainer"] {
font-family: 'Orbitron', sans-serif;
background-color: #0e1117;
}
h1, h2, h3 {
text-shadow: 0 0 6px rgba(57, 255, 20, 0.5),
0 0 12px rgba(57, 255, 20, 0.25);
}
.stButton>button {
font-family: 'Orbitron', sans-serif;
}
[data-testid="stSidebar"] {
background-color: #1A1A1A;
box-shadow: 8px 0 24px rgba(0, 0, 0, 0.4);
border-right: 1px solid rgba(57, 255, 20, 0.15);
}
[data-testid="stSidebar"] .stButton>button {
background: linear-gradient(135deg, #44ff4f, #0f6024);
color: #ffffff;
font-weight: 700;
border-radius: 999px;
box-shadow: 0 0 18px rgba(68, 255, 79, 0.45);
border: none;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
[data-testid="stSidebar"] .stButton>button:hover {
transform: translateY(-1px) scale(1.01);
box-shadow: 0 0 24px rgba(68, 255, 79, 0.6);
}
.f-card {
background: #262730;
border: 1px solid rgba(57, 255, 20, 0.35);
border-radius: 18px;
padding: 1.5rem;
box-shadow: 0 0 26px rgba(57, 255, 20, 0.18);
backdrop-filter: blur(4px);
}
.f-card .stMetric {
margin-bottom: 1rem;
}
.f-card [data-testid="stMetricLabel"] {
font-size: 0.95rem;
letter-spacing: 0.05em;
color: rgba(255, 255, 255, 0.75);
}
.f-card [data-testid="stMetricValue"] {
font-size: 1.75rem;
font-weight: 800;
color: #39ff14;
text-shadow: 0 0 12px rgba(57, 255, 20, 0.45);
}
.f-card__title {
font-size: 1.25rem;
margin-bottom: 1.25rem;
letter-spacing: 0.08em;
}
.f-card__item {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
gap: 1rem;
}
.f-card__label {
color: rgba(255, 255, 255, 0.6);
font-size: 0.95rem;
letter-spacing: 0.05em;
}
.f-card__value {
font-size: 1.65rem;
font-weight: 700;
color: #ffffff;
}
.neon-badge {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.4rem 1.25rem;
border-radius: 999px;
font-weight: 700;
letter-spacing: 0.1em;
font-size: 1.1rem;
font-family: 'Orbitron', sans-serif;
color: #f9f9f9;
border: 1px solid rgba(57, 255, 20, 0.65);
box-shadow: 0 0 14px rgba(57, 255, 20, 0.45);
animation: pulse-glow 2.5s ease-in-out infinite;
background: rgba(0, 0, 0, 0.35);
}
.neon-badge--lime {
border-color: rgba(57, 255, 20, 0.7);
box-shadow: 0 0 16px rgba(57, 255, 20, 0.6);
}
.neon-badge--cyan {
border-color: rgba(0, 255, 255, 0.7);
box-shadow: 0 0 16px rgba(0, 255, 255, 0.55);
}
@keyframes pulse-glow {
0%, 100% {
box-shadow: 0 0 14px rgba(57, 255, 20, 0.4);
}
50% {
box-shadow: 0 0 26px rgba(57, 255, 20, 0.7);
}
}
.holo-card {
background: rgba(18, 22, 32, 0.55);
border: 1px solid rgba(0, 255, 170, 0.4);
border-radius: 24px;
padding: 2rem;
backdrop-filter: blur(14px);
box-shadow: 0 0 32px rgba(0, 255, 170, 0.22);
position: relative;
overflow: hidden;
animation: holo-border 6s ease-in-out infinite;
}
.holo-card::before {
content: "";
position: absolute;
inset: 0;
background: radial-gradient(circle at top left, rgba(0, 255, 170, 0.25), transparent 55%),
radial-gradient(circle at bottom right, rgba(0, 180, 255, 0.2), transparent 60%);
pointer-events: none;
opacity: 0.9;
}
.holo-card__title {
font-size: 1.2rem;
text-transform: uppercase;
letter-spacing: 0.18em;
color: #e7fff6;
margin-bottom: 0.85rem;
position: relative;
}
.holo-title__underline {
display: block;
margin-top: 0.65rem;
height: 2px;
width: 100%;
background: linear-gradient(90deg, rgba(0,255,170,0.8), rgba(0, 180, 255, 0.6));
opacity: 0.9;
}
.holo-intro {
margin: 0.5rem 0 1.25rem 0;
color: rgba(235, 246, 243, 0.88);
letter-spacing: 0.04em;
line-height: 1.6;
}
.holo-list {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 1rem;
}
.holo-list__item {
display: flex;
gap: 1rem;
align-items: flex-start;
background: rgba(6, 12, 20, 0.45);
border-radius: 18px;
padding: 0.85rem 1.1rem;
border: 1px solid rgba(0, 255, 170, 0.25);
box-shadow: inset 0 0 18px rgba(0, 255, 170, 0.08);
}
.holo-icon {
font-size: 1.5rem;
line-height: 1;
margin-top: 0.2rem;
}
.holo-label {
display: block;
font-size: 0.85rem;
letter-spacing: 0.12em;
color: rgba(210, 235, 230, 0.7);
text-transform: uppercase;
}
.holo-value {
margin-top: 0.35rem;
font-size: 1.05rem;
letter-spacing: 0.05em;
color: rgba(243, 255, 253, 0.92);
}
.holo-accent {
color: #00ff8a;
font-weight: 800;
text-shadow: 0 0 12px rgba(0, 255, 170, 0.6);
}
.holo-protip {
margin-top: 1.7rem;
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem 1.25rem;
border-radius: 18px;
background: rgba(40, 32, 4, 0.55);
border: 1px solid rgba(255, 220, 90, 0.8);
box-shadow: 0 0 26px rgba(255, 220, 90, 0.35);
animation: protip-pulse 3.2s ease-in-out infinite;
}
.holo-protip__icon {
font-size: 1.6rem;
}
.holo-protip__text {
color: #fff7c4;
letter-spacing: 0.06em;
font-size: 0.95rem;
}
.holo-protip__label {
display: block;
font-size: 0.75rem;
letter-spacing: 0.2em;
text-transform: uppercase;
color: rgba(255, 240, 156, 0.85);
margin-bottom: 0.25rem;
}
@keyframes holo-border {
0%, 100% {
box-shadow: 0 0 32px rgba(0, 255, 170, 0.18);
border-color: rgba(0, 255, 170, 0.35);
}
50% {
box-shadow: 0 0 42px rgba(0, 255, 170, 0.3);
border-color: rgba(0, 255, 170, 0.6);
}
}
@keyframes protip-pulse {
0%, 100% {
box-shadow: 0 0 20px rgba(255, 220, 90, 0.3);
border-color: rgba(255, 220, 90, 0.65);
}
50% {
box-shadow: 0 0 32px rgba(255, 220, 90, 0.5);
border-color: rgba(255, 220, 90, 0.95);
}
}
</style>
""", unsafe_allow_html=True)
# --- TITLE ---
st.title("π± SoilVision: AI-Powered Soil Analysis")
st.markdown("**Team: The Debug Dynasty** | *24Hrs of Adrenaline*")
st.markdown("---")
# --- SIDEBAR: INPUTS ---
with st.sidebar:
st.header("1. Upload & Location")
# Image Input
uploaded_file = st.file_uploader("Upload Soil Image", type=['jpg', 'png', 'jpeg'])
# Location Inputs
use_current = st.toggle("Use Current Location", value=False, help="Enable to use your browser's geolocation.")
location = st.text_input("City / District", "Chennai", disabled=use_current)
browser_coords = None
if use_current:
coords = streamlit_js_eval(
js_expressions="""
new Promise((resolve) => {
if (!navigator.geolocation) {
resolve(null);
return;
}
navigator.geolocation.getCurrentPosition(
(pos) => resolve({latitude: pos.coords.latitude, longitude: pos.coords.longitude}),
() => resolve(null),
{timeout: 10000}
);
})
""",
key="browser_coords",
)
if coords and isinstance(coords, dict):
lat = coords.get("latitude")
lon = coords.get("longitude")
if lat is not None and lon is not None:
browser_coords = (float(lat), float(lon))
st.success(f"π Location detected: {lat:.4f}, {lon:.4f}")
if browser_coords is None and coords is None:
st.info("β³ Waiting for browser location permission...")
# API Key - try to get from Streamlit secrets first, then env, then user input
default_api_key = ""
try:
if hasattr(st, 'secrets') and 'OPENWEATHER_API_KEY' in st.secrets:
default_api_key = st.secrets['OPENWEATHER_API_KEY']
except Exception:
default_api_key = os.getenv("OPENWEATHER_API_KEY", "")
api_key = st.text_input("OpenWeatherMap API Key", value=default_api_key, type="password")
# Optional Inputs
season = st.selectbox("Crop Season", ["Kharif", "Rabi", "Zaid"])
# The "Go" Button
analyze_btn = st.button("π Analyze Soil")
# --- MAIN DASHBOARD ---
# Use Session State to keep data on screen after button clicks
if "analysis_done" not in st.session_state:
st.session_state.analysis_done = False
LOTTIE_SCAN_URL = "https://assets5.lottiefiles.com/packages/lf20_gamjwr6w.json"
if "lottie_scan" not in st.session_state:
st.session_state.lottie_scan = load_lottie_url(LOTTIE_SCAN_URL)
if analyze_btn:
if not uploaded_file:
st.error("β Upload a soil image before analysis.")
elif not api_key:
st.error("β Provide a valid OpenWeatherMap API key.")
elif use_current and browser_coords is None:
st.error("β Allow location access or switch to manual city input.")
elif not use_current and not location:
st.error("β Enter a city or enable 'Use Current Location'.")
else:
scan_placeholder = st.empty()
with scan_placeholder.container():
if st.session_state.lottie_scan:
st_lottie(st.session_state.lottie_scan, height=200, loop=True)
st.caption("π¬ Bio-Scanning soil sample...")
try:
# 1. Display the Image (if provided)
image = None
if uploaded_file:
image = Image.open(uploaded_file)
# 2. Call Backend Functions
soil_type = confidence = moisture = None
if image is not None:
soil_type, confidence, moisture = backend.process_image_and_predict(uploaded_file)
lat = lon = None
resolved_label = location
if use_current and browser_coords:
lat, lon = browser_coords
resolved_label = "Current Location"
weather_info = backend.get_weather_data(resolved_label, api_key, lat=lat, lon=lon)
recommendation = backend.generate_llm_recommendation(soil_type or "Loamy", weather_info)
# 3. Store in Session State
st.session_state.results = {
"image": image,
"soil_type": soil_type or "Loamy",
"moisture": moisture or "Medium-High",
"weather": weather_info,
"rec": recommendation,
}
st.session_state.analysis_done = True
scan_placeholder.empty()
except ValueError as err:
scan_placeholder.empty()
st.error(f"β {str(err)}")
st.stop()
except RuntimeError as err:
scan_placeholder.empty()
st.error(f"β {str(err)}")
st.stop()
except Exception as err:
scan_placeholder.empty()
st.error(f"β An unexpected error occurred: {str(err)}")
st.stop()
# --- DISPLAY RESULTS ---
if st.session_state.analysis_done:
results = st.session_state.results
# Layout: 3 Columns for Key Metrics
col1, col2, col3 = st.columns(3)
weather_data = results["weather"]
moisture_level = results["moisture"]
with col1:
if results["image"] is not None:
st.image(results["image"], caption="Uploaded Soil Sample", use_container_width=True)
with col2:
soil_html = f"""
<div class="f-card f-card--soil">
<h3 class="f-card__title">β
Soil Analysis</h3>
<div class="f-card__item">
<span class="f-card__label">Soil Type</span>
<span class="neon-badge neon-badge--lime">{results['soil_type']}</span>
</div>
<div class="f-card__item">
<span class="f-card__label">Moisture Estimate</span>
<span class="neon-badge neon-badge--cyan">{moisture_level}</span>
</div>
</div>
"""
st.markdown(soil_html, unsafe_allow_html=True)
with col3:
humidity = weather_data.get("humidity")
humidity_badge = f"{humidity}%" if humidity is not None else "β"
temperature = weather_data.get("temperature")
temperature_display = f"{temperature}Β°C" if temperature is not None else "β"
location_label = weather_data.get("location", location)
forecast_text = weather_data.get("rainfall_forecast", "Moderate Rain")
weather_html = f"""
<div class="f-card f-card--weather">
<h3 class="f-card__title">βοΈ Weather Context</h3>
<div class="f-card__item">
<span class="f-card__label">Location</span>
<span class="f-card__value">{location_label}</span>
</div>
<div class="f-card__item">
<span class="f-card__label">Temperature</span>
<span class="neon-badge neon-badge--cyan">{temperature_display}</span>
</div>
<div class="f-card__item">
<span class="f-card__label">Humidity</span>
<span class="neon-badge neon-badge--lime">{humidity_badge}</span>
</div>
<div class="f-card__item">
<span class="f-card__label">Forecast</span>
<span class="neon-badge neon-badge--cyan">{forecast_text}</span>
</div>
</div>
"""
st.markdown(weather_html, unsafe_allow_html=True)
st.markdown("---")
# Layout: Tabs for Details
tab1, tab2 = st.tabs(["πΎ Crop Recommendations (AI Report)", "π Data Visualizations"])
with tab1:
st.success("β¨ Generative AI Summary")
st.write(results["rec"])
st.info("π‘ **Pro Tip:** Since rain is expected, ensure drainage channels are clear to prevent waterlogging.")
with tab2:
st.subheader("π Rainfall Forecast (Next 7 Days)")
rainfall_series = results["weather"].get("rainfall_data", [0, 0, 0, 0, 0, 0, 0])
chart_data = pd.DataFrame({
"Day": ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"],
"Rainfall (mm)": rainfall_series
})
fig = px.bar(
chart_data,
x="Day",
y="Rainfall (mm)",
color="Rainfall (mm)",
color_continuous_scale="Bluyl",
title="7-Day Rainfall Prediction"
)
fig.update_layout(
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
st.plotly_chart(fig, use_container_width=True)