import streamlit as st import time from typing import Optional, Dict, Any from datetime import datetime from app.api_client import APIClient from app.utils.ui_elements import show_error, show_info def render(api_client: APIClient) -> None: """Render the sidebar component. Uses session state to store API status information between reruns. Args: api_client: Instance of APIClient """ with st.sidebar: st.title("📧 Spam Classifier") st.markdown("---") # Initialize session state for API status if "api_status" not in st.session_state: st.session_state.api_status = {"checked_at": None, "status": None, "error": None} # API Status section st.subheader("API Status") # Check if we need to refresh the API status (e.g., every 5 minutes) current_time = datetime.now() last_check = st.session_state.api_status.get("checked_at") should_refresh = ( last_check is None or (current_time - last_check).total_seconds() > 300 # 5 minutes ) # Only make API call if needed or if user clicks refresh refresh_status = st.button("🔄 Refresh Status") if should_refresh or refresh_status: try: with st.spinner("Checking API status..."): health_status = api_client.get_health() st.session_state.api_status = { "checked_at": current_time, "status": health_status.get("status", "").lower(), "error": None } if st.session_state.api_status["status"] == "ok": st.session_state.api_connected = True else: st.session_state.api_connected = False except Exception as e: st.session_state.api_status = { "checked_at": current_time, "status": "error", "error": str(e) } st.session_state.api_connected = False # Display the status based on session state if st.session_state.api_status["status"] == "ok": st.success("API Connected") if "last_request_time" in st.session_state: st.write(f"Last Request: {st.session_state.last_request_time:.2f}s") elif st.session_state.api_status["status"] == "error": st.error(f"API Connection Error: {st.session_state.api_status['error']}") else: st.error("API Not Responding Correctly") st.markdown("---") # Navigation section with callback functions to avoid reruns st.subheader("Navigation") def set_page(page_name: str) -> None: """Set the current page in session state. Args: page_name: Name of the page to navigate to """ st.session_state.current_page = page_name # Use on_click to avoid page reruns st.button( "🔍 Single Email Analysis", use_container_width=True, on_click=set_page, args=("single_email",) ) st.button( "📊 Batch Email Analysis", use_container_width=True, on_click=set_page, args=("batch_email",) ) st.button( "📚 About", use_container_width=True, on_click=set_page, args=("about",) ) st.markdown("---") # About section in sidebar st.caption(f"Email Spam Classifier v{api_client.config.APP_VERSION}") st.caption(f"© {datetime.now().year} Email Security Team")