Spaces:
Running on Zero
Running on Zero
fix(semantics): add semantic disambiguation between candidate name and job title, preventing role names from being extracted as person names
Browse filesFiles changed (3)
186 unmodified lines1871881891901911923 unmodified lines196197198199200201202203204205186 unmodified lines"""Heuristic name extraction from the header of the resume."""fixed_text = ftfy.fix_text(text)lines = [line.strip() for line in fixed_text.splitlines() if line.strip()]for line in lines[:8]:line = re.sub(r"^['\"]+|['\"]+$", "", line).strip()# Filter out lines that look like emails, URLs, phones, or section headings3 unmodified linescontinueif re.search(r"\b(objective|summary|resume|curriculum|vitae|contact)\b", line, re.I):continue# Must contain letters, mostly alphabeticwords = line.split()if 1 <= len(words) <= 4 and all(re.match(r"^[a-zA-Z\.]+$", w) for w in words):return line.title()return "Unknown"def extract_contact(self, text: str) -> Tuple[Optional[str], Optional[str]]:186 unmodified lines1871881891901911921931941951961971983 unmodified lines202203204205206207208209210211212213214215216217186 unmodified lines"""Heuristic name extraction from the header of the resume."""fixed_text = ftfy.fix_text(text)lines = [line.strip() for line in fixed_text.splitlines() if line.strip()]title_keywords = {"developer", "engineer", "architect", "manager", "lead", "consultant","analyst", "specialist", "administrator", "scientist", "intern", "internship","backend", "frontend", "fullstack", "full-stack", "devops", "designer","programmer", "officer", "director", "head", "expert", "tester", "qa"}for line in lines[:8]:line = re.sub(r"^['\"]+|['\"]+$", "", line).strip()# Filter out lines that look like emails, URLs, phones, or section headings3 unmodified linescontinueif re.search(r"\b(objective|summary|resume|curriculum|vitae|contact)\b", line, re.I):continue# Handle lines with multiple components separated by tabs, multiple spaces, or pipes# e.g. "Java Backend Developer Shashi Bawa"subparts = [p.strip() for p in re.split(r"\s{2,}|\t+|\|", line) if p.strip()]for part in subparts:words = part.split()if 1 <= len(words) <= 4 and all(re.match(r"^[a-zA-Z\.\'-]+$", w) for w in words):# Reject if component contains job title wordsif any(w.lower() in title_keywords for w in words):continuereturn part.title()return "Unknown"def extract_contact(self, text: str) -> Tuple[Optional[str], Optional[str]]:
259 unmodified lines260261262263264265208 unmodified lines47447547647747847912 unmodified lines49249349449549649720 unmodified lines518519520521522523259 unmodified linesreturn cleaneddef map_degree_tier(degree_name: Optional[str]) -> DegreeTier:"""Classifies a raw degree string into a canonical degree tier:208 unmodified linesdef post_process_resume(raw_input: Union[RawResumeExtraction, Dict[str, Any]],reference_date: Optional[datetime] = None,) -> ProcessedResume:"""Deterministic post-processing pipeline for resume extraction.12 unmodified lines# Coerce dict to RawResumeExtraction modelif isinstance(raw_input, dict):raw = RawResumeExtraction.model_validate(raw_input)else:raw = raw_input20 unmodified lines# 4. Job Titlejob_title = clean_title(raw.job_title)# 5. Work Experience & Date Mathprocessed_experience: List[WorkExperienceItem] = []full_time_intervals: List[Tuple[datetime, datetime]] = []259 unmodified lines260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329208 unmodified lines53853954054154254354412 unmodified lines55755855956056156256320 unmodified lines584585586587588589590591592593594595596597598599600601602603604259 unmodified linesreturn cleanedTITLE_ROLE_KEYWORDS = {"developer", "engineer", "architect", "manager", "lead", "consultant","analyst", "specialist", "administrator", "scientist", "intern", "internship","backend", "frontend", "fullstack", "full-stack", "devops", "designer","programmer", "officer", "director", "head", "expert", "tester", "qa","practitioner", "technician", "instructor", "researcher", "coordinator","executive", "president", "vp", "trainee", "associate"}def is_title_not_name(name_str: Optional[str]) -> bool:"""Detects if an extracted candidate name is actually a job title (e.g. 'Java Backend Developer')."""if not name_str:return Falsewords = re.findall(r"[a-zA-Z]+", name_str.lower())return any(w in TITLE_ROLE_KEYWORDS for w in words)def recover_name_and_title_from_text(resume_text: str, email: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:"""Recovers candidate name and title from raw resume header lines,especially when formatted as 'Title Name' (e.g. 'Java Backend Developer Shashi Bawa')."""if not resume_text:return None, Nonelines = [line.strip() for line in resume_text.splitlines() if line.strip()][:10]cand_name = Nonejob_title = None# Check for split lines with multiple componentsfor line in lines:parts = [p.strip() for p in re.split(r"\s{2,}|\t+|\|", line) if p.strip()]if len(parts) >= 2:for part in parts:if is_title_not_name(part):if not job_title:job_title = partelse:words = part.split()if 1 <= len(words) <= 4 and all(re.match(r"^[a-zA-Z\.\'-]+$", w) for w in words):if not cand_name:cand_name = part.title()if cand_name:break# If cand_name still not found, check lines against email usernameif not cand_name and email:email_user = email.split("@")[0].lower()email_clean = re.sub(r"[0-9_\.\-]+", "", email_user)for line in lines:if not is_title_not_name(line) and "@" not in line and "http" not in line and "cell" not in line.lower():words = [w for w in line.split() if re.match(r"^[a-zA-Z]+$", w)]if 2 <= len(words) <= 4:combined = "".join(words).lower()if combined in email_clean or email_clean in combined:cand_name = " ".join(words).title()breakreturn cand_name, job_titledef map_degree_tier(degree_name: Optional[str]) -> DegreeTier:"""Classifies a raw degree string into a canonical degree tier:208 unmodified linesdef post_process_resume(raw_input: Union[RawResumeExtraction, Dict[str, Any]],reference_date: Optional[datetime] = None,raw_text: Optional[str] = None,) -> ProcessedResume:"""Deterministic post-processing pipeline for resume extraction.12 unmodified lines# Coerce dict to RawResumeExtraction modelif isinstance(raw_input, dict):raw_text = raw_text or raw_input.get("resumeText") or raw_input.get("rawText")raw = RawResumeExtraction.model_validate(raw_input)else:raw = raw_input20 unmodified lines# 4. Job Titlejob_title = clean_title(raw.job_title)# Semantic Disambiguation: Detect if cand_name is actually a job title (e.g. 'Java Backend Developer')if cand_name and is_title_not_name(cand_name):misplaced_title = cand_namecand_name = Noneif not job_title or job_title in ("Role not identified", "Unknown"):job_title = clean_title(misplaced_title)# If cand_name is missing, recover from raw_text using header lines and email prefixif not cand_name and raw_text:rec_name, rec_title = recover_name_and_title_from_text(raw_text, email=email)if rec_name:cand_name = rec_nameif rec_title and (not job_title or job_title in ("Role not identified", "Unknown")):job_title = clean_title(rec_title)# 5. Work Experience & Date Mathprocessed_experience: List[WorkExperienceItem] = []full_time_intervals: List[Tuple[datetime, datetime]] = []
26 unmodified lines2728293031323326 unmodified lines' "projects": ["Project Name: Description"]\n'"}\n""IMPORTANT RULES:\n""- 'jobTitle': Extract ONLY the professional title (e.g. 'Generative AI Intern' or 'Software Engineer'). DO NOT include company names, pipe characters ('|'), locations, or modalities like '(On-site Intern)'.\n""- 'education', 'workExperience', and 'projects' MUST be arrays/lists of objects, NEVER dictionary mappings.\n""- Return ONLY raw minified JSON. Do not include markdown codeblocks (no ```json), explanations, or preambles.")26 unmodified lines27282930313233343526 unmodified lines' "projects": ["Project Name: Description"]\n'"}\n""IMPORTANT RULES:\n""- 'candidateName': Extract the person's actual human name (e.g. 'Shashi Bawa'). NEVER extract job titles, roles, or banners (e.g. 'Java Backend Developer' is a job title, NOT a name).\n""- 'jobTitle': Extract ONLY the professional title (e.g. 'Java Backend Developer' or 'Generative AI Intern'). DO NOT include company names, pipe characters ('|'), locations, or modalities like '(On-site Intern)'.\n""- When a header line contains both a job title and a candidate name (e.g. 'Java Backend Developer Shashi Bawa'): candidateName MUST be 'Shashi Bawa' and jobTitle MUST be 'Java Backend Developer'.\n""- 'education', 'workExperience', and 'projects' MUST be arrays/lists of objects, NEVER dictionary mappings.\n""- Return ONLY raw minified JSON. Do not include markdown codeblocks (no ```json), explanations, or preambles.")
app/services/nlp_extractor.py+16-4
app/services/post_processor.py+81
app/services/prompt_templates.py+3-1