-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2312 lines (2080 loc) · 92.2 KB
/
Copy pathapp.py
File metadata and controls
2312 lines (2080 loc) · 92.2 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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from datetime import date, timedelta
from html import escape
from time import perf_counter
from uuid import uuid4
from pprint import pformat
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
from mystripes.api import build_period_indicator_specs
from mystripes.cds import (
CDSCredentialsMissingError,
CDSRequestError,
DEFAULT_CDSAPI_URL,
clear_local_cds_config,
load_local_cds_config,
resolve_cds_config,
save_local_cds_config,
)
from mystripes.climate_stack import (
build_climate_batch_plan,
build_location_climate_requests,
climate_stack_note,
estimate_climate_downloads,
fetch_saved_climate_series_batch,
get_climate_dataset_window,
preflight_download_message,
)
from mystripes.cookie_consent import (
COOKIE_CONSENT_COOKIE_NAME,
COOKIE_CONSENT_MAX_AGE_SECONDS,
build_cookie_consent_payload,
cookie_consent_choice,
decode_cookie_consent_value,
encode_cookie_consent_value,
optional_cookie_consent_granted,
)
from mystripes.geocoding import search_places
from mystripes.gistemp import (
NASA_GISTEMP_GLOBAL_MEAN_URL,
average_global_warming_for_period,
load_global_mean_estimates,
)
from mystripes.models import CDSConfig
from mystripes.notices import (
CONTRIBUTING_GUIDE_URL,
PROJECT_ISSUES_URL,
PROJECT_REPOSITORY_URL,
ERA5_MONTHLY_DATASET_DOI,
ERA5_MONTHLY_DATASET_NAME,
ERA5_REFERENCE_CITATION,
ERA5_MONTHLY_DATASET_URL,
ERA5_LAND_MONTHLY_DATASET_DOI,
ERA5_LAND_REFERENCE_CITATION,
ERA5_LAND_MONTHLY_DATASET_NAME,
ERA5_LAND_MONTHLY_DATASET_URL,
GENERATED_GRAPHICS_CC0_NOTICE,
NASA_GISTEMP_REFERENCE_CITATION,
NASA_GISTEMP_SHORT_SOURCE_CREDIT,
NASA_GISTEMP_SOURCE_CREDIT,
NASA_GISTEMP_WEB_CITATION_GUIDANCE,
NASA_GISTEMP_WEB_CITATION_TEMPLATE,
SHOW_YOUR_STRIPES_CREDIT,
SHOW_YOUR_STRIPES_URL,
SOFTWARE_MIT_NOTICE,
TWCR_ACKNOWLEDGEMENT_TEXT,
TWCR_FOUNDATIONAL_REFERENCE_CITATION,
TWCR_MONTHLY_DATASET_NAME,
TWCR_MONTHLY_DATASET_URL,
TWCR_REFERENCE_CITATION,
copernicus_credit_notice,
)
from mystripes.plotting import export_figure_bytes, render_stripes_figure
from mystripes.refresh import latest_data_end_that_can_change_stripes
from mystripes.processing import (
aggregate_daily_series_to_stripes,
build_merged_daily_series,
build_period_report_tables,
build_periods_from_entries,
)
from mystripes.storyline_cookie_component import sync_storyline_cookie_store
from mystripes.storylines import (
LOCAL_STORYLINES_PATH,
STORYLINE_COOKIE_MAX_AGE_SECONDS,
STORYLINE_COOKIE_PREFIX,
encode_storyline_cookie_value,
load_cookie_storylines,
load_local_storylines,
remove_local_storyline,
save_local_storyline,
serialize_storyline_payload,
storyline_cookie_name,
storyline_storage_backend_from_host,
)
st.set_page_config(
page_title="MyStripes",
page_icon="||",
layout="wide",
)
@st.cache_data(show_spinner=False, ttl=24 * 60 * 60)
def cached_dataset_window():
return get_climate_dataset_window()
@st.cache_data(show_spinner=False, ttl=24 * 60 * 60)
def cached_search_places(query: str, geoapify_api_key: str):
return search_places(query, geoapify_api_key=geoapify_api_key or None)
@st.cache_data(show_spinner=False, ttl=24 * 60 * 60)
def cached_gistemp_global_mean_estimates() -> pd.DataFrame:
return load_global_mean_estimates()
def _storyline_storage_backend() -> str:
headers = getattr(st.context, "headers", None)
host = ""
if headers is not None:
host = str(headers.get("host") or headers.get("Host") or "")
return storyline_storage_backend_from_host(host)
def _cookie_storyline_values() -> dict[str, str]:
raw_values = st.session_state.get("storyline_cookie_values", {})
if not isinstance(raw_values, dict):
return {}
return {str(name): str(value) for name, value in raw_values.items()}
def _cookie_consent_payload_from_session() -> dict[str, object] | None:
raw_payload = st.session_state.get("cookie_consent_payload")
return dict(raw_payload) if isinstance(raw_payload, dict) else None
def _cloud_cookie_consent_choice() -> str | None:
return cookie_consent_choice(_cookie_consent_payload_from_session())
def _cloud_storyline_storage_enabled() -> bool:
return optional_cookie_consent_granted(_cookie_consent_payload_from_session())
def _load_saved_storylines(storage_backend: str) -> dict[str, dict[str, object]]:
if storage_backend == "cookie":
if not _cloud_storyline_storage_enabled():
return {}
return load_cookie_storylines(_cookie_storyline_values())
return load_local_storylines()
def _set_storyline_feedback(kind: str, message: str) -> None:
st.session_state.storyline_feedback = {"kind": kind, "message": message}
def _render_storyline_feedback(sidebar) -> None:
feedback = st.session_state.pop("storyline_feedback", None)
if not isinstance(feedback, dict):
return
message = str(feedback.get("message", "")).strip()
if not message:
return
kind = str(feedback.get("kind", "info"))
if kind == "success":
sidebar.success(message)
elif kind == "error":
sidebar.error(message)
else:
sidebar.info(message)
def _queue_cookie_storyline_operation(
*,
action: str,
storyline_name: str,
cookie_name: str,
cookie_value: str | None = None,
) -> None:
if action == "save":
if cookie_value is None:
raise ValueError("Missing cookie value for save operation.")
cookie_operations = [
{
"action": "set",
"cookie_name": cookie_name,
"cookie_value": cookie_value,
"max_age_seconds": STORYLINE_COOKIE_MAX_AGE_SECONDS,
}
]
elif action == "remove":
cookie_operations = [{"action": "remove", "cookie_name": cookie_name}]
else:
raise ValueError(f"Unsupported storyline cookie action: {action}")
st.session_state.pending_cookie_store_operation = {
"id": uuid4().hex,
"kind": "storyline",
"action": action,
"storyline_name": storyline_name,
"cookie_operations": cookie_operations,
}
def _queue_cookie_consent_operation(choice: str) -> None:
payload = build_cookie_consent_payload(choice)
cookie_operations: list[dict[str, object]] = [
{
"action": "set",
"cookie_name": COOKIE_CONSENT_COOKIE_NAME,
"cookie_value": encode_cookie_consent_value(payload),
"max_age_seconds": COOKIE_CONSENT_MAX_AGE_SECONDS,
}
]
if payload["choice"] == "rejected":
cookie_operations.append(
{
"action": "remove_prefix",
"cookie_prefix": STORYLINE_COOKIE_PREFIX,
}
)
st.session_state.pending_cookie_store_operation = {
"id": uuid4().hex,
"kind": "consent",
"choice": payload["choice"],
"cookie_operations": cookie_operations,
}
def _queue_storyline_widget_update(key: str, value: object) -> None:
st.session_state[f"_pending_{key}"] = "" if value is None else str(value)
def _apply_pending_storyline_widget_updates() -> None:
for key in ("storyline_name", "saved_storyline_name"):
pending_key = f"_pending_{key}"
if pending_key in st.session_state:
st.session_state[key] = st.session_state.pop(pending_key)
def _sync_cookie_store() -> None:
previous_choice = _cloud_cookie_consent_choice()
monitor_storyline_cookies = previous_choice == "accepted"
result = sync_storyline_cookie_store(
monitored_cookie_names=[COOKIE_CONSENT_COOKIE_NAME],
monitored_cookie_prefixes=[STORYLINE_COOKIE_PREFIX] if monitor_storyline_cookies else [],
operation=st.session_state.get("pending_cookie_store_operation"),
key="storyline_cookie_store",
)
if not isinstance(result, dict):
return
raw_cookies = result.get("cookies", {})
normalized_cookies = {}
if isinstance(raw_cookies, dict):
normalized_cookies = {
str(name): str(value)
for name, value in raw_cookies.items()
}
st.session_state.storyline_cookie_values = {
name: value
for name, value in normalized_cookies.items()
if name.startswith(STORYLINE_COOKIE_PREFIX)
}
consent_cookie_value = normalized_cookies.get(COOKIE_CONSENT_COOKIE_NAME, "")
if consent_cookie_value:
try:
st.session_state.cookie_consent_payload = decode_cookie_consent_value(consent_cookie_value)
except ValueError:
st.session_state.cookie_consent_payload = None
else:
st.session_state.cookie_consent_payload = None
pending_operation = st.session_state.get("pending_cookie_store_operation")
current_choice = _cloud_cookie_consent_choice()
if not isinstance(pending_operation, dict):
if current_choice == "accepted" and not monitor_storyline_cookies:
st.rerun()
return
completed_operation_id = str(result.get("completed_operation_id") or "")
if completed_operation_id != str(pending_operation.get("id") or ""):
return
st.session_state.pending_cookie_store_operation = None
error_message = str(result.get("error") or "").strip()
if error_message:
_set_storyline_feedback("error", error_message)
st.rerun()
operation_kind = str(pending_operation.get("kind") or "")
if operation_kind == "consent":
if current_choice == "accepted":
_set_storyline_feedback("success", "Optional convenience cookies enabled in this browser.")
else:
st.session_state.storyline_cookie_values = {}
_queue_storyline_widget_update("saved_storyline_name", "")
_set_storyline_feedback(
"info",
"Optional convenience cookies disabled. Any saved cloud story lines were removed from this browser.",
)
st.rerun()
storyline_name = str(pending_operation.get("storyline_name") or "").strip()
action = str(pending_operation.get("action") or "")
if action == "save":
_queue_storyline_widget_update("storyline_name", storyline_name)
_queue_storyline_widget_update("saved_storyline_name", storyline_name)
_set_storyline_feedback("success", f"Saved story line `{storyline_name}`.")
elif action == "remove":
if st.session_state.storyline_name == storyline_name:
_queue_storyline_widget_update("storyline_name", "")
_queue_storyline_widget_update("saved_storyline_name", "")
_set_storyline_feedback("success", f"Removed story line `{storyline_name}`.")
st.rerun()
def _current_storyline_period_entries() -> list[dict[str, object]]:
synchronized_entries: list[dict[str, object]] = []
entries = st.session_state.period_entries
for index, base_entry in enumerate(entries):
entry = dict(base_entry)
place_query_key = f"place_query_{index}"
latitude_key = f"latitude_{index}"
longitude_key = f"longitude_{index}"
end_date_key = f"end_date_{index}"
indicator_label_key = f"indicator_label_{index}"
show_indicator_key = f"show_indicator_{index}"
if place_query_key in st.session_state:
entry["place_query"] = str(st.session_state[place_query_key])
if latitude_key in st.session_state:
entry["latitude_text"] = str(st.session_state[latitude_key])
if longitude_key in st.session_state:
entry["longitude_text"] = str(st.session_state[longitude_key])
if indicator_label_key in st.session_state:
entry["indicator_label"] = str(st.session_state[indicator_label_key])
if show_indicator_key in st.session_state:
entry["show_indicator"] = bool(st.session_state[show_indicator_key])
if index < len(entries) - 1 and end_date_key in st.session_state:
entry["end_date"] = st.session_state[end_date_key]
elif index == len(entries) - 1:
entry["end_date"] = None
synchronized_entries.append(entry)
return synchronized_entries
def _clear_period_widget_state() -> None:
for key in list(st.session_state.keys()):
if key.startswith((
"_pending_geocode_search_",
"custom_label_",
"end_date_",
"geocode_choice_",
"geocode_results_",
"indicator_label_",
"latitude_",
"longitude_",
"place_query_",
"show_indicator_",
)):
del st.session_state[key]
def _apply_storyline_to_session(payload: dict[str, object], analysis_end: date) -> None:
_clear_period_widget_state()
loaded_birth_date = payload["birth_date"]
if not isinstance(loaded_birth_date, date):
loaded_birth_date = date.fromisoformat(str(loaded_birth_date))
clamped_birth_date = min(max(loaded_birth_date, date(1900, 1, 1)), analysis_end)
raw_entries = payload["period_entries"]
if not isinstance(raw_entries, list) or not raw_entries:
raw_entries = [_blank_entry()]
entries: list[dict[str, object]] = []
for raw_entry in raw_entries:
entry = _blank_entry()
entry.update(dict(raw_entry))
indicator_label = str(entry.get("indicator_label", entry.get("custom_label", "")) or "")
entry["indicator_label"] = indicator_label
entry["show_indicator"] = bool(entry.get("show_indicator", False) or indicator_label)
entries.append(entry)
st.session_state.birth_date = clamped_birth_date
st.session_state.period_entries = entries
for index, entry in enumerate(entries):
st.session_state[f"place_query_{index}"] = str(entry.get("place_query", "") or "")
st.session_state[f"latitude_{index}"] = str(entry.get("latitude_text", "") or "")
st.session_state[f"longitude_{index}"] = str(entry.get("longitude_text", "") or "")
st.session_state[f"indicator_label_{index}"] = str(entry.get("indicator_label", "") or "")
st.session_state[f"show_indicator_{index}"] = bool(entry.get("show_indicator", False))
if index < len(entries) - 1 and entry.get("end_date") is not None:
st.session_state[f"end_date_{index}"] = entry["end_date"]
def _format_progress_duration(total_seconds: float) -> str:
rounded_seconds = max(0, int(round(total_seconds)))
minutes, seconds = divmod(rounded_seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours:
return f"{hours:d}:{minutes:02d}:{seconds:02d}"
return f"{minutes:02d}:{seconds:02d}"
def _format_progress_rate(rate_per_minute: float, unit_label: str) -> str:
if rate_per_minute >= 10:
value_text = f"{rate_per_minute:.0f}"
elif rate_per_minute >= 1:
value_text = f"{rate_per_minute:.1f}"
else:
value_text = f"{rate_per_minute:.2f}"
return f"{value_text} {unit_label}/min"
def _request_batch_label(event: dict[str, object]) -> str:
parts: list[str] = []
request_index = int(event.get("request_index") or 0)
request_count = int(event.get("request_count") or 0)
if request_index and request_count:
parts.append(f"batch {request_index}/{request_count}")
request_year_start = str(event.get("request_year_start") or "")
request_year_end = str(event.get("request_year_end") or "")
if request_year_start and request_year_end:
if request_year_start == request_year_end:
parts.append(request_year_start)
else:
parts.append(f"{request_year_start}-{request_year_end}")
month_count = int(event.get("month_count") or 0)
if month_count:
noun = "month" if month_count == 1 else "months"
parts.append(f"{month_count} {noun}")
return ", ".join(parts)
def _describe_temperature_fetch_event(event: dict[str, object]) -> str:
stage = str(event.get("stage") or "")
purpose = str(event.get("purpose") or "source")
range_index = int(event.get("range_index") or 0)
range_count = int(event.get("range_count") or 0)
range_start = str(event.get("range_start") or "")
range_end = str(event.get("range_end") or "")
dataset_label = str(event.get("dataset_label") or event.get("source_label") or "climate data")
request_origin = str(event.get("request_origin") or "")
location_label = str(event.get("location_label") or "")
cache_scope = str(event.get("cache_scope") or "")
if stage == "batch_plan":
return (
f"Planned {int(event.get('total_shared_tasks') or 0)} shared source tasks for "
f"{int(event.get('total_locations') or 0)} locations."
)
if stage == "shared_task_started":
source_label = str(event.get("source_label") or dataset_label)
return f"Starting shared {source_label} preparation."
if stage == "shared_task_finished":
source_label = str(event.get("source_label") or dataset_label)
return f"Finished shared {source_label} preparation."
if stage == "location_started":
return f"Building the combined climate timeline for {location_label or 'one location'}."
if stage == "location_finished":
return f"{location_label or 'One location'} is ready."
if stage == "timeline_cache_hit":
return f"Using the saved {dataset_label} timeline from local cache."
if stage == "timeline_fetch_plan":
missing_range_count = int(event.get("missing_range_count") or 0)
noun = "segment" if missing_range_count == 1 else "segments"
if bool(event.get("has_cached_data")):
return f"Refreshing {missing_range_count} missing {dataset_label} timeline {noun}."
return f"Preparing {missing_range_count} {dataset_label} timeline {noun}."
if stage == "missing_range_started":
return f"Timeline segment {range_index}/{range_count}: {range_start} to {range_end}."
if stage == "request_cache_hit":
if cache_scope == "shared_grid":
return f"Using a saved shared {dataset_label} grid request."
if cache_scope == "shared_grid_window":
return f"Using a saved shared {dataset_label} bbox window."
if purpose == "calibration":
return f"Using a saved {dataset_label} calibration window."
return f"Using a saved {dataset_label} request chunk for {range_start} to {range_end}."
if stage == "request_plan":
request_count = int(event.get("request_count") or 0)
if str(event.get("dataset") or "").startswith("reanalysis-era5"):
noun = "batch" if request_count == 1 else "batches"
else:
noun = "bbox request" if request_count == 1 else "bbox requests"
if purpose == "calibration":
return f"Preparing {request_count} {dataset_label} calibration {noun}."
return f"Need {request_count} {dataset_label} request {noun} for this timeline segment."
if stage == "request_started":
batch_label = _request_batch_label(event)
request_scope = str(event.get("request_scope") or "")
if request_scope == "bbox_window":
batch_label = batch_label or "bbox window"
if request_origin == "local_cache":
return (
f"Reading saved {dataset_label} {batch_label}."
if batch_label
else f"Reading saved {dataset_label} data."
)
if purpose == "calibration":
return (
f"Downloading {dataset_label} calibration {batch_label}."
if batch_label
else f"Downloading {dataset_label} calibration data."
)
return (
f"Downloading {dataset_label} {batch_label}."
if batch_label
else f"Downloading {dataset_label} data."
)
if stage == "request_finished":
batch_label = _request_batch_label(event)
request_scope = str(event.get("request_scope") or "")
if request_scope == "bbox_window":
batch_label = batch_label or "bbox window"
if request_origin == "local_cache":
return (
f"Finished reading saved {dataset_label} {batch_label}."
if batch_label
else f"Finished reading saved {dataset_label} data."
)
if purpose == "calibration":
return (
f"Finished {dataset_label} calibration {batch_label}."
if batch_label
else f"Finished a {dataset_label} calibration step."
)
return (
f"Finished {dataset_label} {batch_label}."
if batch_label
else f"Finished a {dataset_label} request step."
)
if stage == "request_failed":
message = str(event.get("message") or "")
return message or "A CDS request failed."
if stage == "request_recovery":
message = str(event.get("message") or "")
return message or f"Retrying {dataset_label} after a cache read problem."
if stage == "point_fetch_completed":
if purpose == "calibration":
return f"Prepared the {dataset_label} calibration monthly series."
return f"Prepared monthly {dataset_label} data for the current timeline segment."
if stage == "missing_range_finished":
return f"Finished timeline segment {range_index}/{range_count}: {range_start} to {range_end}."
if stage == "timeline_fetch_completed":
return "Saved the refreshed timeline to the local cache."
if stage == "source_started":
source_label = str(event.get("source_label") or "Climate source")
return f"Switching to {source_label} for {event.get('source_start')} to {event.get('source_end')}."
if stage == "source_finished":
source_label = str(event.get("source_label") or "Climate source")
return f"Finished {source_label} for this time slice."
return "Loading climate data..."
def _render_temperature_fetch_progress(
placeholder,
*,
total_locations: int,
completed_locations: int,
total_shared_tasks: int,
completed_shared_tasks: int,
active_locations: int,
stage_label: str,
current_detail: str,
recent_updates: list[str],
started_at: float,
active: bool,
) -> None:
normalized_total_locations = max(1, total_locations)
location_fraction = min(1.0, completed_locations / normalized_total_locations)
shared_fraction = 1.0 if total_shared_tasks == 0 else min(1.0, completed_shared_tasks / total_shared_tasks)
overall_fraction = location_fraction if total_shared_tasks == 0 else min(
1.0,
(0.65 * shared_fraction) + (0.35 * location_fraction),
)
display_fraction = overall_fraction
if active:
display_fraction = max(display_fraction, min(0.04, 1.0 / max(1, normalized_total_locations + total_shared_tasks)))
elapsed_seconds = perf_counter() - started_at
rate_parts: list[str] = []
if elapsed_seconds > 0 and completed_locations > 0:
rate_parts.append(_format_progress_rate(completed_locations * 60.0 / elapsed_seconds, "locations"))
if elapsed_seconds > 0 and completed_shared_tasks > 0:
rate_parts.append(_format_progress_rate(completed_shared_tasks * 60.0 / elapsed_seconds, "shared tasks"))
title = "Preparing climate-data timelines"
if stage_label:
title = stage_label
if not active and completed_locations >= total_locations:
title = f"Loaded {completed_locations}/{normalized_total_locations} locations"
status_line = current_detail or "Loading climate data..."
summary_left = f"{completed_locations}/{normalized_total_locations} places ready"
summary_right = " | ".join(rate_parts) if rate_parts else "Waiting for the first completed step..."
elapsed_text = f"Elapsed {_format_progress_duration(elapsed_seconds)}"
width_percent = max(0.0, min(100.0, display_fraction * 100.0))
active_class = " mystripes-progress-fill-active" if active else ""
shared_summary = (
f"{completed_shared_tasks}/{total_shared_tasks} shared source tasks ready"
if total_shared_tasks
else "No shared source downloads needed"
)
active_summary = (
f"{active_locations} location timeline{'s' if active_locations != 1 else ''} active"
if active
else "No active location tasks"
)
updates_html = ""
if recent_updates:
items = "".join(f"<li>{escape(update)}</li>" for update in recent_updates[-4:])
updates_html = f'<ul class="mystripes-progress-updates">{items}</ul>'
html = f'''
<style>
@keyframes mystripes-progress-shimmer {{
from {{ background-position: 0 0; }}
to {{ background-position: 1.6rem 0; }}
}}
.mystripes-progress-card {{
border: 1px solid rgba(148, 163, 184, 0.45);
border-radius: 0.9rem;
padding: 0.9rem 1rem;
margin: 0.35rem 0 1rem 0;
background: linear-gradient(180deg, rgba(248, 250, 252, 0.96), rgba(241, 245, 249, 0.96));
}}
.mystripes-progress-kicker {{
font-size: 0.78rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #475569;
}}
.mystripes-progress-title {{
font-size: 1rem;
font-weight: 600;
color: #0f172a;
margin-top: 0.15rem;
}}
.mystripes-progress-detail {{
color: #334155;
margin-top: 0.2rem;
}}
.mystripes-progress-track {{
position: relative;
overflow: hidden;
height: 0.8rem;
margin: 0.75rem 0 0.55rem 0;
border-radius: 999px;
background: rgba(148, 163, 184, 0.22);
}}
.mystripes-progress-fill {{
height: 100%;
border-radius: 999px;
background: linear-gradient(90deg, #0f766e, #38bdf8);
}}
.mystripes-progress-fill-active {{
background-image:
linear-gradient(135deg,
rgba(15, 118, 110, 0.95) 0%,
rgba(15, 118, 110, 0.95) 25%,
rgba(56, 189, 248, 0.95) 25%,
rgba(56, 189, 248, 0.95) 50%,
rgba(15, 118, 110, 0.95) 50%,
rgba(15, 118, 110, 0.95) 75%,
rgba(56, 189, 248, 0.95) 75%,
rgba(56, 189, 248, 0.95) 100%);
background-size: 1.6rem 1.6rem;
animation: mystripes-progress-shimmer 0.9s linear infinite;
}}
.mystripes-progress-meta {{
display: flex;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
font-size: 0.84rem;
color: #475569;
}}
.mystripes-progress-updates {{
margin: 0.7rem 0 0 1rem;
color: #475569;
font-size: 0.84rem;
}}
.mystripes-progress-updates li + li {{
margin-top: 0.2rem;
}}
</style>
<div class="mystripes-progress-card">
<div class="mystripes-progress-kicker">Climate-data load progress</div>
<div class="mystripes-progress-title">{escape(title)}</div>
<div class="mystripes-progress-detail">{escape(status_line)}</div>
<div class="mystripes-progress-track">
<div class="mystripes-progress-fill{active_class}" style="width: {width_percent:.1f}%;"></div>
</div>
<div class="mystripes-progress-meta">
<span>{escape(summary_left)}</span>
<span>{escape(shared_summary)}</span>
<span>{escape(active_summary)}</span>
<span>{escape(summary_right)}</span>
<span>{escape(elapsed_text)}</span>
</div>
{updates_html}
</div>
'''
placeholder.markdown(html, unsafe_allow_html=True)
def _cookie_consent_copy() -> str:
return (
"On Streamlit Community Cloud, MyStripes can optionally store your story line name "
"and place-period timeline entries in browser cookies so you can load them later. "
"The app does not collect or retain user data for itself. Any cookie-stored data "
"stays on your machine and only aids convenience. MyStripes is open-source on "
f"[GitHub]({PROJECT_REPOSITORY_URL})."
)
def _cookie_storage_note() -> str:
return (
"Saved cloud story lines use optional browser cookies that stay on this machine. "
"The app does not collect or retain user data for itself, and the cookies only aid "
"convenience."
)
def _render_cookie_consent_banner(storage_backend: str) -> None:
if storage_backend != "cookie" or _cloud_cookie_consent_choice() is not None:
return
with st.container(border=True):
st.markdown("**Cookie choice for saved story lines**")
st.markdown(_cookie_consent_copy())
st.caption(
"These optional convenience cookies are off until you choose below. Rejecting "
"keeps save-load-remove hidden on Streamlit Community Cloud. You can change this "
"later in Cookie settings in the sidebar."
)
if st.session_state.get("pending_cookie_store_operation"):
st.caption("Updating the cookie choice in this browser...")
accept_column, reject_column = st.columns(2)
if accept_column.button("Allow convenience cookies", key="cookie_banner_accept"):
_queue_cookie_consent_operation("accepted")
st.rerun()
if reject_column.button("Reject optional cookies", key="cookie_banner_reject"):
_queue_cookie_consent_operation("rejected")
st.rerun()
def _render_cookie_settings(sidebar, storage_backend: str) -> None:
if storage_backend != "cookie":
return
consent_choice = _cloud_cookie_consent_choice()
with sidebar.expander("Cookie settings", expanded=consent_choice is None):
st.markdown(_cookie_consent_copy())
st.caption(
"You can change this choice at any time here. Rejecting optional convenience "
"cookies removes saved cloud story lines from this browser."
)
if consent_choice == "accepted":
st.success("Optional convenience cookies are enabled in this browser.")
elif consent_choice == "rejected":
st.info("Optional convenience cookies are disabled in this browser.")
else:
st.warning("Optional convenience cookies are not enabled yet.")
if st.session_state.get("pending_cookie_store_operation"):
st.caption("Updating the cookie choice in this browser...")
accept_column, reject_column = st.columns(2)
if accept_column.button("Allow convenience cookies", key="cookie_settings_accept"):
_queue_cookie_consent_operation("accepted")
st.rerun()
if reject_column.button("Reject optional cookies", key="cookie_settings_reject"):
_queue_cookie_consent_operation("rejected")
st.rerun()
def _render_storyline_panel(sidebar, analysis_end: date, storage_backend: str) -> None:
_render_storyline_feedback(sidebar)
_apply_pending_storyline_widget_updates()
try:
saved_storylines = _load_saved_storylines(storage_backend)
except Exception as exc:
sidebar.error(f"Could not load saved story lines: {exc}")
saved_storylines = {}
cloud_storage_enabled = storage_backend != "cookie" or _cloud_storyline_storage_enabled()
expander_expanded = bool(saved_storylines) or not cloud_storage_enabled
with sidebar.expander("Story lines", expanded=expander_expanded):
st.caption(
"Save, reload, and remove place-based story lines so you can revisit the same "
"timeline later."
)
if storage_backend == "cookie" and not cloud_storage_enabled:
if _cloud_cookie_consent_choice() == "rejected":
st.info(
"Optional convenience cookies are currently disabled in this browser. Use "
"Cookie settings above if you want to save or reload story lines here."
)
else:
st.info(
"On Streamlit Community Cloud, save-load-remove uses optional convenience "
"cookies. Choose in Cookie settings above if you want this feature in this "
"browser."
)
st.caption(_cookie_storage_note())
return
st.text_input(
"Story line name",
key="storyline_name",
placeholder="Life in Vienna, Berlin, Amsterdam...",
help="Used to identify the saved story line when loading it later.",
)
selected_storyline_name = ""
if saved_storylines:
saved_names = list(saved_storylines)
if st.session_state.saved_storyline_name not in saved_names:
st.session_state.saved_storyline_name = saved_names[0]
selected_storyline_name = st.selectbox(
"Saved story lines",
options=saved_names,
key="saved_storyline_name",
)
else:
st.caption("No saved story lines yet.")
action_columns = st.columns(3)
save_requested = action_columns[0].button("Save", key="save_storyline")
load_requested = action_columns[1].button(
"Load",
key="load_storyline",
disabled=not selected_storyline_name,
)
remove_requested = action_columns[2].button(
"Remove",
key="remove_storyline",
disabled=not selected_storyline_name,
)
if storage_backend == "file":
st.caption(f"Local story lines are written to `{LOCAL_STORYLINES_PATH}` on this machine.")
else:
st.caption(_cookie_storage_note())
if st.session_state.get("pending_cookie_store_operation"):
st.caption("Syncing saved story lines in this browser...")
if save_requested:
try:
payload = serialize_storyline_payload(
name=st.session_state.storyline_name,
birth_date=st.session_state.birth_date,
period_entries=_current_storyline_period_entries(),
include_boundary_geojson=storage_backend == "file",
)
if storage_backend == "file":
_queue_storyline_widget_update("storyline_name", payload["name"])
_queue_storyline_widget_update("saved_storyline_name", payload["name"])
save_local_storyline(payload)
_set_storyline_feedback("success", f"Saved story line `{payload['name']}`.")
st.rerun()
_queue_cookie_storyline_operation(
action="save",
storyline_name=str(payload["name"]),
cookie_name=storyline_cookie_name(payload["name"]),
cookie_value=encode_storyline_cookie_value(payload),
)
st.rerun()
except Exception as exc:
st.error(str(exc))
if load_requested and selected_storyline_name:
payload = saved_storylines[selected_storyline_name]
_apply_storyline_to_session(payload, analysis_end)
_queue_storyline_widget_update("storyline_name", selected_storyline_name)
_queue_storyline_widget_update("saved_storyline_name", selected_storyline_name)
_set_storyline_feedback("success", f"Loaded story line `{selected_storyline_name}`.")
st.rerun()
if remove_requested and selected_storyline_name:
try:
if storage_backend == "file":
removed = remove_local_storyline(selected_storyline_name)
if removed:
if st.session_state.storyline_name == selected_storyline_name:
_queue_storyline_widget_update("storyline_name", "")
_queue_storyline_widget_update("saved_storyline_name", "")
_set_storyline_feedback("success", f"Removed story line `{selected_storyline_name}`.")
st.rerun()
st.error(f"No saved story line named `{selected_storyline_name}` was found.")
else:
_queue_cookie_storyline_operation(
action="remove",
storyline_name=selected_storyline_name,
cookie_name=storyline_cookie_name(selected_storyline_name),
)
st.rerun()
except Exception as exc:
st.error(str(exc))
def main() -> None:
dataset_window = cached_dataset_window()
today = date.today()
analysis_end = min(today, dataset_window.max_end)
st.title("MyStripes")
st.write(
"Build climate strips from places and periods using ERA5-Land monthly temperature "
"data with automatic historical fallback for earlier years, and export them as "
"minimal graphic in PNG, SVG, or PDF. Use it to communicate how you or some entity "
"experienced climate change."
)
st.markdown(
f"**[{SHOW_YOUR_STRIPES_CREDIT}]({SHOW_YOUR_STRIPES_URL})** "
"The original warming stripes are a powerful tool to communicate climate change. "
"Also, visit [#BiodiversityStripes](https://biodiversitystripes.info/) "
"to communicate the intensifying biodiversity crisis."
)
st.info(
f"MyStripes is open-source on [GitHub]({PROJECT_REPOSITORY_URL}). Direct contributions "
f"and ideas are welcome: [contributing guide]({CONTRIBUTING_GUIDE_URL}) or "
f"[open a GitHub issue]({PROJECT_ISSUES_URL})."
)
_initialize_state(analysis_end)
storage_backend = _storyline_storage_backend()
if storage_backend == "cookie":
_sync_cookie_store()
_render_cookie_consent_banner(storage_backend)
sidebar = st.sidebar
_render_cookie_settings(sidebar, storage_backend)
_render_storyline_panel(sidebar, analysis_end, storage_backend)
active_cds_config = _render_cds_access_panel(sidebar)
sidebar.header("Output")
birth_date = sidebar.date_input(
"Timeline start",
min_value=dataset_window.min_start,
max_value=analysis_end,
key="birth_date",
help="For personal timelines, set this to your birth date.",
)
spatial_mode = sidebar.selectbox(
"Spatial aggregation",
options=("single_cell", "radius", "boundary"),
format_func=lambda value: {
"single_cell": "Nearest single grid cell",
"radius": "Average grid cells in a radius",
"boundary": "Average grid cells inside place boundary",
}[value],
help=(
"MyStripes uses ERA5-Land where available and automatically falls back to "
"historical datasets for earlier years. Radius mode averages grid cells inside "
"the chosen radius. Boundary mode uses the municipality, district, region, or "
"other place polygon returned by the geocoder when available, with a bounding-box "
"fallback when only an area extent is available."
),
)
radius_km = None
if spatial_mode == "radius":
radius_km = float(
sidebar.number_input("Radius (km)", min_value=5.0, max_value=250.0, value=25.0, step=5.0)
)
aggregation_mode = sidebar.selectbox(
"Stripe period",
options=("full_calendar_years", "rolling_365_day"),
format_func=lambda value: {
"full_calendar_years": "Full calendar years only",
"rolling_365_day": "365-day moving average",
}[value],
help=(
"Full calendar years only drops partial birth and current years. The 365-day "
"moving average mode expands the monthly series to daily values, applies a "
"365-day rolling mean, then samples the smoothed series."
),
)
reference_period_mode = sidebar.selectbox(
"Climatology reference period",
options=("climate_normal_1961_2010", "story_line_period"),
format_func=lambda value: {
"climate_normal_1961_2010": "1961-2010",
"story_line_period": "Story line period",