Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627281 unmodified line303132333435366 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041051061071081092 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561 unmodified line1581591601611621631641651661671681691704 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162171 unmodified line2192202212222232242252262279 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793804 unmodified lines385386387388389390import streamlit as stst.set_page_config(page_title="Corporate Event Venue Matcher", layout="wide")import requestsimport osfrom bs4 import BeautifulSoupfrom datetime import datetime# 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 URLGOOGLE_APPS_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbzQGNdeB-hEg0QqE7HxGuhUskjS2T1ekpf_ZrAc0Wj8KtvGpLjMCfIPHqfsfxNyw94_3Q/exec"def extract_venue_names(recommendations_text):"""Extracts just the venue names from the full recommendations text."""if not recommendations_text:return "No venues found"try:# Look for venue names in various formatsimport re# Pattern to match venue names (typically after headers like "## " or "### " or "**" or numbered lists)patterns = [r'#{2,3}\s+(.+?)(?:\n|$)', # Markdown headersr'\*\*(.+?)\*\*', # Bold text1 unmodified liner'^-\s*(.+?)(?:\n|$)', # Bullet points]venue_names = []lines = recommendations_text.split('\n')for line in lines:6 unmodified linesmatches = re.findall(pattern, line, re.MULTILINE)for match in matches:# Clean up the matchclean_name = match.strip().replace('*', '').replace('#', '')# Skip lines that are clearly not venue names or contain distance infoskip_conditions = ['venue analysis' in clean_name.lower(),'checklist' in clean_name.lower(),'recommendations' in clean_name.lower(),'miles from' in clean_name.lower(),'overview' in clean_name.lower(),'summary' in clean_name.lower(),'preparation' in clean_name.lower(),'site visit' in clean_name.lower(),# Check for distance patterns like "2.5 miles" or "X miles from"re.search(r'\d+\.?\d*\s*miles?', clean_name.lower()),# Check for address patternsre.search(r'\d+\s+\w+\s+(street|st|avenue|ave|road|rd|drive|dr|blvd|boulevard)', clean_name.lower()),# Skip very short or very long nameslen(clean_name) < 5 or len(clean_name) > 80]if not any(skip_conditions):venue_names.append(clean_name)# Remove duplicates while preserving orderunique_venues = []for venue in venue_names:if venue not in unique_venues:unique_venues.append(venue)# Return up to 10 venue names, joined by semicolonsreturn '; '.join(unique_venues[:10]) if unique_venues else "Venues found but names could not be extracted"except Exception as e:return f"Error extracting venue names: {str(e)}"def save_to_google_apps_script(data):"""Saves the submitted event data via Google Apps Script."""try:# Debug: Show what data is being sentresponse = requests.post(GOOGLE_APPS_SCRIPT_URL,json=data,1 unmodified lineheaders={'Content-Type': 'application/json'})# Debug: Show response detailsif response.status_code == 200:try:result = response.json()if result.get('result') == 'success':return True, "Data submitted successfully! We'll be in touch soon."else:return False, f"Script error: {result.get('message', 'Unknown error')}"except:# If response is not JSON, treat as success if status is 200return True, "Data submitted successfully! We'll be in touch soon."else:return False, f"Submission failed with status code: {response.status_code}"2 unmodified linesexcept Exception as e:return False, f"Error submitting data: {str(e)}"def scrape_website(url):"""Scrapes company content from the given website URL."""if not url.startswith("http"):url = f"https://{url}"try:response = requests.get(url, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.content, "html.parser")content = []# Extract meta description if availablemeta_description = soup.find("meta", {"name": "description"})if meta_description and meta_description.get("content"):content.append(meta_description["content"])# Extract text from h1, h2, and p tagsfor tag in ['h1', 'h2', 'p']:elements = soup.find_all(tag)content.extend([elem.get_text(strip=True) for elem in elements if elem.get_text(strip=True)])return " ".join(content[:1500])except Exception as e:st.error(f"Error scraping website: {str(e)}")return Nonedef search_real_venues(zip_code, event_type, attendees, event_style):"""Uses OpenAI to research actual venues within 10 miles of the zip code."""prompt = f"""Your task is to act as a venue research specialist. Research and identify 5 actual, real-world venues within 10 miles of zip code {zip_code} that would be suitable for a {event_type} event with {attendees} attendees.The event style preference is: {event_style if event_style else "No specific style preference"}For each venue, please provide:1. Venue name (must be real, verifiable venues)2. Exact location/address3. Approximate distance from zip code {zip_code} (MUST specify the exact distance in miles, e.g., "3.5 miles from {zip_code}")4. Venue type and atmosphere5. Capacity information6. Key amenities offered7. Why this venue would be a good match for this specific eventBe precise, accurate, and only include venues that actually exist and can be verified. Format each venue recommendation as a separate section with a clear heading. Make sure to always include the exact distance in miles from the requested zip code."""headers = {"Authorization": f"Bearer {OPENAI_API_KEY}",1 unmodified line}data = {"model": "gpt-4", # Using OpenAI GPT-4 model"messages": [{"role": "system", "content": "You are a venue research specialist with extensive knowledge of event spaces across the United States. You provide accurate, up-to-date information about real venues, with precise details that can be verified. Always include the exact distance in miles from the requested zip code for each venue."},{"role": "user", "content": prompt}],"temperature": 0.7,"max_tokens": 2000}try:4 unmodified linesst.error(f"API Error: {str(e)}")return Nonedef generate_venue_recommendations(event_info, zip_code, event_type, attendees, event_style, company_info=None, additional_services=None):"""Generates comprehensive venue recommendations using OpenAI GPT-4."""# First get real venue researchreal_venues = search_real_venues(zip_code, event_type, attendees, event_style)if not real_venues:return None# Include company information if providedcompany_info_text = f"Company Information: {company_info}" if company_info else ""# Include additional services information if providedadditional_services_text = ""if additional_services and len(additional_services) > 0:additional_services_text = f"Additional Services Required: {', '.join(additional_services)}"prompt = f"""As an expert corporate event planning consultant specializing in venue selection, provide detailed venue recommendations for the following event:{event_info}{company_info_text}{additional_services_text}Here are real venues within 10 miles of the specified zip code that match the event requirements:{real_venues}Based on these real venue options, please provide:1. **Venue Analysis:** For each of these real venues, analyze how well they match this specific event's needs and provide specific recommendations for utilizing the space. Always include the distance from the zip code in miles when discussing each venue.2. **Party Preparation & Site Visit Checklist:** Provide a comprehensive checklist that includes:- Venue infrastructure inspection points- Party preparation considerations (decorating timeline, setup requirements, vendor coordination)- Event flow planning (guest arrival, activities, catering service, entertainment timing)- Safety and logistics considerations- Post-event cleanup coordination- Emergency planning and contingencies- Guest experience optimization points- Photography and documentation planning- Weather contingencies (if applicable)- Final walkthrough requirementsFormat your response in clear markdown with headers and bullet points, and explain the strategic reasoning behind each recommendation. Make sure the distance in miles from the requested zip code is clearly stated for each venue."""headers = {"Authorization": f"Bearer {OPENAI_API_KEY}",1 unmodified line}data = {"model": "gpt-4", # Using OpenAI GPT-4 model"messages": [{"role": "system", "content": "You are a top-tier corporate event planning consultant with extensive experience selecting perfect venues for various event types. Always include the distance in miles from the requested zip code when discussing venues."},{"role": "user", "content": prompt}],"temperature": 0.7,9 unmodified linesreturn None# Streamlit UIst.title("🏢 Corporate Event Venue Matcher")st.markdown("### Get personalized venue recommendations for your corporate event.")# Combined form with all necessary fieldscompany_name = st.text_input("Company Name*")event_name = st.text_input("Event Name*")event_type = st.selectbox("Event Type*",["Conference", "Corporate Retreat", "Team Building", "Product Launch","Trade Show", "Gala/Award Ceremony", "Executive Meeting", "Training Session", "Other"])if event_type == "Other":event_type_other = st.text_input("Please specify event type")event_type = event_type_other if event_type_other else event_type# Add zip code inputzip_code = st.text_input("Event Location Zip Code*", help="We'll find venues within 10 miles of this location")# Event date and timecol1, col2 = st.columns(2)with col1:event_date = st.date_input("Event Date*")with col2:event_time = st.time_input("Event Start Time*")# Add event style checkboxesst.write("Event Style (select all that apply):")col1, col2, col3 = st.columns(3)with col1:formal = st.checkbox("Formal")outdoor = st.checkbox("Outdoor")with col2:modern = st.checkbox("Modern")traditional = st.checkbox("Traditional")with col3:creative = st.checkbox("Creative")professional = st.checkbox("Professional")attendees = st.number_input("Expected Number of Attendees*", min_value=1, value=100)col1, col2 = st.columns(2)with col1:budget_min = st.number_input("Budget Minimum ($)", min_value=0, value=5000, step=1000)with col2:budget_max = st.number_input("Budget Maximum ($)", min_value=0, value=20000, step=1000)# Additional services neededst.write("Additional Services Needed:")col1, col2, col3 = st.columns(3)with col1:catering = st.checkbox("Catering")floral = st.checkbox("Floral/Decor")with col2:dj = st.checkbox("DJ/Entertainment")lighting = st.checkbox("Lighting")with col3:meeting_space = st.checkbox("Meeting Spaces/Breakouts")av_services = st.checkbox("AV Services")# Other services text fieldother_services = st.text_input("Other Services Needed (if not listed above)")# Optional fieldsspecial_requirements = st.text_area("Special Requirements or Preferences",help="E.g., accessibility needs, catering preferences, technical requirements")if st.button("Generate Venue Recommendations"):if not all([company_name, event_name, event_type, attendees, zip_code, event_date, event_time]):st.error("Please fill in all required fields marked with *")else:# Collect all form dataevent_style = ', '.join([style for style, selected in zip(['Formal', 'Outdoor', 'Modern', 'Traditional', 'Creative', 'Professional'],[formal, outdoor, modern, traditional, creative, professional]) if selected])# Collect additional servicesadditional_services = []if catering:additional_services.append("Catering")if floral:additional_services.append("Floral/Decor")if dj:additional_services.append("DJ/Entertainment")if lighting:additional_services.append("Lighting")if meeting_space:additional_services.append("Meeting Spaces/Breakouts")if av_services:additional_services.append("AV Services")if other_services:additional_services.append(other_services)service_details = ", ".join(additional_services) if additional_services else "None"# Format event date and time (12-hour format)formatted_date = event_date.strftime("%Y-%m-%d")formatted_time = event_time.strftime("%I:%M %p") # 12-hour clock with AM/PM# Add timestamptimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")with st.spinner("Researching real venues and creating your personalized recommendations..."):event_info = f"""Company Name: {company_name}Event Name: {event_name}Event Type: {event_type}Event Location Zip Code: {zip_code} (please recommend venues within 10 miles of this location)Event Date: {formatted_date}Event Start Time: {formatted_time}Event Style: {event_style}Expected Attendees: {attendees}Budget Range: ${budget_min} - ${budget_max}Special Requirements: {special_requirements if special_requirements else 'None specified'}"""# Generate venue recommendationsrecommendations = generate_venue_recommendations(event_info, zip_code, event_type, attendees, event_style, None, additional_services)if recommendations:# Extract just the venue names for the Google Sheetvenue_names_only = extract_venue_names(recommendations)# Format data for Google Apps Script (now including venue names only)form_data = {"timestamp": timestamp,"company_name": company_name,"event_name": event_name,"event_type": event_type,"zip_code": zip_code,"event_style": event_style,"attendees": str(attendees),"event_date": formatted_date,"event_start_time": formatted_time,"budget_min": f"${budget_min}","budget_max": f"${budget_max}","special_requirements": special_requirements if special_requirements else "None specified","catering": "Yes" if catering else "No","additional_services": ", ".join([service for service in ["Floral/Decor", "DJ/Entertainment", "Lighting", "Meeting Spaces/Breakouts", "AV Services"]if service in additional_services]),"service_details": other_services if other_services else "None","venue_names": venue_names_only # Added venue names only (truncated)}# Save via Google Apps Script4 unmodified linesst.warning(save_message)# Display the recommendationsst.markdown(recommendations)else:st.error("Unable to generate venue recommendations. Please try again.")123456789101112131415161718192021222324251 unmodified line272829303132336 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified line848586878889909192939495969798992 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line1301311321331341351361371381391401411424 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002011 unmodified line2032042052062072082092102119 unmodified lines2212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883894 unmodified lines394395396397398399400401402403404405406407408409410411412413414415import streamlit as stst.set_page_config(page_title="AI Job Interest Matcher", layout="wide")import requestsimport osfrom datetime import datetimeimport 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 URLGOOGLE_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 formatspatterns = [r'#{2,3}\s+(.+?)(?:\n|$)', # Markdown headersr'\*\*(.+?)\*\*', # Bold text1 unmodified liner'^-\s*(.+?)(?:\n|$)', # Bullet points]job_titles = []lines = recommendations_text.split('\n')for line in lines:6 unmodified linesmatches = re.findall(pattern, line, re.MULTILINE)for match in matches:# Clean up the matchclean_title = match.strip().replace('*', '').replace('#', '')# Skip lines that are clearly not job titlesskip_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 titleslen(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 orderunique_jobs = []for job in job_titles:if job not in unique_jobs:unique_jobs.append(job)# Return up to 10 job titles, joined by semicolonsreturn '; '.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,1 unmodified lineheaders={'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 200return 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}"2 unmodified linesexcept 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 details5. Key responsibilities and requirements6. Company overview and culture7. Why this position would be a good match for someone with these skills and preferences8. Application process or next stepsBe 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}",1 unmodified line}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:4 unmodified linesst.error(f"API Error: {str(e)}")return Nonedef 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 researchlocation = 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 goalspersonality_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 consider3. **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}",1 unmodified line}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,9 unmodified linesreturn None# Streamlit UIst.title("🎯 AI Job Interest Matcher")st.markdown("### Find your perfect job match with AI-powered career recommendations")# Main form with all necessary fieldsst.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_preferencest.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 traitspersonality_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 rangesalary_range = f"${salary_min:,} - ${salary_max:,} ({compensation_type})"# Create job seeker profilejob_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 timestamptimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")with st.spinner("🔍 Analyzing job market and finding your perfect matches..."):# Generate job recommendationsrecommendations = generate_job_recommendations(job_seeker_info, personality_traits, career_goals, additional_preferences)if recommendations:# Extract job titles for the Google Sheetjob_titles_only = extract_job_titles(recommendations)# Format data for Google Apps Scriptform_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 Script4 unmodified linesst.warning(save_message)# Display the recommendationsst.markdown("---")st.markdown("## 🎯 Your Personalized Job Recommendations")st.markdown(recommendations)# Add download optionst.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.")# Footerst.markdown("---")st.markdown("*This tool uses AI to match your profile with current job opportunities. Results are suggestions and should be verified independently.*")
app.py+252-227