mrradix commited on
Commit
594f2c9
Β·
verified Β·
1 Parent(s): 8f8bf22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +244 -246
app.py CHANGED
@@ -1,282 +1,280 @@
1
- """
2
- Main application file for MONA
3
- Fixed version with proper imports and error handling
4
- """
5
-
6
  import streamlit as st
 
7
  import sys
8
- from pathlib import Path
9
-
10
- # Add the current directory to Python path for imports
11
- current_dir = Path(__file__).parent
12
- sys.path.append(str(current_dir))
13
-
14
- try:
15
- from pages.dashboard import create_dashboard_page
16
- from utils.logging import setup_logging, get_logger, log_info, log_error
17
- from utils.error_handling import ErrorHandler
18
- from utils.storage import initialize_sample_data
19
- except ImportError as e:
20
- st.error(f"Import Error: {str(e)}")
21
- st.error("Please ensure all required files are present and properly configured.")
22
- st.stop()
23
 
24
-
25
- def setup_streamlit_config():
26
- """Configure Streamlit page settings"""
27
- st.set_page_config(
28
- page_title="MONA - Dashboard",
29
- page_icon="🎯",
30
- layout="wide",
31
- initial_sidebar_state="expanded"
 
 
32
  )
 
33
 
 
 
 
 
 
 
 
 
34
 
35
- def create_sidebar():
36
- """Create application sidebar"""
37
- with st.sidebar:
38
- st.title("🎯 MONA")
39
- st.markdown("---")
40
-
41
- # Navigation
42
- st.subheader("Navigation")
43
- page = st.selectbox(
44
- "Select Page",
45
- ["Dashboard", "Analytics", "Settings", "Help"],
46
- index=0
47
- )
48
-
49
- st.markdown("---")
50
-
51
- # Quick Stats
52
- st.subheader("Quick Stats")
53
- try:
54
- from utils.storage import load_data
55
- metrics = load_data("dashboard_metrics.json", default={})
56
-
57
- if metrics:
58
- st.metric("Total Users", f"{metrics.get('total_users', 0):,}")
59
- st.metric("Active Sessions", f"{metrics.get('active_sessions', 0):,}")
60
- st.metric("System Health", f"{metrics.get('system_health', 0):.1f}%")
61
- except Exception as e:
62
- st.warning("Could not load quick stats")
63
-
64
- st.markdown("---")
65
-
66
- # System Status
67
- st.subheader("System Status")
68
- st.success("🟒 All Systems Operational")
69
-
70
- return page
71
 
 
 
72
 
73
- def create_header():
74
- """Create application header"""
75
- col1, col2, col3 = st.columns([2, 6, 2])
76
-
77
- with col1:
78
- st.image("https://via.placeholder.com/100x50/4CAF50/FFFFFF?text=MONA", width=100)
79
-
80
- with col2:
81
- st.markdown("""
82
- <h1 style='text-align: center; color: #1f77b4;'>
83
- MONA Monitoring & Analytics Platform
84
- </h1>
85
- """, unsafe_allow_html=True)
86
-
87
- with col3:
88
- if st.button("πŸ”„ Refresh All"):
89
- from utils.storage import clear_cache
90
- clear_cache()
91
- st.rerun()
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- def create_footer():
95
- """Create application footer"""
96
- st.markdown("---")
97
- col1, col2, col3 = st.columns([1, 2, 1])
98
-
99
- with col2:
100
  st.markdown("""
101
- <div style='text-align: center; color: #666;'>
102
- <p>MONA Platform v2.1.0 | Built with Streamlit</p>
103
- <p>Β© 2024 MONA Systems. All rights reserved.</p>
104
  </div>
105
  """, unsafe_allow_html=True)
106
-
107
-
108
- def create_analytics_page():
109
- """Create analytics page (placeholder)"""
110
- st.title("πŸ“ˆ Analytics")
111
- st.info("Analytics page coming soon...")
112
-
113
- # Placeholder content
114
- col1, col2 = st.columns(2)
115
-
116
- with col1:
117
- st.subheader("Data Overview")
118
- st.write("β€’ Total Records: 10,000+")
119
- st.write("β€’ Data Sources: 5")
120
- st.write("β€’ Last Update: Just now")
121
-
122
- with col2:
 
 
 
 
 
 
 
 
 
 
 
 
123
  st.subheader("Quick Actions")
124
- if st.button("Generate Report"):
125
- st.success("Report generation initiated")
126
- if st.button("Export Data"):
127
- st.success("Data export started")
128
-
129
-
130
- def create_settings_page():
131
- """Create settings page (placeholder)"""
132
- st.title("βš™οΈ Settings")
133
-
134
- tab1, tab2, tab3 = st.tabs(["General", "Security", "Advanced"])
135
-
136
- with tab1:
137
- st.subheader("General Settings")
138
 
