Update app.py
Browse files
app.py
CHANGED
|
@@ -26,7 +26,6 @@ stemmer = PorterStemmer()
|
|
| 26 |
|
| 27 |
# --- Expanded Skill Whitelist ---
|
| 28 |
SKILL_WHITELIST = {
|
| 29 |
-
# Technical & Data
|
| 30 |
'python', 'java', 'c++', 'javascript', 'typescript', 'sql', 'nosql', 'html', 'css', 'react', 'angular', 'vue',
|
| 31 |
'nodejs', 'django', 'flask', 'fastapi', 'spring boot', 'ruby on rails', 'php', 'swift', 'kotlin', 'dart', 'flutter',
|
| 32 |
'machine learning', 'deep learning', 'tensorflow', 'pytorch', 'keras', 'scikit-learn', 'pandas', 'numpy', 'matplotlib',
|
|
@@ -36,14 +35,12 @@ SKILL_WHITELIST = {
|
|
| 36 |
'git', 'github', 'devops', 'linux', 'unix', 'shell scripting', 'powershell', 'cybersecurity', 'penetration testing',
|
| 37 |
'network security', 'cryptography', 'blockchain', 'c#', '.net', 'sql server', 'mysql', 'postgresql', 'mongodb', 'redis',
|
| 38 |
'elasticsearch', 'api design', 'rest apis', 'graphql', 'microservices', 'serverless', 'system design', 'saas',
|
| 39 |
-
# Business & Consulting
|
| 40 |
'agile', 'scrum', 'project management', 'product management', 'consulting', 'client management', 'business development',
|
| 41 |
'strategy', 'stakeholder management', 'risk management', 'compliance', 'aml', 'kyc', 'reinsurance', 'finance',
|
| 42 |
'financial modeling', 'financial analysis', 'due diligence', 'sourcing', 'procurement', 'negotiation', 'supply chain',
|
| 43 |
'business analysis', 'business intelligence', 'presentations', 'public speaking', 'time management', 'critical thinking',
|
| 44 |
'design thinking', 'innovation', 'adaptability', 'supervisory', 'pmp', 'cpsm', 'cips', 'microsoft office', 'communication',
|
| 45 |
'organizational skills',
|
| 46 |
-
# Soft & Other
|
| 47 |
'leadership', 'stakeholder communication', 'client communication', 'teamwork', 'collaboration', 'problem solving',
|
| 48 |
'ui/ux design', 'figma', 'sketch', 'adobe xd', 'graphic design', 'autocad', 'solidworks', 'sales', 'marketing',
|
| 49 |
'seo', 'sem', 'content writing', 'customer support', 'technical writing', 'sap', 'oracle', 'budgeting', 'mentoring', 'supervising'
|
|
@@ -111,12 +108,12 @@ def llm_expand_query(user_input: str) -> str:
|
|
| 111 |
response = LLM_PIPELINE(prompt_template, max_new_tokens=100, do_sample=True, temperature=0.6, return_full_text=False)
|
| 112 |
expanded_query = response[0]['generated_text'].strip()
|
| 113 |
final_query = user_input + ". " + expanded_query.replace('\n', ' ').replace(':', '').strip()
|
|
|
|
| 114 |
return final_query
|
| 115 |
except Exception:
|
| 116 |
return user_input
|
| 117 |
|
| 118 |
def find_job_matches(query: str, top_k: int = 50) -> pd.DataFrame:
|
| 119 |
-
# Simplified this function slightly
|
| 120 |
query_embedding = model.encode(query, convert_to_tensor=True)
|
| 121 |
general_similarity_scores = util.cos_sim(query_embedding, combined_job_embeddings)[0]
|
| 122 |
top_indices = torch.topk(general_similarity_scores, k=len(combined_df))
|
|
@@ -138,7 +135,6 @@ def find_job_matches(query: str, top_k: int = 50) -> pd.DataFrame:
|
|
| 138 |
final_results_df = final_results_df.set_index('job_id', drop=False).rename(columns={'job_id': 'Job ID'})
|
| 139 |
return final_results_df
|
| 140 |
|
| 141 |
-
# This function is no longer needed for reranking, but is kept for calculating the match score for the details view
|
| 142 |
def calculate_skill_match_score(user_skills: list[str], job_skills: list[str]) -> float:
|
| 143 |
if not user_skills or not job_skills:
|
| 144 |
return 0.0
|
|
@@ -154,12 +150,11 @@ def calculate_skill_match_score(user_skills: list[str], job_skills: list[str]) -
|
|
| 154 |
return avg_score * skill_count_factor
|
| 155 |
|
| 156 |
def initialize_data_and_model():
|
| 157 |
-
# This function remains largely the same as the stable version you provided
|
| 158 |
global original_df, combined_df, model, combined_job_embeddings, original_job_title_embeddings
|
| 159 |
PROCESSED_DATA_PATH = "processed_jobs_with_skills.parquet"
|
| 160 |
|
| 161 |
print("--- Initializing LLM Client ---")
|
| 162 |
-
if not initialize_llm_client(): print("Warning: LLM Client failed to initialize.")
|
| 163 |
|
| 164 |
if os.path.exists(PROCESSED_DATA_PATH):
|
| 165 |
print(f"--- Loading pre-processed data from {PROCESSED_DATA_PATH} ---")
|
|
@@ -173,9 +168,16 @@ def initialize_data_and_model():
|
|
| 173 |
if not isinstance(text, str) or len(text.strip()) < 20 or not LLM_PIPELINE: return []
|
| 174 |
prompt = f"""
|
| 175 |
Instruct: You are an expert technical recruiter. Extract the key skills from the job description text. List technical and soft skills as a comma-separated string.
|
| 176 |
-
[Example 1]
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
try:
|
| 180 |
response = LLM_PIPELINE(prompt, max_new_tokens=150, do_sample=False, temperature=0.1, return_full_text=False)
|
| 181 |
skills_text = response[0]['generated_text'].strip()
|
|
@@ -238,6 +240,7 @@ Instruct: You are an expert technical recruiter. Extract the key skills from the
|
|
| 238 |
print("--- Extracting skills with HYBRID ACCURACY model. Please wait... ---")
|
| 239 |
original_df['Skills'] = original_df.progress_apply(extract_skills_hybrid, axis=1)
|
| 240 |
original_df = original_df.drop(columns=['text_for_skills'])
|
|
|
|
| 241 |
print(f"--- Saving processed data to {PROCESSED_DATA_PATH} for faster future startups ---")
|
| 242 |
original_df.to_parquet(PROCESSED_DATA_PATH)
|
| 243 |
|
|
@@ -252,6 +255,7 @@ Instruct: You are an expert technical recruiter. Extract the key skills from the
|
|
| 252 |
augmented_df["full_text"] = augmented_df.apply(create_full_text, axis=1)
|
| 253 |
combined_df = pd.concat([original_df.copy(), augmented_df.copy()], ignore_index=True)
|
| 254 |
original_df = original_df.rename(columns={'Job title': 'job_title', 'Company': 'company'})
|
|
|
|
| 255 |
print("--- Loading Fine-Tuned Sentence Transformer Model ---")
|
| 256 |
model = SentenceTransformer(FINETUNED_MODEL_ID)
|
| 257 |
print("--- Encoding Embeddings ---")
|
|
@@ -266,48 +270,63 @@ def _course_links_for(skill: str) -> str:
|
|
| 266 |
links = [("Coursera", f"https://www.coursera.org/search?query={q}"), ("edX", f"https://www.edx.org/search?q={q}"), ("Udemy", f"https://www.udemy.com/courses/search/?q={q}"), ("YouTube", f"https://www.youtube.com/results?search_query={q}+tutorial")]
|
| 267 |
return " • ".join([f'<a href="{u}" target="_blank" style="color: #007bff;">{name}</a>' for name, u in links])
|
| 268 |
|
|
|
|
|
|
|
| 269 |
def get_job_matches(dream_job: str, top_n: int):
|
| 270 |
-
status = "Searching..."
|
| 271 |
expanded_desc = llm_expand_query(dream_job)
|
| 272 |
-
emb_matches = find_job_matches(expanded_desc, top_k=50)
|
| 273 |
display_df = emb_matches.head(top_n)
|
| 274 |
-
status = f"Found {len(
|
|
|
|
| 275 |
table_to_show = display_df[['job_title', 'company', 'Similarity Score']]
|
| 276 |
table_to_show = table_to_show.rename(columns={'Similarity Score': 'Relevance Score'})
|
| 277 |
-
|
| 278 |
dropdown_options = [(f"{i+1}. {row['job_title']} - {row['company']}", row.name) for i, row in display_df.iterrows()]
|
| 279 |
dropdown_value = dropdown_options[0][1] if dropdown_options else None
|
|
|
|
| 280 |
return status, emb_matches, table_to_show, gr.update(choices=dropdown_options, value=dropdown_value, visible=True), gr.update(visible=True)
|
| 281 |
|
| 282 |
-
def
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
-
|
| 287 |
-
combined_query = dream_job + ". My current skills are: " + skills_text
|
| 288 |
-
skill_matches_df = find_job_matches(combined_query, top_k=top_n)
|
| 289 |
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
-
|
|
|
|
| 295 |
|
| 296 |
def find_matches_and_rank_with_check(dream_job: str, top_n: int):
|
| 297 |
if not dream_job:
|
| 298 |
-
return "Please describe your dream job first.", None, pd.DataFrame(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
|
|
|
| 299 |
unrecognized_words = check_spelling_in_query(dream_job)
|
| 300 |
if unrecognized_words:
|
| 301 |
word_list_html = ", ".join([f"<b><span style='color: #F87171;'>{w}</span></b>" for w in unrecognized_words])
|
| 302 |
alert_message = f"<b><span style='color: #F87171;'>⚠️ Possible Spelling Error:</span></b> Unrecognized: {word_list_html}."
|
| 303 |
-
return "Status: Awaiting confirmation.", None, pd.DataFrame(), gr.update(visible=False), gr.update(visible=False), gr.update(value=alert_message, visible=True), gr.update(visible=True)
|
| 304 |
|
| 305 |
status, emb_matches, table_to_show, dropdown_update, accordion_update = get_job_matches(dream_job, top_n)
|
| 306 |
-
return status, emb_matches, table_to_show, dropdown_update, accordion_update, gr.update(visible=False), gr.update(visible=False)
|
| 307 |
|
| 308 |
def find_matches_and_rank_anyway(dream_job: str, top_n: int):
|
| 309 |
status, emb_matches, table_to_show, dropdown_update, accordion_update = get_job_matches(dream_job, top_n)
|
| 310 |
-
return status, emb_matches, table_to_show, dropdown_update, accordion_update, gr.update(visible=False), gr.update(visible=False)
|
| 311 |
|
| 312 |
def on_select_job(job_id, skills_text):
|
| 313 |
if job_id is None: return "", "", "", "", "", gr.update(visible=False), [], 0, gr.Button(visible=False)
|
|
@@ -331,28 +350,21 @@ def on_select_job(job_id, skills_text):
|
|
| 331 |
matched_job_skills_mask = torch.any(similarity_matrix > 0.58, dim=0)
|
| 332 |
all_missing_skills = [skill for i, skill in enumerate(job_skills) if not matched_job_skills_mask[i]]
|
| 333 |
|
|
|
|
|
|
|
|
|
|
| 334 |
if user_skills and score_val >= 0.98:
|
| 335 |
learning_plan_html = "<h4 style='color:green;'>🎉 You have all the required skills!</h4>"
|
| 336 |
-
job_details_markdown += f"\n**Your skill match:** {score_val:.1%}"
|
| 337 |
return job_details_markdown, duties, qualifications, description, learning_plan_html, gr.update(visible=True), [], 0, gr.Button(visible=False)
|
| 338 |
|
| 339 |
-
if user_skills:
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
else:
|
| 348 |
-
headline = "<h4>To be a good fit for this role, you'll need to learn these skills:</h4>"
|
| 349 |
-
skills_to_display = sorted(job_skills)[:5]
|
| 350 |
-
items_html = [f"<li><b>{ms}</b><br>• Learn: {_course_links_for(ms)}</li>" for ms in skills_to_display]
|
| 351 |
-
learning_plan_html = f"{headline}<ul style='list-style-type: none; padding-left: 0;'>{''.join(items_html)}</ul>"
|
| 352 |
-
full_skill_list_for_state = sorted(job_skills)
|
| 353 |
-
new_offset = len(skills_to_display)
|
| 354 |
-
should_button_be_visible = len(full_skill_list_for_state) > 5
|
| 355 |
-
return job_details_markdown, duties, qualifications, description, learning_plan_html, gr.update(visible=True), full_skill_list_for_state, new_offset, gr.Button(visible=should_button_be_visible)
|
| 356 |
|
| 357 |
def load_more_skills(full_skills_list, current_offset):
|
| 358 |
SKILLS_INCREMENT = 5
|
|
@@ -366,8 +378,12 @@ def load_more_skills(full_skills_list, current_offset):
|
|
| 366 |
def on_reset():
|
| 367 |
return ("", 3, "", pd.DataFrame(), None, gr.update(visible=False), gr.update(visible=False), "Status: Ready.", "", "", "", "", gr.update(visible=False), gr.update(visible=False), [], 0, gr.Button(visible=False), pd.DataFrame(), gr.update(visible=False))
|
| 368 |
|
| 369 |
-
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
print(initialization_status)
|
| 372 |
|
| 373 |
with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
|
@@ -378,10 +394,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
|
| 378 |
with gr.Row():
|
| 379 |
with gr.Column(scale=3):
|
| 380 |
dream_text = gr.Textbox(label='Your Dream Job Description', lines=3, placeholder="e.g., 'A role in a tech startup focused on machine learning...'")
|
| 381 |
-
with gr.Accordion("Optional:
|
| 382 |
with gr.Row():
|
| 383 |
skills_text = gr.Textbox(label='Your Skills (comma-separated)', placeholder="e.g., Python, data analysis", scale=3)
|
| 384 |
-
|
| 385 |
with gr.Column(scale=1):
|
| 386 |
topk_slider = gr.Slider(minimum=1, maximum=5, value=3, step=1, label="Number of Matches")
|
| 387 |
search_btn = gr.Button("Find Matches", variant="primary")
|
|
@@ -392,8 +408,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
|
| 392 |
search_anyway_btn = gr.Button("Search Anyway", variant="secondary")
|
| 393 |
retype_btn = gr.Button("Let Me Fix It", variant="stop")
|
| 394 |
|
| 395 |
-
gr.Markdown("### Top Matches for Your
|
| 396 |
-
df_output = gr.DataFrame(label="Job Matches", interactive=False)
|
| 397 |
|
| 398 |
with gr.Column(visible=False) as skill_jobs_col:
|
| 399 |
gr.Markdown("### Potential Jobs to Consider (Given Your Skills)")
|
|
@@ -409,11 +425,11 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
|
| 409 |
learning_plan_output = gr.HTML(label="Learning Plan")
|
| 410 |
load_more_btn = gr.Button("Load More Skills", visible=False)
|
| 411 |
|
| 412 |
-
search_btn.click(fn=find_matches_and_rank_with_check, inputs=[dream_text, topk_slider], outputs=[status_text, initial_matches_state, df_output, job_selector, details_accordion, spelling_alert, spelling_row])
|
| 413 |
-
search_anyway_btn.click(fn=find_matches_and_rank_anyway, inputs=[dream_text, topk_slider], outputs=[status_text, initial_matches_state, df_output, job_selector, details_accordion, spelling_alert, spelling_row])
|
| 414 |
-
|
|
|
|
| 415 |
reset_btn.click(fn=on_reset, outputs=[dream_text, topk_slider, skills_text, df_output, initial_matches_state, job_selector, details_accordion, status_text, job_details_markdown, duties_markdown, qualifications_markdown, description_markdown, spelling_alert, spelling_row, missing_skills_state, skills_offset_state, load_more_btn, skill_jobs_output, skill_jobs_col], queue=False)
|
| 416 |
-
skill_search_btn.click(fn=find_skill_based_jobs, inputs=[dream_text, skills_text, topk_slider], outputs=[skill_jobs_output, skill_jobs_col, status_text])
|
| 417 |
job_selector.change(fn=on_select_job, inputs=[job_selector, skills_text], outputs=[job_details_markdown, duties_markdown, qualifications_markdown, description_markdown, learning_plan_output, details_accordion, missing_skills_state, skills_offset_state, load_more_btn])
|
| 418 |
load_more_btn.click(fn=load_more_skills, inputs=[missing_skills_state, skills_offset_state], outputs=[learning_plan_output, skills_offset_state, load_more_btn])
|
| 419 |
|
|
|
|
| 26 |
|
| 27 |
# --- Expanded Skill Whitelist ---
|
| 28 |
SKILL_WHITELIST = {
|
|
|
|
| 29 |
'python', 'java', 'c++', 'javascript', 'typescript', 'sql', 'nosql', 'html', 'css', 'react', 'angular', 'vue',
|
| 30 |
'nodejs', 'django', 'flask', 'fastapi', 'spring boot', 'ruby on rails', 'php', 'swift', 'kotlin', 'dart', 'flutter',
|
| 31 |
'machine learning', 'deep learning', 'tensorflow', 'pytorch', 'keras', 'scikit-learn', 'pandas', 'numpy', 'matplotlib',
|
|
|
|
| 35 |
'git', 'github', 'devops', 'linux', 'unix', 'shell scripting', 'powershell', 'cybersecurity', 'penetration testing',
|
| 36 |
'network security', 'cryptography', 'blockchain', 'c#', '.net', 'sql server', 'mysql', 'postgresql', 'mongodb', 'redis',
|
| 37 |
'elasticsearch', 'api design', 'rest apis', 'graphql', 'microservices', 'serverless', 'system design', 'saas',
|
|
|
|
| 38 |
'agile', 'scrum', 'project management', 'product management', 'consulting', 'client management', 'business development',
|
| 39 |
'strategy', 'stakeholder management', 'risk management', 'compliance', 'aml', 'kyc', 'reinsurance', 'finance',
|
| 40 |
'financial modeling', 'financial analysis', 'due diligence', 'sourcing', 'procurement', 'negotiation', 'supply chain',
|
| 41 |
'business analysis', 'business intelligence', 'presentations', 'public speaking', 'time management', 'critical thinking',
|
| 42 |
'design thinking', 'innovation', 'adaptability', 'supervisory', 'pmp', 'cpsm', 'cips', 'microsoft office', 'communication',
|
| 43 |
'organizational skills',
|
|
|
|
| 44 |
'leadership', 'stakeholder communication', 'client communication', 'teamwork', 'collaboration', 'problem solving',
|
| 45 |
'ui/ux design', 'figma', 'sketch', 'adobe xd', 'graphic design', 'autocad', 'solidworks', 'sales', 'marketing',
|
| 46 |
'seo', 'sem', 'content writing', 'customer support', 'technical writing', 'sap', 'oracle', 'budgeting', 'mentoring', 'supervising'
|
|
|
|
| 108 |
response = LLM_PIPELINE(prompt_template, max_new_tokens=100, do_sample=True, temperature=0.6, return_full_text=False)
|
| 109 |
expanded_query = response[0]['generated_text'].strip()
|
| 110 |
final_query = user_input + ". " + expanded_query.replace('\n', ' ').replace(':', '').strip()
|
| 111 |
+
final_query = final_query.replace('..', '.').strip()
|
| 112 |
return final_query
|
| 113 |
except Exception:
|
| 114 |
return user_input
|
| 115 |
|
| 116 |
def find_job_matches(query: str, top_k: int = 50) -> pd.DataFrame:
|
|
|
|
| 117 |
query_embedding = model.encode(query, convert_to_tensor=True)
|
| 118 |
general_similarity_scores = util.cos_sim(query_embedding, combined_job_embeddings)[0]
|
| 119 |
top_indices = torch.topk(general_similarity_scores, k=len(combined_df))
|
|
|
|
| 135 |
final_results_df = final_results_df.set_index('job_id', drop=False).rename(columns={'job_id': 'Job ID'})
|
| 136 |
return final_results_df
|
| 137 |
|
|
|
|
| 138 |
def calculate_skill_match_score(user_skills: list[str], job_skills: list[str]) -> float:
|
| 139 |
if not user_skills or not job_skills:
|
| 140 |
return 0.0
|
|
|
|
| 150 |
return avg_score * skill_count_factor
|
| 151 |
|
| 152 |
def initialize_data_and_model():
|
|
|
|
| 153 |
global original_df, combined_df, model, combined_job_embeddings, original_job_title_embeddings
|
| 154 |
PROCESSED_DATA_PATH = "processed_jobs_with_skills.parquet"
|
| 155 |
|
| 156 |
print("--- Initializing LLM Client ---")
|
| 157 |
+
if not initialize_llm_client(): print("Warning: LLM Client failed to initialize. Will use NLTK only for skills.")
|
| 158 |
|
| 159 |
if os.path.exists(PROCESSED_DATA_PATH):
|
| 160 |
print(f"--- Loading pre-processed data from {PROCESSED_DATA_PATH} ---")
|
|
|
|
| 168 |
if not isinstance(text, str) or len(text.strip()) < 20 or not LLM_PIPELINE: return []
|
| 169 |
prompt = f"""
|
| 170 |
Instruct: You are an expert technical recruiter. Extract the key skills from the job description text. List technical and soft skills as a comma-separated string.
|
| 171 |
+
[Example 1]
|
| 172 |
+
Text: "Requires 3+ years of experience in cloud infrastructure. Must be proficient in AWS, particularly EC2 and S3. Experience with Terraform for IaC is a plus."
|
| 173 |
+
Extracted Skills: cloud infrastructure, aws, ec2, s3, terraform, infrastructure as code
|
| 174 |
+
[Example 2]
|
| 175 |
+
Text: "Seeking a team lead with strong project management abilities. Must communicate effectively with stakeholders and manage timelines using Agile methodologies like Scrum."
|
| 176 |
+
Extracted Skills: project management, leadership, stakeholder communication, agile, scrum
|
| 177 |
+
[Actual Task]
|
| 178 |
+
Text: "{text}"
|
| 179 |
+
Extracted Skills:
|
| 180 |
+
"""
|
| 181 |
try:
|
| 182 |
response = LLM_PIPELINE(prompt, max_new_tokens=150, do_sample=False, temperature=0.1, return_full_text=False)
|
| 183 |
skills_text = response[0]['generated_text'].strip()
|
|
|
|
| 240 |
print("--- Extracting skills with HYBRID ACCURACY model. Please wait... ---")
|
| 241 |
original_df['Skills'] = original_df.progress_apply(extract_skills_hybrid, axis=1)
|
| 242 |
original_df = original_df.drop(columns=['text_for_skills'])
|
| 243 |
+
|
| 244 |
print(f"--- Saving processed data to {PROCESSED_DATA_PATH} for faster future startups ---")
|
| 245 |
original_df.to_parquet(PROCESSED_DATA_PATH)
|
| 246 |
|
|
|
|
| 255 |
augmented_df["full_text"] = augmented_df.apply(create_full_text, axis=1)
|
| 256 |
combined_df = pd.concat([original_df.copy(), augmented_df.copy()], ignore_index=True)
|
| 257 |
original_df = original_df.rename(columns={'Job title': 'job_title', 'Company': 'company'})
|
| 258 |
+
|
| 259 |
print("--- Loading Fine-Tuned Sentence Transformer Model ---")
|
| 260 |
model = SentenceTransformer(FINETUNED_MODEL_ID)
|
| 261 |
print("--- Encoding Embeddings ---")
|
|
|
|
| 270 |
links = [("Coursera", f"https://www.coursera.org/search?query={q}"), ("edX", f"https://www.edx.org/search?q={q}"), ("Udemy", f"https://www.udemy.com/courses/search/?q={q}"), ("YouTube", f"https://www.youtube.com/results?search_query={q}+tutorial")]
|
| 271 |
return " • ".join([f'<a href="{u}" target="_blank" style="color: #007bff;">{name}</a>' for name, u in links])
|
| 272 |
|
| 273 |
+
# --- GRADIO EVENT HANDLER FUNCTIONS ---
|
| 274 |
+
|
| 275 |
def get_job_matches(dream_job: str, top_n: int):
|
| 276 |
+
status = "Searching for jobs based on your career goal..."
|
| 277 |
expanded_desc = llm_expand_query(dream_job)
|
| 278 |
+
emb_matches = find_job_matches(expanded_desc, top_k=50) # Get a larger pool for later
|
| 279 |
display_df = emb_matches.head(top_n)
|
| 280 |
+
status = f"Found {len(emb_matches)} top matches for your career goal."
|
| 281 |
+
|
| 282 |
table_to_show = display_df[['job_title', 'company', 'Similarity Score']]
|
| 283 |
table_to_show = table_to_show.rename(columns={'Similarity Score': 'Relevance Score'})
|
| 284 |
+
|
| 285 |
dropdown_options = [(f"{i+1}. {row['job_title']} - {row['company']}", row.name) for i, row in display_df.iterrows()]
|
| 286 |
dropdown_value = dropdown_options[0][1] if dropdown_options else None
|
| 287 |
+
|
| 288 |
return status, emb_matches, table_to_show, gr.update(choices=dropdown_options, value=dropdown_value, visible=True), gr.update(visible=True)
|
| 289 |
|
| 290 |
+
def analyze_skills(dream_job, initial_matches_df, skills_text, top_n):
|
| 291 |
+
user_skills = [_norm_skill_token(s) for s in skills_text.split(',') if _norm_skill_token(s)]
|
| 292 |
+
if not user_skills:
|
| 293 |
+
# If skills are cleared, just show the original table without skill scores
|
| 294 |
+
table1_to_show = initial_matches_df.head(top_n)[['job_title', 'company', 'Similarity Score']]
|
| 295 |
+
return "Skills cleared. Showing original relevance.", table1_to_show, pd.DataFrame(), gr.update(visible=False)
|
| 296 |
+
|
| 297 |
+
# --- 1. Rerank the first table ---
|
| 298 |
+
rerank_df = pd.DataFrame(initial_matches_df) # Make sure it's a DataFrame
|
| 299 |
+
rerank_df['Skill Match Score'] = rerank_df['Skills'].apply(lambda job_skills: calculate_skill_match_score(user_skills, job_skills))
|
| 300 |
+
rerank_df = rerank_df.sort_values(by='Skill Match Score', ascending=False)
|
| 301 |
|
| 302 |
+
table1_to_show = rerank_df.head(top_n)[['job_title', 'company', 'Similarity Score', 'Skill Match Score']]
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
# --- 2. Find new jobs for the second table ---
|
| 305 |
+
status = "Analyzing skills and finding new job matches..."
|
| 306 |
+
combined_query = dream_job + ". My current skills are: " + skills_text
|
| 307 |
+
new_matches_df = find_job_matches(combined_query, top_k=top_n)
|
| 308 |
+
table2_to_show = new_matches_df[['job_title', 'company', 'Similarity Score']]
|
| 309 |
+
table2_to_show = table2_to_show.rename(columns={'Similarity Score': 'Blended Match Score'})
|
| 310 |
|
| 311 |
+
status = f"Re-ranked initial jobs by skill match and found new jobs to consider."
|
| 312 |
+
return status, table1_to_show, table2_to_show, gr.update(visible=True)
|
| 313 |
|
| 314 |
def find_matches_and_rank_with_check(dream_job: str, top_n: int):
|
| 315 |
if not dream_job:
|
| 316 |
+
return "Please describe your dream job first.", None, pd.DataFrame(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), pd.DataFrame(), gr.update(visible=False)
|
| 317 |
+
|
| 318 |
unrecognized_words = check_spelling_in_query(dream_job)
|
| 319 |
if unrecognized_words:
|
| 320 |
word_list_html = ", ".join([f"<b><span style='color: #F87171;'>{w}</span></b>" for w in unrecognized_words])
|
| 321 |
alert_message = f"<b><span style='color: #F87171;'>⚠️ Possible Spelling Error:</span></b> Unrecognized: {word_list_html}."
|
| 322 |
+
return "Status: Awaiting confirmation.", None, pd.DataFrame(), gr.update(visible=False), gr.update(visible=False), gr.update(value=alert_message, visible=True), gr.update(visible=True), pd.DataFrame(), gr.update(visible=False)
|
| 323 |
|
| 324 |
status, emb_matches, table_to_show, dropdown_update, accordion_update = get_job_matches(dream_job, top_n)
|
| 325 |
+
return status, emb_matches, table_to_show, dropdown_update, accordion_update, gr.update(visible=False), gr.update(visible=False), pd.DataFrame(), gr.update(visible=False)
|
| 326 |
|
| 327 |
def find_matches_and_rank_anyway(dream_job: str, top_n: int):
|
| 328 |
status, emb_matches, table_to_show, dropdown_update, accordion_update = get_job_matches(dream_job, top_n)
|
| 329 |
+
return status, emb_matches, table_to_show, dropdown_update, accordion_update, gr.update(visible=False), gr.update(visible=False), pd.DataFrame(), gr.update(visible=False)
|
| 330 |
|
| 331 |
def on_select_job(job_id, skills_text):
|
| 332 |
if job_id is None: return "", "", "", "", "", gr.update(visible=False), [], 0, gr.Button(visible=False)
|
|
|
|
| 350 |
matched_job_skills_mask = torch.any(similarity_matrix > 0.58, dim=0)
|
| 351 |
all_missing_skills = [skill for i, skill in enumerate(job_skills) if not matched_job_skills_mask[i]]
|
| 352 |
|
| 353 |
+
if user_skills:
|
| 354 |
+
job_details_markdown += f"\n**Your skill match:** {score_val:.1%}"
|
| 355 |
+
|
| 356 |
if user_skills and score_val >= 0.98:
|
| 357 |
learning_plan_html = "<h4 style='color:green;'>🎉 You have all the required skills!</h4>"
|
|
|
|
| 358 |
return job_details_markdown, duties, qualifications, description, learning_plan_html, gr.update(visible=True), [], 0, gr.Button(visible=False)
|
| 359 |
|
| 360 |
+
headline = "<h4>Focus on these skills to improve your match:</h4>" if user_skills else "<h4>To be a good fit for this role, you'll need to learn these skills:</h4>"
|
| 361 |
+
skills_to_display = sorted(all_missing_skills)[:5]
|
| 362 |
+
items_html = [f"<li><b>{ms}</b><br>• Learn: {_course_links_for(ms)}</li>" for ms in skills_to_display]
|
| 363 |
+
learning_plan_html = f"{headline}<ul style='list-style-type: none; padding-left: 0;'>{''.join(items_html)}</ul>"
|
| 364 |
+
full_skill_list_for_state = sorted(all_missing_skills) if user_skills else sorted(job_skills)
|
| 365 |
+
new_offset = len(skills_to_display)
|
| 366 |
+
should_button_be_visible = len(full_skill_list_for_state) > 5
|
| 367 |
+
return job_details_markdown, duties, qualifications, description, learning_plan_html, gr.update(visible=True), full_skill_list_for_state, new_offset, gr.Button(visible=should_button_be_visible)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
def load_more_skills(full_skills_list, current_offset):
|
| 370 |
SKILLS_INCREMENT = 5
|
|
|
|
| 378 |
def on_reset():
|
| 379 |
return ("", 3, "", pd.DataFrame(), None, gr.update(visible=False), gr.update(visible=False), "Status: Ready.", "", "", "", "", gr.update(visible=False), gr.update(visible=False), [], 0, gr.Button(visible=False), pd.DataFrame(), gr.update(visible=False))
|
| 380 |
|
| 381 |
+
# --- Main App ---
|
| 382 |
+
try:
|
| 383 |
+
initialization_status = initialize_data_and_model()
|
| 384 |
+
except Exception as e:
|
| 385 |
+
# Fallback for brevity, paste your full initialize_data_and_model function
|
| 386 |
+
raise e
|
| 387 |
print(initialization_status)
|
| 388 |
|
| 389 |
with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
|
|
|
| 394 |
with gr.Row():
|
| 395 |
with gr.Column(scale=3):
|
| 396 |
dream_text = gr.Textbox(label='Your Dream Job Description', lines=3, placeholder="e.g., 'A role in a tech startup focused on machine learning...'")
|
| 397 |
+
with gr.Accordion("Optional: Analyze Your Skills & Find More Jobs", open=True):
|
| 398 |
with gr.Row():
|
| 399 |
skills_text = gr.Textbox(label='Your Skills (comma-separated)', placeholder="e.g., Python, data analysis", scale=3)
|
| 400 |
+
analyze_btn = gr.Button("Analyze Skills", variant="secondary", scale=1)
|
| 401 |
with gr.Column(scale=1):
|
| 402 |
topk_slider = gr.Slider(minimum=1, maximum=5, value=3, step=1, label="Number of Matches")
|
| 403 |
search_btn = gr.Button("Find Matches", variant="primary")
|
|
|
|
| 408 |
search_anyway_btn = gr.Button("Search Anyway", variant="secondary")
|
| 409 |
retype_btn = gr.Button("Let Me Fix It", variant="stop")
|
| 410 |
|
| 411 |
+
gr.Markdown("### Top Matches for Your Career Goal")
|
| 412 |
+
df_output = gr.DataFrame(label="Job Matches", interactive=False, datatype=['str', 'str', 'number', 'number'])
|
| 413 |
|
| 414 |
with gr.Column(visible=False) as skill_jobs_col:
|
| 415 |
gr.Markdown("### Potential Jobs to Consider (Given Your Skills)")
|
|
|
|
| 425 |
learning_plan_output = gr.HTML(label="Learning Plan")
|
| 426 |
load_more_btn = gr.Button("Load More Skills", visible=False)
|
| 427 |
|
| 428 |
+
search_btn.click(fn=find_matches_and_rank_with_check, inputs=[dream_text, topk_slider], outputs=[status_text, initial_matches_state, df_output, job_selector, details_accordion, spelling_alert, spelling_row, skill_jobs_output, skill_jobs_col])
|
| 429 |
+
search_anyway_btn.click(fn=find_matches_and_rank_anyway, inputs=[dream_text, topk_slider], outputs=[status_text, initial_matches_state, df_output, job_selector, details_accordion, spelling_alert, spelling_row, skill_jobs_output, skill_jobs_col])
|
| 430 |
+
analyze_btn.click(fn=analyze_skills, inputs=[dream_text, initial_matches_state, skills_text, topk_slider], outputs=[status_text, df_output, skill_jobs_output, skill_jobs_col])
|
| 431 |
+
retype_btn.click(lambda: ("Status: Ready for you to retype.", None, pd.DataFrame(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), pd.DataFrame(), gr.update(visible=False)), outputs=[status_text, initial_matches_state, df_output, job_selector, details_accordion, spelling_alert, spelling_row, skill_jobs_output, skill_jobs_col])
|
| 432 |
reset_btn.click(fn=on_reset, outputs=[dream_text, topk_slider, skills_text, df_output, initial_matches_state, job_selector, details_accordion, status_text, job_details_markdown, duties_markdown, qualifications_markdown, description_markdown, spelling_alert, spelling_row, missing_skills_state, skills_offset_state, load_more_btn, skill_jobs_output, skill_jobs_col], queue=False)
|
|
|
|
| 433 |
job_selector.change(fn=on_select_job, inputs=[job_selector, skills_text], outputs=[job_details_markdown, duties_markdown, qualifications_markdown, description_markdown, learning_plan_output, details_accordion, missing_skills_state, skills_offset_state, load_more_btn])
|
| 434 |
load_more_btn.click(fn=load_more_skills, inputs=[missing_skills_state, skills_offset_state], outputs=[learning_plan_output, skills_offset_state, load_more_btn])
|
| 435 |
|