mrradix commited on
Commit
26840bb
Β·
verified Β·
1 Parent(s): 23345eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -53
app.py CHANGED
@@ -1,68 +1,182 @@
 
 
 
1
  import streamlit as st
2
  import sys
3
  import os
4
- from pathlib import Path
 
5
 
6
- # Add the app directory to Python path
7
- app_dir = Path(__file__).parent
8
- sys.path.insert(0, str(app_dir))
9
 
10
- from pages.dashboard import create_dashboard_page
11
- from pages.settings import create_settings_page
12
- from utils.config import load_config
13
- from utils.logging import setup_logging, get_logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Initialize logging
16
- setup_logging()
17
- logger = get_logger(__name__)
18
 
19
  def main():
20
- """Main application entry point"""
21
- try:
22
- # Configure Streamlit page
23
- st.set_page_config(
24
- page_title="MONA - Monitoring & Analytics",
25
- page_icon="πŸ“Š",
26
- layout="wide",
27
- initial_sidebar_state="expanded"
28
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # Load configuration
31
- config = load_config()
32
- logger.info("Application started successfully")
 
 
33
 
34
- # Create sidebar navigation
35
- st.sidebar.title("MONA Dashboard")
36
- page = st.sidebar.selectbox(
37
- "Navigate to:",
38
- ["Dashboard", "Settings", "About"]
39
  )
40
 
41
- # Route to appropriate page
42
- if page == "Dashboard":
43
- create_dashboard_page()
44
- elif page == "Settings":
45
- create_settings_page()
46
- elif page == "About":
47
- create_about_page()
48
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  except Exception as e:
50
- logger.error(f"Application error: {str(e)}")
51
- st.error(f"An error occurred: {str(e)}")
52
-
53
- def create_about_page():
54
- """Create the about page"""
55
- st.title("About MONA")
56
- st.write("""
57
- MONA (Monitoring & Analytics) is a comprehensive dashboard application
58
- for data visualization and monitoring.
59
-
60
- **Features:**
61
- - Real-time data monitoring
62
- - Interactive dashboards
63
- - Data analytics and reporting
64
- - Customizable settings
65
- """)
 
 
 
66
 
67
  if __name__ == "__main__":
68
- main()
 
 
 
 
 
 
1
+ """
2
+ Main Streamlit Application
3
+ """
4
  import streamlit as st
5
  import sys
6
  import os
7
+ from datetime import datetime
8
+ import logging
9
 
10
+ # Add the current directory to Python path
11
+ current_dir = os.path.dirname(os.path.abspath(__file__))
12
+ sys.path.insert(0, current_dir)
13
 
14
+ print(f"===== Application Startup at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")
15
+
16
+ try:
17
+ from pages.dashboard import create_dashboard_page
18
+ from utils.error_handling import handle_data_exceptions, log_error, display_error
19
+ from utils.storage import init_session_state, get_session_state, set_session_state
20
+ except ImportError as e:
21
+ st.error(f"Import Error: {e}")
22
+ st.stop()
23
+
24
+
25
+ # Configure Streamlit page
26
+ st.set_page_config(
27
+ page_title="Dashboard App",
28
+ page_icon="πŸ“Š",
29
+ layout="wide",
30
+ initial_sidebar_state="expanded",
31
+ menu_items={
32
+ 'Get Help': 'https://www.streamlit.io/community',
33
+ 'Report a bug': None,
34
+ 'About': "# Dashboard App\nBuilt with Streamlit"
35
+ }
36
+ )
37
 
 
 
 
38
 
39
  def main():
40
+ """
41
+ Main application function
42
+ """
43
+ # Initialize session state
44
+ init_session_state('current_page', 'dashboard')
45
+ init_session_state('user_settings', {})
46
+ init_session_state('app_initialized', False)
47
+
48
+ # App initialization
49
+ if not get_session_state('app_initialized'):
50
+ initialize_app()
51
+ set_session_state('app_initialized', True)
52
+
53
+ # Create sidebar navigation
54
+ create_sidebar()
55
+
56
+ # Main content area
57
+ current_page = get_session_state('current_page', 'dashboard')
58
+
59
+ if current_page == 'dashboard':
60
+ create_dashboard_page()
61
+ else:
62
+ st.error("Page not found!")
63
+
64
+
65
+ def initialize_app():
66
+ """
67
+ Initialize the application
68
+ """
69
+ # Create necessary directories
70
+ os.makedirs('data', exist_ok=True)
71
+ os.makedirs('cache', exist_ok=True)
72
+ os.makedirs('logs', exist_ok=True)
73
+
74
+ # Configure logging
75
+ logging.basicConfig(
76
+ level=logging.INFO,
77
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
78
+ handlers=[
79
+ logging.FileHandler('logs/app.log'),
80
+ logging.StreamHandler()
81
+ ]
82
+ )
83
+
84
+ logging.info("Application initialized successfully")
85
+
86
+
87
+ def create_sidebar():
88
+ """
89
+ Create sidebar navigation
90
+ """
91
+ with st.sidebar:
92
+ st.title("🏠 Navigation")
93
 
94
+ # Page navigation
95
+ page_options = {
96
+ 'dashboard': 'πŸ“Š Dashboard',
97
+ # Add more pages here as needed
98
+ }
99
 
100
+ current_page = st.radio(
101
+ "Select Page",
102
+ options=list(page_options.keys()),
103
+ format_func=lambda x: page_options[x],
104
+ index=0
105
  )
106
 
107
+ set_session_state('current_page', current_page)
108
+
109
+ st.markdown("---")
110
+
111
+ # App info
112
+ st.subheader("ℹ️ App Info")
113
+ st.info(f"**Version:** 1.0.0\n**Last Updated:** {datetime.now().strftime('%Y-%m-%d')}")
114
+
115
+ # Settings
116
+ st.subheader("βš™οΈ Settings")
117
+
118
+ # Theme toggle (placeholder)
119
+ theme = st.selectbox("Theme", ["Light", "Dark"], index=0)
120
+
121
+ # Auto-refresh toggle
122
+ auto_refresh = st.checkbox("Auto Refresh", value=False)
123
+ if auto_refresh:
124
+ refresh_interval = st.slider("Refresh Interval (seconds)", 30, 300, 60)
125
+ st.session_state.refresh_interval = refresh_interval
126
+
127
+ # Save settings
128
+ user_settings = {
129
+ 'theme': theme,
130
+ 'auto_refresh': auto_refresh,
131
+ 'refresh_interval': st.session_state.get('refresh_interval', 60)
132
+ }
133
+ set_session_state('user_settings', user_settings)
134
+
135
+ st.markdown("---")
136
+
137
+ # Debug info (only show in development)
138
+ if st.checkbox("Show Debug Info"):
139
+ st.subheader("πŸ› Debug Info")
140
+ st.json({
141
+ 'Current Page': current_page,
142
+ 'Session State Keys': list(st.session_state.keys()),
143
+ 'User Settings': get_session_state('user_settings', {}),
144
+ 'App Initialized': get_session_state('app_initialized', False)
145
+ })
146
+
147
+
148
+ @handle_data_exceptions
149
+ def handle_error_boundary():
150
+ """
151
+ Global error handler for the application
152
+ """
153
+ try:
154
+ main()
155
  except Exception as e:
156
+ log_error("Critical application error", e)
157
+ st.error("A critical error occurred. Please refresh the page.")
158
+
159
+ # Show error details in expander
160
+ with st.expander("Error Details"):
161
+ st.exception(e)
162
+
163
+
164
+ # Health check endpoint
165
+ def health_check():
166
+ """
167
+ Simple health check for the application
168
+ """
169
+ return {
170
+ 'status': 'healthy',
171
+ 'timestamp': datetime.now().isoformat(),
172
+ 'version': '1.0.0'
173
+ }
174
+
175
 
176
  if __name__ == "__main__":
177
+ try:
178
+ handle_error_boundary()
179
+ except Exception as e:
180
+ print(f"Fatal error: {e}")
181
+ import traceback
182
+ traceback.print_exc()