mrradix commited on
Commit
6b85b68
Β·
verified Β·
1 Parent(s): d1e9503

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +270 -132
app.py CHANGED
@@ -1,144 +1,282 @@
1
- import gradio as gr
2
- import os
3
- import json
4
- import datetime
 
 
 
5
  from pathlib import Path
6
 
7
- # Import pages
8
- from pages.dashboard import create_dashboard_page
9
- from pages.tasks import create_tasks_page
10
- from pages.notes import create_notes_page
11
- from pages.goals import create_goals_page
12
- from pages.ai_assistant import create_ai_assistant_page
13
- from pages.search import create_search_page
14
- from pages.analytics import create_analytics_page
15
- from pages.focus import create_focus_page
16
- from pages.integrations_new import create_integrations_page # Using the new integrations page
17
- from pages.settings import create_settings_page
18
- from pages.multimedia import create_multimedia_page
19
-
20
- # Import utilities
21
- from utils.storage import load_data, save_data
22
- from utils.state import initialize_state, record_activity
23
- from utils.config import DATA_DIR, LOGGING_CONFIG
24
- from utils.logging import get_logger
25
- from utils.error_handling import handle_exceptions
26
-
27
- # Initialize logger
28
- logger = get_logger(__name__)
29
-
30
- # Define sidebar items
31
- sidebar_items = [
32
- "🏠 Dashboard",
33
- "πŸ“‹ Tasks & Projects",
34
- "πŸ“ Notes & Docs",
35
- "🎯 Goals & Planning",
36
- "πŸ€– AI Assistant Hub",
37
- "πŸ” Smart Search",
38
- "πŸ“Š Analytics",
39
- "🧘 Focus & Wellness",
40
- "πŸ–ΌοΈ Multimedia",
41
- "πŸ”„ Integrations",
42
- "βš™οΈ Settings"
43
- ]
44
-
45
- # Map sidebar items to page creation functions
46
- page_creators = {
47
- "🏠 Dashboard": create_dashboard_page,
48
- "πŸ“‹ Tasks & Projects": create_tasks_page,
49
- "πŸ“ Notes & Docs": create_notes_page,
50
- "🎯 Goals & Planning": create_goals_page,
51
- "πŸ€– AI Assistant Hub": create_ai_assistant_page,
52
- "πŸ” Smart Search": create_search_page,
53
- "πŸ“Š Analytics": create_analytics_page,
54
- "🧘 Focus & Wellness": create_focus_page,
55
- "πŸ–ΌοΈ Multimedia": create_multimedia_page,
56
- "πŸ”„ Integrations": create_integrations_page,
57
- "βš™οΈ Settings": create_settings_page
58
- }
59
-
60
- @handle_exceptions
61
- def create_app():
62
- """Create and configure the Gradio application"""
63
- logger.info("Initializing Mona application")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Initialize application state
66
- state = initialize_state()
67
 
68
- # Create the Gradio Blocks app
69
- with gr.Blocks(title="Mona - AI Productivity Platform", theme=gr.themes.Soft()) as app:
70
- # Create header
71
- with gr.Row(elem_id="header"):
72
- gr.Markdown("# Mona - AI Productivity Platform")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- # Create main layout with sidebar and content area
75
- with gr.Row():
76
- # Sidebar navigation
77
- with gr.Column(scale=1, elem_id="sidebar"):
78
- # User profile section
79
- with gr.Group(elem_id="user-profile"):
80
- gr.Markdown("### Welcome!")
81
-
82
- # Navigation menu
83
- selected_page = gr.Radio(
84
- choices=sidebar_items,
85
- value=sidebar_items[0],
86
- label="Navigation",
87
- elem_id="nav-menu"
88
- )
89
-
90
- # App info
91
- with gr.Group(elem_id="app-info"):
92
- gr.Markdown("v0.1.0 | Using Free AI Models")
 
 
 
 
 
93
 
94
  # Main content area
95
- with gr.Column(scale=4, elem_id="content-area"):
96
- # Create a container for each page
97
- for page_name, create_page in page_creators.items():
98
- with gr.Group(visible=(page_name == sidebar_items[0])) as page_container:
99
- create_page(state)
100
- # Store the container in state for navigation
101
- state[f"{page_name}_container"] = page_container
102
-
103
- # Handle navigation changes
104
- @handle_exceptions
105
- def change_page(page_name):
106
- """Show the selected page and hide others"""
107
- logger.debug(f"Navigating to page: {page_name}")
108
- return [gr.update(visible=(name == page_name)) for name in sidebar_items]
109
-
110
- # Set up navigation event handler
111
- page_containers = [state[f"{name}_container"] for name in sidebar_items]
112
- selected_page.change(change_page, inputs=selected_page, outputs=page_containers)
113
-
114
- # Record app usage for analytics
115
- @handle_exceptions
116
- def record_app_usage():
117
- """Record app usage for analytics"""
118
- logger.info("Recording app usage")
119
 
120
- # Record activity using the centralized function
121
- # Commented out due to incorrect parameters
122
- # record_activity requires state, activity_type, and title
123
- # record_activity({
124
- # "type": "app_opened",
125
- # "timestamp": datetime.datetime.now().isoformat()
126
- # })
 
 
 
 
127
 
128
- # Correct implementation would be:
129
- # record_activity(state, "app_opened", "Application Started")
130
 
131
- # Record app usage on load
132
- app.load(record_app_usage)
133
-
134
- logger.info("Mona application initialized successfully")
135
- return app
 
 
 
 
 
 
 
 
136
 
137
  if __name__ == "__main__":
138
- try:
139
- logger.info("Starting Mona application")
140
- app = create_app()
141
- app.launch()
142
- except Exception as e:
143
- logger.error(f"Failed to start application: {str(e)}")
144
- raise
 
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()