139
  col1, col2 = st.columns(2)
 
140
  with col1:
141
- st.text_input("Application Name", value="MONA")
142
- st.selectbox("Theme", ["Light", "Dark", "Auto"])
143
- st.selectbox("Language", ["English", "Spanish", "French"])
144
 
145
  with col2:
146
- st.number_input("Refresh Interval (seconds)", min_value=1, max_value=300, value=30)
147
- st.checkbox("Enable Notifications", value=True)
148
- st.checkbox("Auto-save Settings", value=True)
149
-
150
- with tab2:
151
- st.subheader("Security Settings")
152
- st.text_input("Admin Password", type="password")
153
- st.checkbox("Enable Two-Factor Authentication")
154
- st.checkbox("Enable Audit Logging", value=True)
155
- st.selectbox("Session Timeout", ["15 minutes", "30 minutes", "1 hour", "4 hours"])
156
-
157
- with tab3:
158
- st.subheader("Advanced Settings")
159
- st.code("""
160
- {
161
- "debug_mode": false,
162
- "cache_size": 100,
163
- "max_connections": 20,
164
- "log_level": "INFO"
165
- }
166
- """)
167
-
168
- if st.button("Reset to Defaults"):
169
- st.warning("Settings reset to default values")
170
-
171
 
172
- def create_help_page():
173
- """Create help page"""
174
- st.title("❓ Help & Documentation")
175
-
176
- col1, col2 = st.columns([1, 2])
177
-
178
- with col1:
179
- st.subheader("Quick Links")
180
- st.markdown("""
181
- - [Getting Started](#getting-started)
182
- - [Dashboard Guide](#dashboard)
183
- - [Analytics](#analytics)
184
- - [Troubleshooting](#troubleshooting)
185
- - [API Documentation](#api)
186
- """)
187
-
188
- with col2:
189
- st.subheader("Getting Started")
190
- st.markdown("""
191
- Welcome to MONA! This platform provides comprehensive monitoring
192
- and analytics capabilities for your systems.
193
-
194
- **Key Features:**
195
- - Real-time dashboard with key metrics
196
- - System performance monitoring
197
- - User activity tracking
198
- - Event logging and analysis
199
- - Customizable alerts and notifications
200
-
201
- **Navigation:**
202
- Use the sidebar to navigate between different sections of the application.
203
- The dashboard provides an overview of system health and key metrics.
204
- """)
205
-
206
- st.subheader("Dashboard Guide")
207
- st.markdown("""
208
- The dashboard displays:
209
- - **Key Metrics:** Total users, active sessions, system health
210
- - **Activity Charts:** User activity over time
211
- - **Performance Graphs:** CPU, memory, and disk usage
212
- - **Recent Events:** Latest system events and alerts
213
- - **System Status:** Current status of all services
214
- """)
215
-
216
- st.subheader("Troubleshooting")
217
- with st.expander("Common Issues"):
218
- st.markdown("""
219
- **Data not loading:**
220
- - Check your internet connection
221
- - Try refreshing the page
222
- - Contact support if issue persists
223
 
224
- **Charts not displaying:**
225
- - Ensure JavaScript is enabled
226
- - Try a different browser
227
- - Clear browser cache
228
- """)
229
-
 
 
 
 
 
230
 
231
- def main():
232
- """Main application function"""
233
  try:
234
- # Setup logging
235
- setup_logging()
236
- logger = get_logger(__name__)
237
- log_info("Starting MONA application")
238
 
239
- # Configure Streamlit
240
- setup_streamlit_config()
 
 
 
241
 
242
- with ErrorHandler("main_application", raise_on_error=False):
243
- # Create header
244
- create_header()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
- # Create sidebar and get selected page
247
- selected_page = create_sidebar()
 
 
 
248
 
249
- # Main content area
250
  st.markdown("---")
251
 
252
- # Route to appropriate page
253
- if selected_page == "Dashboard":
254
- create_dashboard_page()
255
- elif selected_page == "Analytics":
256
- create_analytics_page()
257
- elif selected_page == "Settings":
258
- create_settings_page()
259
- elif selected_page == "Help":
260
- create_help_page()
261
- else:
262
- st.error(f"Unknown page: {selected_page}")
263
 
264
- # Create footer
265
- create_footer()
 
 
 
266
 
267
- log_info("MONA application loaded successfully")
268
 
269
  except Exception as e:
270
- log_error("Critical error in main application", error=e)
271
- st.error("⚠️ Application Error")
272
- st.error("A critical error occurred. Please check the logs and try again.")
273
-
274
- # Show error details for debugging
275
- with st.expander("Error Details"):
276
- st.code(str(e))
277
- import traceback
278
- st.code(traceback.format_exc())
279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
281
  if __name__ == "__main__":
