earlsab commited on
Commit
8fb760e
·
1 Parent(s): b0baff3

Add handler

Browse files
Files changed (4) hide show
  1. .gitignore +2 -0
  2. README.md +3 -0
  3. handler.py +263 -0
  4. requirements.txt +3 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ skill_db_relax_20.json
2
+ token_dist.json
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Model task in handle.py does not segment a job description. \
2
+ It returns the skills found in the requirements section of a job description. \
3
+ This is to make it easier to code for the spaces found in earlsab/beyond-keywords
handler.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline, LongformerTokenizer
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import spacy
7
+ from spacy.matcher import PhraseMatcher
8
+ from transformers import LongformerModel
9
+ from skillNer.general_params import SKILL_DB
10
+ from skillNer.skill_extractor_class import SkillExtractor
11
+
12
+
13
+ Job_num_labels = None
14
+ class EndpointHandler():
15
+ def __init__(self, path=""):
16
+ # Label mapping as provided
17
+ self.Job_label_map = {
18
+ "JT": 0, # Job Title
19
+ "JS": 1, # Job Summary
20
+ "COT": 2, # Title of Company Overview Section
21
+ "COC": 3, # Content of Company Overview Section
22
+ "RT": 4, # Title of Responsibilites Section
23
+ "RC": 5, # Content of Responsibilites Section
24
+ "RQT": 6, # Title of Required Qualifications Section
25
+ "RQC": 7, # Content of Required Qualifications Section
26
+ "PQT": 8, # Title of Preferred Qualifications Section
27
+ "PQC": 9, # Content of Preferred Qualifications Section
28
+ "ET": 10, # Employment Type
29
+ "SBC": 11, # Content of Salary and Benefits Section
30
+ "SBT": 12 # Title of Salary and Benefits Section
31
+ }
32
+ global Job_num_labels
33
+ self.Job_num_labels = len(self.Job_label_map)
34
+ Job_num_labels = self.Job_num_labels
35
+
36
+ self.Job_labels = [
37
+ {"value": "JT", "label": "Job Title"},
38
+ {"value": "JS", "label": "Job Summary"},
39
+ {"value": "COT", "label": "Title of Company Overview Section"},
40
+ {"value": "COC", "label": "Content of Company Overview Section"},
41
+ {"value": "RT", "label": "Title of Responsibilites Section"},
42
+ {"value": "RC", "label": "Content of Responsibilites Section"},
43
+ {"value": "RQT", "label": "Title of Required Qualifications Section"},
44
+ {"value": "RQC", "label": "Content of Required Qualifications Section"},
45
+ {"value": "PQT", "label": "Title of Preferred Qualifications Section"},
46
+ {"value": "PQC", "label": "Content of Preferred Qualifications Section"},
47
+ {"value": "ET", "label": "Employment Type"},
48
+ {"value": "SBC", "label": "Content of Salary and Benefits Section"},
49
+ {"value": "SBT", "label": "Title of Salary and Benefits Section"},
50
+ ]
51
+ # Load tokenizer
52
+ self.Job_tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
53
+ self.Job_tokenizer.cls_token
54
+ # Load model architecture
55
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
56
+ self.Job_model = LongformerSentenceClassifier(num_labels=self.Job_num_labels)
57
+ self.Job_model.to(self.device)
58
+ # Load trained weights
59
+ self.Job_model.load_state_dict(torch.load(path + "/JobSegmentClassifier3rdEpoch_v2.pth", map_location=self.device))
60
+
61
+ # Set model to evaluation mode
62
+ self.Job_model.eval()
63
+
64
+
65
+ nlp = spacy.load("en_core_web_lg")
66
+ self.skill_extractor = SkillExtractor(nlp, SKILL_DB, PhraseMatcher)
67
+
68
+ def predict_job_sections(self, model, text, tokenizer, device):
69
+ model.eval()
70
+
71
+ # Tokenize text and get input tensors
72
+ encoding = tokenizer(
73
+ text,
74
+ return_tensors="pt",
75
+ truncation=True,
76
+ padding="max_length",
77
+ max_length=4096
78
+ )
79
+
80
+ input_ids = encoding["input_ids"].to(device)
81
+ attention_mask = encoding["attention_mask"].to(device)
82
+
83
+ # Identify `[CLS]` positions (assuming each sentence starts with `[CLS]`)
84
+ cls_positions = (input_ids == tokenizer.cls_token_id).nonzero(as_tuple=True)[1]
85
+ cls_positions = cls_positions.unsqueeze(0).to(device) # Shape: (1, num_sentences)
86
+
87
+ # Create global attention mask (Longformer requires at least 1 global attention token)
88
+ global_attention_mask = torch.zeros_like(input_ids)
89
+ global_attention_mask[:, cls_positions] = 1 # Assign global attention to `[CLS]` tokens
90
+
91
+ # Run the model
92
+ with torch.no_grad():
93
+ logits = model(
94
+ input_ids=input_ids,
95
+ attention_mask=attention_mask,
96
+ global_attention_mask=global_attention_mask,
97
+ cls_positions=cls_positions
98
+ ) # Shape: (1, num_sentences, num_labels)
99
+
100
+ logits = logits.squeeze(0) # Shape: (num_sentences, num_labels)
101
+ probs = F.softmax(logits, dim=-1) # Convert logits to probabilities
102
+ predictions = torch.argmax(probs, dim=-1) # Get predicted label indices
103
+
104
+ return predictions.cpu().numpy() # Convert to NumPy array for easy use
105
+
106
+ def extract_job_sections(self, text):
107
+ lines = text.splitlines()
108
+ lines = [line for line in text.splitlines() if line.strip()]
109
+ text = lines
110
+
111
+ concatenated_text = " ".join(f"{self.Job_tokenizer.cls_token} {sentence}" for sentence in text)
112
+ predictions = self.predict_job_sections(self.Job_model, concatenated_text, self.Job_tokenizer, self.device)
113
+
114
+ return predictions, text
115
+
116
+ def extract_job_requirements(self, text):
117
+ lines = text.splitlines()
118
+ lines = [line for line in text.splitlines() if line.strip()]
119
+ text = lines
120
+
121
+ concatenated_text = " ".join(f"{self.Job_tokenizer.cls_token} {sentence}" for sentence in text)
122
+ predictions = self.predict_job_sections(self.Job_model, concatenated_text, self.Job_tokenizer, self.device)
123
+
124
+ requirements = []
125
+ for i, pred in enumerate(predictions):
126
+ if self.Job_labels[pred]['value'] == "RQC":
127
+ requirements.append(lines[i])
128
+
129
+ return requirements
130
+
131
+ def label_job_post(self, text):
132
+ lines = self.extract_job_requirements(text)
133
+ response = {
134
+ "requirements": []
135
+ }
136
+ for item in lines:
137
+ response["requirements"].append(item)
138
+
139
+ response["skills"] = []
140
+ seen = set()
141
+ if response["requirements"]: # Only process if we have requirements
142
+ annotations = self.skill_extractor.annotate(" ".join(response["requirements"]))
143
+ if 'results' in annotations and 'full_matches' in annotations['results']:
144
+ for result in annotations['results']['full_matches']:
145
+ # Standardizing the skill names
146
+ skill_info = SKILL_DB.get(result["skill_id"], {})
147
+ skill_name = skill_info.get('skill_name', 'Unknown Skill')
148
+ if skill_name not in seen:
149
+ seen.add(skill_name)
150
+ response["skills"].append({'name': skill_name, 'skill_id': result["skill_id"]})
151
+ if 'results' in annotations and 'ngram_scored' in annotations['results']:
152
+ for result in annotations['results']['ngram_scored']:
153
+ if result['score'] >= 1:
154
+ # Standardizing the skill names
155
+ skill_info = SKILL_DB.get(result["skill_id"], {})
156
+ skill_name = skill_info.get('skill_name', 'Unknown Skill')
157
+ if skill_name not in seen:
158
+ seen.add(skill_name)
159
+ response["skills"].append({'name': skill_name, 'skill_id': result["skill_id"]})
160
+ return response
161
+
162
+
163
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
164
+ """
165
+ data args:
166
+ inputs (:obj: `str` | `PIL.Image` | `np.array`)
167
+ kwargs
168
+ Return:
169
+ A :obj:`list` | `dict`: will be serialized and returned
170
+ """
171
+ text = data['inputs']
172
+ # predictions, text = self.extract_job_sections(text)
173
+ # requirements = self.extract_job_requirements(text)
174
+ label_job_post = self.label_job_post(text)
175
+ return label_job_post
176
+
177
+ class LongformerSentenceClassifier(nn.Module):
178
+ def __init__(self, model_name="allenai/longformer-base-4096", num_labels=Job_num_labels):
179
+ """
180
+ Custom Longformer model for sentence classification.
181
+
182
+ Args:
183
+ model_name (str): Hugging Face Longformer model.
184
+ num_labels (int): Number of possible sentence labels.
185
+ """
186
+ super(LongformerSentenceClassifier, self).__init__()
187
+ self.longformer = LongformerModel.from_pretrained(model_name)
188
+ self.classifier = nn.Linear(self.longformer.config.hidden_size, num_labels)
189
+
190
+ def forward(self, input_ids, attention_mask, global_attention_mask, cls_positions):
191
+ """
192
+ Forward pass for sentence classification.
193
+
194
+ Args:
195
+ input_ids (Tensor): Tokenized input IDs, shape (batch_size, max_length)
196
+ attention_mask (Tensor): Attention mask, shape (batch_size, max_length)
197
+ global_attention_mask (Tensor): Global attention mask, shape (batch_size, max_length)
198
+ cls_positions (List[Tensor]): Indices of `[CLS]` tokens for each batch element.
199
+ """
200
+ outputs = self.longformer(
201
+ input_ids=input_ids,
202
+ attention_mask=attention_mask,
203
+ global_attention_mask=global_attention_mask
204
+ )
205
+
206
+ last_hidden_state = outputs.last_hidden_state
207
+ cls_positions = cls_positions.view(input_ids.shape[0], -1)
208
+ cls_embeddings = last_hidden_state.gather(1, cls_positions.unsqueeze(-1).expand(-1, -1, last_hidden_state.size(-1)))
209
+ logits = self.classifier(cls_embeddings)
210
+
211
+ return logits
212
+
213
+
214
+ if __name__ == "__main__":
215
+ # init handler
216
+ my_handler = EndpointHandler(path=".")
217
+
218
+ # prepare sample payload
219
+ payload = {"inputs": """
220
+ About the job
221
+ Job Title: Frontend Developer
222
+ Job Type: Full-time or Part-Time
223
+ Location: Remote
224
+
225
+ About Us:
226
+ Our mission at micro1 is to match the most talented people in the world with their dream jobs. If you are looking to be at the forefront of AI innovation and work with some of the fastest growing companies in Silicon Valley, we invite you to apply for a role. By joining the micro1 community, your resume will become visible to top industry leaders, unlocking access to the best career opportunities on the market.
227
+
228
+ Job Summary:
229
+ Join our dynamic team at micro1 as a Frontend Developer where you will be instrumental in creating engaging and dynamic user experiences for web applications. At micro1, we provide opportunities to work with leading companies in Silicon Valley, ensuring a stable and competitive income in a flexible remote setting. Embrace the opportunity to grow your career, access top industry opportunities, and enjoy a range of great benefits.
230
+
231
+ Key Responsibilities:
232
+ Develop high-quality frontend components for web applications.
233
+ Optimize user interfaces to enhance user experiences.
234
+ Collaborate with cross-functional teams to define and design new features.
235
+ Ensure cross-browser compatibility and implement responsive designs.
236
+ Maintain code quality and ensure responsiveness of applications.
237
+ Utilize industry best practices and design patterns.
238
+ Participate in code reviews to maintain high code quality standards.
239
+
240
+ Required Skills and Qualifications:
241
+ Proficiency in HTML, CSS, and JavaScript.
242
+ Strong experience with React and Angular frameworks.
243
+ Excellent written and verbal communication skills.
244
+ Ability to work effectively in a remote setting.
245
+ Demonstrated ability to develop and optimize user interfaces.
246
+ Experience with ensuring cross-browser compatibility of applications.
247
+ Strong problem-solving skills and attention to detail.
248
+
249
+ Preferred Qualifications:
250
+ Experience with responsive design and mobile-first development.
251
+ Familiarity with version control systems, such as Git.
252
+ Understanding of Agile methodologies.
253
+ It's okay if you don't. Having a Native to C2/C1 level in another language such as German, French, or Spanish is nice to have.
254
+ """}
255
+ # holiday_payload = {"inputs": "Today is a though day"}
256
+
257
+ # test the handler
258
+ non_holiday_pred=my_handler(payload)
259
+ # holiday_payload=my_handler(holiday_payload)
260
+
261
+ # show results
262
+ print(non_holiday_pred)
263
+ # print("holiday_payload", holiday_payload)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ skillNer>=1.0.0
2
+ spacy>=3.7.2
3
+ en-core-web-lg @ https://github.com/explosion/spacy-models/releases/download/en_core_web_lg-3.7.0/en_core_web_lg-3.7.0-py3-none-any.whl