Download src/streamlit_app.py from faiz3123/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/spaces/faiz3123/chatbot/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/faiz3123/chatbot/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/faiz3123/chatbot/resolve/main/src/streamlit_app.py
15.8 kB
| 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() |