import streamlit as st st.set_page_config(page_title="AI Job Interest Matcher", layout="wide") import requests import os from datetime import datetime import re # Configure OpenAI API (using OPENAI_API_KEY) OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions" # Google Apps Script endpoint - REPLACE WITH YOUR NEW DEPLOYMENT URL GOOGLE_APPS_SCRIPT_URL = "https://script.google.com/macros/s/YOUR_DEPLOYMENT_URL_HERE/exec" def extract_job_titles(recommendations_text): """Extracts just the job titles from the full recommendations text.""" if not recommendations_text: return "No jobs found" try: # Look for job titles in various formats patterns = [ r'#{2,3}\s+(.+?)(?:\n|$)', # Markdown headers r'\*\*(.+?)\*\*', # Bold text r'^\d+\.\s*(.+?)(?:\n|$)', # Numbered lists r'^-\s*(.+?)(?:\n|$)', # Bullet points ] job_titles = [] lines = recommendations_text.split('\n') for line in lines: line = line.strip() if not line: continue # Check each pattern for pattern in patterns: matches = re.findall(pattern, line, re.MULTILINE) for match in matches: # Clean up the match clean_title = match.strip().replace('*', '').replace('#', '') # Skip lines that are clearly not job titles skip_conditions = [ 'job analysis' in clean_title.lower(), 'summary' in clean_title.lower(), 'recommendations' in clean_title.lower(), 'overview' in clean_title.lower(), 'career guidance' in clean_title.lower(), 'next steps' in clean_title.lower(), 'company:' in clean_title.lower(), 'salary:' in clean_title.lower(), 'location:' in clean_title.lower(), # Skip very short or very long titles len(clean_title) < 5 or len(clean_title) > 80, # Skip lines with dollar signs (salary info) '$' in clean_title ] if not any(skip_conditions): job_titles.append(clean_title) # Remove duplicates while preserving order unique_jobs = [] for job in job_titles: if job not in unique_jobs: unique_jobs.append(job) # Return up to 10 job titles, joined by semicolons return '; '.join(unique_jobs[:10]) if unique_jobs else "Jobs found but titles could not be extracted" except Exception as e: return f"Error extracting job titles: {str(e)}" def save_to_google_apps_script(data): """Saves the submitted job seeker data via Google Apps Script.""" try: response = requests.post( GOOGLE_APPS_SCRIPT_URL, json=data, timeout=30, headers={'Content-Type': 'application/json'} ) if response.status_code == 200: try: result = response.json() if result.get('result') == 'success': return True, "Your job search profile has been saved! We'll be in touch with opportunities." else: return False, f"Script error: {result.get('message', 'Unknown error')}" except: # If response is not JSON, treat as success if status is 200 return True, "Your job search profile has been saved! We'll be in touch with opportunities." else: return False, f"Submission failed with status code: {response.status_code}" except requests.exceptions.Timeout: return False, "Request timed out. Please try again later." except Exception as e: return False, f"Error submitting data: {str(e)}" def search_real_jobs(location, work_type, skills, experience_level, industry_preference, salary_range): """Uses OpenAI to research actual job openings that match the criteria.""" prompt = f"""Your task is to act as a job market research specialist. Research and identify 5 actual, real-world job openings that match the following criteria: Location: {location} ({'Remote work preferred' if work_type == 'Remote' else 'In-person work preferred' if work_type == 'In-Person' else 'Flexible work arrangement'}) Skills: {skills} Experience Level: {experience_level} Industry Preference: {industry_preference if industry_preference else 'Open to all industries'} Salary Range: {salary_range} For each job opportunity, please provide: 1. Job title and company name (must be real, current openings) 2. Location details (city, state, or remote status) 3. Job type (Full-time, Part-time, Contract, etc.) 4. Salary range or compensation details 5. Key responsibilities and requirements 6. Company overview and culture 7. Why this position would be a good match for someone with these skills and preferences 8. Application process or next steps Be precise, accurate, and only include job opportunities that actually exist and can be verified through major job boards or company websites. Format each job recommendation as a separate section with a clear heading.""" headers = { "Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json" } data = { "model": "gpt-4", "messages": [ {"role": "system", "content": "You are a professional job market research specialist with extensive knowledge of current job openings across various industries. You provide accurate, up-to-date information about real job opportunities that can be verified through legitimate job boards and company websites."}, {"role": "user", "content": prompt} ], "temperature": 0.7, "max_tokens": 2500 } try: response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except Exception as e: st.error(f"API Error: {str(e)}") return None def generate_job_recommendations(job_seeker_info, personality_traits, career_goals, additional_preferences=None): """Generates comprehensive job recommendations using OpenAI GPT-4.""" # First get real job research location = job_seeker_info.get('location', '') work_type = job_seeker_info.get('work_type', '') skills = job_seeker_info.get('skills', '') experience_level = job_seeker_info.get('experience_level', '') industry_preference = job_seeker_info.get('industry_preference', '') salary_range = job_seeker_info.get('salary_range', '') real_jobs = search_real_jobs(location, work_type, skills, experience_level, industry_preference, salary_range) if not real_jobs: return None # Include personality traits and career goals personality_text = f"Personality Traits: {', '.join(personality_traits)}" if personality_traits else "" career_goals_text = f"Career Goals: {career_goals}" if career_goals else "" additional_prefs_text = f"Additional Preferences: {additional_preferences}" if additional_preferences else "" prompt = f"""As an expert career counselor and job placement specialist, provide detailed job recommendations and career guidance for the following job seeker: {job_seeker_info.get('profile_summary', '')} {personality_text} {career_goals_text} {additional_prefs_text} Here are real job opportunities that match the job seeker's criteria: {real_jobs} Based on these real job opportunities, please provide: 1. **Job Match Analysis:** For each of these real job opportunities, analyze how well they align with this person's skills, personality traits, and career goals. Provide specific recommendations for how to position themselves for each role. 2. **Career Development Strategy:** Provide a comprehensive strategy that includes: - Skills gap analysis and development recommendations - Interview preparation specific to these types of roles - Resume and LinkedIn optimization tips - Networking strategies within target industries - Professional development opportunities - Salary negotiation guidance - Career progression planning - Personal branding recommendations - Industry trend insights - Alternative career paths to consider 3. **Next Steps Action Plan:** Create a prioritized action plan with specific steps the job seeker should take in the next 30, 60, and 90 days. Format your response in clear markdown with headers and bullet points, and explain the strategic reasoning behind each recommendation. Focus on actionable advice that will help the job seeker successfully transition into their ideal role.""" headers = { "Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json" } data = { "model": "gpt-4", "messages": [ {"role": "system", "content": "You are a top-tier career counselor and job placement specialist with extensive experience matching candidates to ideal positions across various industries. You provide actionable, strategic career guidance."}, {"role": "user", "content": prompt} ], "temperature": 0.7, "max_tokens": 4000 } try: response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except Exception as e: st.error(f"API Error: {str(e)}") return None # Streamlit UI st.title("🎯 AI Job Interest Matcher") st.markdown("### Find your perfect job match with AI-powered career recommendations") # Main form with all necessary fields st.markdown("## 👤 Personal Information") full_name = st.text_input("Full Name*") email = st.text_input("Email Address*") phone = st.text_input("Phone Number") st.markdown("## 📍 Location & Work Preferences") col1, col2 = st.columns(2) with col1: location = st.text_input("Current Location (City, State)*", help="Where are you located or willing to work?") with col2: work_type = st.selectbox("Work Preference*", ["Remote", "In-Person", "Hybrid", "Flexible"]) st.markdown("## 💼 Professional Background") experience_level = st.selectbox("Experience Level*", ["Entry Level (0-2 years)", "Mid-Level (3-5 years)", "Senior Level (6-10 years)", "Executive Level (10+ years)"]) current_title = st.text_input("Current/Most Recent Job Title") industry_preference = st.selectbox("Preferred Industry", ["Technology", "Healthcare", "Finance", "Education", "Marketing", "Sales", "Engineering", "Human Resources", "Operations", "Consulting", "Non-Profit", "Government", "Retail", "Manufacturing", "Other", "Open to All"]) if industry_preference == "Other": industry_other = st.text_input("Please specify industry") industry_preference = industry_other if industry_other else industry_preference st.markdown("## 🛠️ Skills & Qualifications") skills = st.text_area("Key Skills & Technologies*", help="List your technical skills, software proficiency, certifications, etc.") education = st.selectbox("Highest Education Level", ["High School", "Associate Degree", "Bachelor's Degree", "Master's Degree", "PhD/Doctorate", "Professional Certification"]) languages = st.text_input("Languages Spoken", help="e.g., English (Native), Spanish (Fluent)") st.markdown("## 💰 Compensation Expectations") col1, col2 = st.columns(2) with col1: salary_min = st.number_input("Minimum Salary ($)", min_value=0, value=50000, step=5000) with col2: salary_max = st.number_input("Maximum Salary ($)", min_value=0, value=100000, step=5000) compensation_type = st.selectbox("Compensation Type", ["Annual Salary", "Hourly Rate", "Contract Rate", "Flexible"]) st.markdown("## 🧠 Personality & Work Style") st.write("Select personality traits that describe you:") col1, col2, col3 = st.columns(3) with col1: analytical = st.checkbox("Analytical") creative = st.checkbox("Creative") detail_oriented = st.checkbox("Detail-Oriented") with col2: collaborative = st.checkbox("Collaborative") independent = st.checkbox("Independent") leadership = st.checkbox("Leadership-Minded") with col3: problem_solver = st.checkbox("Problem Solver") communicator = st.checkbox("Strong Communicator") adaptable = st.checkbox("Adaptable") work_environment = st.selectbox("Preferred Work Environment", ["Fast-paced startup", "Established corporation", "Small team", "Large organization", "Non-profit", "Government", "Consulting", "Flexible"]) st.markdown("## 🎯 Career Goals & Preferences") career_goals = st.text_area("Career Goals & Aspirations", help="What are your short-term and long-term career objectives?") job_type = st.multiselect("Job Type Preferences", ["Full-time", "Part-time", "Contract", "Freelance", "Internship"]) benefits_priority = st.multiselect("Important Benefits", ["Health Insurance", "401k/Retirement", "Flexible Schedule", "Professional Development", "Work-Life Balance", "Stock Options", "Vacation Time", "Remote Work Options"]) additional_preferences = st.text_area("Additional Preferences or Requirements", help="Any other specific requirements, preferences, or deal-breakers?") if st.button("🔍 Find My Perfect Job Matches", type="primary"): if not all([full_name, email, location, skills]): st.error("Please fill in all required fields marked with *") else: # Collect personality traits personality_traits = [] traits_map = { 'Analytical': analytical, 'Creative': creative, 'Detail-Oriented': detail_oriented, 'Collaborative': collaborative, 'Independent': independent, 'Leadership-Minded': leadership, 'Problem Solver': problem_solver, 'Strong Communicator': communicator, 'Adaptable': adaptable } personality_traits = [trait for trait, selected in traits_map.items() if selected] # Format salary range salary_range = f"${salary_min:,} - ${salary_max:,} ({compensation_type})" # Create job seeker profile job_seeker_info = { 'profile_summary': f""" Full Name: {full_name} Location: {location} Work Preference: {work_type} Experience Level: {experience_level} Current/Recent Title: {current_title if current_title else 'Not specified'} Industry Preference: {industry_preference} Key Skills: {skills} Education: {education} Languages: {languages if languages else 'Not specified'} Salary Range: {salary_range} Job Type Preferences: {', '.join(job_type) if job_type else 'Flexible'} Preferred Work Environment: {work_environment} Priority Benefits: {', '.join(benefits_priority) if benefits_priority else 'Standard benefits'} """, 'location': location, 'work_type': work_type, 'skills': skills, 'experience_level': experience_level, 'industry_preference': industry_preference, 'salary_range': salary_range } # Add timestamp timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with st.spinner("🔍 Analyzing job market and finding your perfect matches..."): # Generate job recommendations recommendations = generate_job_recommendations( job_seeker_info, personality_traits, career_goals, additional_preferences ) if recommendations: # Extract job titles for the Google Sheet job_titles_only = extract_job_titles(recommendations) # Format data for Google Apps Script form_data = { "timestamp": timestamp, "full_name": full_name, "email": email, "phone": phone if phone else "Not provided", "location": location, "work_type": work_type, "experience_level": experience_level, "current_title": current_title if current_title else "Not specified", "industry_preference": industry_preference, "skills": skills, "education": education, "languages": languages if languages else "Not specified", "salary_range": salary_range, "personality_traits": ', '.join(personality_traits), "work_environment": work_environment, "career_goals": career_goals if career_goals else "Not specified", "job_type_preferences": ', '.join(job_type) if job_type else "Flexible", "benefits_priority": ', '.join(benefits_priority) if benefits_priority else "Standard", "additional_preferences": additional_preferences if additional_preferences else "None", "job_matches": job_titles_only } # Save via Google Apps Script save_success, save_message = save_to_google_apps_script(form_data) if save_success: st.success(save_message) else: st.warning(save_message) # Display the recommendations st.markdown("---") st.markdown("## 🎯 Your Personalized Job Recommendations") st.markdown(recommendations) # Add download option st.markdown("---") st.download_button( label="📄 Download Recommendations as Text File", data=recommendations, file_name=f"job_recommendations_{full_name.replace(' ', '_')}_{datetime.now().strftime('%Y%m%d')}.txt", mime="text/plain" ) else: st.error("Unable to generate job recommendations. Please check your OpenAI API key and try again.") # Footer st.markdown("---") st.markdown("*This tool uses AI to match your profile with current job opportunities. Results are suggestions and should be verified independently.*")