282
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import logging
3
  import sys
4
+ import traceback
5
+ from datetime import datetime
6
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Configure logging at the module level
9
+ def setup_logging():
10
+ """Setup logging configuration"""
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
14
+ handlers=[
15
+ logging.StreamHandler(sys.stdout),
16
+ logging.FileHandler('app.log', mode='a')
17
+ ]
18
  )
19
+ return logging.getLogger(__name__)
20
 
21
+ def log_error(message, error=None):
22
+ """Log error with traceback if available"""
23
+ logger = logging.getLogger(__name__)
24
+ if error:
25
+ logger.error(f"{message}: {str(error)}")
26
+ logger.error(f"Traceback: {traceback.format_exc()}")
27
+ else:
28
+ logger.error(message)
29
 
30
+ def log_info(message):
31
+ """Log info message"""
32
+ logger = logging.getLogger(__name__)
33
+ logger.info(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # Initialize logging
36
+ logger = setup_logging()
37
 
38
+ # Page configuration
39
+ st.set_page_config(
40
+ page_title="Mona - AI Assistant",
41
+ page_icon="πŸ€–",
42
+ layout="wide",
43
+ initial_sidebar_state="expanded"
44
+ )
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # Custom CSS
47
+ st.markdown("""
48
+ <style>
49
+ .main-header {
50
+ font-size: 3rem;
51
+ font-weight: bold;
52
+ text-align: center;
53
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
54
+ -webkit-background-clip: text;
55
+ -webkit-text-fill-color: transparent;
56
+ margin-bottom: 2rem;
57
+ }
58
+ .feature-card {
59
+ background: white;
60
+ padding: 1.5rem;
61
+ border-radius: 10px;
62
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
63
+ border-left: 4px solid #667eea;
64
+ margin: 1rem 0;
65
+ }
66
+ .sidebar-content {
67
+ background: #f8f9fa;
68
+ padding: 1rem;
69
+ border-radius: 10px;
70
+ margin: 1rem 0;
71
+ }
72
+ </style>
73
+ """, unsafe_allow_html=True)
74
 
75
+ def create_dashboard_page():
76
+ """Create the main dashboard page"""
77
+ try:
78
+ st.markdown('<h1 class="main-header">πŸ€– Mona AI Assistant</h1>', unsafe_allow_html=True)
79
+
80
+ # Welcome message
81
  st.markdown("""
82
+ <div class="feature-card">
83
+ <h3>Welcome to Mona!</h3>
84
+ <p>Your intelligent AI assistant ready to help with various tasks.</p>
85
  </div>
86
  """, unsafe_allow_html=True)
87
+
88
+ # Feature cards
89
+ col1, col2, col3 = st.columns(3)
90
+
91
+ with col1:
92
+ st.markdown("""
93
+ <div class="feature-card">
94
+ <h4>πŸ’¬ Chat</h4>
95
+ <p>Have conversations with AI</p>
96
+ </div>
97
+ """, unsafe_allow_html=True)
98
+
99
+ with col2:
100
+ st.markdown("""
101
+ <div class="feature-card">
102
+ <h4>πŸ“Š Analytics</h4>
103
+ <p>Data analysis and insights</p>
104
+ </div>
105
+ """, unsafe_allow_html=True)
106
+
107
+ with col3:
108
+ st.markdown("""
109
+ <div class="feature-card">
110
+ <h4>πŸ”§ Tools</h4>
111
+ <p>Various utility functions</p>
112
+ </div>
113
+ """, unsafe_allow_html=True)
114
+
115
+ # Main content area
116
  st.subheader("Quick Actions")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  col1, col2 = st.columns(2)
119
+
120
  with col1:
121
+ if st.button("Start Chat", type="primary"):
122
+ st.switch_page("pages/chat.py")
 
123
 
124
  with col2:
125
+ if st.button("View Analytics"):
126
+ st.switch_page("pages/analytics.py")
127
+
128
+ # Recent activity
129
+ st.subheader("Recent Activity")
130
+ st.info("No recent activity to display.")
131
+
132
+ log_info("Dashboard page loaded successfully")
133
+
134
+ except Exception as e:
135
+ log_error("Error in dashboard page", error=e)
136
+ st.error("An error occurred while loading the dashboard. Please try again.")
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
+ def create_chat_page():
139
+ """Create the chat page"""
140
+ try:
141
+ st.title("πŸ’¬ Chat with Mona")
142
+
143
+ # Initialize session state
144
+ if "messages" not in st.session_state:
145
+ st.session_state.messages = []
146
+
147
+ # Display chat messages
148
+ for message in st.session_state.messages:
149
+ with st.chat_message(message["role"]):
150
+ st.markdown(message["content"])
151
+
152
+ # Chat input
153
+ if prompt := st.chat_input("What would you like to know?"):
154
+ # Add user message
155
+ st.session_state.messages.append({"role": "user", "content": prompt})
156
+ with st.chat_message("user"):
157
+ st.markdown(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
+ # Add assistant response
160
+ with st.chat_message("assistant"):
161
+ response = f"I received your message: '{prompt}'. This is a demo response. In a real implementation, this would connect to an AI service."
162
+ st.markdown(response)
163
+ st.session_state.messages.append({"role": "assistant", "content": response})
164
+
165
+ log_info("Chat page loaded successfully")
166
+
167
+ except Exception as e:
168
+ log_error("Error in chat page", error=e)
169
+ st.error("An error occurred in the chat. Please try again.")
170
 
171
+ def create_analytics_page():
172
+ """Create the analytics page"""
173
  try:
174
+ st.title("πŸ“Š Analytics Dashboard")
175
+
176
+ # Sample analytics content
177
+ col1, col2, col3 = st.columns(3)
178
 
179
+ with col1:
180
+ st.metric("Total Users", "1,234", "+5%")
181
+
182
+ with col2:
183
+ st.metric("Active Sessions", "456", "+12%")
184
 
185
+ with col3:
186
+ st.metric("Messages Sent", "7,890", "+8%")
187
+
188
+ # Sample chart
189
+ import pandas as pd
190
+ import numpy as np
191
+
192
+ chart_data = pd.DataFrame(
193
+ np.random.randn(20, 3),
194
+ columns=['Series A', 'Series B', 'Series C']
195
+ )
196
+
197
+ st.line_chart(chart_data)
198
+
199
+ log_info("Analytics page loaded successfully")
200
+
201
+ except Exception as e:
202
+ log_error("Error in analytics page", error=e)
203
+ st.error("An error occurred while loading analytics. Please try again.")
204
+
205
+ def create_sidebar():
206
+ """Create the sidebar navigation"""
207
+ try:
208
+ with st.sidebar:
209
+ st.markdown('<div class="sidebar-content">', unsafe_allow_html=True)
210
+ st.title("Navigation")
211
+
212
+ # Navigation buttons
213
+ if st.button("🏠 Dashboard", use_container_width=True):
214
+ st.switch_page("app.py")
215
 
216
+ if st.button("πŸ’¬ Chat", use_container_width=True):
217
+ st.switch_page("pages/chat.py")
218
+
219
+ if st.button("πŸ“Š Analytics", use_container_width=True):
220
+ st.switch_page("pages/analytics.py")
221
 
 
222
  st.markdown("---")
223
 
224
+ # Settings section
225
+ st.subheader("Settings")
226
+ theme = st.selectbox("Theme", ["Light", "Dark"])
227
+ language = st.selectbox("Language", ["English", "Spanish", "French"])
228
+
229
+ st.markdown("---")
 
 
 
 
 
230
 
231
+ # Info section
232
+ st.subheader("Info")
233
+ st.markdown(f"**Version:** 1.0.0")
234
+ st.markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d')}")
235
+ st.markdown('</div>', unsafe_allow_html=True)
236
 
237
+ log_info("Sidebar created successfully")
238
 
239
  except Exception as e:
240
+ log_error("Error creating sidebar", error=e)
 
 
 
 
 
 
 
 
241
 
242
+ def main():
243
+ """Main application function"""
244
+ try:
245
+ # Setup logging first
246
+ setup_logging()
247
+ log_info("Application starting up")
248
+
249
+ # Create sidebar
250
+ create_sidebar()
251
+
252
+ # Get current page
253
+ current_page = st.session_state.get('page', 'dashboard')
254
+
255
+ # Route to appropriate page
256
+ if current_page == 'chat':
257
+ create_chat_page()
258
+ elif current_page == 'analytics':
259
+ create_analytics_page()
260
+ else:
261
+ create_dashboard_page()
262
+
263
+ log_info("Application loaded successfully")
264
+
265
+ except Exception as e:
266
+ log_error("Critical error in main application", error=e)
267
+ st.error("A critical error occurred. Please refresh the page or contact support.")
268
+ st.exception(e)
269
 
270
  if __name__ == "__main__":
271
+ try:
272
+ main()
273
+ except Exception as e:
274
+ # Final fallback error handling
275
+ print(f"Critical application error: {str(e)}")
276
+ print(f"Traceback: {traceback.format_exc()}")
277
+
278
+ # Still try to show something in Streamlit
279
+ st.error("Application failed to start. Please check the logs.")
280
+ st.exception(e)