mona / app.py
mrradix's picture
Update app.py
594f2c9 verified
raw
history blame
8.67 kB
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)