File size: 8,667 Bytes
6b85b68
594f2c9
6b85b68
594f2c9
 
 
6b85b68
594f2c9
 
 
 
 
 
 
 
 
 
6b85b68
594f2c9
6b85b68
594f2c9
 
 
 
 
 
 
 
6b85b68
594f2c9
 
 
 
6b85b68
594f2c9
 
6b85b68
594f2c9
 
 
 
 
 
 
6b85b68
594f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b85b68
594f2c9
 
 
 
 
 
6b85b68
594f2c9
 
 
6b85b68
 
594f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b85b68
 
 
594f2c9
6b85b68
594f2c9
 
6b85b68
 
594f2c9
 
 
 
 
 
 
 
 
 
 
 
6b85b68
594f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72215e9
594f2c9
 
 
 
 
 
 
 
 
 
 
6b85b68
594f2c9
 
6b85b68
594f2c9
 
 
 
6b85b68
594f2c9
 
 
 
 
6b85b68
594f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b85b68
594f2c9
 
 
 
 
72215e9
6b85b68
72215e9
594f2c9
 
 
 
 
 
72215e9
594f2c9
 
 
 
 
8e4018d
594f2c9
6b85b68
 
594f2c9
6b85b68
594f2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e4018d
 
594f2c9
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import streamlit as st
import logging
import sys
import traceback
from datetime import datetime
import os

# Configure logging at the module level
def setup_logging():
    """Setup logging configuration"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler('app.log', mode='a')
        ]
    )
    return logging.getLogger(__name__)

def log_error(message, error=None):
    """Log error with traceback if available"""
    logger = logging.getLogger(__name__)
    if error:
        logger.error(f"{message}: {str(error)}")
        logger.error(f"Traceback: {traceback.format_exc()}")
    else:
        logger.error(message)

def log_info(message):
    """Log info message"""
    logger = logging.getLogger(__name__)
    logger.info(message)

# Initialize logging
logger = setup_logging()

# Page configuration
st.set_page_config(
    page_title="Mona - AI Assistant",
    page_icon="πŸ€–",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""
<style>
    .main-header {
        font-size: 3rem;
        font-weight: bold;
        text-align: center;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 2rem;
    }
    .feature-card {
        background: white;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        border-left: 4px solid #667eea;
        margin: 1rem 0;
    }
    .sidebar-content {
        background: #f8f9fa;
        padding: 1rem;
        border-radius: 10px;
        margin: 1rem 0;
    }
</style>
""", unsafe_allow_html=True)

def create_dashboard_page():
    """Create the main dashboard page"""
    try:
        st.markdown('<h1 class="main-header">πŸ€– Mona AI Assistant</h1>', unsafe_allow_html=True)
        
        # Welcome message
        st.markdown("""
        <div class="feature-card">
            <h3>Welcome to Mona!</h3>
            <p>Your intelligent AI assistant ready to help with various tasks.</p>
        </div>
        """, unsafe_allow_html=True)
        
        # Feature cards
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.markdown("""
            <div class="feature-card">
                <h4>πŸ’¬ Chat</h4>
                <p>Have conversations with AI</p>
            </div>
            """, unsafe_allow_html=True)
        
        with col2:
            st.markdown("""
            <div class="feature-card">
                <h4>πŸ“Š Analytics</h4>
                <p>Data analysis and insights</p>
            </div>
            """, unsafe_allow_html=True)
        
        with col3:
            st.markdown("""
            <div class="feature-card">
                <h4>πŸ”§ Tools</h4>
                <p>Various utility functions</p>
            </div>
            """, unsafe_allow_html=True)
        
        # Main content area
        st.subheader("Quick Actions")
        
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("Start Chat", type="primary"):
                st.switch_page("pages/chat.py")
        
        with col2:
            if st.button("View Analytics"):
                st.switch_page("pages/analytics.py")
        
        # Recent activity
        st.subheader("Recent Activity")
        st.info("No recent activity to display.")
        
        log_info("Dashboard page loaded successfully")
        
    except Exception as e:
        log_error("Error in dashboard page", error=e)
        st.error("An error occurred while loading the dashboard. Please try again.")

