-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
496 lines (427 loc) · 14.7 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# Author: Omkar Pathak
import io
import os
import re
import nltk
import pandas as pd
import docx2txt
from datetime import datetime
from dateutil import relativedelta
from . import constants as cs
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFSyntaxError
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
def extract_text_from_pdf(pdf_path):
'''
Helper function to extract the plain text from .pdf files
:param pdf_path: path to PDF file to be extracted (remote or local)
:return: iterator of string of extracted text
'''
# https://www.blog.pythonlibrary.org/2018/05/03/exporting-data-from-pdfs-with-python/
if not isinstance(pdf_path, io.BytesIO):
# extract text from local pdf file
with open(pdf_path, 'rb') as fh:
try:
for page in PDFPage.get_pages(
fh,
caching=True,
check_extractable=True
):
resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(
resource_manager,
fake_file_handle,
codec='utf-8',
laparams=LAParams()
)
page_interpreter = PDFPageInterpreter(
resource_manager,
converter
)
page_interpreter.process_page(page)
text = fake_file_handle.getvalue()
yield text
# close open handles
converter.close()
fake_file_handle.close()
except PDFSyntaxError:
return
else:
# extract text from remote pdf file
try:
for page in PDFPage.get_pages(
pdf_path,
caching=True,
check_extractable=True
):
resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(
resource_manager,
fake_file_handle,
codec='utf-8',
laparams=LAParams()
)
page_interpreter = PDFPageInterpreter(
resource_manager,
converter
)
page_interpreter.process_page(page)
text = fake_file_handle.getvalue()
yield text
# close open handles
converter.close()
fake_file_handle.close()
except PDFSyntaxError:
return
def get_number_of_pages(file_name):
try:
if isinstance(file_name, io.BytesIO):
# for remote pdf file
count = 0
for page in PDFPage.get_pages(
file_name,
caching=True,
check_extractable=True
):
count += 1
return count
else:
# for local pdf file
if file_name.endswith('.pdf'):
count = 0
with open(file_name, 'rb') as fh:
for page in PDFPage.get_pages(
fh,
caching=True,
check_extractable=True
):
count += 1
return count
else:
return None
except PDFSyntaxError:
return None
def extract_text_from_docx(doc_path):
'''
Helper function to extract plain text from .docx files
:param doc_path: path to .docx file to be extracted
:return: string of extracted text
'''
try:
temp = docx2txt.process(doc_path)
text = [line.replace('\t', ' ') for line in temp.split('\n') if line]
return ' '.join(text)
except KeyError:
return ' '
def extract_text_from_doc(doc_path):
'''
Helper function to extract plain text from .doc files
:param doc_path: path to .doc file to be extracted
:return: string of extracted text
'''
try:
try:
import textract
except ImportError:
return ' '
text = textract.process(doc_path).decode('utf-8')
return text
except KeyError:
return ' '
def extract_text(file_path, extension):
'''
Wrapper function to detect the file extension and call text
extraction function accordingly
:param file_path: path of file of which text is to be extracted
:param extension: extension of file `file_name`
'''
text = ''
if extension == '.pdf':
for page in extract_text_from_pdf(file_path):
text += ' ' + page
elif extension == '.docx':
text = extract_text_from_docx(file_path)
elif extension == '.doc':
text = extract_text_from_doc(file_path)
return text
def extract_entity_sections_grad(text):
'''
Helper function to extract all the raw text from sections of
resume specifically for graduates and undergraduates
:param text: Raw text of resume
:return: dictionary of entities
'''
text_split = [i.strip() for i in text.split('\n')]
# sections_in_resume = [i for i in text_split if i.lower() in sections]
entities = {}
key = False
for phrase in text_split:
if len(phrase) == 1:
p_key = phrase
else:
p_key = set(phrase.lower().split()) & set(cs.RESUME_SECTIONS_GRAD)
try:
p_key = list(p_key)[0]
except IndexError:
pass
if p_key in cs.RESUME_SECTIONS_GRAD:
entities[p_key] = []
key = p_key
elif key and phrase.strip():
entities[key].append(phrase)
# entity_key = False
# for entity in entities.keys():
# sub_entities = {}
# for entry in entities[entity]:
# if u'\u2022' not in entry:
# sub_entities[entry] = []
# entity_key = entry
# elif entity_key:
# sub_entities[entity_key].append(entry)
# entities[entity] = sub_entities
# pprint.pprint(entities)
# make entities that are not found None
# for entity in cs.RESUME_SECTIONS:
# if entity not in entities.keys():
# entities[entity] = None
return entities
def extract_entities_wih_custom_model(custom_nlp_text):
'''
Helper function to extract different entities with custom
trained model using SpaCy's NER
:param custom_nlp_text: object of `spacy.tokens.doc.Doc`
:return: dictionary of entities
'''
entities = {}
for ent in custom_nlp_text.ents:
if ent.label_ not in entities.keys():
entities[ent.label_] = [ent.text]
else:
entities[ent.label_].append(ent.text)
for key in entities.keys():
entities[key] = list(set(entities[key]))
return entities
def get_total_experience(experience_list):
'''
Wrapper function to extract total months of experience from a resume
:param experience_list: list of experience text extracted
:return: total months of experience
'''
exp_ = []
for line in experience_list:
experience = re.search(
r'(?P<fmonth>\w+.\d+)\s*(\D|to)\s*(?P<smonth>\w+.\d+|present)',
line,
re.I
)
if experience:
exp_.append(experience.groups())
total_exp = sum(
[get_number_of_months_from_dates(i[0], i[2]) for i in exp_]
)
total_experience_in_months = total_exp
return total_experience_in_months
def get_number_of_months_from_dates(date1, date2):
'''
Helper function to extract total months of experience from a resume
:param date1: Starting date
:param date2: Ending date
:return: months of experience from date1 to date2
'''
if date2.lower() == 'present':
date2 = datetime.now().strftime('%b %Y')
try:
if len(date1.split()[0]) > 3:
date1 = date1.split()
date1 = date1[0][:3] + ' ' + date1[1]
if len(date2.split()[0]) > 3:
date2 = date2.split()
date2 = date2[0][:3] + ' ' + date2[1]
except IndexError:
return 0
try:
date1 = datetime.strptime(str(date1), '%b %Y')
date2 = datetime.strptime(str(date2), '%b %Y')
months_of_experience = relativedelta.relativedelta(date2, date1)
months_of_experience = (months_of_experience.years
* 12 + months_of_experience.months)
except ValueError:
return 0
return months_of_experience
def extract_entity_sections_professional(text):
'''
Helper function to extract all the raw text from sections of
resume specifically for professionals
:param text: Raw text of resume
:return: dictionary of entities
'''
text_split = [i.strip() for i in text.split('\n')]
entities = {}
key = False
for phrase in text_split:
if len(phrase) == 1:
p_key = phrase
else:
p_key = set(phrase.lower().split()) \
& set(cs.RESUME_SECTIONS_PROFESSIONAL)
try:
p_key = list(p_key)[0]
except IndexError:
pass
if p_key in cs.RESUME_SECTIONS_PROFESSIONAL:
entities[p_key] = []
key = p_key
elif key and phrase.strip():
entities[key].append(phrase)
return entities
def extract_email(text):
'''
Helper function to extract email id from text
:param text: plain text extracted from resume file
'''
email = re.findall(r"([^@|\s]+@[^@]+\.[^@|\s]+)", text)
if email:
try:
return email[0].split()[0].strip(';')
except IndexError:
return None
def extract_name(nlp_text, matcher):
'''
Helper function to extract name from spacy nlp text
:param nlp_text: object of `spacy.tokens.doc.Doc`
:param matcher: object of `spacy.matcher.Matcher`
:return: string of full name
'''
pattern = [cs.NAME_PATTERN]
matcher.add('NAME', None, *pattern)
matches = matcher(nlp_text)
for _, start, end in matches:
span = nlp_text[start:end]
if 'name' not in span.text.lower():
return span.text
def extract_mobile_number(text, custom_regex=None):
'''
Helper function to extract mobile number from text
:param text: plain text extracted from resume file
:return: string of extracted mobile numbers
'''
# Found this complicated regex on :
# https://zapier.com/blog/extract-links-email-phone-regex/
# mob_num_regex = r'''(?:(?:\+?([1-9]|[0-9][0-9]|
# [0-9][0-9][0-9])\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|
# [2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([0-9][1-9]|
# [0-9]1[02-9]|[2-9][02-8]1|
# [2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|
# [2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{7})
# (?:\s*(?:#|x\.?|ext\.?|
# extension)\s*(\d+))?'''
if not custom_regex:
mob_num_regex = r'''(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)
[-\.\s]*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})'''
phone = re.findall(re.compile(mob_num_regex), text)
else:
phone = re.findall(re.compile(custom_regex), text)
if phone:
number = ''.join(phone[0])
return number
def extract_skills(nlp_text, noun_chunks, skills_file=None):
'''
Helper function to extract skills from spacy nlp text
:param nlp_text: object of `spacy.tokens.doc.Doc`
:param noun_chunks: noun chunks extracted from nlp text
:return: list of skills extracted
'''
tokens = [token.text for token in nlp_text if not token.is_stop]
if not skills_file:
data = pd.read_csv(
os.path.join(os.path.dirname(__file__), 'skills.csv')
)
else:
data = pd.read_csv(skills_file)
skills = list(data.columns.values)
skillset = []
# check for one-grams
for token in tokens:
if token.lower() in skills:
skillset.append(token)
# check for bi-grams and tri-grams
for token in noun_chunks:
token = token.text.lower().strip()
if token in skills:
skillset.append(token)
return [i.capitalize() for i in set([i.lower() for i in skillset])]
def cleanup(token, lower=True):
if lower:
token = token.lower()
return token.strip()
def extract_education(nlp_text):
'''
Helper function to extract education from spacy nlp text
:param nlp_text: object of `spacy.tokens.doc.Doc`
:return: tuple of education degree and year if year if found
else only returns education degree
'''
edu = {}
# Extract education degree
try:
for index, text in enumerate(nlp_text):
for tex in text.split():
tex = re.sub(r'[?|$|.|!|,]', r'', tex)
if tex.upper() in cs.EDUCATION and tex not in cs.STOPWORDS:
edu[tex] = text + nlp_text[index + 1]
except IndexError:
pass
# Extract year
education = []
for key in edu.keys():
year = re.search(re.compile(cs.YEAR), edu[key])
if year:
education.append((key, ''.join(year.group(0))))
else:
education.append(key)
return education
def extract_experience(resume_text):
'''
Helper function to extract experience from resume text
:param resume_text: Plain resume text
:return: list of experience
'''
wordnet_lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))
# word tokenization
word_tokens = nltk.word_tokenize(resume_text)
# remove stop words and lemmatize
filtered_sentence = [
w for w in word_tokens if w not
in stop_words and wordnet_lemmatizer.lemmatize(w)
not in stop_words
]
sent = nltk.pos_tag(filtered_sentence)
# parse regex
cp = nltk.RegexpParser('P: {<NNP>+}')
cs = cp.parse(sent)
# for i in cs.subtrees(filter=lambda x: x.label() == 'P'):
# print(i)
test = []
for vp in list(
cs.subtrees(filter=lambda x: x.label() == 'P')
):
test.append(" ".join([
i[0] for i in vp.leaves()
if len(vp.leaves()) >= 2])
)
# Search the word 'experience' in the chunk and
# then print out the text after it
x = [
x[x.lower().index('experience') + 10:]
for i, x in enumerate(test)
if x and 'experience' in x.lower()
]
return x