mona / app.py
mrradix's picture
Update app.py
26840bb verified
"""
Main Streamlit Application
"""
import streamlit as st
import sys
import os
from datetime import datetime
import logging
# Add the current directory to Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
print(f"===== Application Startup at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")
try:
from pages.dashboard import create_dashboard_page
from utils.error_handling import handle_data_exceptions, log_error, display_error
from utils.storage import init_session_state, get_session_state, set_session_state
except ImportError as e:
st.error(f"Import Error: {e}")
st.stop()
# Configure Streamlit page
st.set_page_config(
page_title="Dashboard App",
page_icon="πŸ“Š",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://www.streamlit.io/community',
'Report a bug': None,
'About': "# Dashboard App\nBuilt with Streamlit"
}
)
def main():
"""
Main application function
"""
# Initialize session state
init_session_state('current_page', 'dashboard')
init_session_state('user_settings', {})
init_session_state('app_initialized', False)
# App initialization
if not get_session_state('app_initialized'):
initialize_app()
set_session_state('app_initialized', True)
# Create sidebar navigation
create_sidebar()
# Main content area
current_page = get_session_state('current_page', 'dashboard')
if current_page == 'dashboard':
create_dashboard_page()
else:
st.error("Page not found!")
def initialize_app():
"""
Initialize the application
"""
# Create necessary directories
os.makedirs('data', exist_ok=True)
os.makedirs('cache', exist_ok=True)
os.makedirs('logs', exist_ok=True)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/app.log'),
logging.StreamHandler()
]
)
logging.info("Application initialized successfully")
def create_sidebar():
"""
Create sidebar navigation
"""
with st.sidebar:
st.title("🏠 Navigation")
# Page navigation
page_options = {
'dashboard': 'πŸ“Š Dashboard',
# Add more pages here as needed
}
current_page = st.radio(
"Select Page",
options=list(page_options.keys()),
format_func=lambda x: page_options[x],
index=0
)
set_session_state('current_page', current_page)
st.markdown("---")
# App info
st.subheader("ℹ️ App Info")
st.info(f"**Version:** 1.0.0\n**Last Updated:** {datetime.now().strftime('%Y-%m-%d')}")
# Settings
st.subheader("βš™οΈ Settings")
# Theme toggle (placeholder)
theme = st.selectbox("Theme", ["Light", "Dark"], index=0)
# Auto-refresh toggle
auto_refresh = st.checkbox("Auto Refresh", value=False)
if auto_refresh:
refresh_interval = st.slider("Refresh Interval (seconds)", 30, 300, 60)
st.session_state.refresh_interval = refresh_interval
# Save settings
user_settings = {
'theme': theme,
'auto_refresh': auto_refresh,
'refresh_interval': st.session_state.get('refresh_interval', 60)
}
set_session_state('user_settings', user_settings)
st.markdown("---")
# Debug info (only show in development)
if st.checkbox("Show Debug Info"):
st.subheader("πŸ› Debug Info")
st.json({
'Current Page': current_page,
'Session State Keys': list(st.session_state.keys()),
'User Settings': get_session_state('user_settings', {}),
'App Initialized': get_session_state('app_initialized', False)
})
@handle_data_exceptions
def handle_error_boundary():
"""
Global error handler for the application
"""
try:
main()
except Exception as e:
log_error("Critical application error", e)
st.error("A critical error occurred. Please refresh the page.")
# Show error details in expander
with st.expander("Error Details"):
st.exception(e)
# Health check endpoint
def health_check():
"""
Simple health check for the application
"""
return {
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'version': '1.0.0'
}
if __name__ == "__main__":
try:
handle_error_boundary()
except Exception as e:
print(f"Fatal error: {e}")
import traceback
traceback.print_exc()