File size: 5,486 Bytes
2a502d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
from chatbot import LearningChatbot
import traceback
import gc
import sys

# Configure garbage collection for more aggressive memory management
gc.enable()
gc.set_threshold(700, 10, 5)

# Set memory usage limit for streamlit (4GB)
if sys.platform.startswith('win'):
    import ctypes
    kernel32 = ctypes.windll.kernel32
    kernel32.SetProcessWorkingSetSize(-1, -1, -1)

def init_session_state():
    """Initialize session state variables"""
    try:
        if 'initialized' not in st.session_state:
            st.session_state.initialized = False
        
        if not st.session_state.initialized:
            with st.status("Initializing Learning Assistant...", expanded=True) as status:
                st.write("Loading documents and building knowledge base...")
                st.session_state.chatbot = LearningChatbot()
                st.session_state.messages = []
                st.session_state.error = None
                status.update(label="Ready!", state="complete", expanded=False)
            
            st.session_state.initialized = True
    except Exception as e:
        st.session_state.error = f"Initialization Error: {str(e)}"
        print(f"Error during initialization: {traceback.format_exc()}")

def display_error_message():
    """Display error message with a helpful tone"""
    st.error(
        "I'm having trouble getting started. Could you help me check:\n"
        "1. If the study materials are in the documents folder?\n"
        "2. If the API key is set up correctly?\n"
        "3. If all the required packages are installed?"
    )
    if st.session_state.error:
        with st.expander("Technical Details"):
            st.code(st.session_state.error)

def main():
    try:
        st.set_page_config(
            page_title="OpexA Career Assistant",
            page_icon="πŸš€",
            layout="wide",
            initial_sidebar_state="expanded"
        )
    except Exception as e:
        st.write("Error configuring page:", str(e))
        return

    # Initialize session
    init_session_state()

    # Check for errors
    if hasattr(st.session_state, 'error') and st.session_state.error:
        display_error_message()
        return

    # Header with OpexA branding
    col1, col2 = st.columns([3, 1])
    with col1:
        st.title("πŸš€ OpexA Career Assistant")
        st.caption("Your AI guide for IT career growth and skill development")
    
    # Enhanced sidebar with OpexA info
    with st.sidebar:
        st.info("""

        **Welcome to OpexA!** 🎯

        

        I'm your AI career assistant, here to help you:

        β€’ Navigate your IT career path

        β€’ Understand skill assessments (CMA & SLA)

        β€’ Explore learning opportunities

        β€’ Make informed career decisions

        

        Ask me anything about your professional journey!

        """)
        
        # Add subscription plan info
        with st.expander("πŸ’‘ Available Plans"):
            st.markdown("""

            **Explorer (Free)**

            β€’ Basic career guides

            β€’ Initial assessments

            β€’ Community access

            

            **Starter**

            β€’ Advanced features

            β€’ Full SLA access

            β€’ Personalized learning paths

            β€’ Premium resources

            """)
        
        # Clear conversation button with improved styling
        if st.button("πŸ”„ Start Fresh"):
            st.session_state.messages = []
            st.rerun()

    # Chat interface
    try:
        # Display chat messages with improved formatting
        for message in st.session_state.messages:
            with st.chat_message(message["role"]):
                st.markdown(message["content"])

        # Enhanced chat input
        prompt = st.chat_input("Ask about your IT career journey, skills, or OpexA features...")

        if prompt:
            # Validate chatbot
            if not hasattr(st.session_state, 'chatbot') or not st.session_state.chatbot.verify_knowledge_base():
                st.error("Give me a moment to get ready. Please check if everything is set up correctly.")
                return

            # Show user message
            st.session_state.messages.append({"role": "user", "content": prompt})
            with st.chat_message("user"):
                st.markdown(prompt)

            # Generate and show response with improved error handling
            with st.chat_message("assistant"):
                with st.spinner("Analyzing your question..."):
                    try:
                        response = st.session_state.chatbot.generate_response(prompt)
                        st.markdown(response)
                        st.session_state.messages.append({
                            "role": "assistant",
                            "content": response
                        })
                    except Exception as e:
                        st.error("I apologize, but I'm having trouble understanding that. Could you rephrase your question?")
                        print(f"Error generating response: {str(e)}")

    except Exception as e:
        st.error("Something unexpected happened. Let's start fresh!")
        print(f"Error in main loop: {traceback.format_exc()}")

if __name__ == "__main__":
    main()