Snigdhapaul2003 commited on
Commit
b862851
Β·
verified Β·
1 Parent(s): 92867cb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -0
app.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import groq
2
+ from jobspy import scrape_jobs
3
+ import pandas as pd
4
+ import json
5
+ from typing import List, Dict
6
+ import numpy as np
7
+ import time
8
+ import tempfile
9
+
10
+
11
+ def make_clickable(url):
12
+ return f"{url}"
13
+
14
+ def convert_prompt_to_parameters(client, prompt: str, location_pref) -> Dict[str, str]:
15
+ """
16
+ Convert user input prompt to structured job search parameters using AI.
17
+
18
+ Args:
19
+ client: Groq AI client
20
+ prompt (str): User's job search description
21
+
22
+ Returns:
23
+ Dict[str, str]: Extracted search parameters with search_term and location
24
+ """
25
+ system_prompt = f"""
26
+ You are a language decoder. Extract:
27
+ - search_term: job role/keywords (expand abbreviations)
28
+ - location: mentioned place or "{location_pref}"
29
+ Return only: [{{"search_term": "term", "location": "location"}}]
30
+ """
31
+
32
+ response = client.chat.completions.create(
33
+ messages=[
34
+ {"role": "system", "content": system_prompt},
35
+ {"role": "user", "content": f"Extract from: {prompt}"}
36
+ ],
37
+ max_tokens=1024,
38
+ model='llama3-8b-8192',
39
+ temperature=0.2
40
+ )
41
+
42
+ print("response: ", response.choices[0].message.content)
43
+
44
+ try:
45
+ print("*****************************************")
46
+ content = response.choices[0].message.content.strip()
47
+
48
+ # Find the first and last occurrence of JSON brackets
49
+ json_start = content.find("[")
50
+ json_end = content.rfind("]") + 1 # +1 to include the last bracket
51
+
52
+ # Ensure valid JSON presence
53
+ if json_start == -1 or json_end == -1:
54
+ raise ValueError("No valid JSON array found in LLM response.")
55
+
56
+ # Extract the JSON portion and parse it
57
+ json_str = content[json_start:json_end]
58
+ return json.loads(json_str)
59
+ except json.JSONDecodeError:
60
+ return {"search_term": prompt, "location": location_pref}
61
+
62
+ def get_job_data(search_params: Dict[str, str]) -> pd.DataFrame:
63
+ """
64
+ Fetch job listings from multiple sources based on search parameters.
65
+
66
+ Args:
67
+ search_params (Dict[str, str]): Search parameters including term and location
68
+
69
+ Returns:
70
+ pd.DataFrame: Scraped job listings
71
+ """
72
+ print("location: ", search_params["location"])
73
+ try:
74
+ return scrape_jobs(
75
+ site_name=["indeed", "linkedin", "glassdoor", "google"],
76
+ search_term=search_params["search_term"],
77
+ google_search_term=search_params["search_term"] + " jobs near " + search_params["location"],
78
+ location=search_params["location"],
79
+ results_wanted=60,
80
+ hours_old=72,
81
+ country_indeed=search_params["location"],
82
+ linkedin_fetch_description=True
83
+ )
84
+ except Exception as e:
85
+ return pd.DataFrame()
86
+
87
+
88
+ import json
89
+ import time
90
+ import pandas as pd
91
+ from typing import List, Dict
92
+
93
+ # Define weights (Adjust these as needed)
94
+ WEIGHTS = {
95
+ "qualification_match": 0.3,
96
+ "skills_match": 0.3,
97
+ "experience_match": 0.2,
98
+ "salary_match": 0.2
99
+ }
100
+
101
+
102
+ def analyze_job_batch(
103
+ client,
104
+ resume_json: Dict,
105
+ jobs_batch: List[Dict],
106
+ start_index: int,
107
+ retry_count: int = 0
108
+ ) -> pd.DataFrame:
109
+ """
110
+ Analyze a batch of jobs against the resume with retry logic.
111
+
112
+ Args:
113
+ client: Groq AI client
114
+ resume_json (Dict): Resume details in JSON format
115
+ jobs_batch (List[Dict]): Batch of job listings
116
+ start_index (int): Starting index of the batch
117
+ retry_count (int, optional): Number of retry attempts. Defaults to 0.
118
+
119
+ Returns:
120
+ pd.DataFrame: Job match analysis results with separate scores for qualification, skills, and experience.
121
+ """
122
+ if retry_count >= 3:
123
+ return pd.DataFrame()
124
+
125
+ system_prompt = """
126
+ Rate resume-job matches based on qualifications, skills, and experience separately.
127
+ Ensure the candidate's experience level aligns with the job seniority (e.g., do not recommend senior-level jobs to freshers).
128
+ Consider job requirements, candidate qualifications, relevant skills, and years of experience.
129
+ Consider if the salary of the job matches the candidate's salary expectations. If the salary of the job is more than the expectation it is good. If no salary is mentioned, estimate it based on the job description and find the match.
130
+
131
+ Return only a JSON array:
132
+ [{"job_index": number, "qualification_match": 0-100, "skills_match": 0-100, "experience_match": 0-100, "qualification_reason": "brief reason based on qualifications", "skill_reason": "brief reason based on skill", "experience_reason": "brief reason based on experience", "salary_match": 0-100}]
133
+ """
134
+
135
+ jobs_info = [
136
+ {
137
+ 'index': idx + start_index,
138
+ 'title': job['title'],
139
+ 'desc': job.get('description', ''),
140
+ }
141
+ for idx, job in enumerate(jobs_batch)
142
+ ]
143
+
144
+ analysis_prompt = f"""
145
+ Resume Details: {json.dumps(resume_json)}
146
+ Jobs: {json.dumps(jobs_info)}
147
+ """
148
+
149
+ try:
150
+ response = client.generate_content([system_prompt, analysis_prompt])
151
+ print("Response overall: ", response)
152
+ print("Response: ", response.text)
153
+ content = response.text.strip()
154
+
155
+ # Find the first and last occurrence of JSON brackets
156
+ json_start = content.find("[")
157
+ json_end = content.rfind("]") + 1 # +1 to include the last bracket
158
+
159
+ # Ensure valid JSON presence
160
+ if json_start == -1 or json_end == -1:
161
+ raise ValueError("No valid JSON array found in LLM response.")
162
+
163
+ # Extract the JSON portion and parse it
164
+ json_str = content[json_start:json_end]
165
+ matches = json.loads(json_str)
166
+
167
+ # Compute match_score using weighted sum
168
+ for match in matches:
169
+ match["match_score"] = (
170
+ match["qualification_match"] * WEIGHTS["qualification_match"] +
171
+ match["skills_match"] * WEIGHTS["skills_match"] +
172
+ match["experience_match"] * WEIGHTS["experience_match"]+
173
+ match["salary_match"] * WEIGHTS["salary_match"]
174
+ )
175
+
176
+ # Convert to DataFrame and print
177
+ return pd.DataFrame(matches)
178
+ except Exception as e:
179
+ print(f"Error in analyze_job_batch: {str(e)}")
180
+ if retry_count < 3:
181
+ time.sleep(2)
182
+ return analyze_job_batch(client, resume_json, jobs_batch, start_index, retry_count + 1)
183
+ print(f"Batch {start_index} failed after retries: {str(e)}")
184
+ return pd.DataFrame()
185
+
186
+
187
+ def analyze_jobs_in_batches(
188
+ client,
189
+ resume: str,
190
+ jobs_df: pd.DataFrame,
191
+ batch_size: int = 3
192
+ ) -> pd.DataFrame:
193
+ """
194
+ Process job listings in batches and analyze match with resume.
195
+
196
+ Args:
197
+ client: Groq AI client
198
+ resume (str): Resume text
199
+ jobs_df (pd.DataFrame): DataFrame of job listings
200
+ batch_size (int, optional): Number of jobs to process in each batch. Defaults to 3.
201
+
202
+ Returns:
203
+ pd.DataFrame: Sorted job matches by match score
204
+ """
205
+ all_matches = []
206
+ jobs_dict = jobs_df.to_dict('records')
207
+
208
+ print("jobs_dict: ", jobs_dict)
209
+
210
+ for i in range(0, len(jobs_dict), batch_size):
211
+ batch = jobs_dict[i:i + batch_size]
212
+
213
+ print("batch done", i)
214
+
215
+ batch_matches = analyze_job_batch(client, resume, batch, i)
216
+
217
+ print("batch matches", batch_matches)
218
+
219
+ if not batch_matches.empty:
220
+ all_matches.append(batch_matches)
221
+
222
+ # time.sleep(1) # Rate limiting
223
+
224
+ if all_matches:
225
+ final_matches = pd.concat(all_matches, ignore_index=True)
226
+ return final_matches.sort_values('match_score', ascending=False)
227
+ return pd.DataFrame()
228
+
229
+
230
+ import gradio as gr
231
+ import pandas as pd
232
+ import fitz
233
+ import os
234
+ from groq import Groq
235
+ import google.generativeai as genai
236
+
237
+ def extract_text_from_pdf(pdf_path):
238
+ """Extracts text from a PDF file."""
239
+ text = ""
240
+ pdf_document = fitz.open(pdf_path)
241
+ for page in pdf_document:
242
+ text += page.get_text("text") + "\n"
243
+ pdf_document.close()
244
+ return text
245
+
246
+ def process_resume(file, job_description, location_pref, experience_years, yearly_salary_expectation):
247
+ if not file or not file.name.endswith('.pdf'):
248
+ return "Invalid file. Please upload a PDF.", None
249
+
250
+ resume_text = extract_text_from_pdf(file.name)
251
+
252
+ api_key = "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" # Replace with actual API key
253
+ client = Groq(api_key=api_key)
254
+
255
+ response = client.chat.completions.create(
256
+ model="llama3-70b-8192",
257
+ messages=[
258
+ {"role": "system", "content": "You are an AI that extracts structured data from resumes."},
259
+ {"role": "user", "content": f"Convert the following resume text into a structured JSON format inside third bracket where each section is dynamically detected:\n\n{resume_text}, add years of experience as {experience_years}, salary expectation as {yearly_salary_expectation}"}
260
+ ]
261
+ )
262
+ structured_data = response.choices[0].message.content.strip()
263
+
264
+ genai.configure(api_key="AIzaSyDmC7ayCATc2SKkq49td91bbA928n0SfDA")
265
+ model = genai.GenerativeModel("gemini-1.5-flash-latest")
266
+
267
+ client = Groq(api_key=api_key)
268
+ processed_params = convert_prompt_to_parameters(client, job_description, location_pref)
269
+ jobs_data = get_job_data(processed_params[0])
270
+
271
+ if not jobs_data.empty:
272
+ data = pd.DataFrame(jobs_data)
273
+ data = data[data['description'].notna()].reset_index(drop=True)
274
+ matches_df = analyze_jobs_in_batches(model, structured_data, data, batch_size=30)
275
+
276
+ print(matches_df)
277
+
278
+ # if not matches_df.empty:
279
+ # matched_jobs = data.iloc[matches_df['job_index']].copy()
280
+ # matched_jobs['match_score'] = matches_df['match_score']
281
+ # csv_path = "Job_list.csv"
282
+ # matched_jobs.to_csv(csv_path, index=False)
283
+ # return "Job matches found! Download the file below.", csv_path
284
+ # else:
285
+ # return "No suitable job matches found.", None
286
+ if not matches_df.empty:
287
+ matched_jobs = data.iloc[matches_df['job_index']].copy()
288
+ matched_jobs['match_score'] = matches_df['match_score']
289
+ matched_jobs["qualification_match"] = matches_df["qualification_match"]
290
+ matched_jobs["skills_match"] = matches_df["skills_match"]
291
+ matched_jobs["salary_match"] = matches_df["salary_match"]
292
+ matched_jobs["experience_match"] = matches_df["experience_match"]
293
+ matched_jobs["qualification_reason"] = matches_df["qualification_reason"]
294
+ matched_jobs["skill_reason"] = matches_df["skill_reason"]
295
+ matched_jobs["experience_reason"] = matches_df["experience_reason"]
296
+
297
+ print(f"Found {len(matched_jobs)} recommended matches!")
298
+ display_cols = ['site', 'job_url', 'title', 'company', 'location', 'match_score', 'qualification_match', 'qualification_reason', 'skills_match', 'skill_reason', 'experience_match', 'experience_reason', 'salary_match']
299
+ display_df = matched_jobs[matched_jobs['match_score'] > 50][display_cols].sort_values('match_score', ascending=False)
300
+ display_df['job_url'] = display_df['job_url'].apply(make_clickable)
301
+ print(display_df.to_string(index=False))
302
+ # csv_path = "Job_list.csv"
303
+ # display_df.to_csv(csv_path, index=False)
304
+ # return "βœ… Job matches found! Download your personalized job list below.", csv_path
305
+ # Create a temporary CSV file
306
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode='w', newline='', encoding='utf-8')
307
+ display_df.to_csv(temp_file.name, index=False)
308
+ temp_file.close() # Close the file so it can be accessed later
309
+
310
+ return "βœ… Job matches found! Download your personalized job list below.", temp_file.name
311
+ else:
312
+ return "⚠️ No suitable job matches found.", None
313
+ else:
314
+ return "❌ No jobs found with the given parameters.", None
315
+
316
+
317
+ def gradio_interface():
318
+ with gr.Blocks() as demo:
319
+ gr.Markdown("""
320
+ # πŸš€ Smart Job Search with AI Matching
321
+ ### Upload your resume and get AI-powered job recommendations!
322
+ """)
323
+
324
+ with gr.Row():
325
+ gr.Markdown("# πŸ“‚ Upload Resume")
326
+
327
+ with gr.Row():
328
+ resume_input = gr.File(label="Upload Resume (PDF)")
329
+
330
+ with gr.Row():
331
+ gr.Markdown("### πŸ“ Job Preferences")
332
+
333
+ with gr.Row():
334
+ # gr.Markdown("### πŸ“ Job Preferences")
335
+ job_desc_input = gr.Textbox(label="Job Role", placeholder="Enter desired job role")
336
+ # location_input = gr.Textbox(label="Preferred Location", placeholder="Enter location")
337
+ location_input = gr.Dropdown(
338
+ label="Preferred Location",
339
+ choices=[
340
+ "Argentina", "Australia", "Austria", "Bahrain", "Belgium", "Brazil", "Canada", "Chile",
341
+ "China", "Colombia", "Costa Rica", "Czech Republic", "Denmark", "Ecuador", "Egypt", "Finland",
342
+ "France", "Germany", "Greece", "Hong Kong", "Hungary", "India", "Indonesia", "Ireland",
343
+ "Israel", "Italy", "Japan", "Kuwait", "Luxembourg", "Malaysia", "Mexico", "Morocco",
344
+ "Netherlands", "New Zealand", "Nigeria", "Norway", "Oman", "Pakistan", "Panama", "Peru",
345
+ "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Saudi Arabia", "Singapore",
346
+ "South Africa", "South Korea", "Spain", "Sweden", "Switzerland", "Taiwan", "Thailand",
347
+ "Turkey", "Ukraine", "United Arab Emirates", "UK", "USA", "Uruguay", "Venezuela", "Vietnam"
348
+ ],
349
+ value=None
350
+ )
351
+
352
+ experience_input = gr.Number(label="Years of Experience", value=0)
353
+ salary_input = gr.Number(label="Expected Salary (Yearly)", value=100000)
354
+
355
+ submit_btn = gr.Button("πŸ” Find Jobs", elem_classes="primary-button")
356
+ output_text = gr.Textbox(label="Result", interactive=False)
357
+ download_link = gr.File(label="πŸ“₯ Download Job List")
358
+
359
+ submit_btn.click(
360
+ process_resume,
361
+ inputs=[resume_input, job_desc_input, location_input, experience_input, salary_input],
362
+ outputs=[output_text, download_link]
363
+ )
364
+
365
+ return demo
366
+
367
+ demo = gradio_interface()
368
+ demo.launch(debug=True, share=True)