Spaces:
Sleeping

File size: 15,795 Bytes
604b34a
42510cb
 
 
 
 
604b34a
42510cb
 
 
 
 
 
 
604b34a
42510cb
 
 
 
 
 
 
 
 
 
 
abb2e83
42510cb
 
 
 
 
 
abb2e83
42510cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604b34a
42510cb
 
 
abb2e83
42510cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604b34a
42510cb
 
 
 
 
 
 
 
 
 
 
 
 
 
604b34a
42510cb
 
 
 
 
 
 
 
 
 
 
 
604b34a
42510cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604b34a
42510cb
 
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import streamlit as st
import google.generativeai as genai
import time
import json
from datetime import datetime
import re

# Configure the page
st.set_page_config(
    page_title="CareerPath AI Counselor",
    page_icon="🎯",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# Custom CSS for better styling
st.markdown("""
<style>
    .main-header {
        font-size: 3rem;
        color: #1f77b4;
        text-align: center;
        margin-bottom: 2rem;
        font-weight: bold;
    }
    .counselor-message {
        background-color: #1F1F1F;
        padding: 1rem;
        border-radius: 15px;
        margin: 0.5rem 0;
        border-left: 5px solid #1f77b4;
    }
    .user-message {
        background-color: #1F1F1F;
        padding: 1rem;
        border-radius: 15px;
        margin: 0.5rem 0;
        border-left: 5px solid #ff6b6b;
    }
    .career-button {
        background-color: #4CAF50;
        color: white;
        padding: 0.8rem 1.5rem;
        margin: 0.5rem;
        border: none;
        border-radius: 25px;
        cursor: pointer;
        font-size: 1rem;
        transition: all 0.3s;
    }
    .career-button:hover {
        background-color: #45a049;
        transform: scale(1.05);
    }
    .alternative-button {
        background-color: #ff9800;
        color: white;
        padding: 0.5rem 1rem;
        margin: 0.3rem;
        border: none;
        border-radius: 15px;
        cursor: pointer;
        font-size: 0.9rem;
    }
    .roadmap-section {
        background-color: #f8f9fa;
        padding: 1.5rem;
        border-radius: 10px;
        margin: 1rem 0;
        border-left: 5px solid #2196F3;
    }
    .typing-indicator {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #1f77b4;
        margin: 0 2px;
        animation: typing 1s infinite;
    }
    @keyframes typing {
        0%, 100% { opacity: 0.3; }
        50% { opacity: 1; }
    }
</style>
""", unsafe_allow_html=True)

class CareerCounselor:
    def __init__(self, api_key):
        genai.configure(api_key=api_key)
        self.model = genai.GenerativeModel('gemini-2.0-flash')
        self.conversation_history = []
        
    def get_response(self, prompt, is_initial=False):
        """Get response from Gemini AI with conversation context"""
        try:
            if is_initial:
                system_prompt = """You are a friendly, empathetic career counselor named "PathFinder AI". Your role is to:
                1. Ask engaging questions about hobbies, interests, and skills
                2. Show genuine interest in the user's responses
                3. Guide them toward suitable career paths
                4. Provide detailed, personalized career suggestions
                5. Be encouraging and supportive
                
                Start by introducing yourself and asking about their general interests."""
                full_prompt = system_prompt
            else:
                # Include conversation history for context
                context = "\n".join([f"{'Counselor' if msg['role'] == 'assistant' else 'User'}: {msg['content']}" 
                                   for msg in self.conversation_history[-6:]])  # Last 6 messages for context
                full_prompt = f"Conversation History:\n{context}\n\nCurrent User Message: {prompt}\n\nRespond as a caring career counselor:"
            
            response = self.model.generate_content(full_prompt)
            return response.text
        except Exception as e:
            return f"I apologize, but I'm having trouble processing that right now. Could you try again? Error: {str(e)}"
    
    def analyze_interests(self, conversation_text):
        """Analyze conversation to extract career suggestions"""
        try:
            prompt = f"""Based on the following conversation, analyze the user's interests, skills, and personality traits. 
            Provide 3-4 specific career path suggestions in JSON format with this structure:
            
            {{
                "careers": [
                    {{
                        "title": "Career Title",
                        "description": "Detailed description of why this fits the user",
                        "skills_required": ["skill1", "skill2", "skill3"],
                        "growth_potential": "High/Medium/Low",
                        "education_path": "Required education path"
                    }}
                ]
            }}
            
            Conversation:
            {conversation_text}
            
            Return ONLY valid JSON, no additional text."""
            
            response = self.model.generate_content(prompt)
            # Clean the response to extract JSON
            json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
            if json_match:
                return json.loads(json_match.group())
            return {"careers": []}
        except Exception as e:
            st.error(f"Analysis error: {e}")
            return {"careers": []}
    
    def generate_roadmap(self, career_title, user_interests):
        """Generate detailed roadmap for selected career"""
        try:
            prompt = f"""Create a detailed 12-month roadmap for becoming a {career_title} based on these interests: {user_interests}
            
            Provide the roadmap in this JSON format:
            {{
                "career_title": "{career_title}",
                "roadmap": {{
                    "months_1_3": ["Step 1", "Step 2", "Step 3"],
                    "months_4_6": ["Step 1", "Step 2", "Step 3"],
                    "months_7_9": ["Step 1", "Step 2", "Step 3"],
                    "months_10_12": ["Step 1", "Step 2", "Step 3"]
                }},
                "key_skills": ["skill1", "skill2", "skill3"],
                "resources": ["resource1", "resource2", "resource3"],
                "salary_range": "Expected salary range",
                "job_market": "Current market outlook"
            }}
            
            Return ONLY valid JSON."""
            
            response = self.model.generate_content(prompt)
            json_match = re.search(r'\{.*\}', response.text, re.DOTALL)
            if json_match:
                return json.loads(json_match.group())
            return None
        except Exception as e:
            st.error(f"Roadmap generation error: {e}")
            return None

def initialize_session_state():
    """Initialize session state variables"""
    if 'messages' not in st.session_state:
        st.session_state.messages = []
    if 'counselor_initialized' not in st.session_state:
        st.session_state.counselor_initialized = False
    if 'career_suggestions' not in st.session_state:
        st.session_state.career_suggestions = None
    if 'selected_career' not in st.session_state:
        st.session_state.selected_career = None
    if 'roadmap' not in st.session_state:
        st.session_state.roadmap = None
    if 'conversation_phase' not in st.session_state:
        st.session_state.conversation_phase = "introduction"  # introduction, exploration, suggestions, roadmap

def display_typing_indicator():
    """Show typing indicator"""
    with st.chat_message("assistant"):
        typing_html = """
        <div style='display: flex; align-items: center; gap: 10px;'>
            <div class='typing-indicator' style='animation-delay: 0s;'></div>
            <div class='typing-indicator' style='animation-delay: 0.2s;'></div>
            <div class='typing-indicator' style='animation-delay: 0.4s;'></div>
            <span style='color: #666;'>Counselor is thinking...</span>
        </div>
        """
        st.markdown(typing_html, unsafe_allow_html=True)

def main():
    # Initialize session state
    initialize_session_state()
    
    # Header
    st.markdown("<h1 class='main-header'>🎯 CareerPath AI Counselor</h1>", unsafe_allow_html=True)
    st.markdown("### Your personal guide to discovering fulfilling career paths")
    
    # Initialize counselor
    api_key = "AIzaSyBb9nkfEcRW47ZaczyGTTgAfpTN1wc6D10"  # Your provided API key
    counselor = CareerCounselor(api_key)
    
    # Main chat container
    chat_container = st.container()
    
    # Display chat messages
    with chat_container:
        for message in st.session_state.messages:
            with st.chat_message(message["role"]):
                st.markdown(f"<div class='{message['role']}-message'>{message['content']}</div>", 
                           unsafe_allow_html=True)
    
    # Initial counselor message
    if not st.session_state.counselor_initialized:
        with st.chat_message("assistant"):
            welcome_msg = """
            <div class='counselor-message'>
                <h3>πŸ‘‹ Hello! I'm your CareerPath AI Counselor</h3>
                <p>I'm here to help you discover career paths that align with your passions and interests!</p>
                <p>Let's start by getting to know you better. What are some activities or topics that genuinely interest you? 
                (e.g., coding, art, sports, science, helping others, etc.)</p>
            </div>
            """
            st.markdown(welcome_msg, unsafe_allow_html=True)
            st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
            st.session_state.counselor_initialized = True
    
    # User input
    if prompt := st.chat_input("Share your interests and hobbies..."):
        # Add user message to chat
        with st.chat_message("user"):
            st.markdown(f"<div class='user-message'>{prompt}</div>", unsafe_allow_html=True)
        st.session_state.messages.append({"role": "user", "content": prompt})
        
        # Get counselor response
        with st.chat_message("assistant"):
            display_typing_indicator()
            
            # Determine if this is initial conversation
            is_initial = len(st.session_state.messages) <= 2
            
            # Get response from counselor
            response = counselor.get_response(prompt, is_initial)
            
            # Update conversation phase based on message count
            if len(st.session_state.messages) >= 6 and st.session_state.conversation_phase == "introduction":
                st.session_state.conversation_phase = "exploration"
            
            # Check if we should generate career suggestions
            if len(st.session_state.messages) >= 8 and st.session_state.conversation_phase == "exploration":
                conversation_text = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.messages])
                st.session_state.career_suggestions = counselor.analyze_interests(conversation_text)
                st.session_state.conversation_phase = "suggestions"
            
            # Clear typing indicator and show response
            st.empty()
            st.markdown(f"<div class='counselor-message'>{response}</div>", unsafe_allow_html=True)
            st.session_state.messages.append({"role": "assistant", "content": response})
    
    # Display career suggestions if available
    if st.session_state.career_suggestions and st.session_state.career_suggestions.get("careers"):
        st.markdown("---")
        st.markdown("### πŸš€ Suggested Career Paths")
        
        careers = st.session_state.career_suggestions["careers"]
        cols = st.columns(min(3, len(careers)))
        
        for idx, career in enumerate(careers):
            with cols[idx % 3]:
                st.markdown(f"""
                <div style='border: 2px solid #4CAF50; border-radius: 10px; padding: 1rem; margin: 0.5rem 0;'>
                    <h4>🎯 {career['title']}</h4>
                    <p><strong>Why it fits you:</strong> {career['description']}</p>
                    <p><strong>Growth:</strong> {career.get('growth_potential', 'High')}</p>
                    <p><strong>Education:</strong> {career.get('education_path', 'Varies')}</p>
                </div>
                """, unsafe_allow_html=True)
                
                if st.button(f"Choose {career['title']}", key=f"choose_{idx}"):
                    st.session_state.selected_career = career
                    # Generate roadmap
                    conversation_text = "\n".join([msg['content'] for msg in st.session_state.messages if msg['role'] == 'user'])
                    st.session_state.roadmap = counselor.generate_roadmap(career['title'], conversation_text)
                    st.session_state.conversation_phase = "roadmap"
                    st.rerun()
        
        # Alternative options
        st.markdown("---")
        st.markdown("### πŸ”„ Not quite right?")
        col1, col2 = st.columns(2)
        with col1:
            if st.button("πŸ”„ Get Different Suggestions", use_container_width=True):
                # Clear current suggestions and continue conversation
                st.session_state.career_suggestions = None
                st.session_state.conversation_phase = "exploration"
                st.rerun()
        with col2:
            if st.button("πŸ’¬ Continue Conversation", use_container_width=True):
                st.session_state.career_suggestions = None
                st.rerun()
    
    # Display roadmap if available
    if st.session_state.roadmap and st.session_state.selected_career:
        st.markdown("---")
        st.markdown(f"### πŸ—ΊοΈ Your Roadmap to Becoming a {st.session_state.selected_career['title']}")
        
        roadmap = st.session_state.roadmap
        
        # Key information
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("Career Path", roadmap.get('career_title', ''))
        with col2:
            st.metric("Salary Range", roadmap.get('salary_range', 'Varies'))
        with col3:
            st.metric("Market Outlook", roadmap.get('job_market', 'Positive'))
        
        # Roadmap timeline
        st.markdown("#### πŸ“… 12-Month Action Plan")
        
        if 'roadmap' in roadmap:
            roadmap_data = roadmap['roadmap']
            for period, steps in roadmap_data.items():
                with st.expander(f"πŸ—“οΈ {period.replace('_', ' ').title()}"):
                    for step in steps:
                        st.write(f"β€’ {step}")
        
        # Skills and Resources
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("#### πŸ”§ Key Skills to Develop")
            if 'key_skills' in roadmap:
                for skill in roadmap['key_skills']:
                    st.write(f"β€’ {skill}")
        
        with col2:
            st.markdown("#### πŸ“š Learning Resources")
            if 'resources' in roadmap:
                for resource in roadmap['resources']:
                    st.write(f"β€’ {resource}")
        
        # Action buttons
        st.markdown("---")
        col1, col2, col3 = st.columns(3)
        with col1:
            if st.button("πŸ–¨οΈ Save Roadmap", use_container_width=True):
                st.success("Roadmap saved! (This would typically download a PDF)")
        with col2:
            if st.button("πŸ”„ Explore Other Careers", use_container_width=True):
                st.session_state.selected_career = None
                st.session_state.roadmap = None
                st.session_state.career_suggestions = None
                st.rerun()
        with col3:
            if st.button("🎯 New Session", use_container_width=True):
                for key in list(st.session_state.keys()):
                    del st.session_state[key]
                initialize_session_state()
                st.rerun()

if __name__ == "__main__":
    main()