Spaces:
Sleeping
Sleeping
| 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] | |
| 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() |