Spaces:
macken39
/
Runtime error

File size: 19,283 Bytes
cac9eab
978e4ce
56af34b
bc46207
7409805
32495da
978e4ce
24b72ba
56af34b
dbfa8c2
 
68833e7
339ec80
978e4ce
32495da
978e4ce
 
cee3635
978e4ce
cee3635
 
978e4ce
cee3635
 
 
 
 
 
 
978e4ce
cee3635
 
 
 
 
 
 
 
 
 
 
 
978e4ce
5214e81
978e4ce
5214e81
978e4ce
 
 
 
 
 
 
 
 
 
 
 
 
5214e81
 
 
978e4ce
cee3635
 
978e4ce
 
 
 
cee3635
978e4ce
 
cee3635
 
978e4ce
cee3635
510710f
978e4ce
32495da
e864116
 
 
 
 
 
 
 
 
 
 
978e4ce
e864116
 
 
 
978e4ce
e864116
 
 
 
 
 
 
 
978e4ce
 
 
 
 
 
 
 
 
1d72d1e
978e4ce
 
 
 
 
 
 
 
 
 
 
6b5e351
 
 
 
 
 
 
978e4ce
6b5e351
978e4ce
6b5e351
 
 
978e4ce
6b5e351
 
 
 
 
 
 
 
 
 
978e4ce
 
 
 
 
 
 
 
 
6b5e351
978e4ce
6b5e351
978e4ce
 
f20b620
978e4ce
 
 
 
62d4841
978e4ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5df9d3
1d72d1e
56af34b
1d72d1e
 
 
 
978e4ce
1d72d1e
978e4ce
1d72d1e
 
 
 
 
 
 
dbfa8c2
1d72d1e
 
 
 
 
 
 
978e4ce
 
1d72d1e
978e4ce
 
 
 
 
f20b620
978e4ce
62d4841
 
978e4ce
62d4841
978e4ce
 
62d4841
978e4ce
 
 
 
 
 
 
 
 
 
 
 
 
 
f20b620
978e4ce
 
 
f20b620
978e4ce
 
 
 
 
 
 
f20b620
 
978e4ce
f20b620
978e4ce
 
 
 
f20b620
978e4ce
 
62d4841
 
978e4ce
 
 
62d4841
978e4ce
 
 
62d4841
978e4ce
 
 
 
 
 
 
 
 
 
 
62d4841
978e4ce
 
62d4841
978e4ce
 
 
 
f20b620
978e4ce
 
 
 
 
f20b620
 
978e4ce
 
 
 
 
 
 
 
62d4841
978e4ce
 
62d4841
978e4ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62d4841
510710f
 
 
978e4ce
 
 
 
 
e78a7f5
f20b620
978e4ce
 
cee3635
978e4ce
e78a7f5
 
978e4ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78a7f5
 
 
 
 
 
 
 
 
 
978e4ce
 
e864116
978e4ce
 
 
 
 
 
 
 
 
 
e78a7f5
978e4ce
 
 
 
 
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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.*")