Spaces:
Sleeping
Sleeping
File size: 44,814 Bytes
e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d d596bbe 49bd348 d596bbe 8fcba5d 49bd348 8fcba5d e7979e7 8fcba5d 49bd348 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 d596bbe 49bd348 d596bbe 49bd348 e7979e7 8fcba5d e7979e7 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 d596bbe 49bd348 d596bbe 49bd348 e7979e7 8fcba5d e7979e7 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 d596bbe 49bd348 d596bbe 49bd348 e7979e7 8fcba5d e7979e7 8fcba5d 0c467e9 8fcba5d 0c467e9 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 8fcba5d 49bd348 d596bbe 49bd348 d596bbe 49bd348 e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d d596bbe 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 8fcba5d e7979e7 0c467e9 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
import streamlit as st
import streamlit.components.v1 as components
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from urllib.parse import quote, unquote
import os
import glob
# ClimateLens Menu Structure - Simplified to only Explore and Help & Legal
MENU = {
"Explore": {
"Key Insights": None, # Level 2 endpoint - no sub-items
"Dashboards": None, # Level 2 endpoint - no sub-items (simplified)
},
"Help & Legal": {
"Support/FAQs": None, # Level 2 endpoint - no sub-items
"Disclaimer": None, # Level 2 endpoint - no sub-items
"Terms of Use": None, # Level 2 endpoint - no sub-items
},
}
# Query parameter helpers
def _qp_get(name, default):
val = st.query_params.get(name, default)
if isinstance(val, list):
val = val[0] if val else default
return unquote(str(val))
def get_route():
l1 = _qp_get("l1", next(iter(MENU)))
if l1 not in MENU:
l1 = next(iter(MENU))
# Get l2 only if it exists in the URL parameters
l2 = _qp_get("l2", None)
if l2 is not None and l2 not in MENU[l1]:
l2 = None
# Since we now have simplified 2-level navigation, l3 is always None
l3 = None
return l1, l2, l3
def href(l1, l2, l3=None):
"""Generate href with proper parameters for both 2-level and 3-level navigation"""
if l2 is None:
return f"?l1={quote(l1)}"
elif l3 is not None:
return f"?l1={quote(l1)}&l2={quote(l2)}&l3={quote(l3)}"
else:
return f"?l1={quote(l1)}&l2={quote(l2)}"
def main():
st.set_page_config(page_title="ClimateLens",
page_icon="π",
layout="wide",
initial_sidebar_state="collapsed")
# WordPress-style navigation CSS with proper link handling
nav_css = """
<style>
/* Hide Streamlit default elements */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
.stDeployButton {display:none;}
/* Main header */
.main-header {
background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
padding: 2rem 1.5rem;
margin: -1rem -1rem 0 -1rem;
text-align: center;
border-radius: 0 0 1rem 1rem;
}
.main-header h1 {
color: white;
margin: 0;
font-size: 2.5rem;
font-weight: 700;
}
.main-header p {
color: #bfdbfe;
margin: 0.5rem 0 0 0;
font-size: 1.1rem;
}
/* WordPress Navigation Variables */
:root{
--bg:#1e3a8a;
--bg2:#1e40af;
--ink:#e5e7eb;
--muted:#94a3b8;
--hover:#3b82f6;
--accent:#fbbf24;
}
/* Navigation Wrap */
.wpnav-wrap{
position:sticky; top:0; z-index:1000;
background:linear-gradient(135deg, var(--bg), var(--bg2));
border-bottom:1px solid rgba(255,255,255,.1);
box-shadow:0 2px 10px rgba(0,0,0,.15);
padding:.4rem .8rem;
margin: 0 -1rem 1rem -1rem;
}
/* Hamburger for mobile */
.wpnav-toggle{ display:none; }
.wpnav-hamburger{
display:none; user-select:none; cursor:pointer;
color:var(--ink); font-size:1rem; padding:.4rem .7rem;
border-radius:999px;
}
.wpnav-hamburger:hover{ background:var(--hover); color:#fff; }
.wpnav-hamburger .bars{ font-size:1.1rem; margin-right:.4rem; }
/* Top level navigation */
.wpnav{
display:flex; align-items:center; gap:.4rem; margin:0; padding:0; list-style:none;
justify-content:center;
}
.wpnav > li{ position:relative; }
/* Navigation links - prevent new windows */
.wpnav a{
display:inline-block; text-decoration:none; color:var(--ink);
padding:.6rem .8rem; border-radius:999px; line-height:1; font-size:.95rem;
transition: all 0.3s ease;
target: _self !important;
}
.wpnav a:hover, .wpnav a:focus{ background:var(--hover); color:#fff; outline:none; }
.wpnav a.active{
color:var(--accent);
background:rgba(251,191,36,.15);
border:1px solid rgba(251,191,36,.35);
font-weight: 600;
}
/* Level-2 dropdown - Click to toggle */
.wpnav .dropdown{
display:none; position:absolute; top:100%; left:0;
min-width:260px; list-style:none; margin:.4rem 0 0 0; padding:.4rem;
background:var(--bg2);
border:1px solid rgba(255,255,255,.1);
border-radius:12px;
box-shadow:0 8px 24px rgba(0,0,0,.25);
}
.wpnav > li.show-dropdown > .dropdown{ display:block; }
/* Level-2 items */
.wpnav .dropdown > li{ position:relative; }
.wpnav .dropdown > li > a{
display:block; white-space:nowrap; padding:.6rem .7rem; border-radius:10px; color:var(--ink);
font-size: .9rem; target: _self !important;
}
.wpnav .dropdown > li > a:hover, .wpnav .dropdown > li > a:focus{ background:var(--hover); color:#fff; }
.wpnav .dropdown > li > a.active{ color:var(--accent); background:rgba(251,191,36,.15); }
/* Mobile responsive */
@media (max-width: 900px){
.wpnav-hamburger{ display:inline-flex; align-items:center; }
.wpnav{ display:none; flex-direction:column; align-items:flex-start; gap:.2rem; margin-top:.4rem; }
.wpnav-toggle:checked + label + ul.wpnav{ display:flex; }
.wpnav > li{ width:100%; }
.wpnav a{ width:100%; border-radius:10px; }
.wpnav .dropdown{ position:static; display:none; box-shadow:none; border:none; margin:0; padding:.3rem 0 .3rem .6rem; }
.wpnav > li:hover > .dropdown,
.wpnav > li:focus-within > .dropdown{ display:block; }
.wpnav .flyout{ position:static; display:block; box-shadow:none; border:none; margin:.2rem 0 0 .8rem; }
}
/* Content sections */
.content-section {
background: white;
border-radius: 1rem;
padding: 2rem;
margin: 1.5rem 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
border-left: 4px solid #3b82f6;
}
.section-title {
color: #1e293b;
font-size: 1.8rem;
font-weight: 600;
margin-bottom: 1rem;
}
.section-description {
color: #64748b;
font-size: 1.1rem;
line-height: 1.6;
margin-bottom: 1.5rem;
}
.placeholder-box {
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border: 2px dashed #cbd5e1;
border-radius: 1rem;
padding: 2rem;
text-align: center;
margin: 1rem 0;
color: #64748b;
}
.feature-card {
background: white;
border-radius: 1rem;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
border: 1px solid #e2e8f0;
margin: 1rem 0;
transition: all 0.3s ease;
}
.feature-card:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
transform: translateY(-2px);
}
/* Breadcrumb navigation */
.breadcrumb {
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
padding: 0.75rem 1.5rem;
margin: 0 -1rem 1.5rem -1rem;
border-bottom: 1px solid #e2e8f0;
font-size: 0.9rem;
color: #64748b;
}
.breadcrumb a {
color: #2563eb;
text-decoration: none;
font-weight: 500;
}
.breadcrumb a:hover {
text-decoration: underline;
}
</style>
<script>
function handleMainTabClick(event, element) {
const parentLi = element.parentElement;
const isDropdownOpen = parentLi.classList.contains('show-dropdown');
// Close all other dropdowns
document.querySelectorAll('.wpnav > li').forEach(li => {
if (li !== parentLi) {
li.classList.remove('show-dropdown');
}
});
// If dropdown was closed, show it and prevent navigation
if (!isDropdownOpen) {
parentLi.classList.add('show-dropdown');
event.preventDefault();
return false;
}
// If dropdown was already open, allow navigation
return true;
}
function toggleDropdown(element) {
// Close all dropdowns first
document.querySelectorAll('.wpnav > li').forEach(li => {
li.classList.remove('show-dropdown');
});
// Toggle the clicked dropdown
const parentLi = element.parentElement;
parentLi.classList.add('show-dropdown');
// Prevent default link behavior
return false;
}
// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('.wpnav')) {
document.querySelectorAll('.wpnav > li').forEach(li => {
li.classList.remove('show-dropdown');
});
}
});
</script>
"""
st.markdown(nav_css, unsafe_allow_html=True)
# Header
st.markdown("""
<div class="main-header">
<h1>π ClimateLens</h1>
<p>Understanding climate-related emotions through social media analysis</p>
</div>
""",
unsafe_allow_html=True)
# WordPress-style navigation
render_nav()
# Breadcrumb and content
render_breadcrumbs()
render_current_page()
def build_nav_html(l1_cur, l2_cur, l3_cur):
"""Build the WordPress-style navigation HTML"""
def li_top(label, lvl2):
first_l2 = next(iter(lvl2))
active = "active" if label == l1_cur else ""
# Don't show dropdown by default, only when clicked
show_dropdown = ""
# Add emoji icons for main sections
icons = {"Explore": "π", "Help & Legal": "β"}
icon = icons.get(label, "π")
# For main tabs, allow both navigation and dropdown functionality
main_tab_href = href(label, None, None) # Link to main tab overview
item = [
f'<li role="none" class="{show_dropdown}">'
f'<a role="menuitem" aria-haspopup="true" aria-expanded="false" class="{active}" '
f'href="{main_tab_href}" onclick="handleMainTabClick(event, this);" style="cursor: pointer;" target="_self">{icon} {label}</a>'
]
# level-2 dropdown
item.append(
'<ul class="dropdown" role="menu" aria-label="Submenu level 2">')
for l2, lvl3 in lvl2.items():
active2 = "active" if (label == l1_cur and l2 == l2_cur) else ""
item.append('<li role="none">')
# All items link directly to level 2 (no level 3 in simplified structure)
href_link = href(label, l2, None)
item.append(
f'<a role="menuitem" aria-haspopup="false" aria-expanded="false" class="{active2}" '
f'href="{href_link}" target="_self">{l2}</a>')
item.append('</li>')
item.append('</ul></li>')
return "".join(item)
parts = ['<div class="wpnav-wrap" role="navigation" aria-label="Primary">']
parts.append(
'<input id="wpnav-toggle" class="wpnav-toggle" type="checkbox" aria-label="Toggle menu" />'
)
parts.append(
'<label class="wpnav-hamburger" for="wpnav-toggle"><span class="bars">β°</span> Menu</label>'
)
parts.append('<ul class="wpnav" role="menubar" aria-label="Top level">')
for L1, L2 in MENU.items():
parts.append(li_top(L1, L2))
parts.append('</ul></div>')
return "".join(parts)
def render_nav():
"""Render the WordPress-style navigation"""
l1, l2, l3 = get_route()
html = build_nav_html(l1, l2, l3)
st.markdown(html, unsafe_allow_html=True)
def render_breadcrumbs():
"""Render breadcrumb navigation based on current route and menu structure"""
l1, l2, l3 = get_route()
# Build breadcrumb based on current navigation level
if l2 is None:
# Only main tab selected
breadcrumb_html = f"""
<div class="breadcrumb">
π Home βΊ {l1}
</div>
"""
elif l3 is not None:
# 3-level navigation
breadcrumb_html = f"""
<div class="breadcrumb">
π Home βΊ {l1} βΊ {l2} βΊ {l3}
</div>
"""
else:
# 2-level navigation
breadcrumb_html = f"""
<div class="breadcrumb">
π Home βΊ {l1} βΊ {l2}
</div>
"""
st.markdown(breadcrumb_html, unsafe_allow_html=True)
def render_current_page():
"""Render content based on current route - Updated for ClimateLens simplified structure"""
l1, l2, l3 = get_route()
# Handle case when only main tab is selected (no subtab)
if l2 is None:
if l1 == "Explore":
show_explore_overview()
elif l1 == "Help & Legal":
show_help_legal_overview()
else:
show_explore_overview() # Default fallback
else:
# Route to appropriate content function based on simplified menu structure
if l1 == "Explore" and l2 == "Key Insights":
show_key_insights_page()
elif l1 == "Explore" and l2 == "Dashboards":
show_dashboards_page()
elif l1 == "Help & Legal" and l2 == "Support/FAQs":
show_support_page()
elif l1 == "Help & Legal" and l2 == "Disclaimer":
show_disclaimer_page()
elif l1 == "Help & Legal" and l2 == "Terms of Use":
show_terms_page()
else:
# Default fallback - show Key Insights as home page
show_key_insights_page()
def show_explore_overview():
"""Overview page for Explore section when no subtab is selected"""
st.markdown("""
<div class="content-section">
<div class="section-title">π Explore Climate Emotions</div>
<div class="section-description">
Discover insights into how communities experience climate-related emotions through our data-driven platform.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("### Choose Your Path")
col1, col2 = st.columns(2)
with col1:
st.markdown("""
#### π‘ Key Insights
Get immediate access to our latest findings about climate emotions across different demographics and regions.
**Perfect for:**
- Quick understanding of current trends
- Research starting points
- Presentation-ready statistics
""")
if st.button("View Key Insights", use_container_width=True):
st.query_params.update({"l1": "Explore", "l2": "Key Insights"})
st.rerun()
with col2:
st.markdown("""
#### π Interactive Dashboards
Explore our comprehensive visualization tools to analyze climate emotion patterns in depth.
**Perfect for:**
- Detailed data exploration
- Custom analysis and filtering
- Research and academic work
""")
if st.button("Explore Dashboards", use_container_width=True):
st.query_params.update({"l1": "Explore", "l2": "Dashboards"})
st.rerun()
def show_help_legal_overview():
"""Overview page for Help & Legal section when no subtab is selected"""
st.markdown("""
<div class="content-section">
<div class="section-title">β Help & Legal Information</div>
<div class="section-description">
Find answers to your questions and understand the terms and limitations of using ClimateLens.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("### Available Resources")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
#### π€ Support & FAQs
Get help with using the platform and find answers to common questions about our research methods.
""")
if st.button("Get Support", use_container_width=True):
st.query_params.update({
"l1": "Help & Legal",
"l2": "Support/FAQs"
})
st.rerun()
with col2:
st.markdown("""
#### β οΈ Disclaimer
Important information about the research nature of this tool and its limitations.
""")
if st.button("Read Disclaimer", use_container_width=True):
st.query_params.update({"l1": "Help & Legal", "l2": "Disclaimer"})
st.rerun()
with col3:
st.markdown("""
#### π Terms of Use
Legal terms and conditions for using the ClimateLens platform and data.
""")
if st.button("View Terms", use_container_width=True):
st.query_params.update({
"l1": "Help & Legal",
"l2": "Terms of Use"
})
st.rerun()
# PAGE CONTENT FUNCTIONS
# ClimateLens Page Functions
def show_key_insights_page():
"""Key Insights from Current Data"""
st.markdown("""
<div class="content-section">
<div class="section-title">π Key Insights from Current Data</div>
<div class="section-description">
Climate conversations online reveal not just facts and opinions, but the emotions people carry when talking about the future of our planet. Our analysis of recent discussions highlights several important insights.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("""
### Key Insights from Current Data
**Climate anxiety is widespread:** Many people express worry, stress, or fear about the future, often tied to uncertainty about what can be done.
**Hope and motivation still shine through:** Alongside anxiety, we also see voices of determination β calls for action, sharing solutions, and community support.
**Different groups focus on different concerns:** Some emphasize policy and global decisions, while others focus on personal responsibility or lifestyle changes.
**Emotions are mixed, not one-dimensional:** It's common to see comments that are both worried and hopeful, or frustrated yet motivated.
**Community plays a big role:** Many express that talking, sharing, and organizing with others helps balance the heavy emotions around climate change.
Together, these insights show a picture that is both challenging and inspiring: the emotional weight of climate change is real, but so are the collective voices searching for solutions and connection.
""")
def show_dashboards_page():
"""Comprehensive Dashboards page with Topics and Sentiments tabs"""
st.markdown("""
<div class="content-section">
<div class="section-title">π Dashboards</div>
<div class="section-description">
This section lets you explore the conversations and feelings around climate anxiety. Think of it as moving from the headline to the full story. Use the Topics tab to see what people are talking about, and the Sentiments tab to understand how they feel.
</div>
</div>
""",
unsafe_allow_html=True)
# Introduction & Guide Section
with st.expander("π Introduction & Guide"):
st.markdown("""
This section lets you explore the conversations and feelings around climate anxiety. Think of it as moving from the headline to the full story. Use the Topics tab to see what people are talking about, and the Sentiments tab to understand how they feel.
""")
with st.expander("π§ Understanding the Data Visualization Tools"):
st.markdown("""
Each tool shows the same conversations from a different angle. Some focus on what people discuss (topics), others on how they feel (sentiments). Together, they offer a fuller picture.
""")
with st.expander("π How to Use This Dashboard"):
st.markdown("""
Start with the Barchart or Intertopic Map to see the main conversations. Use the Heatmap and Hierarchy to explore connections and branches. Then open the Sentiments tab to check the feelings behind the words. You don't need to view everythingβfollow your curiosity.
""")
st.markdown(
"### Pick a view and start exploring. You can switch tabs and charts anytime."
)
# Main tabs: Topics and Sentiments
topics_tab, sentiments_tab = st.tabs(["π Topics", "π Sentiments"])
with topics_tab:
show_topics_section()
with sentiments_tab:
show_sentiments_section()
# Helper functions for file discovery and visualization handling
def list_files_in_directory(directory, extensions):
"""List files in directory with specified extensions"""
if not os.path.exists(directory):
return []
files = []
for ext in extensions:
pattern = os.path.join(directory, f"*.{ext}")
files.extend(glob.glob(pattern))
return [os.path.basename(f) for f in files]
@st.cache_data
def prettify_filename(filename):
"""Convert filename to user-friendly display name"""
# Remove extension
name = os.path.splitext(filename)[0]
# Replace underscores and dashes with spaces
name = name.replace('_', ' ').replace('-', ' ')
# Title case
name = name.title()
return name
def categorize_html_files(files):
"""Categorize HTML files by visualization type"""
categories = {
'intertopic': [],
'heatmap': [],
'barchart': [],
'hierarchy': []
}
for file in files:
filename_lower = file.lower()
if 'intertopic' in filename_lower:
categories['intertopic'].append(file)
elif 'heatmap' in filename_lower:
categories['heatmap'].append(file)
elif 'barchart' in filename_lower or 'bar' in filename_lower:
categories['barchart'].append(file)
elif 'hierarchy' in filename_lower or 'tree' in filename_lower:
categories['hierarchy'].append(file)
return categories
def render_html_visualization(file_path, explanation):
"""Render HTML visualization with explanation"""
if not os.path.exists(file_path):
st.error(f"File not found: {file_path}")
return
# Show explanation
st.markdown(explanation)
try:
with open(file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
# Render HTML
components.html(html_content, height=800, scrolling=True)
except Exception as e:
st.error(f"Error loading visualization: {str(e)}")
def render_image_visualization(file_path, explanation):
"""Render image visualization with explanation"""
if not os.path.exists(file_path):
st.error(f"File not found: {file_path}")
return
# Show explanation
st.markdown(explanation)
try:
st.image(file_path, use_container_width=True)
except Exception as e:
st.error(f"Error loading image: {str(e)}")
def show_topics_section():
"""Display Topics section with sub-tabs"""
st.markdown("### Available Visualizations")
# Add refresh button
if st.button("π Refresh Files", key="refresh_topics"):
st.rerun()
# Get HTML files from all directories
idm_files = list_files_in_directory("visualizations/IDM", ["html"])
heatmap_files = list_files_in_directory("visualizations/heatmaps", ["html"])
barchart_files = list_files_in_directory("visualizations/barcharts", ["html"])
hierarchy_files = list_files_in_directory("visualizations/hierarchies", ["html"])
# Combine all files for categorization fallback
all_html_files = idm_files + heatmap_files + barchart_files + hierarchy_files
if not all_html_files:
st.info(
"No visualizations found yet. Visualizations will appear here once data is processed."
)
return
# Categorize files for fallback
categorized = categorize_html_files(all_html_files)
# Create sub-tabs
intertopic_tab, heatmap_tab, barchart_tab, hierarchy_tab = st.tabs(
["π΅ Intertopic Map β", "π₯ Heatmap β", "π Barchart β", "π³ Hierarchy β"])
with intertopic_tab:
st.markdown(
"**What it shows:** Topics as bubbles on a map. Bubbles close together mean the conversations are similar; far apart means they're different."
)
st.markdown(
"**Why it matters:** Quickly spot clusters of related themes (for example, 'policy and activism')."
)
# Use IDM folder files first, then fallback to categorized files
files = idm_files if idm_files else categorized['intertopic']
if not files:
files = all_html_files # Ultimate fallback to all files
if files:
selected_file = st.selectbox("Choose visualization:",
files,
format_func=prettify_filename,
key="intertopic_select")
# Determine correct path based on file source
if selected_file in idm_files:
file_path = os.path.join("visualizations/IDM", selected_file)
else:
file_path = os.path.join("visualizations", selected_file)
render_html_visualization(file_path, "")
else:
st.info("No intertopic distance maps found.")
with heatmap_tab:
st.markdown(
"**What it shows:** A grid where stronger colors mean stronger links between topics."
)
st.markdown(
"**Why it matters:** Reveals which themes often appear together.")
# Use heatmaps folder files first, then fallback to categorized files
files = heatmap_files if heatmap_files else categorized['heatmap']
if not files:
files = all_html_files # Ultimate fallback to all files
if files:
selected_file = st.selectbox("Choose visualization:",
files,
format_func=prettify_filename,
key="heatmap_select")
# Determine correct path based on file source
if selected_file in heatmap_files:
file_path = os.path.join("visualizations/heatmaps", selected_file)
else:
file_path = os.path.join("visualizations", selected_file)
render_html_visualization(file_path, "")
else:
st.info("No heatmap visualizations found.")
with barchart_tab:
st.markdown(
"**What it shows:** A ranking of topics by sizeβhow much people talk about each one."
)
st.markdown(
"**Why it matters:** See which conversations dominate the climate anxiety space."
)
# Use barcharts folder files first, then fallback to categorized files
files = barchart_files if barchart_files else categorized['barchart']
if not files:
files = all_html_files # Ultimate fallback to all files
if files:
selected_file = st.selectbox("Choose visualization:",
files,
format_func=prettify_filename,
key="barchart_select")
# Determine correct path based on file source
if selected_file in barchart_files:
file_path = os.path.join("visualizations/barcharts", selected_file)
else:
file_path = os.path.join("visualizations", selected_file)
render_html_visualization(file_path, "")
else:
st.info("No barchart visualizations found.")
with hierarchy_tab:
st.markdown(
"**What it shows:** Topics arranged like a family treeβbroad categories break down into specific sub-themes."
)
st.markdown(
"**Why it matters:** Perfect for drilling down from general worry to specific concerns.")
# Use hierarchies folder files first, then fallback to categorized files
files = hierarchy_files if hierarchy_files else categorized['hierarchy']
if not files:
files = all_html_files # Ultimate fallback to all files
if files:
selected_file = st.selectbox("Choose visualization:",
files,
format_func=prettify_filename,
key="hierarchy_select")
# Determine correct path based on file source
if selected_file in hierarchy_files:
file_path = os.path.join("visualizations/hierarchies", selected_file)
else:
file_path = os.path.join("visualizations", selected_file)
render_html_visualization(file_path, "")
else:
st.info("No hierarchy visualizations found.")
def show_sentiments_section():
"""Display Sentiments section with sub-tabs"""
st.markdown("### Sentiment Analysis Visualizations")
# Add refresh button
if st.button("π Refresh Files", key="refresh_sentiments"):
st.rerun()
# Create sub-tabs
distribution_tab, histograms_tab, violins_tab = st.tabs([
"π Distribution", "π Probability - Histograms",
"π» Probability - Violins"
])
with distribution_tab:
st.markdown(
"**What it shows:** The overall balance of positive, neutral, and negative feelings."
)
st.markdown(
"**Why it matters:** A quick snapshot of the general mood.")
# Get PNG files from sentiment distribution directory
png_files = list_files_in_directory(
"visualizations/sentiment insights/sentiment distribution",
["png", "jpg", "jpeg"])
if png_files:
selected_file = st.selectbox("Choose visualization:",
png_files,
format_func=prettify_filename,
key="distribution_select")
file_path = os.path.join(
"visualizations/sentiment insights/sentiment distribution",
selected_file)
render_image_visualization(file_path, "")
else:
st.info("No sentiment distribution visualizations found yet.")
with histograms_tab:
st.markdown(
"**What it shows:** For each emotion label (positive/neutral/negative), a histogram shows how many messages fall into each 'confidence' level."
)
st.markdown(
"**Why it's useful:** Helps you see how certain or uncertain the system is. If many messages sit in the middle, feelings are mixed; if most are at the high end, the labeling is confident."
)
# Get image files from sentiment probability histograms directory
hist_files = list_files_in_directory(
"visualizations/sentiment insights/sentiment probability histograms",
["png", "jpg", "jpeg"])
if hist_files:
selected_file = st.selectbox("Choose visualization:",
hist_files,
format_func=prettify_filename,
key="histograms_select")
file_path = os.path.join(
"visualizations/sentiment insights/sentiment probability histograms",
selected_file)
render_image_visualization(file_path, "")
else:
st.info(
"No sentiment probability histogram visualizations found yet.")
with violins_tab:
st.markdown(
"**What it shows:** For each emotion label, a violin plot shows the shape of the confidence scores (where they bunch up, spread out, or have multiple peaks)."
)
st.markdown(
"**Why it's useful:** Makes it easy to spot uncertainty and overlap between emotions. For example, if negative and neutral have similar shapes, people may be expressing worry without being strongly negative."
)
# Get image files from sentiment probability violins directory
violin_files = list_files_in_directory(
"visualizations/sentiment insights/sentiment probability violins",
["png", "jpg", "jpeg"])
if violin_files:
selected_file = st.selectbox("Choose visualization:",
violin_files,
format_func=prettify_filename,
key="violins_select")
file_path = os.path.join(
"visualizations/sentiment insights/sentiment probability violins",
selected_file)
render_image_visualization(file_path, "")
else:
st.info(
"No sentiment probability violin visualizations found yet.")
def show_support_page():
"""Support and FAQs"""
# Add Google Form button at the very top
st.markdown("### π¬ Share Your Feedback")
st.link_button("Submit Feedback",
"https://forms.gle/o7QQBZNijJo9E76E7",
use_container_width=True)
st.markdown("---")
st.markdown("""
<div class="content-section">
<div class="section-title">β Support & FAQs</div>
<div class="section-description">
Get help using ClimateLens and find answers to common questions.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("### Frequently Asked Questions")
with st.expander("1) What will your tool not do?"):
st.markdown("""
It won't run live surveillance or score individual youth in real time. And it won't auto-prescribe personalized interventions. Those are explicitly out-of-scope for this phase.
""")
with st.expander(
"2) If it doesn't flag individuals, what does a counselor actually see?"
):
st.markdown("""
A visual dashboard of aggregate themes and interpretable signals (e.g., prevalent concerns, representative phrases), with an interface to explore how a prediction was made; KHP designs the human intervention guidance that sits beside these insights.
""")
with st.expander("3) What counts as a 'good' model here?"):
st.markdown("""
Not just accuracy. We'll judge success on:
- (a) detection quality against baselines
- (b) interpretability: clear linguistic cues you can inspect, and
- (c) fairness across subgroups.
""")
with st.expander("4) Where does the data come from and do youth consent?"):
st.markdown("""
Phase I uses open-source, climate-related text. Phase II contemplates anonymized/de-identified Kids Help Phone transcripts that are used only after de-identification and governance review.
""")
with st.expander(
"5) How do you keep the system from drifting or getting brittle over time (slang, memes, shifts)?"
):
st.markdown("""
We treat this like a living system: evaluate routinely, watch for distribution shift, and use human-in-the-loop review to update lexicons/models when new patterns appear. The lifecycle includes explicit monitoring and testing for changes.
""")
with st.expander("6) Could this be biased against certain groups?"):
st.markdown("""
Bias risk is real. We address it by measuring subgroup performance, requiring interpretable rationales (so reviewers can spot skewed cues), and baking fairness checks into testing alongside clear documentation of limits.
""")
with st.expander("7) Will this replace counselors?"):
st.markdown("""
No. It's decision support, not decision maker. The deliverables include an interpretable model + UI meant to surface patterns and speed human judgment. KHP leads on intervention strategy and practice.
""")
with st.expander("8) What happens when the model is wrong?"):
st.markdown("""
We plan for error. Baselines and evaluation tests are set up to catch regressions; the UI shows why a prediction happened; and there's a human feedback loop to correct mistakes and refine the system.
""")
with st.expander(
"9) Can communities reuse this without heavy ML expertise?"):
st.markdown("""
Yes! Code and models are released with usage guidelines, and the interface ships with built-in visualizations so non-technical teams can explore results safely and meaningfully.
""")
st.markdown("### For Mental Health Professionals")
st.markdown("""
If you are a licensed psychologist, counselor, or other mental health professional:
- Use your professional judgment when interpreting research findings
- Maintain appropriate boundaries between research tools and clinical practice
- Consult with supervisors or colleagues when applying research insights to professional contexts
- Follow your profession's ethical guidelines regarding use of research tools and data
- Seek appropriate training if you plan to incorporate climate psychology research into your practice
""")
st.markdown("### Questions or Concerns")
st.markdown("""
For questions about appropriate use, data sources, or research methodology, please contact the project team through programs@crcgreen.com
""")
st.markdown("### Help Us Improve ClimateLens")
st.markdown("""
Your feedback helps us improve the platform for everyone. Share your experience, suggest features, or report issues.
[π¬ Submit Feedback via Google Form](https://forms.gle/o7QQBZNijJo9E76E7)
""")
def show_disclaimer_page():
"""Disclaimer"""
st.markdown("""
<div class="content-section">
<div class="section-title">β οΈ Disclaimer</div>
<div class="section-description">
Important information about using ClimateLens data and platform.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("""
### Research and Educational Purposes Only
This application and its associated data, models, and findings are provided solely for research, educational, and informational purposes. The project developers are not licensed psychologists, counselors, or accredited researchers. This tool is not intended to provide clinical advice, psychological assessment, diagnosis, or treatment recommendations.
### No Clinical or Therapeutic Claims
The climate anxiety taxonomy, emotional mapping, and analytical outputs provided by this application are research tools only and should not be used as substitutes for professional mental health services, clinical assessment, or therapeutic intervention. Users who are mental health professionals must exercise their own professional judgment when interpreting or applying any insights from this tool.
### Data Limitations and Accuracy
The data and models are derived from public social media conversations and computational analysis. Results may contain biases, inaccuracies, or limitations inherent in:
- Social media data collection and processing
- Automated topic modeling and sentiment analysis
- Self-selected online populations
- Temporal and demographic sampling limitations
### Open Source Nature
This project is open source and provided "as is" without warranties of any kind, either express or implied. The developers make no guarantees regarding the accuracy, completeness, reliability, or fitness for any particular purpose.
""")
def show_terms_page():
"""Terms of Use"""
st.markdown("""
<div class="content-section">
<div class="section-title">π Terms of Use</div>
<div class="section-description">
Terms and conditions for using the ClimateLens platform.
</div>
</div>
""",
unsafe_allow_html=True)
st.markdown("""
### Scope of Acceptable Use
By accessing this application, users acknowledge and agree that their use shall be limited exclusively to:
- Legitimate research purposes in academic, clinical, or policy contexts
- Educational activities in professional training or public education settings
- Professional development for qualified mental health practitioners
- Policy research related to climate mental health initiatives
Users expressly agree to comply with all applicable laws, regulations, and professional standards.
### Prohibited Applications
Users are strictly prohibited from utilizing this application or its outputs to:
- Provide direct clinical care or psychological services to individuals
- Make diagnostic or treatment decisions without appropriate professional oversight
- Replace or substitute for professional mental health assessment or intervention
- Make claims about individual mental health status based on social media activity
- Violate the privacy or confidentiality of individuals whose data may be included in the analysis
### Professional Responsibility and Standards
Mental health professionals utilizing this application acknowledge and affirm that they remain solely and exclusively responsible for their professional practice and clinical decisions. Users further acknowledge that this application does not replace, supplement, or substitute for their professional training, clinical judgment, or ethical obligations as licensed practitioners. All professional users agree to maintain appropriate boundaries between research tools and clinical practice.
### Attribution and Intellectual Property
When utilizing insights, data, or findings from this application in research, publications, or professional contexts, users must:
- Provide appropriate citation and attribution to the project
- Acknowledge the open source nature and inherent limitations of the tool
- Refrain from misrepresenting the credentials or institutional affiliations of the project developers
- Include appropriate disclaimers regarding the research nature and limitations of the tool
Failure to provide proper attribution constitutes a violation of these terms.
### Data Use and Privacy Obligations
This application analyzes publicly available social media content in accordance with applicable terms of service and data use policies. Users bear sole responsibility for ensuring their use complies with all relevant privacy laws, institutional ethics requirements, and regulatory frameworks applicable to their jurisdiction and professional context. Users are expressly prohibited from extracting or utilizing any personally identifiable information from the application's outputs.
### Limitation of Liability and Indemnification
The project developers, contributors, and affiliated institutions shall not be liable for any direct, indirect, incidental, consequential, or punitive damages, claims, or losses arising from the use or misuse of this application. This limitation includes, but is not limited to:
- Clinical or professional decisions made based on application outputs
- Misinterpretation or misapplication of research findings
- Technical errors, data inaccuracies, system failures
- Consequences arising from violation of these terms of use
### Modification of Terms and Continued Use
These terms of use may be modified, updated, or revised at any time without prior notice. Continued use of the application following any such modifications constitutes acceptance of the revised terms. Users bear the responsibility for regularly reviewing these terms to ensure continued compliance with current provisions.
### Governing Law and Jurisdiction
These terms of use are governed by and construed in accordance with the laws of Canada. Any disputes, claims, or controversies arising from or relating to these terms or the use of this application shall be resolved exclusively through appropriate legal channels within the jurisdiction where the project is maintained, and users hereby consent to the exclusive jurisdiction of such courts.
*Last updated: August 2025*
""")
if __name__ == "__main__":
main() |