-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresume_ner_to_mysql.py
More file actions
405 lines (308 loc) · 10.9 KB
/
Copy pathresume_ner_to_mysql.py
File metadata and controls
405 lines (308 loc) · 10.9 KB
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
#NER model
import os
import re
import csv
import logging
from typing import List, Union
from datetime import datetime
import pdfplumber
import spacy
import mysql.connector
import boto3
from docx import Document
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
BUCKET_NAME = os.getenv("S3_BUCKET_NAME", "resume-input-pdfs")
MYSQL_CONFIG = {
"host": os.getenv("MYSQL_HOST"),
"user": os.getenv("MYSQL_USER"),
"password": os.getenv("MYSQL_PASSWORD"),
"database": os.getenv("MYSQL_DB"),
}
s3 = boto3.client("s3")
nlp = spacy.load("en_core_web_sm")
def read_pdf(path: str) -> str:
text = ""
try:
with pdfplumber.open(path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
except Exception as e:
logger.error(f"PDF read failed: {e}")
return text.strip()
def read_docx(path: str) -> str:
try:
doc = Document(path)
return "\n".join(p.text for p in doc.paragraphs if p.text.strip())
except Exception as e:
logger.error(f"DOCX read failed: {e}")
return ""
def read_txt(path: str) -> str:
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
except Exception as e:
logger.error(f"TXT read failed: {e}")
return ""
def read_any_file(path: str) -> str:
ext = os.path.splitext(path)[1].lower()
if ext == ".pdf":
return read_pdf(path)
if ext == ".docx":
return read_docx(path)
if ext == ".txt":
return read_txt(path)
logger.warning(f"Unknown file type {ext}. Attempting raw text read.")
return read_txt(path)
def extract_email(text):
m = re.search(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
return m.group(0) if m else None
def extract_phone(text):
mobile_indicators = [
r"(?:Mobile|Phone|Contact|Tel|Telephone|mobile:|phone:|contact:|tel:)\s*[:\-]?\s*([+]?[0-9\s\-\(\)]{10,15})",
r"(?:Mobile No|Phone No|Contact No)\s*[:\-]?\s*([+]?[0-9\s\-\(\)]{10,15})",
r"(?:Mobile Number|Phone Number)\s*[:\-]?\s*([+]?[0-9\s\-\(\)]{10,15})"
]
for pattern in mobile_indicators:
match = re.search(pattern, text, re.I)
if match:
phone = match.group(1)
digits = re.sub(r"\D", "", phone)
if len(digits) > 10:
digits = digits[-10:]
if len(digits) == 10 and digits[0] in "6789":
return digits
text_cleaned = re.sub(r"[^\d+]", " ", text)
candidates = re.findall(r"\+?\d{10,13}", text_cleaned)
for c in candidates:
digits = re.sub(r"\D", "", c)
if len(digits) > 10:
digits = digits[-10:]
if len(digits) == 10 and digits[0] in "6789":
return digits
return None
def extract_dob(text):
dob_indicators = [
r"(?:DOB|Date of Birth|Birth Date|Date of birth)[::\s]+(\d{1,2}[/-]\d{1,2}[/-]\d{4})",
r"(?:DOB|Date of Birth|Birth Date|Date of birth)[::\s]+(\d{1,2}\s+[A-Za-z]{3,9},?\s*\d{4})",
r"(?:DOB|Date of Birth|Birth Date|Date of birth)\s+(\d{1,2}[/-]\d{1,2}[/-]\d{4})",
r"(?:DOB|Date of Birth|Birth Date|Date of birth)\s+(\d{1,2}\s+[A-Za-z]{3,9},?\s*\d{4})"
]
for pattern in dob_indicators:
match = re.search(pattern, text, re.I)
if match:
return match.group(1)
general_patterns = [
r"\b\d{1,2}[/-]\d{1,2}[/-]\d{4}\b",
r"\b\d{1,2}\s+[A-Za-z]{3,9},?\s*\d{4}\b",
]
context_patterns = [
r"(?:DOB|Date of Birth|Birth Date|date of birth|birth|DOB:|Date:|Born|Born on)\W*(\d{1,2}[/-]\d{1,2}[/-]\d{4})",
r"(?:DOB|Date of Birth|Birth Date|date of birth|birth|DOB:|Date:|Born|Born on)\W*(\d{1,2}\s+[A-Za-z]{3,9},?\s*\d{4})"
]
for pattern in context_patterns:
match = re.search(pattern, text, re.I)
if match:
return match.group(1)
for pattern in general_patterns:
match = re.search(pattern, text, re.I)
if match:
return match.group(0)
return None
def normalize_dob(dob_raw):
if not dob_raw:
return None
dob_raw = dob_raw.replace('"', '').strip()
dob_raw = re.sub(r"\s+", " ", dob_raw)
formats = [
"%d %B %Y", # 19 November 2004
"%d %b %Y", # 29 Oct 2003
"%d %b, %Y", # 29 Oct, 2003
"%d/%m/%Y",
"%d-%m-%Y"
]
for fmt in formats:
try:
return datetime.strptime(dob_raw, fmt).date().isoformat()
except ValueError:
continue
return None
def extract_gender(text):
gender_indicators = [
r"(?:Gender:|Sex:|Male/Female:|gender:|sex:)\s*(Male|Female|Other|M|F)",
r"(?:Gender|Sex)\s*[:\-]\s*(Male|Female|Other|M|F)",
r"(?:Personal Info|Profile|Basic Info).*?(Male|Female|Other|M|F)"
]
for pattern in gender_indicators:
match = re.search(pattern, text, re.I)
if match:
g = match.group(1).lower()
return "Male" if g in ("m", "male") else "Female" if g in ("f", "female") else "Other"
pattern = r"\b(Male|Female|Other|M|F)\b"
matches = list(re.finditer(pattern, text, re.I))
if matches:
first_match = matches[0]
g = first_match.group(1).lower()
return "Male" if g in ("m", "male") else "Female" if g in ("f", "female") else "Other"
return None
def extract_name(text, email=None):
lines = [l.strip() for l in text.splitlines() if l.strip()]
top = lines[:10] # slightly wider window
ignore = {
"b.tech","m.tech","b.e","m.e","mba","msc","bsc",
"engineering","technology","computer",
"resume","curriculum vitae","cv",
"student","intern","engineer","developer","profile",
"electronics","communication","brief","summary",
"data","scientist","software","manager","director",
"analyst","consultant","architect","lead","senior",
"junior","fresher","experience","years","year",
"company", "organization", "inc", "llc", "ltd"
}
name_indicators = {
"name","full name","candidate name",
"first name","last name","surname","given name"
}
def clean(line):
return re.sub(r"[^A-Za-z.\s]", " ", line).strip()
def looks_like_name(words):
return (
2 <= len(words) <= 4 and
not any(w.lower() in ignore for w in words)
)
# 1. Try explicit name lines
for line in top:
lower = line.lower()
# Check if line contains name indicators and extract the actual name
for key in name_indicators:
if key in lower:
name_part = re.sub(
rf"(?i).*{re.escape(key)}\s*[:\-]*\s*",
"",
line
)
c = clean(name_part)
words = c.split()
if looks_like_name(words):
if c.replace(".", "").isupper():
return c.title()
return c
c = clean(line)
words = c.split()
if looks_like_name(words):
if not any(w.lower() in ignore for w in words):
if c.replace(".", "").isupper():
return c.title()
return c
doc = nlp(" ".join(top))
for ent in doc.ents:
if ent.label_ == "PERSON":
c = clean(ent.text)
words = c.split()
if looks_like_name(words):
if c.replace(".", "").isupper():
return c.title()
return c
if email:
username = email.split("@")[0]
username = re.sub(r"\d+", "", username)
parts = re.split(r"[._]", username)
if 1 < len(parts) <= 3:
return " ".join(p.capitalize() for p in parts)
return None
DEFAULT_DOB = "NA"
def extract_entities(text):
raw_dob = extract_dob(text)
dob = normalize_dob(raw_dob) or DEFAULT_DOB
return {
"name": extract_name(text),
"email": extract_email(text),
"mobile": extract_phone(text),
"dob": dob,
"gender": extract_gender(text) or "Not Specified", # Default value for Gender
}
# --------------------------------------------------
# MYSQL + S3
# --------------------------------------------------
def save_and_fetch_mysql(entity):
conn = mysql.connector.connect(**MYSQL_CONFIG)
cursor = conn.cursor(dictionary=True, buffered=True)
cursor.execute(
"""
INSERT INTO resume_entities (name, email, mobile, dob, gender)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
mobile = VALUES(mobile),
dob = VALUES(dob),
gender = VALUES(gender)
""",
(
entity["name"],
entity["email"],
entity["mobile"],
entity["dob"],
entity["gender"],
),
)
conn.commit()
cursor.execute(
"SELECT * FROM resume_entities WHERE email = %s",
(entity["email"],)
)
row = cursor.fetchone()
cursor.close()
conn.close()
return row
def save_csv_to_s3(row):
filename = f"{row['id']}.csv"
with open(filename, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(
f,
quoting=csv.QUOTE_MINIMAL # 🔑 THIS is mandatory
)
writer.writerow([
row["id"],
row["name"],
row["email"],
row["mobile"],
row["dob"], # "29 Oct, 2003" will be auto-quoted
row["gender"]
])
s3.upload_file(filename, BUCKET_NAME, f"processed/{filename}")
os.remove(filename)
logger.info(f"Uploaded CSV to S3: processed/{filename}")
def run_pipeline(files: Union[str, List[str]]):
if isinstance(files, str):
files = [files]
results = []
for file_path in files:
logger.info(f"Processing: {file_path}")
try:
text = read_any_file(file_path)
if not text or len(text.strip()) < 30:
raise ValueError("No readable text found")
entity = extract_entities(text)
logger.info(f"Extracted: {entity}")
row = save_and_fetch_mysql(entity)
save_csv_to_s3(row)
results.append({
"file": os.path.basename(file_path),
"status": "success",
"data": entity
})
except Exception as e:
logger.error(f"Failed processing {file_path}: {e}")
results.append({
"file": os.path.basename(file_path),
"status": "failed",
"error": str(e)
})
return results