File size: 13,219 Bytes
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c79a004
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c79a004
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816b8af
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13b3e6
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9db828
42f62ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import groq
from jobspy import scrape_jobs
import pandas as pd
import json
from typing import List, Dict
import numpy as np
import time

def make_clickable(url: str) -> str:
    """
    Convert a URL to a clickable HTML link.
    
    Args:
        url (str): The URL to make clickable
    
    Returns:
        str: HTML anchor tag with the URL
    """
    return f'<a href="{url}" target="_blank" style="color: #4e79a7;">Link</a>'

def convert_prompt_to_parameters(client, prompt: str) -> Dict[str, str]:
    """
    Convert user input prompt to structured job search parameters using AI.
    
    Args:
        client: Groq AI client
        prompt (str): User's job search description
    
    Returns:
        Dict[str, str]: Extracted search parameters with search_term and location
    """
    system_prompt = """
    You are a language decoder. Extract:
    - search_term: job role/keywords (expand abbreviations)
    - location: mentioned place or 'USA'
    Return only: {"search_term": "term", "location": "location"}
    """
    
    response = client.chat.completions.create(
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"Extract from: {prompt}"}
        ],
        max_tokens=1024,
        model='llama3-8b-8192',
        temperature=0.2
    )
    
    try:
        return json.loads(response.choices[0].message.content)
    except json.JSONDecodeError:
        return {"search_term": prompt, "location": "USA"}

def analyze_resume(client, resume: str) -> str:
    """
    Generate a comprehensive resume analysis using AI.
    
    Args:
        client: Groq AI client
        resume (str): Full resume text
    
    Returns:
        str: Concise professional overview of the resume
    """
    system_prompt = """Analyze resume comprehensively in 150 words:
    1. Professional Profile Summary
    2. Key Technical Skills
    3. Educational Background
    4. Core Professional Experience Highlights
    5. Unique Strengths/Achievements
    Return a concise, structured professional overview."""
    
    response = client.chat.completions.create(
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": resume}
        ],
        max_tokens=400,
        model='llama3-8b-8192',
        temperature=0.3
    )
    
    return response.choices[0].message.content

@st.cache_data(ttl=3600)
def get_job_data(search_params: Dict[str, str]) -> pd.DataFrame:
    """
    Fetch job listings from multiple sources based on search parameters.
    
    Args:
        search_params (Dict[str, str]): Search parameters including term and location
    
    Returns:
        pd.DataFrame: Scraped job listings
    """
    try:
        return scrape_jobs(
            site_name=["indeed", "linkedin", "zip_recruiter"],
            search_term=search_params["search_term"],
            location=search_params["location"],
            results_wanted=60,
            hours_old=24,
            country_indeed='USA'
        )
    except Exception as e:
        st.warning(f"Error in job scraping: {str(e)}")
        return pd.DataFrame()

def analyze_job_batch(
    client, 
    resume: str, 
    jobs_batch: List[Dict], 
    start_index: int, 
    retry_count: int = 0
) -> pd.DataFrame:
    """
    Analyze a batch of jobs against the resume with retry logic.
    
    Args:
        client: Groq AI client
        resume (str): Resume text
        jobs_batch (List[Dict]): Batch of job listings
        start_index (int): Starting index of the batch
        retry_count (int, optional): Number of retry attempts. Defaults to 0.
    
    Returns:
        pd.DataFrame: Job match analysis results
    """
    if retry_count >= 3:
        return pd.DataFrame()
        
    system_prompt = """Rate resume-job matches. Return only JSON array:
[{"job_index": number, "match_score": 0-100, "reason": "brief reason"}]"""
    
    jobs_info = [
        {
            'index': idx + start_index,
            'title': job['title'],
            'desc': job.get('description', '')[:400],
        }
        for idx, job in enumerate(jobs_batch)
    ]
    
    resume_summary = analyze_resume(client, resume)
    
    analysis_prompt = f"Resume: {resume_summary}\nJobs: {json.dumps(jobs_info)}"
    
    try:
        response = client.chat.completions.create(
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": analysis_prompt}
            ],
            max_tokens=1024,
            model='llama3-70b-8192',
            temperature=0.3
        )
        
        matches = json.loads(response.choices[0].message.content)
        return pd.DataFrame(matches)
    except Exception as e:
        if retry_count < 3:
            time.sleep(2)
            return analyze_job_batch(client, resume, jobs_batch, start_index, retry_count + 1)
        st.warning(f"Batch {start_index} failed after retries: {str(e)}")
        return pd.DataFrame()

def analyze_jobs_in_batches(
    client, 
    resume: str, 
    jobs_df: pd.DataFrame, 
    batch_size: int = 3
) -> pd.DataFrame:
    """
    Process job listings in batches and analyze match with resume.
    
    Args:
        client: Groq AI client
        resume (str): Resume text
        jobs_df (pd.DataFrame): DataFrame of job listings
        batch_size (int, optional): Number of jobs to process in each batch. Defaults to 3.
    
    Returns:
        pd.DataFrame: Sorted job matches by match score
    """
    all_matches = []
    jobs_dict = jobs_df.to_dict('records')
    progress_bar = st.progress(0)
    status_text = st.empty()
    
    for i in range(0, len(jobs_dict), batch_size):
        batch = jobs_dict[i:i + batch_size]
        status_text.text(f"Processing batch {i//batch_size + 1} of {len(jobs_dict)//batch_size + 1}")
        
        batch_matches = analyze_job_batch(client, resume, batch, i)
        if not batch_matches.empty:
            all_matches.append(batch_matches)
            
        progress = min((i + batch_size) / len(jobs_dict), 1.0)
        progress_bar.progress(progress)
        time.sleep(1)  # Rate limiting
    
    progress_bar.empty()
    status_text.empty()
    
    if all_matches:
        final_matches = pd.concat(all_matches, ignore_index=True)
        return final_matches.sort_values('match_score', ascending=False)
    return pd.DataFrame()

