Spaces:
Paused
Paused
Update resume_parser.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""app.py======Smart Recruiter β Resume ParserHuggingFace Space DeploymentRuns with: uvicorn app:app --host 0.0.0.0 --port 7860 --workers 1"""import jsonimport loggingimport osimport refrom contextlib import asynccontextmanagerimport torchfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import JSONResponsefrom peft import PeftModelfrom pydantic import BaseModelfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfiglogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(message)s",)logger = logging.getLogger(__name__)# ---------------------------------------------------------------------------# Config# ---------------------------------------------------------------------------ADAPTER_REPO = "DarkSting/resume_parser"BASE_MODEL = "google/gemma-4-E2B-it"MAX_NEW_TOKENS = 800SYSTEM_PROMPT = """You are an expert resume parser. Extract structured information from resume text and return ONLY valid JSON with no extra text, no markdown, no explanation.Always follow this exact schema. Use null for missing fields and [] for missing lists:{"name": "Full Name or null","email": "email@example.com or null","phone": "phone number or null","skills": ["skill1", "skill2"],"programming_languages": ["Python", "JavaScript"],"experience": [{"job_title": "Job Title","company": "Company Name","start_date": "MM/YYYY or MM/DD/YYYY or null","end_date": "MM/YYYY or MM/DD/YYYY or Present or null","responsibilities": ["responsibility1", "responsibility2"]}],"total_experience_years": 0.0,"education": [{"degree": "Degree Name","field": "Field of Study or null","institution": "Institution Name or null","year": 2020}],"certifications": ["cert1", "cert2"],"projects": ["Project Name 1", "Project Name 2"],"publications": ["publication1"],"achievements": ["achievement1"],"summary": "Brief professional summary or null"}"""# ---------------------------------------------------------------------------# Global model state# ---------------------------------------------------------------------------model = Nonetokenizer = Noneload_error = None# ---------------------------------------------------------------------------# Model loading# ---------------------------------------------------------------------------def load_model():global model, tokenizer, load_errorlogger.info("Loading base model: %s", BASE_MODEL)logger.info("Loading adapter : %s", ADAPTER_REPO)try:if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8:torch_dtype = torch.bfloat16else:torch_dtype = torch.float16model_kwargs = dict(dtype=torch_dtype,device_map="auto",)model_kwargs["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch_dtype,bnb_4bit_quant_storage=torch_dtype,)logger.info("Loading base model ...")base_model = AutoModelForCausalLM.from_pretrained(BASE_MODEL, **model_kwargs)logger.info("Loading LoRA adapter ...")model = PeftModel.from_pretrained(base_model, ADAPTER_REPO)model.eval()tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)logger.info("Model ready on device: %s", model.device)except Exception as e:load_error = str(e)logger.exception("Failed to load model: %s", e)# ---------------------------------------------------------------------------# Lifespan β load model once at startup# ---------------------------------------------------------------------------@asynccontextmanagerasync def lifespan(app: FastAPI):load_model()yield# ---------------------------------------------------------------------------# FastAPI app# ---------------------------------------------------------------------------app = FastAPI(title="Smart Recruiter β Resume Parser",description="Fine-tuned Gemma-4-E2B-it resume parser. POST raw resume text, get structured JSON.",version="1.0.0",lifespan=lifespan,)# ---------------------------------------------------------------------------# Schemas# ---------------------------------------------------------------------------class AnalyzeRequest(BaseModel):content: str# ---------------------------------------------------------------------------# Inference# ---------------------------------------------------------------------------def parse_resume(resume_text: str) -> dict:messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user","content": (f"Parse this resume and return ONLY a JSON object:\n\n"f"RESUME:\n{resume_text[:3000]}\n\n"f"Return ONLY the JSON object, nothing else."),},]text = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True,)inputs = tokenizer(text=text, return_tensors="pt").to(model.device)with torch.no_grad():output = model.generate(**inputs,max_new_tokens=MAX_NEW_TOKENS,do_sample=False,temperature=None,top_p=None,repetition_penalty=1.1,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id,)generated = output[0][inputs["input_ids"].shape[1]:]response = tokenizer.decode(generated, skip_special_tokens=True).strip()response = re.sub(r"^```json\s*", "", response)response = re.sub(r"```$", "", response).strip()try:return json.loads(response)except json.JSONDecodeError:match = re.search(r"\{[\s\S]*\}", response)if match:return json.loads(match.group())raise ValueError(f"Model output was not valid JSON:\n{response[:300]}")# ---------------------------------------------------------------------------# Routes# ---------------------------------------------------------------------------@app.get("/health")def health():return {"status": "ready" if model else "degraded","model_loaded": model is not None,"base_model": BASE_MODEL,"adapter_repo": ADAPTER_REPO,"load_error": load_error,"device": str(model.device) if model else None,}@app.post("/analyze")def analyze(request: AnalyzeRequest):if model is None:raise HTTPException(status_code=503,detail=f"Model not loaded. Check /health. Error: {load_error}",)content = request.content.strip()if not content:raise HTTPException(status_code=400,detail="'content' field is empty. Send raw resume text.",)logger.info("Parsing resume (%d chars) ...", len(content))try:result = parse_resume(content)logger.info("Parse successful. Skills: %s", result.get("skills", []))return JSONResponse(content=result)except ValueError as e:raise HTTPException(status_code=500, detail=str(e))except Exception as e:logger.exception("Inference error: %s", e)raise HTTPException(status_code=500, detail=f"Inference failed: {str(e)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759"""resume_parser.py================Component 1 β Resume Parser ClientSmart Recruiter APIFlow:PDF bytes βββΊ extract text locallyβ ATS-friendly PDF β pdfplumber (text layer)β Scanned/image PDF β pytesseract OCR (auto fallback)β Clean & normalise textββΌPOST multipart {"content": "<resume text>", "resume": <pdf bytes>}βHuggingFace endpoint (local model + ChatGPT verification pass)https://SapunMendis-Resume-Parser.hf.space/analyzeββΌstructured resume JSON βββΊ ScoringEngineNote: ChatGPT verification/correction now happens server-side (in the HFSpace's app.py + chatgpt_verifier.py), not in this client. This client'sonly job is to extract text locally, send both the text AND the originalPDF bytes to the HF endpoint, and normalise whatever comes back."""import ioimport reimport loggingimport requeststry:import pdfplumberPDFPLUMBER_AVAILABLE = Trueexcept ImportError:PDFPLUMBER_AVAILABLE = Falsetry:from pdf2image import convert_from_bytesimport pytesseractOCR_AVAILABLE = Trueexcept ImportError:OCR_AVAILABLE = Falselogger = logging.getLogger(__name__)HF_ENDPOINT = "https://SapunMendis-Resume-Parser.hf.space/analyze"REQUEST_TIMEOUT = (10, 300) # seconds β HF cold starts can be slowclass ResumeParserClient:"""Thin client around the HuggingFace resume-parsing endpoint.The PDF text is extracted locally, then BOTH the plain text and theoriginal PDF bytes are POSTed (multipart/form-data) to the HFendpoint, which runs the local model + a ChatGPT verification passserver-side and returns the final corrected JSON.If parsing fails for any reason, a graceful fallback with emptyfields is returned so the rest of the pipeline can still run."""def __init__(self, endpoint: str = HF_ENDPOINT, timeout: int = REQUEST_TIMEOUT):self.endpoint = endpointself.timeout = timeout# ------------------------------------------------------------------# Public# ------------------------------------------------------------------def parse_from_file(self, pdf_bytes: bytes) -> dict:"""Extract text from PDF bytes, then send BOTH the text and the rawPDF bytes to the HF endpoint (which handles model parsing +ChatGPT verification internally).Parameters----------pdf_bytes : bytes Raw PDF content from multipart uploadReturns-------dict Structured resume data ready for ScoringEngine"""logger.info("[ResumeParser] Extracting text from PDF β¦")text = self._extract_pdf_text(pdf_bytes)if not text.strip():logger.warning("[ResumeParser] PDF text extraction produced empty result.")return self._fallback(error="empty_pdf_text")logger.info("[ResumeParser] Extracted %d characters from PDF.", len(text))return self._call_hf(text, resume_text=text, pdf_bytes=pdf_bytes)def parse_from_text(self, text: str) -> dict:"""Send pre-extracted resume text to the HF endpoint (no PDFavailable in this path β server-side verification falls back totext-only mode automatically).Parameters----------text : str Plain-text resume contentReturns-------dict Structured resume data"""if not text.strip():return self._fallback(error="empty_text_input")return self._call_hf(text, resume_text=text, pdf_bytes=None)# ------------------------------------------------------------------# PDF extraction# ------------------------------------------------------------------def _extract_pdf_text(self, pdf_bytes: bytes) -> str:"""Extract text from PDF bytes.Strategy (auto-detected):1. pdfplumber β for normal/ATS-friendly PDFs with a text layer2. pytesseract β OCR fallback for scanned / image-based PDFsReturns cleaned plain text, or empty string on failure.Install dependencies:pip install pdfplumber pdf2image pytesseract pillow# Linux / Colab:sudo apt-get install -y tesseract-ocr poppler-utils"""if not PDFPLUMBER_AVAILABLE:logger.error("[ResumeParser] pdfplumber not installed. Run: pip install pdfplumber")return ""try:if self._has_text_layer(pdf_bytes):logger.info("[ResumeParser] Text layer detected β using pdfplumber.")raw_text = self._extract_with_pdfplumber(pdf_bytes)else:logger.info("[ResumeParser] No text layer β falling back to OCR.")raw_text = self._extract_with_ocr(pdf_bytes)return self._clean_text(raw_text)except Exception as e:logger.error("[ResumeParser] PDF extraction error: %s", e)return ""def _has_text_layer(self, pdf_bytes: bytes, min_chars_per_page: int = 50) -> bool:"""Returns True if the PDF has a usable text layer (ATS-friendly),False if it is scanned / image-based and needs OCR."""with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:total_chars = sum(len((p.extract_text() or "").strip()) for p in pdf.pages)avg_chars = total_chars / max(len(pdf.pages), 1)return avg_chars >= min_chars_per_pagedef _extract_with_pdfplumber(self, pdf_bytes: bytes) -> str:"""Extract text from a text-layer PDF using pdfplumber."""pages = []with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:for page in pdf.pages:text = page.extract_text(x_tolerance=2, y_tolerance=2)if text:pages.append(text.strip())return "\n\n".join(pages)def _extract_with_ocr(self, pdf_bytes: bytes, dpi: int = 300) -> str:"""Extract text from a scanned PDF using pytesseract OCR."""if not OCR_AVAILABLE:logger.error("[ResumeParser] OCR dependencies missing. ""Run: pip install pdf2image pytesseract ""and: sudo apt-get install -y tesseract-ocr poppler-utils")return ""images = convert_from_bytes(pdf_bytes, dpi=dpi)pages = []for image in images:text = pytesseract.image_to_string(image, config="--psm 6 --oem 3")if text.strip():pages.append(text.strip())return "\n\n".join(pages)@staticmethoddef _clean_text(text: str) -> str:"""Normalise unicode characters, remove OCR noise, collapseexcessive whitespace β so the model receives clean input.Also fixes common pdfplumber issues with merged words andsection headers that lose their spaces:"ITINFRASTRUCTURE" β "IT INFRASTRUCTURE""EDUCATION&CERTIFICATIONS" β "EDUCATION & CERTIFICATIONS""PROFESSIONALEXPERIENCE" β "PROFESSIONAL EXPERIENCE""""if not text:return ""# Normalise unicode punctuationtext = text.replace("\u2013", "-").replace("\u2014", "-") # em/en dashtext = text.replace("\u2018", "'").replace("\u2019", "'") # curly quotestext = text.replace("\u201c", '"').replace("\u201d", '"')text = text.replace("\u2022", "-").replace("\u25cf", "-") # bulletstext = text.replace("\u00a0", " ") # non-breaking space# Fix "&" merged into ALL-CAPS section headers:# "EDUCATION&CERTIFICATIONS" β "EDUCATION & CERTIFICATIONS"text = re.sub(r'([A-Z])&([A-Z])', r'\1 & \2', text)# Fix merged CamelCase/TitleCase word boundaries:# "TechnicalManager" β "Technical Manager"text = re.sub(r'([A-Z]{2,})([A-Z][a-z])', r'\1 \2', text)# Fix known fully-uppercase merged section headers_SECTION_FIXES = {'PROFESSIONALEXPERIENCE': 'PROFESSIONAL EXPERIENCE','WORKEXPERIENCE': 'WORK EXPERIENCE','SELECTACHIEVEMENTS': 'SELECT ACHIEVEMENTS','KEYACHIEVEMENTS': 'KEY ACHIEVEMENTS','ITINFRASTRUCTURE': 'IT INFRASTRUCTURE','TECHNICALSKILLS': 'TECHNICAL SKILLS','KEYSKILLS': 'KEY SKILLS','CORECOMPETENCIES': 'CORE COMPETENCIES','CAREERHISTORY': 'CAREER HISTORY','CAREEROBJECTIVE': 'CAREER OBJECTIVE','STATEUNIVERSITY': 'STATE UNIVERSITY',}for merged, fixed in _SECTION_FIXES.items():text = text.replace(merged, fixed)# Remove non-printable characters (OCR artifacts)text = re.sub(r'[^\x20-\x7E\n]', ' ', text)# Remove repeated separator lines (e.g. "------", "......")text = re.sub(r'[.\-_=]{4,}', ' ', text)# Collapse multiple spaces/tabs into onetext = re.sub(r'[ \t]+', ' ', text)# Collapse more than 2 consecutive blank linestext = re.sub(r'\n{3,}', '\n\n', text)# Strip leading/trailing whitespace per linelines = [line.strip() for line in text.splitlines()]return "\n".join(lines).strip()# ------------------------------------------------------------------# HuggingFace API call# ------------------------------------------------------------------def _call_hf(self, text: str, resume_text: str = "", pdf_bytes: bytes = None) -> dict:"""POST the resume text (and, when available, the original PDFbytes) to the HuggingFace endpoint.The HF Space runs the local model AND the ChatGPT verificationpass server-side, so whatever JSON comes back is already final.Sends multipart/form-data:content : "<resume text>" (always)resume : <pdf bytes> (only when available)Expects back: structured resume JSON (already verified server-side)"""logger.info("[ResumeParser] Calling HuggingFace endpoint (pdf=%s) β¦", pdf_bytes is not None)try:files = Noneif pdf_bytes:files = {"resume": ("resume.pdf", pdf_bytes, "application/pdf")}resp = requests.post(self.endpoint,data={"content": text},files=files,timeout=self.timeout,)resp.raise_for_status()raw = resp.json()logger.info("[ResumeParser] HF parse successful. parser_source=%s", raw.get("parser_source"))return self._normalise(raw, resume_text=resume_text)except requests.exceptions.Timeout:logger.error("[ResumeParser] Request timed out after %ds.", self.timeout)return self._fallback(error="timeout")except requests.exceptions.HTTPError as e:logger.error("[ResumeParser] HTTP error: %s", e)return self._fallback(error=str(e))except Exception as e:logger.error("[ResumeParser] Unexpected error: %s", e)return self._fallback(error=str(e))# ------------------------------------------------------------------# Private helpers# ------------------------------------------------------------------def _normalise(self, raw: dict, resume_text: str = "") -> dict:"""Normalise the HuggingFace model output into the schema expectedby ScoringEngine._score_resume().For any field the model omits (name, education, projects),post-processing regex fallbacks extract the value directlyfrom the raw resume text."""experience_list = raw.get("experience") or []# ββ Model outputs ββββββββββββββββββββββββββββββββββββββββββββββββname = (raw.get("name") or raw.get("candidate_name")or raw.get("full_name") or "")education = raw.get("education") or []projects = self._to_list(raw.get("projects") or raw.get("project_titles") or [])certifications = self._to_list(raw.get("certifications") or [])# ββ Post-processing fallbacks (only when model missed the field) βif resume_text:if not name:name = self._fallback_extract_name(resume_text)if not education:education = self._fallback_extract_education(resume_text)if not projects:projects = self._fallback_extract_projects(resume_text)return {"name": name,"skills": self._to_list(raw.get("skills") orraw.get("technical_skills") or []),"programming_languages": self._to_list(raw.get("programming_languages") or []),"total_experience_years": self._calc_experience_years(experience_list),"experience": experience_list,"education": education,"certifications": certifications,"projects": projects,"publications": self._to_list(raw.get("publications") or []),"achievements": self._to_list(raw.get("achievements") or []),"parser_source": raw.get("parser_source", "huggingface"),"raw_parser_response": raw,}# ------------------------------------------------------------------# Post-processing fallback extractors# ------------------------------------------------------------------@staticmethoddef _fallback_extract_name(text: str) -> str:"""Extract candidate name from the first line of the resume.Handles all-caps, title case, and names with credentials.e.g. "KARAN PRATAP SINGH" β "Karan Pratap Singh""PRIYA SILVA, B.Eng" β "Priya Silva""Maria A. Garcia" β "Maria A. Garcia""""first_line = text.strip().splitlines()[0].strip()lines = [l.strip() for l in text.strip().splitlines() if l.strip()]def clean_name_candidate(raw):# Strip after pipe, comma, email, phone or credential suffixesraw = re.split(r'[|,]', raw)[0].strip()# Remove trailing credentials like "M.ENG.", "PhD", "MBA"raw = re.sub(r'\s*[,\|]\s*.*$', '', raw).strip()return raw# Try first linename_part = clean_name_candidate(lines[0])if re.match(r'^[A-Z][a-zA-Z\s\-\.]{2,50}$', name_part) and len(name_part.split()) >= 2:return name_part.title() if name_part.isupper() else name_part# Try combining first two lines (two-column PDF β name split across lines)if len(lines) >= 2:combined = clean_name_candidate(lines[0] + " " + lines[1])if re.match(r'^[A-Z][a-zA-Z\s\-\.]{2,50}$', combined) and len(combined.split()) >= 2:return combined.title() if combined.isupper() else combined# Fallback: first line even if single wordif re.match(r'^[A-Z][a-zA-Z\s\-\.]{2,50}$', name_part):return name_part.title() if name_part.isupper() else name_partreturn ""@staticmethoddef _fallback_extract_education(text: str) -> list:"""Extract education entries from the EDUCATION section.Handles formats:Format A: "BSc CS, University of X 2020" (inline institution)Format B: "BSc CS 2018-2022 \\n SLIIT City" (institution next line)Format C: "BSc CS \\n University \\n 2020" (year on own line)Multiple degrees on consecutive lines."""# Stop at known section headers only β not at every line starting with 3 uppercase letters# (which would wrongly stop at "SRM Institute..." or "NSBM Green University...")_SECTION_STOP = (r'(?=\n(?:EXPERIENCE|WORK EXPERIENCE|PROFESSIONAL EXPERIENCE|'r'SKILLS|TECHNICAL SKILLS|PROJECTS|FREELANCING|PUBLICATIONS|'r'ACHIEVEMENTS|CERTIFICATIONS|REFERENCES|SUMMARY|OBJECTIVE|'r'CAREER|AWARDS|INTERESTS|LANGUAGES|VOLUNTEER)[\s\n]|$)')edu_section = re.search(r'EDUCATION(?:\s*[&/]\s*[\w\s]+)?\s*\n(.*?)' + _SECTION_STOP,text, re.IGNORECASE | re.DOTALL)if not edu_section:return []lines = [l.strip() for l in edu_section.group(1).splitlines() if l.strip()]DEGREE_KEYWORDS = ['bachelor', 'master', 'phd', 'doctorate', 'bsc', 'msc', 'mba','b.tech', 'b.e', 'm.tech', 'diploma', 'associate', 'b.s', 'm.s','honours', 'hons', 'b.eng', 'm.eng', 'b.sc', 'm.sc', 'hnd','beng', 'meng', 'gce', 'a/l',]# 'engineering' and 'sciences' intentionally excluded β# they appear in field-of-study strings like "Computer Science and Engineering"INST_ENDINGS = ['university', 'universities', 'institute', 'institution','college', 'school', 'academy', 'polytechnic', 'faculty','technology', 'technologies']INST_ACRONYMS = {'sliit', 'mit', 'nsbm', 'iit', 'nit', 'bits', 'vit','lpu', 'pearson'}DEGREE_STARTS = ['bsc', 'msc', 'beng', 'meng', 'b.sc', 'm.sc', 'b.eng','m.eng', 'hnd', 'phd', 'mba', 'bachelor', 'master','diploma', 'gce', 'a/l', 'associate', 'honours']def is_institution_line(line):ll = line.lower().strip()# Reject lines that start with a degree abbreviationif any(ll.startswith(d) for d in DEGREE_STARTS):return Falsereturn (any(kw in ll for kw in INST_ENDINGS) orany(ll.startswith(ac) for ac in INST_ACRONYMS) orll in INST_ACRONYMS)def is_year_line(line):return bool(re.match(r'^\d{4}\s*[-β]?\s*(\d{4}|present)?$',line.strip(), re.IGNORECASE))def extract_inline_institution(line):"""Extract institution from inline patterns like:"HND in Software Engineering - Pearson (2020-2022)"β institution = "Pearson", year = 2022Returns (institution, year) or ("", None)"""# Pattern: "Degree - Institution (year)" or "Degree - Institution year-year"m = re.search(r'[-β]\s*([A-Z][^\d\n(]+?)\s*(?:\((\d{4})[-β]\d{4}\)|(\d{4})[-β]\d{4})', line)if m:inst_raw = m.group(1).strip().rstrip('.,')yr_str = m.group(2) or m.group(3)year = int(yr_str) if yr_str else Nonereturn inst_raw, yearreturn "", Noneresults = []i = 0while i < len(lines):line = lines[i]# ββ Format A: institution line BEFORE degree (two-column PDFs) ββ# e.g. "London Metropolitan University - March 2023 - February 2024"# "BEng (Hons) Software Engineering (First class honours)"if is_institution_line(line) and (i + 1) < len(lines):nxt = lines[i + 1]if any(kw in nxt.lower() for kw in DEGREE_KEYWORDS):institution = ResumeParserClient._extract_institution_name(line)yr = re.search(r'\b(20\d{2}|19\d{2})\b', line)grad_year = int(yr.group(1)) if yr else Nonedegree_line = re.sub(r'\s+Overall\s+\w+$', '', nxt, flags=re.IGNORECASE).strip()results.append({"degree": degree_line,"field": None,"institution": institution,"year": grad_year,})i += 2continue# ββ Format B: degree line with optional inline institution βββββββif any(kw in line.lower() for kw in DEGREE_KEYWORDS):year_match = re.search(r'(\d{4})\s*[-β]\s*(\d{4}|\bpresent\b)', line, re.IGNORECASE)single_year = re.search(r'\b(20\d{2}|19\d{2})\b\s*$', line)grad_year = Noneif year_match:end = year_match.group(2)grad_year = int(end) if end.isdigit() else Noneline = line[:year_match.start()].strip()elif single_year:grad_year = int(single_year.group(1))line = line[:single_year.start()].strip()# Check for inline institution after dash:# "HND in Software Engineering - Pearson (2020-2022)"inline_inst, inline_yr = extract_inline_institution(lines[i])if inline_inst:# Strip the "- Institution (year)" part from degreedegree_clean = re.sub(r'\s*[-β]\s*' + re.escape(inline_inst) + r'.*$','', lines[i]).strip()degree_clean = re.sub(r'\s*[-β]\s*\w+\s+\(\d{4}[-β]\d{4}\).*$','', degree_clean).strip()results.append({"degree": degree_clean,"field": None,"institution": inline_inst,"year": inline_yr or grad_year,})i += 1continue# Split by comma for degree / field / inline institutionparts = [p.strip() for p in line.split(',')]degree = parts[0]field = ""institution = ""if len(parts) >= 2:last = parts[-1].strip()if is_institution_line(last):institution = ResumeParserClient._extract_institution_name(last)field = parts[1] if len(parts) >= 3 else ""else:field = parts[1] if len(parts) > 1 else ""# Look at following lines for institution / yearj = i + 1while j < len(lines) and not institution:nxt = lines[j]if is_year_line(nxt):if not grad_year:yr = re.search(r'\b(20\d{2}|19\d{2})\b', nxt)if yr: grad_year = int(yr.group(1))j += 1elif is_institution_line(nxt):institution = ResumeParserClient._extract_institution_name(nxt)j += 1breakelse:breaki = j - 1 if j > i + 1 else iresults.append({"degree": degree,"field": field or None,"institution": institution or None,"year": grad_year,})i += 1return results@staticmethoddef _fallback_extract_projects(text: str) -> list:"""Extract project names from the PROJECTS section.Handles bullet styles (β’, -, *, βΊ), colon separators, and plain lines.Returns just the project name (text before dash/colon description)."""_SECTION_STOP = (r'(?=\n(?:EXPERIENCE|WORK EXPERIENCE|PROFESSIONAL EXPERIENCE|'r'SKILLS|TECHNICAL SKILLS|EDUCATION|PUBLICATIONS|'r'ACHIEVEMENTS|CERTIFICATIONS|REFERENCES|SUMMARY|OBJECTIVE|'r'CAREER|AWARDS|INTERESTS|LANGUAGES|VOLUNTEER)[\s\n]|$)')proj_section = re.search(r'(?:FREELANCING\s+)?PROJECTS?\s*\n(.*?)' + _SECTION_STOP,text, re.IGNORECASE | re.DOTALL)if not proj_section:return []raw_lines = proj_section.group(1).splitlines()has_bullets = any(re.match(r'^[β’\-\*βΊβͺβΈ]', l.strip()) for l in raw_lines if l.strip())bullets, current = [], ""if has_bullets:# Join continuation lines into their parent bulletfor line in raw_lines:line = line.strip()if not line:continueif re.match(r'^[β’\-\*βΊβͺβΈ]', line):if current: bullets.append(current)current = re.sub(r'^[β’\-\*βΊβͺβΈ]\s*', '', line)elif current:current += " " + lineif current: bullets.append(current)else:# No bullets β each non-empty line is a project entrybullets = [l.strip() for l in raw_lines if l.strip()]projects = []for b in bullets:# "SYSCONEX co-founder 2024 May to 2024 December" β "SYSCONEX co-founder"year_in_middle = re.search(r'\s+\d{4}\s+\w+', b)if year_in_middle:projects.append(b[:year_in_middle.start()].strip())continue# "Name - description" or "Name: description"m = re.match(r'^(.+?)\s*[-β:]\s*.+', b)if m:projects.append(m.group(1).strip())continue# No separator β take first 1-3 words as project name# (handles "PaymentGateway API open source..." β "PaymentGateway API")words = b.split()if len(words) <= 3:projects.append(b.strip())else:# Take up to first 3 words if they look like a name (title-case or camelcase)name_words = []for w in words:if w[0].isupper() or w[0].isdigit():name_words.append(w)else:breakprojects.append(' '.join(name_words) if name_words else words[0])return [p for p in projects if len(p) > 1]@staticmethoddef _extract_institution_name(raw_inst: str) -> str:"""Extract institution name from a line that may containtrailing location, year, or other noise.Examples:"SRM Institute of Science and Technology Delhi NCR, India"β "SRM Institute of Science and Technology""Stanford University 2019"β "Stanford University""NIBM Colombo, Sri Lanka"β "NIBM""Khalifa University, Abu Dhabi, UAE"β "Khalifa University""""# Strip trailing year (e.g. "Stanford University 2019")raw_inst = re.sub(r'\s+\b(19|20)\d{2}\b\s*$', '', raw_inst).strip()# Double-space split β PDF column alignment artifactif ' ' in raw_inst:return raw_inst.split(' ')[0].strip()INST_ENDINGS = ['technology', 'technologies', 'university', 'universities','institute', 'institution', 'college', 'school', 'academy','polytechnic', 'faculty', 'sciences', 'engineering',]INST_ACRONYMS = {'sliit', 'mit', 'nsbm', 'iit', 'nit', 'bits', 'vit', 'lpu','nibm', 'iisc', 'nus', 'ntu', 'uom', 'ucl', 'eth',}CONNECTORS = {'of', 'and', 'the', 'for', 'in', 'at', '&', 'de', 'la'}tokens = raw_inst.split()raw_lower = raw_inst.lower()# Standalone acronym: only when no inst_ending keyword in lineif (tokens and tokens[0].lower() in INST_ACRONYMS andnot any(kw in raw_lower for kw in INST_ENDINGS)):return tokens[0]# Find last institution keyword token, then extend through connectorsbest_end = -1for i, tok in enumerate(tokens):if tok.lower().rstrip('.,') in INST_ENDINGS:best_end = iif best_end >= 0:end = best_end + 1while end < len(tokens):if tokens[end].lower() in CONNECTORS and end + 1 < len(tokens):end += 2else:breakreturn ' '.join(tokens[:end]).strip()# Fallback: strip after last commacomma_idx = raw_inst.rfind(',')return raw_inst[:comma_idx].strip() if comma_idx > 0 else raw_inst.strip()@staticmethoddef _calc_experience_years(experience_list: list) -> float:"""Calculate total years of experience from a list of job entries.Handles overlapping date ranges by merging intervals."""from datetime import datetimedef parse_date(date_str: str):if not date_str:return Nonedate_str = date_str.strip()if date_str.lower() == "present":return datetime.today()for fmt in ("%m/%d/%Y", "%m/%Y", "%B %Y", "%b %Y","%B %d, %Y", "%b %d, %Y", "%Y-%m-%d", "%Y"):try:return datetime.strptime(date_str, fmt)except ValueError:continuereturn Noneintervals = []for job in experience_list:start = parse_date(job.get("start_date", ""))end = parse_date(job.get("end_date", ""))if start and end and end >= start:intervals.append((start, end))if not intervals:return 0.0intervals.sort(key=lambda x: x[0])merged = [intervals[0]]for start, end in intervals[1:]:if start <= merged[-1][1]:merged[-1] = (merged[-1][0], max(merged[-1][1], end))else:merged.append((start, end))total_days = sum((end - start).days for start, end in merged)return round(total_days / 365.25, 1)@staticmethoddef _to_list(value) -> list:"""Ensure value is always a list."""if isinstance(value, list):return valueif isinstance(value, str):return [v.strip() for v in value.split(",") if v.strip()]return []@staticmethoddef _fallback(error: str = "unknown") -> dict:"""Return a minimal valid dict so the pipeline can still runusing only GitHub + graph signals."""logger.warning("[ResumeParser] Using fallback empty resume data (error: %s)", error)return {"name": "","skills": [],"programming_languages": [],"total_experience_years": 0,"education": [],"certifications": [],"projects": [],"parser_error": error,"parser_source": "none",}
resume_parser.py+746-234