mona / pages /settings.py
mrradix's picture
Update pages/settings.py
b0eb8e1 verified
import streamlit as st
from datetime import datetime
from utils.config import load_config, save_config, reset_config, AppConfig
from utils.storage import get_storage_info, clear_storage, list_keys
from utils.error_handling import handle_ui_exceptions
from utils.logging import get_logger
logger = get_logger(__name__)
@handle_ui_exceptions
def create_settings_page():
"""Create the settings page"""
st.title("βš™οΈ Settings")
st.write("Configure your MONA dashboard preferences and system settings.")
# Create tabs for different settings categories
tab1, tab2, tab3, tab4 = st.tabs(["General", "Display", "Data", "System"])
with tab1:
create_general_settings()
with tab2:
create_display_settings()
with tab3:
create_data_settings()
with tab4:
create_system_settings()
@handle_ui_exceptions
def create_general_settings():
"""Create general settings section"""
st.header("πŸ”§ General Settings")
config = load_config()
# Application settings
with st.form("general_settings_form"):
st.subheader("Application Configuration")
app_name = st.text_input("Application Name", value=config.app_name)
version = st.text_input("Version", value=config.version, disabled=True)
debug_mode = st.checkbox("Debug Mode", value=config.debug_mode)
st.subheader("Performance Settings")
max_data_points = st.number_input(
"Maximum Data Points",
min_value=100,
max_value=10000,
value=config.max_data_points,
step=100
)
refresh_interval = st.number_input(
"Refresh Interval (seconds)",
min_value=1,
max_value=300,
value=config.refresh_interval,
step=1
)
if st.form_submit_button("Save General Settings"):
config.app_name = app_name
config.debug_mode = debug_mode
config.max_data_points = max_data_points
config.refresh_interval = refresh_interval
if save_config(config):
st.success("General settings saved successfully!")
st.rerun()
else:
st.error("Failed to save general settings.")
@handle_ui_exceptions
def create_display_settings():
"""Create display settings section"""
st.header("🎨 Display Settings")
config = load_config()
with st.form("display_settings_form"):
st.subheader("Theme & Appearance")
theme = st.selectbox(
"Theme",
options=["light", "dark"],
index=0 if config.theme == "light" else 1
)
default_chart_type = st.selectbox(
"Default Chart Type",
options=["line", "bar", "scatter", "area"],
index=["line", "bar", "scatter", "area"].index(config.default_chart_type)
)
st.subheader("Layout Settings")
sidebar_width = st.slider(
"Sidebar Width (px)",
min_value=200,
max_value=500,
value=config.sidebar_width,
step=10
)
chart_height = st.slider(
"Default Chart Height (px)",
min_value=300,
max_value=800,
value=config.chart_height,
step=50
)
table_page_size = st.number_input(
"Table Page Size",
min_value=10,
max_value=200,
value=config.table_page_size,
step=10
)
if st.form_submit_button("Save Display Settings"):
config.theme = theme
config.default_chart_type = default_chart_type
config.sidebar_width = sidebar_width
config.chart_height = chart_height
config.table_page_size = table_page_size
if save_config(config):
st.success("Display settings saved successfully!")
st.rerun()
else:
st.error("Failed to save display settings.")
@handle_ui_exceptions
def create_data_settings():
"""Create data settings section"""
st.header("πŸ“Š Data Settings")
config = load_config()
with st.form("data_settings_form"):
st.subheader("Data Processing")
data_cache_timeout = st.number_input(
"Data Cache Timeout (seconds)",
min_value=60,
max_value=3600,
value=config.data_cache_timeout,
step=60
)
max_file_size_mb = st.number_input(
"Maximum File Size (MB)",
min_value=1,
max_value=100,
value=config.max_file_size_mb,
step=1
)
st.subheader("Supported File Types")
current_types = config.supported_file_types or ['.csv', '.xlsx', '.json', '.parquet']
col1, col2 = st.columns(2)
with col1:
csv_support = st.checkbox("CSV Files (.csv)", value='.csv' in current_types)
xlsx_support = st.checkbox("Excel Files (.xlsx)", value='.xlsx' in current_types)
with col2:
json_support = st.checkbox("JSON Files (.json)", value='.json' in current_types)
parquet_support = st.checkbox("Parquet Files (.parquet)", value='.parquet' in current_types)
if st.form_submit_button("Save Data Settings"):
supported_types = []
if csv_support:
supported_types.append('.csv')
if xlsx_support:
supported_types.append('.xlsx')
if json_support:
supported_types.append('.json')
if parquet_support:
supported_types.append('.parquet')
config.data_cache_timeout = data_cache_timeout
config.max_file_size_mb = max_file_size_mb
config.supported_file_types = supported_types
if save_config(config):
st.success("Data settings saved successfully!")
st.rerun()
else:
st.error("Failed to save data settings.")
# Data management section
st.subheader("πŸ“ Data Management")
col1, col2 = st.columns(2)
with col1:
st.write("**Memory Storage**")
memory_info = get_storage_info("memory")
st.write(f"Keys stored: {memory_info['total_keys']}")
if st.button("Clear Memory Storage", type="secondary"):
if clear_storage("memory"):
st.success("Memory storage cleared!")
st.rerun()
else:
st.error("Failed to clear memory storage.")
with col2:
st.write("**Session Storage**")
session_info = get_storage_info("session")
st.write(f"Keys stored: {session_info['total_keys']}")
if st.button("Clear Session Storage", type="secondary"):
if clear_storage("session"):
st.success("Session storage cleared!")
st.rerun()
else:
st.error("Failed to clear session storage.")
# Show stored data keys
with st.expander("View Stored Data Keys"):
memory_keys = list_keys("memory")
session_keys = list_keys("session")
col1, col2 = st.columns(2)
with col1:
st.write("**Memory Keys:**")
for key in memory_keys:
st.write(f"- {key}")
with col2:
st.write("**Session Keys:**")
for key in session_keys:
st.write(f"- {key}")
@handle_ui_exceptions
def create_system_settings():
"""Create system settings section"""
st.header("πŸ”§ System Settings")
# System information
st.subheader("πŸ“‹ System Information")
col1, col2 = st.columns(2)
with col1:
st.write("**Application Info:**")
config = load_config()
st.write(f"- Name: {config.app_name}")
st.write(f"- Version: {config.version}")
st.write(f"- Debug Mode: {'Enabled' if config.debug_mode else 'Disabled'}")
with col2:
st.write("**Runtime Info:**")
st.write(f"- Current Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
st.write(f"- Streamlit Version: {st.__version__}")
st.write("- Python Version: 3.8+")
# Configuration management
st.subheader("βš™οΈ Configuration Management")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Export Configuration", type="secondary"):
config_dict = config.__dict__
st.download_button(
label="Download Config",
data=str(config_dict),
file_name=f"mona_config_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
mime="text/plain"
)
with col2:
if st.button("Reset to Defaults", type="secondary"):
if st.session_state.get('confirm_reset', False):
reset_config()
st.success("Configuration reset to defaults!")
st.session_state['confirm_reset'] = False
st.rerun()
else:
st.session_state['confirm_reset'] = True
st.warning("Click again to confirm reset.")
with col3:
if st.button("Reload Configuration", type="secondary"):
# Force reload by clearing the global config
from utils.config import _config
if '_config' in globals():
globals()['_config'] = None
st.success("Configuration reloaded!")
st.rerun()
# Advanced settings
with st.expander("πŸ”§ Advanced Settings"):
st.subheader("Developer Options")
if config.debug_mode:
st.write("**Debug Information:**")
st.json(config.__dict__)
if st.button("View Session State"):
st.write("**Session State:**")
st.json(dict(st.session_state))
else:
st.info("Enable Debug Mode in General Settings to access developer options.")
# System actions
st.subheader("πŸ”„ System Actions")
col1, col2 = st.columns(2)
with col1:
if st.button("Clear All Cache", type="secondary"):
st.cache_data.clear()
st.success("All cache cleared!")
with col2:
if st.button("Restart Application", type="primary"):
st.info("Application will restart...")
st.rerun()