Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,10 +1,9 @@
|
|
1 |
import os
|
2 |
import re
|
3 |
-
import io
|
4 |
from datetime import datetime
|
5 |
-
import PyPDF2
|
6 |
import torch
|
7 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForSeq2SeqLM
|
|
|
8 |
from groq import Groq
|
9 |
import gradio as gr
|
10 |
from docxtpl import DocxTemplate
|
@@ -48,49 +47,64 @@ def extract_skills_llama(text):
|
|
48 |
except Exception as e:
|
49 |
raise RuntimeError(f"Error during skill extraction: {e}")
|
50 |
|
51 |
-
# ---
|
52 |
-
def
|
53 |
-
"""
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
def
|
59 |
-
"""
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
-
# --- Communication Generation --- #
|
78 |
-
def communication_generator(resume_skills, job_description_skills,
|
79 |
-
"""Generates a communication response based on
|
80 |
model_name = "google/flan-t5-base"
|
81 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
82 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
83 |
|
84 |
-
# Assess candidate fit based on similarity
|
85 |
-
fit_status = "fit
|
86 |
-
|
87 |
-
|
|
|
88 |
message = (
|
89 |
-
f"After a
|
90 |
-
f"
|
91 |
-
f"
|
92 |
-
f"{
|
93 |
-
f"
|
|
|
|
|
|
|
|
|
94 |
)
|
95 |
|
96 |
inputs = tokenizer(message, return_tensors="pt", padding=True, truncation=True)
|
@@ -111,70 +125,65 @@ def sentiment_analysis(text):
|
|
111 |
predicted_sentiment = torch.argmax(outputs.logits).item()
|
112 |
return ["Negative", "Neutral", "Positive"][predicted_sentiment]
|
113 |
|
114 |
-
# --- Resume Analysis Function --- #
|
115 |
def analyze_resume(resume_file, job_description_file):
|
116 |
-
"""Analyzes the resume and job description, returning similarity score, skills, and
|
117 |
-
# Extract resume
|
118 |
try:
|
119 |
resume_text = extract_text_from_file(resume_file.name)
|
120 |
job_description_text = extract_text_from_file(job_description_file.name)
|
121 |
except ValueError as ve:
|
122 |
return str(ve)
|
123 |
|
124 |
-
#
|
125 |
-
job_description_skills = process_job_description(job_description_text)
|
126 |
resume_skills = extract_skills_llama(resume_text)
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
sentiment = sentiment_analysis(resume_text)
|
130 |
|
|
|
131 |
return (
|
132 |
-
f"Similarity
|
|
|
|
|
133 |
communication_response,
|
134 |
f"Sentiment: {sentiment}",
|
135 |
-
",
|
136 |
-
",
|
|
|
|
|
|
|
|
|
137 |
)
|
138 |
|
139 |
-
# --- Offer Letter Generation --- #
|
140 |
-
def generate_offer_letter(template_file, candidate_name, role, start_date, hours):
|
141 |
-
"""Generates an offer letter from a template."""
|
142 |
-
try:
|
143 |
-
start_date = datetime.strptime(start_date, "%Y-%m-%d").strftime("%B %d, %Y")
|
144 |
-
except ValueError:
|
145 |
-
return "Invalid date format. Please use YYYY-MM-DD."
|
146 |
-
|
147 |
-
context = {
|
148 |
-
'candidate_name': candidate_name,
|
149 |
-
'role': role,
|
150 |
-
'start_date': start_date,
|
151 |
-
'hours': hours
|
152 |
-
}
|
153 |
-
|
154 |
-
doc = DocxTemplate(template_file)
|
155 |
-
doc.render(context)
|
156 |
-
|
157 |
-
offer_letter_path = f"{candidate_name.replace(' ', '_')}_offer_letter.docx"
|
158 |
-
doc.save(offer_letter_path)
|
159 |
-
|
160 |
-
return offer_letter_path
|
161 |
-
|
162 |
# --- Gradio Interface --- #
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
description="This tool analyzes a resume against a job description to extract skills, calculate similarity, and generate communication responses."
|
178 |
-
)
|
179 |
-
|
180 |
-
iface.launch()
|
|
|
1 |
import os
|
2 |
import re
|
|
|
3 |
from datetime import datetime
|
|
|
4 |
import torch
|
5 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForSeq2SeqLM
|
6 |
+
from sentence_transformers import SentenceTransformer, util
|
7 |
from groq import Groq
|
8 |
import gradio as gr
|
9 |
from docxtpl import DocxTemplate
|
|
|
47 |
except Exception as e:
|
48 |
raise RuntimeError(f"Error during skill extraction: {e}")
|
49 |
|
50 |
+
# --- Qualification and Experience Extraction --- #
|
51 |
+
def extract_qualifications(text):
|
52 |
+
"""Extracts qualifications from text (e.g., degrees, certifications)."""
|
53 |
+
# Simplified logic to extract qualifications (can be improved)
|
54 |
+
qualifications = re.findall(r'(bachelor|master|phd|certified|degree)', text, re.IGNORECASE)
|
55 |
+
return qualifications if qualifications else ['No specific qualifications found']
|
56 |
+
|
57 |
+
def extract_experience(text):
|
58 |
+
"""Extracts years of experience from the text."""
|
59 |
+
experience_years = re.findall(r'(\d+)\s*(years|year) of experience', text, re.IGNORECASE)
|
60 |
+
job_titles = re.findall(r'\b(software engineer|developer|manager|analyst)\b', text, re.IGNORECASE)
|
61 |
+
experience_years = [int(year[0]) for year in experience_years]
|
62 |
+
return experience_years, job_titles
|
63 |
+
|
64 |
+
# --- Matching Function using Semantic Similarity --- #
|
65 |
+
def calculate_semantic_similarity(text1, text2):
|
66 |
+
"""Calculates semantic similarity using a sentence transformer model and returns the score as a percentage."""
|
67 |
+
model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
68 |
+
embeddings1 = model.encode(text1, convert_to_tensor=True)
|
69 |
+
embeddings2 = model.encode(text2, convert_to_tensor=True)
|
70 |
+
similarity_score = util.pytorch_cos_sim(embeddings1, embeddings2).item()
|
71 |
+
|
72 |
+
# Convert similarity score to percentage
|
73 |
+
similarity_percentage = similarity_score * 100
|
74 |
+
return similarity_percentage
|
75 |
+
|
76 |
+
# --- Thresholds --- #
|
77 |
+
def categorize_similarity(score):
|
78 |
+
"""Categorizes the similarity score into thresholds for better insights."""
|
79 |
+
if score >= 80:
|
80 |
+
return "High Match"
|
81 |
+
elif score >= 50:
|
82 |
+
return "Moderate Match"
|
83 |
+
else:
|
84 |
+
return "Low Match"
|
85 |
|
86 |
+
# --- Communication Generation with Enhanced Response --- #
|
87 |
+
def communication_generator(resume_skills, job_description_skills, skills_similarity, qualifications_similarity, experience_similarity, max_length=200):
|
88 |
+
"""Generates a more detailed communication response based on similarity scores."""
|
89 |
model_name = "google/flan-t5-base"
|
90 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
91 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
92 |
|
93 |
+
# Assess candidate fit based on similarity scores
|
94 |
+
fit_status = "strong fit" if skills_similarity >= 80 and qualifications_similarity >= 80 and experience_similarity >= 80 else \
|
95 |
+
"moderate fit" if skills_similarity >= 50 else "weak fit"
|
96 |
+
|
97 |
+
# Create a detailed communication message based on match levels
|
98 |
message = (
|
99 |
+
f"After a detailed analysis of the candidate's resume, we found the following insights:\n\n"
|
100 |
+
f"- **Skills Match**: {skills_similarity:.2f}% ({categorize_similarity(skills_similarity)})\n"
|
101 |
+
f"- **Qualifications Match**: {qualifications_similarity:.2f}% ({categorize_similarity(qualifications_similarity)})\n"
|
102 |
+
f"- **Experience Match**: {experience_similarity:.2f}% ({categorize_similarity(experience_similarity)})\n\n"
|
103 |
+
f"The overall assessment indicates that the candidate is a {fit_status} for the role. "
|
104 |
+
f"Skills such as {', '.join(resume_skills)} align {categorize_similarity(skills_similarity).lower()} with the job's requirements of {', '.join(job_description_skills)}. "
|
105 |
+
f"In terms of qualifications and experience, the candidate shows a {categorize_similarity(qualifications_similarity).lower()} match with the role's needs. "
|
106 |
+
f"Based on these findings, we believe the candidate could potentially excel in the role, "
|
107 |
+
f"but additional evaluation or interviews are recommended for further clarification."
|
108 |
)
|
109 |
|
110 |
inputs = tokenizer(message, return_tensors="pt", padding=True, truncation=True)
|
|
|
125 |
predicted_sentiment = torch.argmax(outputs.logits).item()
|
126 |
return ["Negative", "Neutral", "Positive"][predicted_sentiment]
|
127 |
|
128 |
+
# --- Updated Resume Analysis Function --- #
|
129 |
def analyze_resume(resume_file, job_description_file):
|
130 |
+
"""Analyzes the resume and job description, returning similarity score, skills, qualifications, and experience matching."""
|
131 |
+
# Extract resume and job description text
|
132 |
try:
|
133 |
resume_text = extract_text_from_file(resume_file.name)
|
134 |
job_description_text = extract_text_from_file(job_description_file.name)
|
135 |
except ValueError as ve:
|
136 |
return str(ve)
|
137 |
|
138 |
+
# Extract skills, qualifications, and experience
|
|
|
139 |
resume_skills = extract_skills_llama(resume_text)
|
140 |
+
job_description_skills = process_job_description(job_description_text)
|
141 |
+
resume_qualifications = extract_qualifications(resume_text)
|
142 |
+
job_description_qualifications = extract_qualifications(job_description_text)
|
143 |
+
resume_experience, resume_job_titles = extract_experience(resume_text)
|
144 |
+
job_description_experience, job_description_titles = extract_experience(job_description_text)
|
145 |
+
|
146 |
+
# Calculate semantic similarity for different sections in percentages
|
147 |
+
skills_similarity = calculate_semantic_similarity(' '.join(resume_skills), ' '.join(job_description_skills))
|
148 |
+
qualifications_similarity = calculate_semantic_similarity(' '.join(resume_qualifications), ' '.join(job_description_qualifications))
|
149 |
+
experience_similarity = calculate_semantic_similarity(' '.join([str(e) for e in resume_experience]), ' '.join([str(e) for e in job_description_experience]))
|
150 |
+
|
151 |
+
# Generate a communication response based on the similarity percentages
|
152 |
+
communication_response = communication_generator(
|
153 |
+
resume_skills, job_description_skills,
|
154 |
+
skills_similarity, qualifications_similarity, experience_similarity
|
155 |
+
)
|
156 |
+
|
157 |
+
# Perform Sentiment Analysis
|
158 |
sentiment = sentiment_analysis(resume_text)
|
159 |
|
160 |
+
# Return the results including thresholds and percentage scores
|
161 |
return (
|
162 |
+
f"Skills Similarity: {skills_similarity:.2f}% ({categorize_similarity(skills_similarity)})",
|
163 |
+
f"Qualifications Similarity: {qualifications_similarity:.2f}% ({categorize_similarity(qualifications_similarity)})",
|
164 |
+
f"Experience Similarity: {experience_similarity:.2f}% ({categorize_similarity(experience_similarity)})",
|
165 |
communication_response,
|
166 |
f"Sentiment: {sentiment}",
|
167 |
+
f"Resume Skills: {', '.join(resume_skills)}",
|
168 |
+
f"Job Description Skills: {', '.join(job_description_skills)}",
|
169 |
+
f"Resume Qualifications: {', '.join(resume_qualifications)}",
|
170 |
+
f"Job Description Qualifications: {', '.join(job_description_qualifications)}",
|
171 |
+
f"Resume Experience: {', '.join([f'{y} years' for y, _ in resume_experience])}",
|
172 |
+
f"Job Description Experience: {', '.join([f'{y} years' for y, _ in job_description_experience])}"
|
173 |
)
|
174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
# --- Gradio Interface --- #
|
176 |
+
def process_job_description(job_description_text):
|
177 |
+
"""Simplified job description processing for skills (can be extended)."""
|
178 |
+
return re.findall(r'\b(Python|AWS|Machine Learning|Deep Learning|NLP|Docker|Kubernetes)\b', job_description_text, re.IGNORECASE)
|
179 |
+
|
180 |
+
def gradio_app(resume_file, job_description_file):
|
181 |
+
return analyze_resume(resume_file, job_description_file)
|
182 |
+
|
183 |
+
# --- Launch Gradio App --- #
|
184 |
+
gr.Interface(fn=gradio_app,
|
185 |
+
inputs=["file", "file"],
|
186 |
+
outputs="text",
|
187 |
+
title="Resume and Job Description Matching Tool",
|
188 |
+
description="Upload a resume and a job description to assess the matching scores for skills, qualifications, and experience."
|
189 |
+
).launch()
|
|
|
|
|
|
|
|