def create_chat_page():
    """Create the chat page"""
    try:
        st.title("πŸ’¬ Chat with Mona")
        
        # Initialize session state
        if "messages" not in st.session_state:
            st.session_state.messages = []
        
        # Display chat messages
        for message in st.session_state.messages:
            with st.chat_message(message["role"]):
                st.markdown(message["content"])
        
        # Chat input
        if prompt := st.chat_input("What would you like to know?"):
            # Add user message
            st.session_state.messages.append({"role": "user", "content": prompt})
            with st.chat_message("user"):
                st.markdown(prompt)
            
            # Add assistant response
            with st.chat_message("assistant"):
                response = f"I received your message: '{prompt}'. This is a demo response. In a real implementation, this would connect to an AI service."
                st.markdown(response)
                st.session_state.messages.append({"role": "assistant", "content": response})
        
        log_info("Chat page loaded successfully")
        
    except Exception as e:
        log_error("Error in chat page", error=e)
        st.error("An error occurred in the chat. Please try again.")

def create_analytics_page():
    """Create the analytics page"""
    try:
        st.title("πŸ“Š Analytics Dashboard")
        
        # Sample analytics content
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("Total Users", "1,234", "+5%")
        
        with col2:
            st.metric("Active Sessions", "456", "+12%")
        
        with col3:
            st.metric("Messages Sent", "7,890", "+8%")
        
        # Sample chart
        import pandas as pd
        import numpy as np
        
        chart_data = pd.DataFrame(
            np.random.randn(20, 3),
            columns=['Series A', 'Series B', 'Series C']
        )
        
        st.line_chart(chart_data)
        
        log_info("Analytics page loaded successfully")
        
    except Exception as e:
        log_error("Error in analytics page", error=e)
        st.error("An error occurred while loading analytics. Please try again.")

def create_sidebar():
    """Create the sidebar navigation"""
    try:
        with st.sidebar:
            st.markdown('<div class="sidebar-content">', unsafe_allow_html=True)
            st.title("Navigation")
            
            # Navigation buttons
            if st.button("🏠 Dashboard", use_container_width=True):
                st.switch_page("app.py")
            
            if st.button("πŸ’¬ Chat", use_container_width=True):
                st.switch_page("pages/chat.py")
            
            if st.button("πŸ“Š Analytics", use_container_width=True):
                st.switch_page("pages/analytics.py")
            
            st.markdown("---")
            
            # Settings section
            st.subheader("Settings")
            theme = st.selectbox("Theme", ["Light", "Dark"])
            language = st.selectbox("Language", ["English", "Spanish", "French"])
            
            st.markdown("---")
            
            # Info section
            st.subheader("Info")
            st.markdown(f"**Version:** 1.0.0")
            st.markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d')}")
            st.markdown('</div>', unsafe_allow_html=True)
        
        log_info("Sidebar created successfully")
        
    except Exception as e:
        log_error("Error creating sidebar", error=e)

def main():
    """Main application function"""
    try:
        # Setup logging first
        setup_logging()
        log_info("Application starting up")
        
        # Create sidebar
        create_sidebar()
        
        # Get current page
        current_page = st.session_state.get('page', 'dashboard')
        
        # Route to appropriate page
        if current_page == 'chat':
            create_chat_page()
        elif current_page == 'analytics':
            create_analytics_page()
        else:
            create_dashboard_page()
        
        log_info("Application loaded successfully")
        
    except Exception as e:
        log_error("Critical error in main application", error=e)
        st.error("A critical error occurred. Please refresh the page or contact support.")
        st.exception(e)

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        # Final fallback error handling
        print(f"Critical application error: {str(e)}")
        print(f"Traceback: {traceback.format_exc()}")
        
        # Still try to show something in Streamlit
        st.error("Application failed to start. Please check the logs.")
        st.exception(e)