-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
727 lines (642 loc) · 26.8 KB
/
Copy pathstreamlit_app.py
File metadata and controls
727 lines (642 loc) · 26.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
"""Streamlit demo app for KisanVision AI.
Run it from the project root (once Streamlit is installed):
.venv\\Scripts\\python.exe -m streamlit run streamlit_app.py
The app lets a farmer upload a crop leaf photo (tomato, potato or
corn/maize) and shows the disease prediction from the trained model
together with simple guidance: what the disease is, its symptoms,
what to do now, and how to prevent it. Healthy leaves are clearly
shown as healthy — no disease guidance is invented for them.
After a disease prediction, the app also shows:
1. VISIBLE severity (Low / Moderate / High) from the photo's colours
via app.severity — an image-based estimate, not a laboratory
measurement, and never a trained severity model.
2. WEATHER RISK ANALYSIS from app.weather + app.weather_risk — a
transparent, rule-based assessment of how favourable the current
weather is for the detected pathogen. The weather section never
changes the AI diagnosis and is clearly labelled as a separate
estimate. Open-Meteo is used because it requires no API key.
3. AI FARMER ADVISOR from app.advisor — personalized farmer guidance
generated by an LLM based on the actual diagnosis, severity and
weather results. The LLM never performs image diagnosis and never
overrides the model's prediction. If the LLM is unavailable, the
app falls back to rule-based guidance from app.disease_info.
Supports English and Urdu output.
The demo uses the 17-class checkpoint models/best_model_17class.pt
(config.DEMO_CHECKPOINT_PATH). If that file is missing or cannot be
loaded, the app shows a friendly "model not available" screen instead
of crashing.
All the real work happens in the existing app/ package: predictions
come from app.model_handler.ModelHandler, settings from app.config,
image decoding reuses OpenCV like app.image_processing, the disease
text comes from app.disease_info, weather risk comes from
app.weather and app.weather_risk, and AI guidance comes from
app.advisor.
"""
import cv2
import numpy as np
import streamlit as st
from PIL import Image
from app import (
advisor,
config,
disease_info,
image_processing,
localization,
severity,
weather,
weather_risk,
)
from app.model_download import ensure_model_downloaded
from app.model_handler import ModelHandler
from app.localization import Language
# When the model is less sure than this, we show an extra hint to
# retake the photo instead of silently showing a weak answer.
LOW_CONFIDENCE_THRESHOLD = 60.0
def _rtl_styles(language: Language) -> str:
"""Return global RTL CSS when the active language is Urdu."""
if language != "urdu":
return ""
return """
<style>
body { direction: rtl; text-align: right; }
.kv-urdu-block {
direction: rtl;
text-align: right;
font-family: 'Noto Nastaliq Urdu', 'Jameel Noori Nastaleeq',
'Urdu Typesetting', serif;
line-height: 2;
}
.kv-urdu-block ul, .kv-urdu-block ol {
padding-right: 1.2rem;
padding-left: 0;
}
</style>
"""
def _maybe_rtl_block(content: str, language: Language) -> str:
"""Wrap content in an RTL block when showing Urdu."""
if language != "urdu":
return content
return f"<div class='kv-urdu-block'>{content}</div>"
def _render_localized_markdown(content: str, language: Language) -> None:
"""Render markdown, wrapping Urdu text in the RTL block."""
st.markdown(_maybe_rtl_block(content, language), unsafe_allow_html=True)
@st.cache_resource(show_spinner=False)
def load_model_handler() -> ModelHandler:
"""Load the trained 17-class model once and keep it for the session.
Without the cache, Streamlit would reload the model after every
button click, which would make the app feel slow.
"""
# Download the model first when running in the cloud (the .pt file is
# excluded from Git). Local development is unaffected when the file
# already exists.
ensure_model_downloaded(config.DEMO_CHECKPOINT_PATH, config.MODEL_URL)
handler = ModelHandler()
handler.load_model(config.DEMO_CHECKPOINT_PATH)
return handler
@st.cache_data(ttl=config.WEATHER_CACHE_TTL_SECONDS, show_spinner=False)
def fetch_cached_weather(city: str) -> dict:
"""Resolve a city name and fetch current weather.
The result is cached for a few minutes so changing a sidebar
control does not hammer the Open-Meteo API.
"""
return weather.get_weather_for_city(city, config.WEATHER_DEFAULT_COUNTRY_CODE)
def decode_upload(uploaded_file) -> np.ndarray:
"""Decode an uploaded file into a BGR NumPy image (OpenCV order).
Streamlit gives us the file as raw bytes in memory, so we decode
those bytes directly — the result is the same kind of array that
app.image_processing.load_image returns from disk.
"""
file_bytes = np.frombuffer(uploaded_file.getvalue(), dtype=np.uint8)
image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
if image is None:
raise ValueError("image decode failed")
return image
def render_header(language: Language) -> None:
"""The big green KisanVision AI banner at the top of the page."""
tagline = localization.text("app_tagline", language)
urdu_tagline = localization.text("app_tagline_urdu", language)
show_secondary_tagline = language == "english"
secondary_tagline_html = (
f"<p class='kv-urdu'>{urdu_tagline}</p>" if show_secondary_tagline else ""
)
st.markdown(
f"""
<style>
.kv-hero {{
background: linear-gradient(135deg, #15803d 0%, #4d7c0f 100%);
border-radius: 16px;
padding: 26px 24px 22px 24px;
margin-bottom: 10px;
}}
.kv-hero h1 {{
color: #ffffff;
font-size: 2.1rem;
font-weight: 800;
margin: 0 0 6px 0;
}}
.kv-hero p {{
color: #dcfce7;
font-size: 1.02rem;
margin: 0;
}}
.kv-hero .kv-urdu {{
color: #bbf7d0;
font-size: 0.95rem;
margin-top: 8px;
}}
.kv-diagnosis {{
font-size: 1.55rem;
font-weight: 800;
color: #166534;
margin: 0 0 4px 0;
}}
.kv-diagnosis.kv-diseased {{
color: #b91c1c;
}}
.kv-severity {{
font-size: 1.3rem;
font-weight: 800;
margin: 0 0 6px 0;
}}
.kv-severity-low {{
color: #15803d;
}}
.kv-severity-moderate {{
color: #b45309;
}}
.kv-severity-high {{
color: #b91c1c;
}}
.kv-weather-risk {{
font-size: 1.3rem;
font-weight: 800;
margin: 0 0 6px 0;
}}
.kv-weather-risk-low {{
color: #15803d;
}}
.kv-weather-risk-moderate {{
color: #b45309;
}}
.kv-weather-risk-high {{
color: #b91c1c;
}}
</style>
<div class="kv-hero">
<h1>🌾 {localization.text('app_title', language)}</h1>
<p>{tagline}</p>
{secondary_tagline_html}
</div>
""",
unsafe_allow_html=True,
)
def render_sidebar(
handler: ModelHandler | None, default_language: Language
) -> tuple[str, bool, str]:
"""Sidebar: language selector, project info, model status, weather controls.
The language radio is rendered first so the rest of the sidebar can
be shown in the currently selected language without a one-rerun lag.
Returns:
(city_name, show_weather, advisor_language) from the sidebar inputs.
"""
language_options = ["English", "اردو (Urdu)"]
default_index = 0 if default_language == "english" else 1
with st.sidebar:
st.markdown(
f"#### {localization.text('advisor_language_heading', default_language)}"
)
advisor_language = st.radio(
localization.text("language_label", default_language),
language_options,
index=default_index,
horizontal=True,
help=localization.text("language_help", default_language),
)
language = localization.parse_language(advisor_language)
st.session_state.kv_language = language
st.markdown(f"### 🌱 {localization.text('sidebar_app_name', language)}")
st.caption(
localization.text("version_caption", language, version=config.APP_VERSION)
)
st.markdown(f"#### {localization.text('model_status_heading', language)}")
if handler is None:
st.warning(localization.text("model_unavailable", language))
else:
n_crops = len(
{disease_info.get_crop(name) for name in handler.class_names}
)
st.success(
localization.text(
"model_ready",
language,
n_classes=len(handler.class_names),
n_crops=n_crops,
)
)
with st.expander(localization.text("crops_and_diseases_heading", language)):
by_crop: dict[str, list[str]] = {}
for name in handler.class_names:
by_crop.setdefault(disease_info.get_crop(name), []).append(name)
for crop, class_names in by_crop.items():
localized_crop = localization.translate_crop(crop, language)
st.markdown(f"**{localized_crop}**")
for name in class_names:
icon = "✅" if disease_info.is_healthy_class(name) else "🦠"
info = disease_info.get_disease_info(name)
localized = localization.get_localized_disease_info(
info, language
)
st.markdown(f"- {icon} {localized['display_name']}")
st.markdown("---")
st.markdown(f"#### {localization.text('weather_location_heading', language)}")
city = st.text_input(
localization.text("city_label", language),
value=config.WEATHER_DEFAULT_CITY,
help=localization.text("city_help", language),
)
show_weather = st.checkbox(
localization.text("show_weather_label", language),
value=True,
help=localization.text("show_weather_help", language),
)
st.caption(
localization.text(
"weather_provider_caption", language, provider=config.WEATHER_PROVIDER
)
)
st.markdown("---")
st.markdown(
f"**{localization.text('how_to_use_heading', language)}**\n\n"
+ localization.text("how_to_use_steps", language)
)
st.markdown("---")
st.caption(localization.text("sidebar_disclaimer", language))
return city.strip(), show_weather, advisor_language
def render_model_unavailable_screen(model_error: str | None, language: Language) -> None:
"""Friendly screen when no loadable demo checkpoint exists."""
st.info(
localization.text("model_unavailable_title", language)
+ "\n\n"
+ localization.text(
"model_unavailable_body",
language,
checkpoint=config.DEMO_CHECKPOINT_PATH.name,
)
)
if model_error:
st.error(model_error)
st.markdown(
f"#### {localization.text('model_unavailable_features_heading', language)}"
)
st.markdown(localization.text("model_unavailable_features", language))
def render_prediction_screen(
handler: ModelHandler, city: str, show_weather: bool, language: Language
) -> None:
"""The main screen: upload a leaf, get the diagnosis."""
uploaded_file = st.file_uploader(
localization.text("upload_label", language),
type=["jpg", "jpeg", "png", "bmp", "webp"],
help=localization.text("upload_help", language),
)
if uploaded_file is None:
st.markdown(localization.text("upload_prompt", language))
return
try:
image_bgr = decode_upload(uploaded_file)
except ValueError:
st.error(localization.text("decode_error", language))
return
# Run the real prediction (this is app.model_handler doing the work).
with st.spinner(localization.text("analyzing", language)):
result = handler.predict(image_bgr)
raw_info = disease_info.get_disease_info(result["predicted_class"])
healthy = disease_info.is_healthy_class(result["predicted_class"])
info = localization.get_localized_disease_info(raw_info, language)
# Visible severity is a SEPARATE, purely image-based estimate
# (app.severity). It runs after the prediction and never changes
# it. Healthy leaves do not get a severity level at all.
severity_result = None
if not healthy:
with st.spinner(localization.text("estimating_severity", language)):
severity_result = severity.estimate_visible_severity(image_bgr)
# ---- Healthy vs diseased banner ----
if healthy:
st.success(localization.text("healthy_banner", language))
else:
st.error(
localization.text(
"diseased_banner", language, disease=info["display_name"]
)
)
# ---- Result panel: photo on the left, diagnosis on the right ----
col_image, col_result = st.columns([1, 1], gap="large")
with col_image:
st.image(
Image.fromarray(image_processing.to_rgb(image_bgr)),
caption=localization.text("photo_caption", language),
use_container_width=True,
)
with col_result:
st.markdown(f"#### {localization.text('diagnosis_heading', language)}")
css_class = "kv-diagnosis" if healthy else "kv-diagnosis kv-diseased"
st.markdown(
f"<p class='{css_class}'>{info['display_name']}</p>",
unsafe_allow_html=True,
)
if healthy:
st.caption(
f"{localization.text('crop_label', language)}: {info['crop']} · "
f"{localization.text('status_label', language)}: "
f"{localization.text('healthy_status', language)} ✅"
)
else:
st.caption(
f"{localization.text('crop_label', language)}: {info['crop']} · "
f"{localization.text('cause_label', language)}: {info['type']} · "
f"{localization.text('risk_label', language)}: {info['severity']}"
)
st.metric(localization.text("confidence_metric", language), f"{result['confidence_percent']}%")
if result["confidence_percent"] < LOW_CONFIDENCE_THRESHOLD:
st.warning(localization.text("low_confidence_warning", language))
# ---- Visible severity estimate (image-based, not a lab test) ----
st.markdown(f"#### {localization.text('severity_heading', language)}")
if healthy:
st.success(localization.text("severity_healthy", language))
elif severity_result is not None and severity_result["estimated"]:
level = severity_result["label"]
localized_level = localization.translate_severity_label(level, language)
icon = {"Low": "🟢", "Moderate": "🟠", "High": "🔴"}[level]
st.markdown(
f"<p class='kv-severity kv-severity-{level.lower()}'>"
f"{icon} {localized_level}</p>",
unsafe_allow_html=True,
)
st.progress(
severity_result["affected_percent"] / 100.0,
text=localization.text(
"severity_progress_text",
language,
percent=severity_result["affected_percent"],
),
)
st.info(
f"**{localization.text('severity_meaning_label', language)}:** "
f"{localization.translate_severity_advice(level, language)}"
)
st.caption(localization.text("severity_caption", language))
else:
reason = (
severity_result["reason"]
if severity_result is not None
else localization.text("severity_not_estimated", language)
)
st.info(localization.translate_severity_reason(reason, language))
st.caption(localization.text("severity_not_estimated_caption", language))
# ---- Weather-based disease risk (separate from the AI diagnosis) ----
st.markdown(f"#### {localization.text('weather_heading', language)}")
weather_error: str | None = None
weather_data: dict | None = None
risk_result: dict | None = None
if not show_weather:
st.info(localization.text("weather_off", language))
elif not city:
st.info(localization.text("weather_enter_city", language))
else:
try:
with st.spinner(localization.text("fetching_weather", language)):
weather_data = fetch_cached_weather(city)
risk_result = weather_risk.assess_weather_risk(
result["predicted_class"], weather_data["weather"]
)
except weather.WeatherError as error:
weather_error = str(error)
if weather_error:
st.warning(localization.text("weather_error", language, error=weather_error))
elif risk_result is not None and weather_data is not None:
level = risk_result["risk_level"]
localized_level = localization.translate_weather_level(level, language)
icon = {"Low": "🟢", "Moderate": "🟠", "High": "🔴"}[level]
location = weather_data["location"]
current = weather_data["weather"]
localized_condition = localization.translate_weather_condition(
current["condition"], language
)
st.caption(
localization.text(
"weather_caption",
language,
city=location["name"],
country=location["country"],
temp=current["temperature_c"],
humidity=current["humidity_percent"],
condition=localized_condition,
)
)
localized_context = localization.translate_weather_context(
risk_result["context"], language
)
st.markdown(
f"<p class='kv-weather-risk kv-weather-risk-{level.lower()}'>"
f"{icon} {localized_context}: {localized_level}</p>",
unsafe_allow_html=True,
)
st.markdown(f"**{localization.text('weather_why_label', language)}:**")
if risk_result["factors"]:
for factor in risk_result["factors"]:
st.markdown(
f"- {localization.translate_weather_factor(factor, language)}"
)
else:
st.markdown(localization.text("weather_why_none", language))
# Defensive: some Streamlit Cloud deployments may cache an older
# app/localization.py that lacks translate_weather_advice(). In that
# case fall back to the raw English advice rather than crashing.
translate_weather_advice = getattr(
localization, "translate_weather_advice", None
)
if translate_weather_advice is not None:
localized_advice = translate_weather_advice(
risk_result["advice"], language
)
else:
localized_advice = risk_result["advice"]
st.info(
f"**{localization.text('weather_advice_label', language)}:** "
f"{localized_advice}"
)
st.caption(localization.text("weather_caption_footer", language))
# ---- AI Farmer Advisor (generative guidance) ----
st.markdown(f"#### 🤖 {localization.text('advisor_heading', language)}")
with st.spinner(localization.text("generating_guidance", language)):
advice = advisor.get_advice(
predicted_class=result["predicted_class"],
confidence_percent=result["confidence_percent"],
severity_result=severity_result,
weather_data=weather_data,
risk_result=risk_result,
language=language,
)
if not config.LLM_API_KEY:
st.info(
localization.text(
"llm_fallback", language, env_var=config.LLM_API_KEY_ENV
)
)
summary_text = advice.get("summary", advice.get("urdu", ""))
if language == "urdu":
st.markdown(
localization.rtl_block(
f"<strong>{localization.text('summary_label', language)}:</strong> "
f"{summary_text}"
),
unsafe_allow_html=True,
)
else:
st.markdown(f"**{localization.text('summary_label', language)}:** {summary_text}")
with st.expander(localization.text("immediate_actions_expander", language)):
actions = advice.get("immediate_actions", [])
if actions:
if language == "urdu":
st.markdown(localization.rtl_list(actions), unsafe_allow_html=True)
else:
for action in actions:
st.markdown(f"- {action}")
else:
st.markdown(localization.text("no_actions", language))
with st.expander(localization.text("prevention_expander", language)):
prevention = advice.get("prevention", [])
if prevention:
if language == "urdu":
st.markdown(localization.rtl_list(prevention), unsafe_allow_html=True)
else:
for item in prevention:
st.markdown(f"- {item}")
else:
st.markdown(localization.text("no_prevention", language))
with st.expander(localization.text("monitoring_expander", language)):
monitoring = advice.get("monitoring", [])
if monitoring:
if language == "urdu":
st.markdown(localization.rtl_list(monitoring), unsafe_allow_html=True)
else:
for item in monitoring:
st.markdown(f"- {item}")
else:
st.markdown(localization.text("no_monitoring", language))
with st.expander(localization.text("expert_help_expander", language)):
expert_help = advice.get("expert_help", "")
if expert_help:
if language == "urdu":
st.markdown(
localization.rtl_block(expert_help), unsafe_allow_html=True
)
else:
st.markdown(expert_help)
else:
st.markdown(localization.text("no_expert_help", language))
if language == "urdu":
st.markdown(
localization.rtl_block(
f"<em>{localization.text('advisor_footer', language)}</em>"
),
unsafe_allow_html=True,
)
else:
st.caption(localization.text("advisor_footer", language))
# ---- Top-3 predictions as progress bars ----
st.markdown(f"#### {localization.text('top_predictions_heading', language)}")
for item in result["top_3"]:
item_info = disease_info.get_disease_info(item["class"])
localized_item = localization.get_localized_disease_info(item_info, language)
icon = "✅" if disease_info.is_healthy_class(item["class"]) else "🦠"
st.progress(
item["confidence_percent"] / 100.0,
text=f"{icon} {localized_item['display_name']} — {item['confidence_percent']}%",
)
# ---- Guidance tabs ----
st.markdown("---")
if healthy:
tabs = st.tabs(
[
f"🩺 {localization.text('tab_about_healthy', language)}",
f"🔍 {localization.text('tab_watch_for', language)}",
f"✅ {localization.text('tab_care', language)}",
f"🛡️ {localization.text('tab_prevention', language)}",
]
)
else:
tabs = st.tabs(
[
f"🩺 {localization.text('tab_about', language)}",
f"🔍 {localization.text('tab_symptoms', language)}",
f"✅ {localization.text('tab_actions', language)}",
f"🛡️ {localization.text('tab_prevention', language)}",
]
)
about_tab, symptoms_tab, actions_tab, prevention_tab = tabs
with about_tab:
if language == "urdu":
st.markdown(
localization.rtl_block(info["about"]), unsafe_allow_html=True
)
else:
st.write(info["about"])
with symptoms_tab:
if language == "urdu":
st.markdown(localization.rtl_list(info["symptoms"]), unsafe_allow_html=True)
else:
for symptom in info["symptoms"]:
st.markdown(f"- {symptom}")
with actions_tab:
heading = (
localization.text("actions_heading_healthy", language)
if healthy
else localization.text("actions_heading_diseased", language)
)
if language == "urdu":
st.markdown(
localization.rtl_block(f"<strong>{heading}</strong>"),
unsafe_allow_html=True,
)
st.markdown(localization.rtl_list(info["actions"]), unsafe_allow_html=True)
else:
st.markdown(f"**{heading}**")
for action in info["actions"]:
st.markdown(f"- {action}")
with prevention_tab:
if language == "urdu":
st.markdown(localization.rtl_list(info["prevention"]), unsafe_allow_html=True)
else:
for tip in info["prevention"]:
st.markdown(f"- {tip}")
def main() -> None:
# Mobile-friendly: a centered layout stacks cleanly on phones.
st.set_page_config(
page_title="KisanVision AI",
page_icon="🌱",
layout="centered",
)
# Load the 17-class demo model. In the cloud the .pt file is first
# downloaded from KISANVISION_MODEL_URL if it is not already cached
# locally. If anything goes wrong, the app shows a friendly
# "model not available" screen instead of crashing.
handler: ModelHandler | None = None
model_error: str | None = None
try:
handler = load_model_handler()
except Exception as error:
model_error = str(error)
# The sidebar radio determines the language for the whole result UI.
# Default to English until the user explicitly chooses Urdu.
default_language = st.session_state.get("kv_language", "english")
city, show_weather, advisor_language = render_sidebar(handler, default_language)
language = localization.parse_language(advisor_language)
# Inject RTL styles once the language is known.
st.markdown(_rtl_styles(language), unsafe_allow_html=True)
render_header(language)
if handler is None:
render_model_unavailable_screen(model_error, language)
else:
render_prediction_screen(handler, city, show_weather, language)
if __name__ == "__main__":
main()