def main():
    """
    Main Streamlit application entry point for Smart Job Search.
    Handles user interface, job search, and AI-powered job matching.
    """
    st.set_page_config(
        layout="wide",
        page_title="Multi Agent Job Search and Match",
        initial_sidebar_state="collapsed"
    )

    # Custom CSS with reduced text sizes
    st.markdown("""
        <style>
        .block-container {
            padding-top: 1.5rem;
            padding-bottom: 1.5rem;
            max-width: 1200px;
        }
        .stButton>button {
            background-color: #2563eb;
            color: white;
            border-radius: 0.375rem;
            padding: 0.75rem 1.5rem;
            border: none;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            margin: 0.5rem;
            min-width: 200px;
            font-size: 0.875rem;
        }
        [data-testid="stFileUploader"] {
            border: 2px dashed #e5e7eb;
            border-radius: 0.5rem;
            padding: 0.875rem;
            min-height: 220px;
            font-size: 0.875rem;
        }
        .stTextArea>div>div {
            border-radius: 0.5rem;
            min-height: 220px !important;
            font-size: 0.875rem;
        }
        .stTextInput>div>div>input {
            border-radius: 0.5rem;
            font-size: 0.875rem;
        }
        .resume-html {
            padding: 1.5rem;
            max-width: 800px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
            font-size: 0.875rem;
        }
        h1 {font-size: 3rem !important;  /* Adjust this value to increase the font size */
        } h2 {font-size: 1.5rem !important;  /* Adjust this value to increase the font size */
        h3, h4, h5, h6 {
            font-size: 80% !important;
        }
        p, li {
            font-size: 0.875rem !important;
        }
        </style>
    """, unsafe_allow_html=True)

    # Header with smaller text
    st.markdown("""
        <h1 style='text-align: center; font-size: 2.5rem; font-weight: 800; margin-bottom: 0.875rem;'>
        πŸš€ Multi Agent Job Search and Match 
        </h1>
    """, unsafe_allow_html=True)

    col1, col2 = st.columns(2)
    
    with col1:
        user_input = st.text_area(
            "Describe the job you're looking for",
            placeholder="E.g., 'Senior Python developer with React experience in San Francisco'",
            height=150
        )
    
    with col2:
        user_resume = st.text_area(
            "Paste your resume here (for AI-powered matching)",
            placeholder="Paste your resume for AI-powered job matching",
            height=150
        )
        
    api_key = st.text_input(
        "Enter your Groq API key",
        type="password",
        help="Your API key will be used to process the job search query"
    )

   # Add this CSS styling right after st.set_page_config()
    

    if st.button("πŸ” Search Jobs", disabled=not api_key):
        st.markdown("""
    <style>
    .stTabs [data-baseweb="tab-list"] {
        display: flex;
        justify-content: space-between;
        width: 100%;
    }
    .stTabs [data-baseweb="tab"] {
        flex: 1;
        text-align: center;
    }
    </style>
    """, unsafe_allow_html=True)

    # Modify tab creation to use descriptive names
        tab1, tab2, tab3 = st.tabs([
        "πŸ” Job Listings", 
        "πŸ“„ Resume Summary", 
        "πŸ€– AI Job Matching"
    ])
        if user_input and api_key:
            try:
                client = groq.Client(api_key=api_key)
                
                with st.spinner("Processing search parameters..."):
                    processed_params = convert_prompt_to_parameters(client, user_input)
                
                with st.spinner("Searching for jobs..."):
                    jobs_data = get_job_data(processed_params)
                    
                    if not jobs_data.empty:
                        data = pd.DataFrame(jobs_data)
                        data = data[data['description'].notna()].reset_index(drop=True)
                        
                        with tab1:
                            st.success(f"Found {len(data)} jobs!")
                            display_df = data[['site', 'job_url', 'title', 'company', 'location', 'job_type', 'date_posted']]
                            display_df['job_url'] = display_df['job_url'].apply(make_clickable)
                            st.write(display_df.to_html(escape=False), unsafe_allow_html=True)
                        
                        if user_resume:
                            with tab2:
                                st.info("Analyzing resume summary...")
                                resume_summary = analyze_resume(client, user_resume)
                                st.success("Resume summary:")
                                st.write(resume_summary)
                            
                            with tab3:
                                st.info("Analyzing job matches in small batches...")
                                matches_df = analyze_jobs_in_batches(client, resume_summary, data, batch_size=3)
                                
                                if not matches_df.empty:
                                    matched_jobs = data.iloc[matches_df['job_index']].copy()
                                    matched_jobs['match_score'] = matches_df['match_score']
                                    matched_jobs['match_reason'] = matches_df['reason']
                                    
                                    st.success(f"Found {len(matched_jobs)} recommended matches!")
                                    display_cols = ['site', 'job_url', 'title', 'company', 'location', 'match_score', 'match_reason']
                                    display_df = matched_jobs[display_cols].sort_values('match_score', ascending=False)
                                    display_df['job_url'] = display_df['job_url'].apply(make_clickable)
                                    st.write(display_df.to_html(escape=False), unsafe_allow_html=True)
                                else:
                                    st.warning("Could not process job matches. Please try again.")
                    else:
                        st.warning("No jobs found with the given parameters.")
                        
            except Exception as e:
                st.error(f"Error: {str(e)}")
        elif not api_key:
            st.warning("Please enter your API key.")
        else:
            st.warning("Please enter a job description.")

if __name__ == "__main__":
    main()