Spaces:
Running
Running
add chuncker to pipeline
Browse files- __pycache__/main.cpython-312.pyc +0 -0
- main.py +11 -0
- services/__pycache__/cv_chunker.cpython-312.pyc +0 -0
- services/cv_chunker.py +507 -0
__pycache__/main.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/main.cpython-312.pyc and b/__pycache__/main.cpython-312.pyc differ
|
|
|
main.py
CHANGED
|
@@ -7,7 +7,9 @@ from fastapi import FastAPI, UploadFile, File
|
|
| 7 |
from fastapi.responses import JSONResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from services.cv_converter import CVConverter
|
|
|
|
| 10 |
from fastapi.exceptions import RequestValidationError
|
|
|
|
| 11 |
|
| 12 |
app = FastAPI()
|
| 13 |
@app.exception_handler(RequestValidationError)
|
|
@@ -58,11 +60,20 @@ async def process_cv(file: UploadFile = File(...)):
|
|
| 58 |
|
| 59 |
end_time = datetime.now(timezone.utc).isoformat()
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return APIResponse(
|
| 62 |
message="CV processed successfully",
|
| 63 |
statusCode=200,
|
| 64 |
payload={
|
| 65 |
"markdown": result.markdown,
|
|
|
|
| 66 |
"file_type": result.file_type,
|
| 67 |
"method_used": result.method_used,
|
| 68 |
"is_scanned": result.is_scanned,
|
|
|
|
| 7 |
from fastapi.responses import JSONResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from services.cv_converter import CVConverter
|
| 10 |
+
from services.cv_chunker import CVChunker, SectionKind
|
| 11 |
from fastapi.exceptions import RequestValidationError
|
| 12 |
+
from dataclasses import asdict
|
| 13 |
|
| 14 |
app = FastAPI()
|
| 15 |
@app.exception_handler(RequestValidationError)
|
|
|
|
| 60 |
|
| 61 |
end_time = datetime.now(timezone.utc).isoformat()
|
| 62 |
|
| 63 |
+
chunker = CVChunker()
|
| 64 |
+
chunks_raw = chunker.chunk(result.markdown)
|
| 65 |
+
|
| 66 |
+
chunks = {
|
| 67 |
+
kind.value: asdict(chunk)
|
| 68 |
+
for kind, chunk in chunks_raw.items()
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
return APIResponse(
|
| 72 |
message="CV processed successfully",
|
| 73 |
statusCode=200,
|
| 74 |
payload={
|
| 75 |
"markdown": result.markdown,
|
| 76 |
+
"chunks": chunks,
|
| 77 |
"file_type": result.file_type,
|
| 78 |
"method_used": result.method_used,
|
| 79 |
"is_scanned": result.is_scanned,
|
services/__pycache__/cv_chunker.cpython-312.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
services/cv_chunker.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
cv_chunker.py
|
| 3 |
+
=============
|
| 4 |
+
Splits clean Markdown CV text into typed :class:`CVChunk` objects,
|
| 5 |
+
one per detected section. Scoring/weighting happens downstream.
|
| 6 |
+
|
| 7 |
+
Pipeline position
|
| 8 |
+
-----------------
|
| 9 |
+
CVConverter.convert() β clean Markdown
|
| 10 |
+
β
|
| 11 |
+
CVChunker.chunk() β this file
|
| 12 |
+
β
|
| 13 |
+
dict[SectionKind, CVChunk]
|
| 14 |
+
β
|
| 15 |
+
(your scorer / embedder)
|
| 16 |
+
|
| 17 |
+
Usage
|
| 18 |
+
-----
|
| 19 |
+
from cv_chunker import CVChunker, SectionKind
|
| 20 |
+
|
| 21 |
+
chunker = CVChunker()
|
| 22 |
+
chunks = chunker.chunk(markdown_text)
|
| 23 |
+
|
| 24 |
+
# chunks is dict[SectionKind, CVChunk]
|
| 25 |
+
print(chunks[SectionKind.EXPERIENCE].items)
|
| 26 |
+
print(chunks[SectionKind.SKILLS].items)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import json
|
| 32 |
+
import re
|
| 33 |
+
from dataclasses import asdict, dataclass, field
|
| 34 |
+
from enum import Enum
|
| 35 |
+
from typing import Optional
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
# Section taxonomy
|
| 40 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
+
|
| 42 |
+
class SectionKind(str, Enum):
|
| 43 |
+
SUMMARY = "summary"
|
| 44 |
+
SKILLS = "skills"
|
| 45 |
+
EXPERIENCE = "experience"
|
| 46 |
+
EDUCATION = "education"
|
| 47 |
+
PROJECTS = "projects"
|
| 48 |
+
CERTIFICATIONS = "certifications"
|
| 49 |
+
AWARDS = "awards"
|
| 50 |
+
PUBLICATIONS = "publications"
|
| 51 |
+
LANGUAGES = "languages"
|
| 52 |
+
VOLUNTEERING = "volunteering"
|
| 53 |
+
REFERENCES = "references"
|
| 54 |
+
CONTACT = "contact"
|
| 55 |
+
OTHER = "other"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Heading aliases per section kind
|
| 59 |
+
_SECTION_KEYWORDS: dict[SectionKind, list[str]] = {
|
| 60 |
+
SectionKind.SUMMARY: [
|
| 61 |
+
"summary", "profile", "objective", "about me", "about",
|
| 62 |
+
"professional summary", "career objective", "personal statement",
|
| 63 |
+
"overview", "introduction", "bio", "career summary",
|
| 64 |
+
],
|
| 65 |
+
SectionKind.SKILLS: [
|
| 66 |
+
"skills", "technical skills", "core competencies", "competencies",
|
| 67 |
+
"technologies", "tools", "expertise", "proficiencies",
|
| 68 |
+
"key skills", "areas of expertise", "skill set", "tech stack",
|
| 69 |
+
"programming languages", "software", "technologies & tools",
|
| 70 |
+
],
|
| 71 |
+
SectionKind.EXPERIENCE: [
|
| 72 |
+
"experience", "work experience", "professional experience",
|
| 73 |
+
"employment", "employment history", "work history",
|
| 74 |
+
"career history", "positions held", "job history",
|
| 75 |
+
"relevant experience", "internships", "internship experience",
|
| 76 |
+
],
|
| 77 |
+
SectionKind.EDUCATION: [
|
| 78 |
+
"education", "academic background", "academic history",
|
| 79 |
+
"qualifications", "academic qualifications", "degrees",
|
| 80 |
+
"educational background", "training", "academic",
|
| 81 |
+
],
|
| 82 |
+
SectionKind.PROJECTS: [
|
| 83 |
+
"projects", "personal projects", "side projects",
|
| 84 |
+
"notable projects", "portfolio", "open source", "open-source",
|
| 85 |
+
"key projects", "selected projects",
|
| 86 |
+
],
|
| 87 |
+
SectionKind.CERTIFICATIONS: [
|
| 88 |
+
"certifications", "certificates", "certification",
|
| 89 |
+
"licenses", "accreditations", "professional development",
|
| 90 |
+
"credentials", "courses",
|
| 91 |
+
],
|
| 92 |
+
SectionKind.AWARDS: [
|
| 93 |
+
"awards", "honours", "honors", "achievements",
|
| 94 |
+
"accomplishments", "recognition", "scholarships",
|
| 95 |
+
],
|
| 96 |
+
SectionKind.PUBLICATIONS: [
|
| 97 |
+
"publications", "papers", "research", "journal articles",
|
| 98 |
+
"conference papers", "academic publications",
|
| 99 |
+
],
|
| 100 |
+
SectionKind.LANGUAGES: [
|
| 101 |
+
"languages", "language skills", "spoken languages",
|
| 102 |
+
],
|
| 103 |
+
SectionKind.VOLUNTEERING: [
|
| 104 |
+
"volunteering", "volunteer", "volunteer experience",
|
| 105 |
+
"community involvement", "community service", "civic",
|
| 106 |
+
],
|
| 107 |
+
SectionKind.REFERENCES: [
|
| 108 |
+
"references", "referees", "reference",
|
| 109 |
+
],
|
| 110 |
+
SectionKind.CONTACT: [
|
| 111 |
+
"contact", "contact information", "contact details",
|
| 112 |
+
"personal information", "personal details", "details",
|
| 113 |
+
],
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# Flat inverted index: normalised keyword β SectionKind
|
| 117 |
+
_KW_INDEX: dict[str, SectionKind] = {
|
| 118 |
+
kw.lower().strip(): kind
|
| 119 |
+
for kind, keywords in _SECTION_KEYWORDS.items()
|
| 120 |
+
for kw in keywords
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 125 |
+
# Output dataclass
|
| 126 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 127 |
+
|
| 128 |
+
@dataclass
|
| 129 |
+
class CVChunk:
|
| 130 |
+
"""
|
| 131 |
+
One section of a CV after splitting.
|
| 132 |
+
|
| 133 |
+
Attributes
|
| 134 |
+
----------
|
| 135 |
+
kind : SectionKind β What type of section this is.
|
| 136 |
+
heading : str β Raw heading text as it appeared in the document.
|
| 137 |
+
raw_text : str β Full Markdown body of the section (sub-headings
|
| 138 |
+
and all), ready for embedding or LLM prompting.
|
| 139 |
+
items : list[str] β Normalised list of individual entries extracted
|
| 140 |
+
from the body (bullets, numbered items,
|
| 141 |
+
comma-separated tokens, or paragraphs).
|
| 142 |
+
"""
|
| 143 |
+
kind: SectionKind
|
| 144 |
+
heading: str
|
| 145 |
+
raw_text: str
|
| 146 |
+
items: list[str] = field(default_factory=list)
|
| 147 |
+
|
| 148 |
+
def to_dict(self) -> dict:
|
| 149 |
+
d = asdict(self)
|
| 150 |
+
d["kind"] = self.kind.value
|
| 151 |
+
return d
|
| 152 |
+
|
| 153 |
+
def to_json(self, indent: int = 2) -> str:
|
| 154 |
+
return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 158 |
+
# Chunker
|
| 159 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 160 |
+
|
| 161 |
+
class CVChunker:
|
| 162 |
+
"""
|
| 163 |
+
Splits clean Markdown CV text into a dict of :class:`CVChunk` objects.
|
| 164 |
+
|
| 165 |
+
One chunk is produced per *top-level* section. Sub-headings (e.g.
|
| 166 |
+
individual job titles inside **Work Experience**) are folded into their
|
| 167 |
+
parent chunk's ``raw_text`` and ``items`` rather than becoming separate
|
| 168 |
+
chunks.
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
----------
|
| 172 |
+
keep_unmatched : bool
|
| 173 |
+
When True, sections whose heading cannot be mapped to any
|
| 174 |
+
:class:`SectionKind` are included under ``SectionKind.OTHER``.
|
| 175 |
+
Default is True.
|
| 176 |
+
|
| 177 |
+
Example
|
| 178 |
+
-------
|
| 179 |
+
>>> chunker = CVChunker()
|
| 180 |
+
>>> chunks = chunker.chunk(markdown)
|
| 181 |
+
>>> chunks[SectionKind.SKILLS].items
|
| 182 |
+
['Python', 'TypeScript', 'Docker', ...]
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
# ATX heading β captures depth and text
|
| 186 |
+
_ATX_RE = re.compile(r"^(#{1,6})\s+(.+)$")
|
| 187 |
+
|
| 188 |
+
# Item-extraction patterns
|
| 189 |
+
_BULLET = re.compile(r"^\s*[-*β’β¦βͺβΈβΊββ]\s+(.+)$")
|
| 190 |
+
_NUMBERED = re.compile(r"^\s*\d+[.)]\s+(.+)$")
|
| 191 |
+
_SUBHEAD = re.compile(r"^#{1,6}\s+")
|
| 192 |
+
|
| 193 |
+
# Patterns used only for content-based fallback classification
|
| 194 |
+
_DURATION_RE = re.compile(
|
| 195 |
+
r"\d{4}\s*[-ββ]\s*(\d{4}|present|current|now)", re.IGNORECASE
|
| 196 |
+
)
|
| 197 |
+
_DEGREE_RE = re.compile(
|
| 198 |
+
r"\b(b\.?sc|m\.?sc|ph\.?d|b\.?a|m\.?a|mba|beng|meng|llb|"
|
| 199 |
+
r"bachelor|master|doctorate|degree|diploma|certificate)\b",
|
| 200 |
+
re.IGNORECASE,
|
| 201 |
+
)
|
| 202 |
+
_TECH_RE = re.compile(
|
| 203 |
+
r"\b(python|java|javascript|typescript|react|angular|vue|node|"
|
| 204 |
+
r"django|flask|fastapi|sql|nosql|mongodb|postgresql|mysql|redis|"
|
| 205 |
+
r"aws|azure|gcp|docker|kubernetes|git|linux|rust|golang|go|c\+\+|"
|
| 206 |
+
r"c#|\.net|ruby|rails|php|swift|kotlin|scala|spark|hadoop|"
|
| 207 |
+
r"tensorflow|pytorch|pandas|numpy|excel|powerbi|tableau)\b",
|
| 208 |
+
re.IGNORECASE,
|
| 209 |
+
)
|
| 210 |
+
_EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}")
|
| 211 |
+
_PHONE_RE = re.compile(r"[\+\(]?[\d\s\-\(\)]{7,15}\d")
|
| 212 |
+
|
| 213 |
+
def __init__(self, keep_unmatched: bool = True) -> None:
|
| 214 |
+
self.keep_unmatched = keep_unmatched
|
| 215 |
+
|
| 216 |
+
# ββ public βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 217 |
+
|
| 218 |
+
def chunk(self, markdown: str) -> dict[SectionKind, CVChunk]:
|
| 219 |
+
"""
|
| 220 |
+
Split *markdown* into section chunks.
|
| 221 |
+
|
| 222 |
+
Parameters
|
| 223 |
+
----------
|
| 224 |
+
markdown : str
|
| 225 |
+
Clean Markdown produced by ``CVConverter.convert()``.
|
| 226 |
+
|
| 227 |
+
Returns
|
| 228 |
+
-------
|
| 229 |
+
dict[SectionKind, CVChunk]
|
| 230 |
+
Keyed by section kind. If the same kind appears more than once
|
| 231 |
+
(rare), the later occurrence overwrites the earlier one β use
|
| 232 |
+
``chunk_all()`` if you need all occurrences.
|
| 233 |
+
"""
|
| 234 |
+
return {c.kind: c for c in self.chunk_all(markdown)}
|
| 235 |
+
|
| 236 |
+
def chunk_all(self, markdown: str) -> list[CVChunk]:
|
| 237 |
+
"""
|
| 238 |
+
Like :meth:`chunk` but returns a flat list, preserving duplicates
|
| 239 |
+
and document order.
|
| 240 |
+
"""
|
| 241 |
+
raw = self._split_into_segments(markdown)
|
| 242 |
+
merged = self._merge_sub_headings(raw)
|
| 243 |
+
chunks = []
|
| 244 |
+
for heading, body in merged:
|
| 245 |
+
kind = self._classify(heading, body)
|
| 246 |
+
if kind == SectionKind.OTHER and not self.keep_unmatched:
|
| 247 |
+
continue
|
| 248 |
+
chunks.append(CVChunk(
|
| 249 |
+
kind = kind,
|
| 250 |
+
heading = heading,
|
| 251 |
+
raw_text = body,
|
| 252 |
+
items = self._extract_items(body),
|
| 253 |
+
))
|
| 254 |
+
return chunks
|
| 255 |
+
|
| 256 |
+
# ββ step 1: split into (heading, body, depth) segments βββββββββββββββββββ
|
| 257 |
+
|
| 258 |
+
def _split_into_segments(
|
| 259 |
+
self, markdown: str
|
| 260 |
+
) -> list[tuple[str, str, int]]:
|
| 261 |
+
"""
|
| 262 |
+
Detect headings and pair each with its body text.
|
| 263 |
+
|
| 264 |
+
Returns triples of (heading_text, body_text, atx_depth).
|
| 265 |
+
Non-ATX headings (ALL-CAPS lines, **bold** lines, setext underlines)
|
| 266 |
+
are assigned depth 2 so they behave as section-level headings.
|
| 267 |
+
"""
|
| 268 |
+
lines = markdown.splitlines()
|
| 269 |
+
total = len(lines)
|
| 270 |
+
visited: set[int] = set()
|
| 271 |
+
|
| 272 |
+
# (line_index, heading_text, depth)
|
| 273 |
+
positions: list[tuple[int, str, int]] = []
|
| 274 |
+
|
| 275 |
+
# Priority 1: ATX β depth from # count
|
| 276 |
+
for i, line in enumerate(lines):
|
| 277 |
+
m = self._ATX_RE.match(line)
|
| 278 |
+
if m:
|
| 279 |
+
positions.append((i, m.group(2).strip(), len(m.group(1))))
|
| 280 |
+
visited.add(i)
|
| 281 |
+
|
| 282 |
+
# Priority 2: setext underlines β depth 2
|
| 283 |
+
for i in range(1, total):
|
| 284 |
+
if i in visited or (i - 1) in visited:
|
| 285 |
+
continue
|
| 286 |
+
if re.match(r"^[=\-]{3,}\s*$", lines[i]):
|
| 287 |
+
candidate = lines[i - 1].strip()
|
| 288 |
+
if candidate and not candidate.startswith("|"):
|
| 289 |
+
positions.append((i - 1, candidate, 2))
|
| 290 |
+
visited.update({i - 1, i})
|
| 291 |
+
|
| 292 |
+
# Priority 3: ALL-CAPS lines β depth 2
|
| 293 |
+
for i, line in enumerate(lines):
|
| 294 |
+
if i in visited:
|
| 295 |
+
continue
|
| 296 |
+
s = line.strip()
|
| 297 |
+
if re.match(r"^[A-Z][A-Z\s&/\-]{3,}$", s) and len(s) >= 4:
|
| 298 |
+
positions.append((i, s.title(), 2))
|
| 299 |
+
visited.add(i)
|
| 300 |
+
|
| 301 |
+
# Priority 4: **Bold** standalone lines β depth 3
|
| 302 |
+
for i, line in enumerate(lines):
|
| 303 |
+
if i in visited:
|
| 304 |
+
continue
|
| 305 |
+
m = re.match(r"^\*\*([^*]+)\*\*\s*$", line.strip())
|
| 306 |
+
if m:
|
| 307 |
+
positions.append((i, m.group(1).strip(), 3))
|
| 308 |
+
visited.add(i)
|
| 309 |
+
|
| 310 |
+
if not positions:
|
| 311 |
+
return []
|
| 312 |
+
|
| 313 |
+
positions.sort(key=lambda x: x[0])
|
| 314 |
+
|
| 315 |
+
segments: list[tuple[str, str, int]] = []
|
| 316 |
+
for idx, (line_no, heading, depth) in enumerate(positions):
|
| 317 |
+
start = line_no + 1
|
| 318 |
+
end = positions[idx + 1][0] if idx + 1 < len(positions) else total
|
| 319 |
+
body = "\n".join(lines[start:end]).strip()
|
| 320 |
+
segments.append((heading, body, depth))
|
| 321 |
+
|
| 322 |
+
return segments
|
| 323 |
+
|
| 324 |
+
# ββ step 2: fold sub-headings into their parent βββββββββββββββββββββββββββ
|
| 325 |
+
|
| 326 |
+
def _merge_sub_headings(
|
| 327 |
+
self, raw: list[tuple[str, str, int]]
|
| 328 |
+
) -> list[tuple[str, str]]:
|
| 329 |
+
"""
|
| 330 |
+
Collapse deeper ATX headings into the body of their parent section.
|
| 331 |
+
|
| 332 |
+
Finds the shallowest depth that matches a known CV section keyword
|
| 333 |
+
and treats anything deeper as sub-content (e.g. individual job
|
| 334 |
+
titles inside Work Experience).
|
| 335 |
+
"""
|
| 336 |
+
if not raw:
|
| 337 |
+
return []
|
| 338 |
+
|
| 339 |
+
# Determine the dominant section-heading depth
|
| 340 |
+
matched_depths = [
|
| 341 |
+
depth for heading, _body, depth in raw
|
| 342 |
+
if self._classify_heading(heading) != SectionKind.OTHER
|
| 343 |
+
]
|
| 344 |
+
section_depth = min(matched_depths) if matched_depths else 2
|
| 345 |
+
|
| 346 |
+
merged: list[tuple[str, str]] = []
|
| 347 |
+
cur_heading: str = ""
|
| 348 |
+
cur_parts: list[str] = []
|
| 349 |
+
|
| 350 |
+
def flush() -> None:
|
| 351 |
+
if cur_heading:
|
| 352 |
+
merged.append((cur_heading, "\n\n".join(cur_parts).strip()))
|
| 353 |
+
|
| 354 |
+
for heading, body, depth in raw:
|
| 355 |
+
if depth <= section_depth:
|
| 356 |
+
flush()
|
| 357 |
+
cur_heading = heading
|
| 358 |
+
cur_parts = [body] if body else []
|
| 359 |
+
else:
|
| 360 |
+
# Sub-heading: re-attach as a ### block inside the parent
|
| 361 |
+
block = f"### {heading}"
|
| 362 |
+
if body:
|
| 363 |
+
block += f"\n{body}"
|
| 364 |
+
cur_parts.append(block)
|
| 365 |
+
|
| 366 |
+
flush()
|
| 367 |
+
return merged
|
| 368 |
+
|
| 369 |
+
# ββ step 3: classify a heading β SectionKind βββββββββββββββββββββββββββββ
|
| 370 |
+
|
| 371 |
+
def _classify(self, heading: str, body: str) -> SectionKind:
|
| 372 |
+
"""Classify using heading first, body content as fallback."""
|
| 373 |
+
kind = self._classify_heading(heading)
|
| 374 |
+
if kind != SectionKind.OTHER:
|
| 375 |
+
return kind
|
| 376 |
+
return self._classify_body(body)
|
| 377 |
+
|
| 378 |
+
def _classify_heading(self, heading: str) -> SectionKind:
|
| 379 |
+
"""
|
| 380 |
+
Three-tier keyword match against the heading string.
|
| 381 |
+
|
| 382 |
+
Tier A exact normalised match
|
| 383 |
+
Tier B keyword is contained in heading (or vice-versa)
|
| 384 |
+
Tier C token overlap β₯ 50 %
|
| 385 |
+
"""
|
| 386 |
+
norm = _normalise(heading)
|
| 387 |
+
|
| 388 |
+
# Tier A
|
| 389 |
+
if norm in _KW_INDEX:
|
| 390 |
+
return _KW_INDEX[norm]
|
| 391 |
+
|
| 392 |
+
# Tier B
|
| 393 |
+
for kw, kind in _KW_INDEX.items():
|
| 394 |
+
if kw in norm or norm in kw:
|
| 395 |
+
return kind
|
| 396 |
+
|
| 397 |
+
# Tier C
|
| 398 |
+
h_tokens = set(norm.split())
|
| 399 |
+
best_kind: Optional[SectionKind] = None
|
| 400 |
+
best_overlap: float = 0.0
|
| 401 |
+
for kw, kind in _KW_INDEX.items():
|
| 402 |
+
kw_tokens = set(kw.split())
|
| 403 |
+
overlap = len(h_tokens & kw_tokens) / max(len(kw_tokens), 1)
|
| 404 |
+
if overlap > best_overlap:
|
| 405 |
+
best_overlap = overlap
|
| 406 |
+
best_kind = kind
|
| 407 |
+
|
| 408 |
+
if best_overlap >= 0.5 and best_kind is not None:
|
| 409 |
+
return best_kind
|
| 410 |
+
|
| 411 |
+
return SectionKind.OTHER
|
| 412 |
+
|
| 413 |
+
def _classify_body(self, body: str) -> SectionKind:
|
| 414 |
+
"""Last-resort: infer kind from body content patterns."""
|
| 415 |
+
if self._DURATION_RE.search(body):
|
| 416 |
+
return SectionKind.EXPERIENCE
|
| 417 |
+
if self._DEGREE_RE.search(body):
|
| 418 |
+
return SectionKind.EDUCATION
|
| 419 |
+
if len(self._TECH_RE.findall(body)) >= 3:
|
| 420 |
+
return SectionKind.SKILLS
|
| 421 |
+
if self._EMAIL_RE.search(body) or self._PHONE_RE.search(body):
|
| 422 |
+
return SectionKind.CONTACT
|
| 423 |
+
return SectionKind.OTHER
|
| 424 |
+
|
| 425 |
+
# ββ step 4: extract normalised items from a section body βββββββββββββββββ
|
| 426 |
+
|
| 427 |
+
def _extract_items(self, raw_text: str) -> list[str]:
|
| 428 |
+
"""
|
| 429 |
+
Pull individual entries out of the section body.
|
| 430 |
+
|
| 431 |
+
Handles
|
| 432 |
+
-------
|
| 433 |
+
* Markdown bullets ``- item``, ``* item``, ``β’ item`` β¦
|
| 434 |
+
* Numbered lists ``1. item``
|
| 435 |
+
* Sub-headings ``### Job Title`` β plain text item
|
| 436 |
+
* Comma/semicolon lists (skills lines with β₯ 3 delimiters, no full stops)
|
| 437 |
+
* Freeform paragraphs (joined across line-breaks, split on blank lines)
|
| 438 |
+
"""
|
| 439 |
+
items: list[str] = []
|
| 440 |
+
para_lines: list[str] = []
|
| 441 |
+
|
| 442 |
+
def flush_para() -> None:
|
| 443 |
+
para = " ".join(para_lines).strip()
|
| 444 |
+
para_lines.clear()
|
| 445 |
+
if not para:
|
| 446 |
+
return
|
| 447 |
+
# Split comma/semicolon/pipe skill lines into individual tokens
|
| 448 |
+
if para.count(",") + para.count(";") + para.count("|") >= 3 \
|
| 449 |
+
and "." not in para:
|
| 450 |
+
items.extend(
|
| 451 |
+
s.strip()
|
| 452 |
+
for s in re.split(r"[,;|]", para)
|
| 453 |
+
if s.strip()
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
items.append(para)
|
| 457 |
+
|
| 458 |
+
for line in raw_text.splitlines():
|
| 459 |
+
stripped = line.strip()
|
| 460 |
+
|
| 461 |
+
if not stripped:
|
| 462 |
+
flush_para()
|
| 463 |
+
continue
|
| 464 |
+
|
| 465 |
+
# Sub-heading inside body β plain text item
|
| 466 |
+
if self._SUBHEAD.match(stripped):
|
| 467 |
+
flush_para()
|
| 468 |
+
items.append(stripped.lstrip("#").strip())
|
| 469 |
+
continue
|
| 470 |
+
|
| 471 |
+
# Bullet
|
| 472 |
+
m = self._BULLET.match(line)
|
| 473 |
+
if m:
|
| 474 |
+
flush_para()
|
| 475 |
+
items.append(m.group(1).strip())
|
| 476 |
+
continue
|
| 477 |
+
|
| 478 |
+
# Numbered
|
| 479 |
+
m = self._NUMBERED.match(line)
|
| 480 |
+
if m:
|
| 481 |
+
flush_para()
|
| 482 |
+
items.append(m.group(1).strip())
|
| 483 |
+
continue
|
| 484 |
+
|
| 485 |
+
para_lines.append(stripped)
|
| 486 |
+
|
| 487 |
+
flush_para()
|
| 488 |
+
|
| 489 |
+
# De-duplicate while preserving order
|
| 490 |
+
seen: set[str] = set()
|
| 491 |
+
unique: list[str] = []
|
| 492 |
+
for item in items:
|
| 493 |
+
if item and item not in seen:
|
| 494 |
+
seen.add(item)
|
| 495 |
+
unique.append(item)
|
| 496 |
+
|
| 497 |
+
return unique
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 501 |
+
# Helpers
|
| 502 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 503 |
+
|
| 504 |
+
def _normalise(text: str) -> str:
|
| 505 |
+
text = text.lower().strip()
|
| 506 |
+
text = re.sub(r"[^\w\s&/]", " ", text)
|
| 507 |
+
return re.sub(r"\s+", " ", text).strip()
|