Muhammad Salman Akbar commited on
Commit
bf0e217
1 Parent(s): 055e0f9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +180 -0
app.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
11
+
12
+ # Set your API key for Groq
13
+ os.environ["GROQ_API_KEY"] = "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"
14
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
15
+
16
+ # --- PDF/Text Extraction Functions --- #
17
+ def extract_text_from_file(file_path):
18
+ """Extracts text from PDF or TXT files based on file extension."""
19
+ if file_path.endswith('.pdf'):
20
+ return extract_text_from_pdf(file_path)
21
+ elif file_path.endswith('.txt'):
22
+ return extract_text_from_txt(file_path)
23
+ else:
24
+ raise ValueError("Unsupported file type. Only PDF and TXT files are accepted.")
25
+
26
+ def extract_text_from_pdf(pdf_file_path):
27
+ """Extracts text from a PDF file."""
28
+ with open(pdf_file_path, 'rb') as pdf_file:
29
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
30
+ text = ''.join(page.extract_text() for page in pdf_reader.pages if page.extract_text())
31
+ return text
32
+
33
+ def extract_text_from_txt(txt_file_path):
34
+ """Extracts text from a .txt file."""
35
+ with open(txt_file_path, 'r', encoding='utf-8') as txt_file:
36
+ return txt_file.read()
37
+
38
+ # --- Skill Extraction with Llama Model --- #
39
+ def extract_skills_llama(text):
40
+ """Extracts skills from the text using the Llama model via Groq API."""
41
+ try:
42
+ response = client.chat.completions.create(
43
+ messages=[{"role": "user", "content": f"Extract skills from the following text: {text}"}],
44
+ model="llama3-70b-8192",
45
+ )
46
+ skills = response.choices[0].message.content.split(', ') # Expecting a comma-separated list
47
+ return skills
48
+ except Exception as e:
49
+ raise RuntimeError(f"Error during skill extraction: {e}")
50
+
51
+ # --- Job Description Processing --- #
52
+ def process_job_description(job_description_text):
53
+ """Processes the job description text and extracts relevant skills."""
54
+ job_description_text = preprocess_text(job_description_text)
55
+ return extract_skills_llama(job_description_text)
56
+
57
+ # --- Text Preprocessing --- #
58
+ def preprocess_text(text):
59
+ """Preprocesses text for analysis (lowercase, punctuation removal)."""
60
+ text = text.lower()
61
+ text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
62
+ return re.sub(r'\s+', ' ', text).strip() # Remove extra whitespace
63
+
64
+ # --- Resume Similarity Calculation --- #
65
+ def calculate_resume_similarity(resume_text, job_description_text):
66
+ """Calculates similarity score between resume and job description using a sentence transformer model."""
67
+ model_name = "cross-encoder/stsb-roberta-base"
68
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
69
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
70
+
71
+ inputs = tokenizer(resume_text, job_description_text, return_tensors="pt", padding=True, truncation=True)
72
+ with torch.no_grad():
73
+ outputs = model(**inputs)
74
+ similarity_score = torch.sigmoid(outputs.logits).item()
75
+ return similarity_score
76
+
77
+ # --- Communication Generation --- #
78
+ def communication_generator(resume_skills, job_description_skills, similarity_score, max_length=150):
79
+ """Generates a communication response based on the extracted skills from the resume and job description."""
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 score
85
+ fit_status = "fit for the job" if similarity_score >= 0.7 else "not a fit for the job"
86
+
87
+ # Create a more detailed communication message
88
+ message = (
89
+ f"After a thorough review of the candidate's resume, we found a significant alignment "
90
+ f"between their skills and the job description requirements. The candidate possesses the following "
91
+ f"key skills: {', '.join(resume_skills)}. These align well with the job requirements, particularly in areas such as "
92
+ f"{', '.join(job_description_skills)}. The candidate’s diverse expertise suggests they would make a valuable addition to our team. "
93
+ f"We believe the candidate is {fit_status}. If further evaluation is needed, please let us know how we can assist."
94
+ )
95
+
96
+ inputs = tokenizer(message, return_tensors="pt", padding=True, truncation=True)
97
+ response = model.generate(**inputs, max_length=max_length, num_beams=4, early_stopping=True)
98
+
99
+ return tokenizer.decode(response[0], skip_special_tokens=True)
100
+
101
+ # --- Sentiment Analysis --- #
102
+ def sentiment_analysis(text):
103
+ """Analyzes the sentiment of the text."""
104
+ model_name = "mrm8488/distiluse-base-multilingual-cased-v2-finetuned-stsb_multi_mt-es"
105
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
106
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
107
+
108
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
109
+ with torch.no_grad():
110
+ outputs = model(**inputs)
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 communication response."""
117
+ # Extract resume text based on file type
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
+ # Analyze texts
125
+ job_description_skills = process_job_description(job_description_text)
126
+ resume_skills = extract_skills_llama(resume_text)
127
+ similarity_score = calculate_resume_similarity(resume_text, job_description_text)
128
+ communication_response = communication_generator(resume_skills, job_description_skills, similarity_score)
129
+ sentiment = sentiment_analysis(resume_text)
130
+
131
+ return (
132
+ f"Similarity Score: {similarity_score:.2f}",
133
+ communication_response,
134
+ f"Sentiment: {sentiment}",
135
+ ", ".join(resume_skills),
136
+ ", ".join(job_description_skills),
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
+ iface = gr.Interface(
164
+ fn=analyze_resume,
165
+ inputs=[
166
+ gr.File(label="Upload Resume (PDF/TXT)"),
167
+ gr.File(label="Upload Job Description (PDF/TXT)")
168
+ ],
169
+ outputs=[
170
+ gr.Textbox(label="Similarity Score"),
171
+ gr.Textbox(label="Communication Response"),
172
+ gr.Textbox(label="Sentiment Analysis"),
173
+ gr.Textbox(label="Extracted Resume Skills"),
174
+ gr.Textbox(label="Extracted Job Description Skills"),
175
+ ],
176
+ title="Resume and Job Description Analyzer",
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()