Eng-Musa commited on
Commit
37c64f2
·
1 Parent(s): 0918462

new ai based chunker

Browse files
Files changed (3) hide show
  1. main.py +88 -50
  2. services/cv_chunk_refiner.py +0 -683
  3. services/cv_chunker.py +530 -479
main.py CHANGED
@@ -1,25 +1,35 @@
1
- from pathlib import Path
2
- import tempfile
3
- from typing import Any, List, Optional
4
 
 
5
  from datetime import datetime, timezone
6
- from fastapi import FastAPI, UploadFile, File, Body
7
- from fastapi.responses import JSONResponse
 
 
 
8
  from pydantic import BaseModel, Field
 
 
9
  from services.cv_converter import CVConverter
10
- from services.cv_chunker import CVChunker, SectionKind
11
- from services.cv_chunk_refiner import CVChunkRefiner
12
- from services.job_matcher import JobMatcher, JobInput
13
- from fastapi.exceptions import RequestValidationError
14
- from dataclasses import asdict
15
 
16
- app = FastAPI()
17
- @app.exception_handler(RequestValidationError)
18
- async def validation_exception_handler(request, exc):
19
- return APIResponse(message="File is required", statusCode=400)
 
 
 
 
 
20
 
21
  converter = CVConverter()
22
- matcher = JobMatcher() # loads SentenceTransformer model once at startup
 
 
 
 
 
23
 
24
  class APIResponse(BaseModel):
25
  message: str
@@ -27,25 +37,52 @@ class APIResponse(BaseModel):
27
  payload: Optional[Any] = None
28
 
29
 
30
- # python -m uvicorn main:app --reload
31
- @app.get("/")
 
 
 
 
 
 
 
 
 
 
 
 
32
  def home():
33
  return APIResponse(message="Job Processor API is running", statusCode=200)
34
 
35
 
 
 
 
 
 
 
 
 
 
36
  @app.post("/process-cv", response_model=APIResponse)
37
  async def process_cv(file: UploadFile = File(...)):
 
 
 
 
 
 
 
38
  if not file.filename:
39
  return APIResponse(message="No file uploaded", statusCode=400)
40
 
41
- allowed_extensions = (".pdf", ".docx", ".doc")
42
- if not file.filename.lower().endswith(allowed_extensions):
43
  return APIResponse(
44
- message=f"Invalid file format. Allowed formats are: {', '.join(allowed_extensions)}",
45
- statusCode=400
46
  )
47
 
48
- tmp_path = None
49
  try:
50
  start_time = datetime.now(timezone.utc).isoformat()
51
  file_bytes = await file.read()
@@ -55,40 +92,39 @@ async def process_cv(file: UploadFile = File(...)):
55
  tmp.write(file_bytes)
56
  tmp_path = Path(tmp.name)
57
 
58
- result = converter.convert(tmp_path)
59
- end_time = datetime.now(timezone.utc).isoformat()
60
-
61
- if not result.success:
62
- return APIResponse(message=result.error, statusCode=422)
63
 
 
 
64
  end_time = datetime.now(timezone.utc).isoformat()
65
 
66
- chunker = CVChunker()
67
- chunks_raw = chunker.chunk(result.markdown)
68
-
69
- refiner = CVChunkRefiner()
70
- refined_cv = refiner.refine(chunks_raw)
71
-
72
  return APIResponse(
73
  message="CV processed successfully",
74
  statusCode=200,
75
  payload={
76
- "markdown": result.markdown,
77
- "chunks": refined_cv.to_dict(),
78
- "file_type": result.file_type,
79
- "method_used": result.method_used,
80
- "is_scanned": result.is_scanned,
81
- "page_count": result.page_count,
82
- "warnings": result.warnings,
83
- "start_time": start_time,
84
- "end_time": end_time,
85
- }
 
 
 
 
86
  )
87
 
88
- except Exception as e:
89
  return APIResponse(
90
- message=f"An error occurred during processing: {str(e)}",
91
- statusCode=500
92
  )
93
 
94
  finally:
@@ -97,7 +133,9 @@ async def process_cv(file: UploadFile = File(...)):
97
 
98
 
99
  # ---------------------------------------------------------------------------
100
- # Match CV against a job posting
 
 
101
  # ---------------------------------------------------------------------------
102
 
103
  class MatchCVRequest(BaseModel):
@@ -112,7 +150,7 @@ def match_cv_to_job(payload: MatchCVRequest):
112
  Match a Markdown CV against a structured job posting.
113
 
114
  Returns a detailed qualification prediction including:
115
- - Overall match score (0–100%)
116
  - Match level label (e.g. "Strong Match")
117
  - Per-dimension score breakdown (skill, semantic, title, category, seniority, experience)
118
  - Mismatch analysis and improvement advice
@@ -127,8 +165,8 @@ def match_cv_to_job(payload: MatchCVRequest):
127
  statusCode=200,
128
  payload=result,
129
  )
130
- except Exception as e:
131
  return APIResponse(
132
- message=f"An error occurred during matching: {str(e)}",
133
  statusCode=500,
134
  )
 
1
+ from __future__ import annotations
 
 
2
 
3
+ import tempfile
4
  from datetime import datetime, timezone
5
+ from pathlib import Path
6
+ from typing import Any, Optional
7
+
8
+ from fastapi import FastAPI, File, UploadFile
9
+ from fastapi.exceptions import RequestValidationError
10
  from pydantic import BaseModel, Field
11
+
12
+ from services.cv_chunker import chunk_cv
13
  from services.cv_converter import CVConverter
14
+ from services.job_matcher import JobInput, JobMatcher
 
 
 
 
15
 
16
+ # ---------------------------------------------------------------------------
17
+ # App setup
18
+ # ---------------------------------------------------------------------------
19
+
20
+ app = FastAPI(
21
+ title="Job Processor API",
22
+ description="CV parsing, chunking, and job-match prediction service.",
23
+ version="2.0.0",
24
+ )
25
 
26
  converter = CVConverter()
27
+ matcher = JobMatcher() # SentenceTransformer loaded once at startup
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Shared response model
32
+ # ---------------------------------------------------------------------------
33
 
34
  class APIResponse(BaseModel):
35
  message: str
 
37
  payload: Optional[Any] = None
38
 
39
 
40
+ # ---------------------------------------------------------------------------
41
+ # Validation error handler
42
+ # ---------------------------------------------------------------------------
43
+
44
+ @app.exception_handler(RequestValidationError)
45
+ async def validation_exception_handler(request, exc):
46
+ return APIResponse(message="Invalid request: " + str(exc.errors()[0].get("msg", exc)), statusCode=400)
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Health check
51
+ # ---------------------------------------------------------------------------
52
+
53
+ @app.get("/", response_model=APIResponse)
54
  def home():
55
  return APIResponse(message="Job Processor API is running", statusCode=200)
56
 
57
 
58
+ # ---------------------------------------------------------------------------
59
+ # POST /process-cv
60
+ # Accepts a PDF / DOCX / DOC file, converts it to Markdown,
61
+ # then runs the CV chunker to return structured sections.
62
+ # ---------------------------------------------------------------------------
63
+
64
+ _ALLOWED_EXT = (".pdf", ".docx", ".doc")
65
+
66
+
67
  @app.post("/process-cv", response_model=APIResponse)
68
  async def process_cv(file: UploadFile = File(...)):
69
+ """
70
+ Upload a CV file (PDF, DOCX, DOC) and receive:
71
+ - Raw Markdown text
72
+ - Structured chunks (summary, experience, education, skills, projects)
73
+ - Detected CV metadata (title, seniority, category, years of experience)
74
+ - File metadata (type, method used, page count, warnings)
75
+ """
76
  if not file.filename:
77
  return APIResponse(message="No file uploaded", statusCode=400)
78
 
79
+ if not file.filename.lower().endswith(_ALLOWED_EXT):
 
80
  return APIResponse(
81
+ message=f"Invalid file format. Allowed formats: {', '.join(_ALLOWED_EXT)}",
82
+ statusCode=400,
83
  )
84
 
85
+ tmp_path: Optional[Path] = None
86
  try:
87
  start_time = datetime.now(timezone.utc).isoformat()
88
  file_bytes = await file.read()
 
92
  tmp.write(file_bytes)
93
  tmp_path = Path(tmp.name)
94
 
95
+ # Convert file → Markdown
96
+ conversion = converter.convert(tmp_path)
97
+ if not conversion.success:
98
+ return APIResponse(message=conversion.error or "Conversion failed", statusCode=422)
 
99
 
100
+ # Chunk the Markdown into structured sections
101
+ chunks = chunk_cv(conversion.markdown)
102
  end_time = datetime.now(timezone.utc).isoformat()
103
 
 
 
 
 
 
 
104
  return APIResponse(
105
  message="CV processed successfully",
106
  statusCode=200,
107
  payload={
108
+ "markdown": conversion.markdown,
109
+ "cv_title": chunks["cv_title"],
110
+ "seniority": chunks["seniority"],
111
+ "years_experience": chunks["years_experience"],
112
+ "category": chunks["category"],
113
+ "chunks": chunks["chunks"],
114
+ "file_type": conversion.file_type,
115
+ "method_used": conversion.method_used,
116
+ "is_scanned": conversion.is_scanned,
117
+ "page_count": conversion.page_count,
118
+ "warnings": conversion.warnings,
119
+ "start_time": start_time,
120
+ "end_time": end_time,
121
+ },
122
  )
123
 
124
+ except Exception as exc:
125
  return APIResponse(
126
+ message=f"An error occurred during processing: {exc}",
127
+ statusCode=500,
128
  )
129
 
130
  finally:
 
133
 
134
 
135
  # ---------------------------------------------------------------------------
136
+ # POST /match-cv
137
+ # Accepts a structured job JSON + a CV Markdown string,
138
+ # returns a full qualification prediction.
139
  # ---------------------------------------------------------------------------
140
 
141
  class MatchCVRequest(BaseModel):
 
150
  Match a Markdown CV against a structured job posting.
151
 
152
  Returns a detailed qualification prediction including:
153
+ - Overall match score (0–100 %)
154
  - Match level label (e.g. "Strong Match")
155
  - Per-dimension score breakdown (skill, semantic, title, category, seniority, experience)
156
  - Mismatch analysis and improvement advice
 
165
  statusCode=200,
166
  payload=result,
167
  )
168
+ except Exception as exc:
169
  return APIResponse(
170
+ message=f"An error occurred during matching: {exc}",
171
  statusCode=500,
172
  )
services/cv_chunk_refiner.py DELETED
@@ -1,683 +0,0 @@
1
- """
2
- cv_chunk_refiner.py
3
- ===================
4
- Refines coarse :class:`CVChunk` objects (one per section) into structured
5
- per-entity sub-chunks ready for embedding and scoring.
6
-
7
- Designed to be format-agnostic: it makes no assumptions about separator
8
- characters, date formats, heading styles, or table markup. It works by
9
- signal detection — looking for the *presence* of date-like strings,
10
- degree-like strings, and block-boundary cues — rather than by matching
11
- a fixed template.
12
-
13
- Pipeline position
14
- -----------------
15
- CVChunker.chunk()
16
- ↓
17
- dict[SectionKind, CVChunk] ← input to this module
18
- ↓
19
- CVChunkRefiner.refine() ← this file
20
- ↓
21
- RefinedCV ← structured, per-entity output
22
- ↓
23
- Embedder → one vector per entity
24
- ↓
25
- Scorer → weights per entity
26
-
27
- Output shapes
28
- -------------
29
- Experience → list[ExperienceEntry]
30
- Education → list[EducationEntry]
31
- Skills → SkillsEntry
32
-
33
- Usage
34
- -----
35
- from cv_chunker import CVChunker, SectionKind
36
- from cv_chunk_refiner import CVChunkRefiner
37
-
38
- chunks = CVChunker().chunk(markdown)
39
- refined = CVChunkRefiner().refine(chunks)
40
-
41
- for job in refined.experience:
42
- print(job.company, job.role, job.bullets)
43
-
44
- for edu in refined.education:
45
- print(edu.institution, edu.degree)
46
-
47
- print(refined.skills.items)
48
- """
49
-
50
- from __future__ import annotations
51
-
52
- import json
53
- import re
54
- from dataclasses import asdict, dataclass, field
55
- from typing import Optional
56
-
57
- from .cv_chunker import CVChunk, SectionKind
58
-
59
-
60
- # ─────────────────────────────────────────────────────────────────────────────
61
- # Output dataclasses
62
- # ─────────────────────────────────────────────────────────────────────────────
63
-
64
- @dataclass
65
- class ExperienceEntry:
66
- """One job / internship / role."""
67
- company: str
68
- role: str
69
- period: str
70
- bullets: list[str] = field(default_factory=list)
71
-
72
- def to_dict(self) -> dict:
73
- return asdict(self)
74
-
75
- def to_text(self) -> str:
76
- lines = [f"{self.role} at {self.company} ({self.period})"]
77
- lines.extend(f"- {b}" for b in self.bullets)
78
- return "\n".join(lines)
79
-
80
-
81
- @dataclass
82
- class EducationEntry:
83
- """One degree / certificate / qualification."""
84
- institution: str
85
- degree: str
86
- period: str
87
-
88
- def to_dict(self) -> dict:
89
- return asdict(self)
90
-
91
- def to_text(self) -> str:
92
- parts = [self.degree, self.institution]
93
- if self.period:
94
- parts.append(f"({self.period})")
95
- return " — ".join(p for p in parts if p)
96
-
97
-
98
- @dataclass
99
- class SkillsEntry:
100
- """Flat, deduplicated skill token list."""
101
- items: list[str] = field(default_factory=list)
102
-
103
- def to_dict(self) -> dict:
104
- return asdict(self)
105
-
106
- def to_text(self) -> str:
107
- return ", ".join(self.items)
108
-
109
-
110
- @dataclass
111
- class RefinedCV:
112
- """Top-level container returned by :meth:`CVChunkRefiner.refine`."""
113
- experience: list[ExperienceEntry] = field(default_factory=list)
114
- education: list[EducationEntry] = field(default_factory=list)
115
- skills: SkillsEntry = field(default_factory=SkillsEntry)
116
-
117
- def to_dict(self) -> dict:
118
- return {
119
- "experience": [e.to_dict() for e in self.experience],
120
- "education": [e.to_dict() for e in self.education],
121
- "skills": self.skills.to_dict(),
122
- }
123
-
124
- def to_json(self, indent: int = 2) -> str:
125
- return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
126
-
127
-
128
- # ─────────────────────────────────────────────────────────────────────────────
129
- # Shared low-level helpers (module-level so they can be used pre-class)
130
- # ─────────────────────────────────────────────────────────────────────────────
131
-
132
- def _strip_md(text: str) -> str:
133
- """Remove *italic*, **bold**, ***both***, and ``code`` spans."""
134
- text = re.sub(r"\*{1,3}([^*]+)\*{1,3}", r"\1", text)
135
- text = re.sub(r"`([^`]+)`", r"\1", text)
136
- return text.strip()
137
-
138
-
139
- def _strip_noise(text: str) -> str:
140
- """Remove HTML tags, <br>, markdown table pipes, and normalise whitespace."""
141
- text = re.sub(r"<br\s*/?>", " ", text, flags=re.IGNORECASE)
142
- text = re.sub(r"<[^>]+>", "", text) # any remaining HTML
143
- text = text.strip("|").strip()
144
- text = re.sub(r"\s{2,}", " ", text)
145
- return text.strip()
146
-
147
-
148
- def _clean_token(text: str) -> str:
149
- """Strip leading/trailing punctuation and whitespace from a token."""
150
- return re.sub(r"^[\s\-–—*•·|,;:#\[\]()]+|[\s\-–—*•·|,;:#\[\]()]+$",
151
- "", text).strip()
152
-
153
-
154
- # ─────────────────────────────────────────────────────────────────────────────
155
- # Signal detectors (pure functions; no format assumptions)
156
- # ─────────────────────────────────────────────────────────────────────────────
157
-
158
- # --- Date / period signals ---------------------------------------------------
159
-
160
- # Named-month period: "Jan 2020 - Dec 2021" / "March 2019 – Present"
161
- _NAMED_MONTH = (
162
- r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|"
163
- r"Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|"
164
- r"Dec(?:ember)?)"
165
- )
166
- _END_TOKEN = r"(?:" + _NAMED_MONTH + r"\s+\d{4}|present|current|now|ongoing|till\s+date|to\s+date)"
167
- _PERIOD_RE = re.compile(
168
- r"(?:"
169
- # named-month start
170
- r"(?P<nm>" + _NAMED_MONTH + r"\s+\d{4}\s*[-–—/to]+\s*" + _END_TOKEN + r")"
171
- r"|"
172
- # year-only: "2018 - 2021" / "2022–Present"
173
- r"(?P<yr>\d{4}\s*[-–—/to]+\s*(?:\d{4}|present|current|now|ongoing))"
174
- r")",
175
- re.IGNORECASE,
176
- )
177
-
178
- # Single year (used as a weak heuristic, not for period extraction alone)
179
- _YEAR_RE = re.compile(r"\b(19|20)\d{2}\b")
180
-
181
-
182
- def _extract_period(text: str) -> tuple[str, str]:
183
- """
184
- Return (period_string, remainder) where remainder is *text* with the
185
- period portion removed. If no period is found both are returned as-is
186
- with an empty period.
187
- """
188
- m = _PERIOD_RE.search(text)
189
- if not m:
190
- return "", text
191
- period = (m.group("nm") or m.group("yr") or "").strip()
192
- period = re.sub(r"\s*[-–—]\s*", " - ", period) # normalise separator
193
- remainder = (text[: m.start()] + text[m.end():]).strip(" ,-–—|")
194
- return period, remainder
195
-
196
-
197
- def _has_period(text: str) -> bool:
198
- return bool(_PERIOD_RE.search(text))
199
-
200
-
201
- # --- Degree signals ----------------------------------------------------------
202
-
203
- _DEGREE_KEYWORDS = re.compile(
204
- r"\b("
205
- r"b\.?\s*sc|m\.?\s*sc|ph\.?\s*d|b\.?\s*a|m\.?\s*a|mba|b\.?\s*eng|m\.?\s*eng|"
206
- r"b\.?\s*tech|m\.?\s*tech|llb|llm|md|bcom|mcom|"
207
- r"bachelor(?:'?s)?|master(?:'?s)?|doctorate|associate(?:'?s)?|"
208
- r"diploma|certificate|higher\s+national|hnd|hnc|"
209
- r"a\s*-?\s*levels?|o\s*-?\s*levels?|gcse|kcse|waec|neco|"
210
- r"degree|qualification"
211
- r")\b",
212
- re.IGNORECASE,
213
- )
214
-
215
- _DEGREE_SUBJECTS = re.compile(
216
- r"\b("
217
- r"engineering|science|arts|commerce|law|medicine|nursing|education|"
218
- r"business|management|economics|finance|accounting|mathematics|"
219
- r"physics|chemistry|biology|computer|information|technology|"
220
- r"communication|psychology|sociology|history|geography|philosophy"
221
- r")\b",
222
- re.IGNORECASE,
223
- )
224
-
225
-
226
- def _is_degree_line(text: str) -> bool:
227
- return bool(_DEGREE_KEYWORDS.search(text))
228
-
229
-
230
- # --- Block-boundary signals --------------------------------------------------
231
-
232
- # Lines that are purely structural noise (table separators, horizontal rules)
233
- _NOISE_LINE_RE = re.compile(r"^[\-=|:\s]{3,}$")
234
-
235
- # Bullet character at line start
236
- _BULLET_RE = re.compile(r"^\s*(?:[-*•·◦▪▸›✓✔]|\d+[.)])\s+(.+)$")
237
-
238
- # Markdown heading prefix
239
- _HEADING_RE = re.compile(r"^#{1,6}\s+(.+)$")
240
-
241
- # A line that looks like a role/job title (no period, short, title-cased or ALL-CAPS)
242
- _ROLE_HINT_RE = re.compile(
243
- r"\b("
244
- r"engineer|developer|analyst|manager|director|consultant|architect|"
245
- r"designer|officer|lead|head|senior|junior|associate|intern|"
246
- r"specialist|coordinator|administrator|executive|president|vice|"
247
- r"founder|co-?founder|cto|ceo|coo|ciso|vp\b"
248
- r")\b",
249
- re.IGNORECASE,
250
- )
251
-
252
-
253
- def _is_noise_line(text: str) -> bool:
254
- return bool(_NOISE_LINE_RE.match(text)) or not text.strip()
255
-
256
-
257
- def _bullet_text(raw_line: str) -> Optional[str]:
258
- m = _BULLET_RE.match(raw_line)
259
- return m.group(1).strip() if m else None
260
-
261
-
262
- # ─────────────────────────────────────────────────────────────────────────────
263
- # Block splitter — the format-agnostic core
264
- # ─────────────────────────────────────────────────────────────────────────────
265
-
266
- @dataclass
267
- class _RawBlock:
268
- """
269
- One contiguous block of lines that likely describes a single entity
270
- (job, degree, project …). Format-free; classification happens later.
271
- """
272
- header_lines: list[str] = field(default_factory=list) # non-bullet lines at top
273
- bullet_lines: list[str] = field(default_factory=list) # bullet body
274
-
275
-
276
- def _split_into_blocks(raw_text: str) -> list[_RawBlock]:
277
- """
278
- Split a section's raw_text into entity blocks without relying on any
279
- specific separator character or date format.
280
-
281
- A new block starts when ALL of the following hold for a non-bullet line:
282
- 1. It is not structural noise.
283
- 2. It contains a year or looks like a header (has title casing / all-caps
284
- word, or follows a blank line after bullets have already started).
285
- 3. The current block already has at least one header line OR at least
286
- one bullet.
287
-
288
- This covers the most common CV patterns:
289
- • "Company | Role Jan 2020 – Dec 2021" (pipe-separated, single line)
290
- • "Company\nRole\nJan 2020 – Dec 2021" (three separate lines)
291
- • "### Company — Role (2020–2021)" (heading prefix)
292
- • "**Company** — Role — 2020 to 2021" (bold, em-dash)
293
- • Plain indented blocks with only bullet content
294
- """
295
- lines = raw_text.splitlines()
296
- blocks: list[_RawBlock] = []
297
- cur = _RawBlock()
298
- after_blank = False
299
-
300
- def _flush():
301
- if cur.header_lines or cur.bullet_lines:
302
- blocks.append(_RawBlock(
303
- header_lines=list(cur.header_lines),
304
- bullet_lines=list(cur.bullet_lines),
305
- ))
306
- cur.header_lines.clear()
307
- cur.bullet_lines.clear()
308
-
309
- for raw_line in lines:
310
- stripped = raw_line.strip()
311
-
312
- # ── blank line ────────────────────────────────────────────────────
313
- if not stripped:
314
- after_blank = True
315
- continue
316
-
317
- # ── noise (table separators, HR) ──────────────────────────────────
318
- if _is_noise_line(stripped):
319
- after_blank = False
320
- continue
321
-
322
- # ── strip markdown heading prefix (### …) ────────────────────────
323
- hm = _HEADING_RE.match(stripped)
324
- if hm:
325
- stripped = hm.group(1).strip()
326
-
327
- stripped = _strip_md(_strip_noise(stripped))
328
- if not stripped:
329
- continue
330
-
331
- bt = _bullet_text(raw_line)
332
-
333
- if bt is not None:
334
- # Bullet line → always belongs to current block
335
- cur.bullet_lines.append(_strip_md(bt))
336
- after_blank = False
337
- else:
338
- # Non-bullet line: decide if it starts a new block
339
- is_new_block = (
340
- (cur.header_lines or cur.bullet_lines) # something exists
341
- and (
342
- _has_period(stripped) # has a date → new entry
343
- or (after_blank and cur.bullet_lines) # blank after bullets
344
- or ( # looks like a standalone header
345
- not cur.bullet_lines
346
- and len(cur.header_lines) >= 3 # already 3 header lines
347
- )
348
- )
349
- )
350
- if is_new_block:
351
- _flush()
352
- cur.header_lines.append(stripped)
353
- after_blank = False
354
-
355
- _flush()
356
- return blocks
357
-
358
-
359
- # ─────────────────────────────────────────────────────────────────────────────
360
- # Header parser — extracts (company, role, period) from a list of strings
361
- # ─────────────────────────────────────────────────────────────────────────────
362
-
363
- # Common separators between company and role on one line
364
- _INLINE_SEP_RE = re.compile(r"\s*(?:[|·–—/]|[-]{2,})\s*")
365
-
366
-
367
- def _parse_job_header(header_lines: list[str]) -> tuple[str, str, str]:
368
- """
369
- Given 1-4 header lines for a job block, return (company, role, period).
370
-
371
- Strategy (format-agnostic):
372
- 1. Extract and remove the period substring from whichever line contains it.
373
- 2. On the remaining text, look for an inline separator (|, –, ·) to split
374
- company and role. If none, use line order (first line = company,
375
- second = role) or role-keyword detection.
376
- 3. If everything is on one line, split by inline separator.
377
- """
378
- if not header_lines:
379
- return "", "", ""
380
-
381
- period = ""
382
- clean_lines: list[str] = []
383
-
384
- for line in header_lines:
385
- p, remainder = _extract_period(line)
386
- if p and not period:
387
- period = p
388
- remainder = remainder.strip(" ,-–—|")
389
- if remainder:
390
- clean_lines.append(remainder)
391
-
392
- # Join remaining lines as one string, then attempt to split
393
- combined = " | ".join(clean_lines) if len(clean_lines) > 1 else (clean_lines[0] if clean_lines else "")
394
-
395
- # Try inline separator split
396
- parts = [p.strip() for p in _INLINE_SEP_RE.split(combined) if p.strip()]
397
-
398
- if len(parts) >= 2:
399
- # Heuristic: the part most likely to be a *role* contains role keywords
400
- role_scores = [
401
- (i, len(_ROLE_HINT_RE.findall(p))) for i, p in enumerate(parts)
402
- ]
403
- best_role_idx = max(role_scores, key=lambda x: x[1])[0]
404
-
405
- if best_role_idx == 0:
406
- # Role is first → swap assumption: maybe it's role | company
407
- role = parts[0]
408
- company = parts[1] if len(parts) > 1 else ""
409
- else:
410
- company = parts[0]
411
- role = parts[best_role_idx]
412
-
413
- elif len(parts) == 1:
414
- # Only one segment — can't split; treat as company, role unknown
415
- company = parts[0]
416
- role = ""
417
- else:
418
- company = combined
419
- role = ""
420
-
421
- return _clean_token(company), _clean_token(role), period
422
-
423
-
424
- # ─────────────────────────────────────────────────────────────────────────────
425
- # Education parser
426
- # ─────────────────────────────────────────────────────────────────────────────
427
-
428
- def _parse_edu_block(header_lines: list[str], bullet_lines: list[str]) -> Optional[EducationEntry]:
429
- """
430
- Extract (institution, degree, period) from a raw education block.
431
-
432
- Works by:
433
- 1. Extracting any period substring.
434
- 2. Looking for a line that contains a degree keyword → that line is the
435
- degree; remaining lines form the institution.
436
- 3. Falling back to first-line = institution, second-line = degree.
437
- """
438
- all_lines = header_lines + bullet_lines
439
- if not all_lines:
440
- return None
441
-
442
- period = ""
443
- degree_line = ""
444
- other_lines: list[str] = []
445
-
446
- for line in all_lines:
447
- if _is_noise_line(line):
448
- continue
449
- p, remainder = _extract_period(line)
450
- if p and not period:
451
- period = p
452
- remainder = _clean_token(_strip_md(_strip_noise(remainder)))
453
- if not remainder:
454
- continue
455
- if _is_degree_line(remainder) and not degree_line:
456
- degree_line = remainder
457
- else:
458
- other_lines.append(remainder)
459
-
460
- institution = " ".join(other_lines[:2]).strip() # first 1-2 non-degree lines
461
-
462
- # If no explicit degree line found, try splitting first line on comma / "in"
463
- if not degree_line and institution:
464
- # "BSc Computer Science, University of Nairobi" pattern
465
- comma_parts = [p.strip() for p in institution.split(",", 1)]
466
- if len(comma_parts) == 2 and _is_degree_line(comma_parts[0]):
467
- degree_line = comma_parts[0]
468
- institution = comma_parts[1]
469
- else:
470
- in_parts = re.split(r"\s+in\s+", institution, maxsplit=1, flags=re.IGNORECASE)
471
- if len(in_parts) == 2:
472
- degree_line = in_parts[0].strip()
473
- institution = in_parts[1].strip()
474
-
475
- if not institution and not degree_line:
476
- return None
477
-
478
- return EducationEntry(
479
- institution = _clean_token(institution),
480
- degree = _clean_token(degree_line),
481
- period = period,
482
- )
483
-
484
-
485
- # ─────────────────────────────────────────────────────────────────────────────
486
- # Main refiner class
487
- # ─────────────────────────────────────────────────────────────────────────────
488
-
489
- class CVChunkRefiner:
490
- """
491
- Converts coarse :class:`CVChunk` dicts into fine-grained, typed entities.
492
-
493
- Format-agnostic design
494
- ----------------------
495
- No regex is hard-coded to a specific separator, date format, or CV
496
- template. Instead the refiner uses *signal detection*:
497
-
498
- - **Period signals**: any date-like substring (named month, year-only,
499
- "present" / "current" / "now" / "ongoing") marks a block boundary and
500
- supplies the entry's period.
501
- - **Degree signals**: keywords like "Bachelor", "MSc", "Diploma",
502
- "Certificate", "KCSE" etc. identify the degree line regardless of its
503
- position in the block.
504
- - **Role signals**: occupation keywords ("Engineer", "Manager", "Intern" …)
505
- help decide which part of a compound header is the role vs company.
506
- - **Block boundaries**: a new non-bullet line that contains a period (or
507
- follows a blank line after bullets) starts the next entity.
508
-
509
- This means the same class handles:
510
- • "Company | Role Month YYYY – Month YYYY" (pipe-inline)
511
- • "Company\nRole\nJan YYYY – Present" (three-line stacked)
512
- • "### **Company** — Role (YYYY–YYYY)" (heading + em-dash)
513
- • "Role, Company, YYYY–YYYY" (comma-separated)
514
- • "YYYY – YYYY | Company | Role" (period-first)
515
- • Euro-style: "Company (YYYY–YYYY)\nRole" (parenthesised period)
516
- • US resume: "Company City, ST" with role on next line
517
- • Plain bullets with no header (role inferred from bullets)
518
-
519
- Parameters
520
- ----------
521
- min_skill_len : int
522
- Discard skill tokens shorter than this many characters. Default 2.
523
- skill_separators : str
524
- Regex pattern used to split skill tokens on a single line.
525
- Default covers commas, semicolons, pipes, slashes, and " and ".
526
- keep_partial : bool
527
- When True (default), experience / education entries where company
528
- *or* role could not be determined are still kept with an empty string
529
- for the missing field, so no data is silently dropped.
530
- """
531
-
532
- _DEFAULT_SKILL_SEP = r"[,;|/]|\s+and\s+"
533
-
534
- def __init__(
535
- self,
536
- min_skill_len: int = 2,
537
- skill_separators: str = _DEFAULT_SKILL_SEP,
538
- keep_partial: bool = True,
539
- ) -> None:
540
- self._min_skill_len = min_skill_len
541
- self._skill_sep_re = re.compile(skill_separators, re.IGNORECASE)
542
- self._keep_partial = keep_partial
543
-
544
- # ── public ───────────────────────────────────────────────────────────────
545
-
546
- def refine(self, chunks: dict[SectionKind, CVChunk]) -> RefinedCV:
547
- """
548
- Refine a full dict of :class:`CVChunk` objects.
549
-
550
- Parameters
551
- ----------
552
- chunks : dict[SectionKind, CVChunk]
553
- Direct output of ``CVChunker().chunk(markdown)``.
554
-
555
- Returns
556
- -------
557
- RefinedCV
558
- """
559
- result = RefinedCV()
560
-
561
- if SectionKind.EXPERIENCE in chunks:
562
- result.experience = self._refine_experience(chunks[SectionKind.EXPERIENCE])
563
-
564
- if SectionKind.EDUCATION in chunks:
565
- result.education = self._refine_education(chunks[SectionKind.EDUCATION])
566
-
567
- if SectionKind.SKILLS in chunks:
568
- result.skills = self._refine_skills(chunks[SectionKind.SKILLS])
569
-
570
- return result
571
-
572
- # ── experience ───────────────────────────────────────────────────────────
573
-
574
- def _refine_experience(self, chunk: CVChunk) -> list[ExperienceEntry]:
575
- """Split experience section into one ExperienceEntry per job."""
576
- blocks = _split_into_blocks(chunk.raw_text)
577
- entries: list[ExperienceEntry] = []
578
-
579
- for block in blocks:
580
- company, role, period = _parse_job_header(block.header_lines)
581
-
582
- # Skip blocks that look like section sub-headings with no content
583
- if not block.bullet_lines and not company and not role:
584
- continue
585
-
586
- # keep_partial: retain entries even if company/role is partially missing
587
- if not self._keep_partial and not (company and role):
588
- continue
589
-
590
- entries.append(ExperienceEntry(
591
- company = company,
592
- role = role,
593
- period = period,
594
- bullets = [b for b in block.bullet_lines if b.strip()],
595
- ))
596
-
597
- return entries
598
-
599
- # ── education ────────────────────────────────────────────────────────────
600
-
601
- def _refine_education(self, chunk: CVChunk) -> list[EducationEntry]:
602
- """Split education section into one EducationEntry per qualification."""
603
- blocks = _split_into_blocks(chunk.raw_text)
604
- entries: list[EducationEntry] = []
605
-
606
- for block in blocks:
607
- entry = _parse_edu_block(block.header_lines, block.bullet_lines)
608
- if entry is None:
609
- continue
610
- # Skip blocks that have no institution and no degree (pure noise)
611
- if not entry.institution and not entry.degree:
612
- continue
613
- entries.append(entry)
614
-
615
- return entries
616
-
617
- # ── skills ───────────────────────────────────────────────────────────────
618
-
619
- def _refine_skills(self, chunk: CVChunk) -> SkillsEntry:
620
- """
621
- Produce a flat, deduplicated, noise-free list of skill tokens.
622
-
623
- Handles all common formats:
624
- • "Languages: Java, JavaScript, TypeScript" (labelled line)
625
- • "Python · Django · PostgreSQL" (mid-dot separated)
626
- • "React | Node.js | Docker" (pipe separated)
627
- • "Python, TypeScript" (comma, no label)
628
- • "Python" (one per bullet)
629
- • "Advanced: Python; Intermediate: SQL" (proficiency levels)
630
- """
631
- seen: set[str] = set()
632
- tokens: list[str] = []
633
-
634
- # Also scan raw_text for label-prefixed lines the chunker may have
635
- # merged into one item (e.g. "**Languages:** Java, JS, TS")
636
- all_text_lines = chunk.raw_text.splitlines()
637
- all_items = chunk.items + [
638
- _strip_md(_strip_noise(ln))
639
- for ln in all_text_lines
640
- if ln.strip() and not _is_noise_line(ln.strip())
641
- ]
642
-
643
- def _add(tok: str) -> None:
644
- t = _clean_token(_strip_md(tok))
645
- if len(t) >= self._min_skill_len and t.lower() not in seen:
646
- seen.add(t.lower())
647
- tokens.append(t)
648
-
649
- for item in all_items:
650
- item = _strip_md(_strip_noise(item))
651
- if not item or _is_noise_line(item):
652
- continue
653
-
654
- # Strip "Category:" label prefix before splitting
655
- colon_idx = item.find(":")
656
- if colon_idx != -1:
657
- label = item[:colon_idx].strip()
658
- payload = item[colon_idx + 1:].strip()
659
- # Only strip the label if it looks like a category, not a URL
660
- if len(label.split()) <= 4 and "://" not in label:
661
- item = payload if payload else item
662
-
663
- # Split on any recognised delimiter
664
- # Also handle mid-dot (·) and en-dash used as list separators
665
- normalised = re.sub(r"\s*[·•]\s*", ",", item)
666
- parts = self._skill_sep_re.split(normalised)
667
-
668
- if len(parts) > 1:
669
- for p in parts:
670
- p = p.strip()
671
- if p:
672
- # Some parts may themselves be "Level: skill" — strip level
673
- colon_idx2 = p.find(":")
674
- if colon_idx2 != -1 and len(p[:colon_idx2].split()) <= 2:
675
- p = p[colon_idx2 + 1:].strip()
676
- _add(p)
677
- else:
678
- # Single token — could still be a whole skill phrase
679
- item_stripped = item.strip()
680
- if item_stripped:
681
- _add(item_stripped)
682
-
683
- return SkillsEntry(items=tokens)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
services/cv_chunker.py CHANGED
@@ -1,507 +1,558 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
 
3
  import re
4
+ from typing import Any, Dict, List, Optional, Set, Tuple
5
+
6
+ # ---------------------------------------------------------------------------
7
+ # Inlined helpers from job_matcher (no local module dependency)
8
+ # ---------------------------------------------------------------------------
9
+
10
+ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
11
+ "microsoft word": ["microsoft word", "ms word", "word"],
12
+ "microsoft excel": ["microsoft excel", "ms excel", "excel"],
13
+ "microsoft powerpoint": ["microsoft powerpoint", "ms powerpoint", "powerpoint"],
14
+ "inventory management": ["inventory management", "inventory", "stock control", "stock management"],
15
+ "warehouse": ["warehouse", "stockroom", "store room"],
16
+ "data entry": ["data entry", "typing"],
17
+ "communication": ["communication", "communicate"],
18
+ "teamwork": ["teamwork", "team work", "team member"],
19
+ "critical thinking": ["critical thinking", "problem solving", "problem-solving"],
20
+ "customer service": ["customer service", "client service"],
21
+ "reporting": ["report", "reporting"],
22
+ "html": ["html", "html5"],
23
+ "css": ["css", "css3"],
24
+ "javascript": ["javascript", "js"],
25
+ "typescript": ["typescript", "ts"],
26
+ "react": ["react", "react.js", "reactjs"],
27
+ "next.js": ["next.js", "nextjs"],
28
+ "vue": ["vue", "vue.js", "vuejs"],
29
+ "angular": ["angular"],
30
+ "tailwind css": ["tailwind", "tailwind css"],
31
+ "node.js": ["node", "node.js", "nodejs"],
32
+ "express.js": ["express", "express.js"],
33
+ "python": ["python"],
34
+ "java": ["java"],
35
+ "kotlin": ["kotlin"],
36
+ "android": ["android", "android studio"],
37
+ "php": ["php"],
38
+ "laravel": ["laravel"],
39
+ "mysql": ["mysql"],
40
+ "postgresql": ["postgresql", "postgres", "supabase"],
41
+ "mongodb": ["mongodb", "mongo"],
42
+ "rest api": ["rest api", "restful api", "api"],
43
+ "git": ["git", "github", "gitlab"],
44
+ "docker": ["docker"],
45
+ "ui design": ["ui", "ui design", "user interface"],
46
+ "ux design": ["ux", "ux design", "user experience"],
47
+ "figma": ["figma"],
48
+ "wireframing": ["wireframe", "wireframing"],
49
+ "prototyping": ["prototype", "prototyping"],
50
+ "seo": ["seo", "search engine optimization"],
51
+ "content writing": ["content writing", "copywriting", "writing"],
52
+ "digital marketing": ["digital marketing", "marketing campaign"],
53
+ "sql": ["sql"],
54
+ "machine learning": ["machine learning", "ml"],
55
+ "data analysis": ["data analysis", "analytics", "data analyst"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  }
57
 
58
+ DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
59
+ "Admin & Stock": {
60
+ "microsoft word", "microsoft excel", "microsoft powerpoint", "inventory management",
61
+ "warehouse", "data entry", "communication", "teamwork", "customer service", "reporting",
62
+ },
63
+ "Software Engineering": {
64
+ "html", "css", "javascript", "typescript", "react", "next.js", "vue", "angular",
65
+ "tailwind css", "node.js", "express.js", "python", "java", "kotlin", "android", "php",
66
+ "laravel", "mysql", "postgresql", "mongodb", "rest api", "git", "docker",
67
+ },
68
+ "Design & Creative": {"ui design", "ux design", "figma", "wireframing", "prototyping"},
69
+ "Marketing & Growth": {"seo", "content writing", "digital marketing"},
70
+ "Data & Analytics": {"sql", "python", "machine learning", "data analysis", "microsoft excel"},
71
  }
72
 
73
+ SENIORITY_PATTERNS: Dict[str, List[str]] = {
74
+ "intern": ["intern", "internship", "trainee"],
75
+ "junior": ["junior", "entry level", "entry-level", "assistant", "fresh graduate"],
76
+ "mid": ["mid", "officer", "specialist", "developer", "designer", "engineer"],
77
+ "senior": ["senior", "lead", "manager", "head", "principal", "architect"],
78
+ }
79
+ SENIORITY_ORDER: Dict[str, int] = {"intern": 0, "junior": 1, "mid": 2, "senior": 3}
80
+
81
+
82
+ def _normalize(text: str) -> str:
83
+ text = (text or "").lower()
84
+ text = text.replace("/", " ").replace("_", " ")
85
+ text = re.sub(r"[^a-z0-9+.#\s-]", " ", text)
86
+ return re.sub(r"\s+", " ", text).strip()
87
+
88
+
89
+ def _has_alias(text_norm: str, alias: str) -> bool:
90
+ alias_norm = _normalize(alias)
91
+ if not alias_norm:
92
+ return False
93
+ return re.search(rf"(?<![a-z0-9]){re.escape(alias_norm)}(?![a-z0-9])", text_norm) is not None
94
+
95
+
96
+ def _extract_skills(text: str, aliases: Dict[str, List[str]]) -> Set[str]:
97
+ text_norm = _normalize(text)
98
+ return {canon for canon, ali_list in aliases.items() if any(_has_alias(text_norm, a) for a in ali_list)}
99
+
100
+
101
+ def _infer_category(text: str, skills: Set[str], category_skills: Dict[str, Set[str]]) -> str:
102
+ text_norm = _normalize(text)
103
+ title_keywords = {
104
+ "Admin & Stock": ["stock", "inventory", "warehouse", "admin", "office", "cashier"],
105
+ "Software Engineering": ["developer", "engineer", "programmer", "frontend", "backend", "full stack", "mobile"],
106
+ "Design & Creative": ["designer", "ui", "ux", "creative"],
107
+ "Marketing & Growth": ["marketing", "seo", "content", "social media"],
108
+ "Data & Analytics": ["data", "analyst", "analytics", "machine learning", "ai"],
109
+ }
110
+ best, best_score = "Other", 0.0
111
+ for cat, cat_skills in category_skills.items():
112
+ score = len(skills & cat_skills) * 2.0 + sum(1 for kw in title_keywords.get(cat, []) if kw in text_norm) * 1.25
113
+ if score > best_score:
114
+ best_score, best = score, cat
115
+ return best
116
+
117
+
118
+ def _extract_years(text: str) -> int:
119
+ text_norm = _normalize(text)
120
+ patterns = [
121
+ r"(\d+)\+?\s*(?:years|year|yrs|yr)\s*(?:of)?\s*(?:experience|exp)",
122
+ r"experience\s*(?:of)?\s*(\d+)\+?\s*(?:years|year|yrs|yr)",
123
+ ]
124
+ years = [int(m.group(1)) for p in patterns for m in re.finditer(p, text_norm)]
125
+ return max(years) if years else 0
126
+
127
+
128
+ def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
129
+ text_norm = _normalize(text)
130
+ order = ["senior", "junior", "intern", "mid"] if is_cv else ["senior", "intern", "junior", "mid"]
131
+ for level in order:
132
+ if any(_has_alias(text_norm, term) for term in SENIORITY_PATTERNS[level]):
133
+ return level
134
+ years = _extract_years(text)
135
+ if years >= 5:
136
+ return "senior"
137
+ if years >= 2:
138
+ return "mid"
139
+ return "junior" if is_cv else "mid"
140
+
141
+
142
+ def _extract_cv_title(cv_text: str) -> str:
143
+ title_words = [
144
+ "officer", "developer", "engineer", "designer", "assistant", "accountant",
145
+ "manager", "marketing", "stock", "cashier", "admin", "student", "intern",
146
+ "analyst", "teacher",
147
+ ]
148
+ lines = [re.sub(r"\s+", " ", x).strip() for x in cv_text.splitlines() if x.strip()]
149
+ for line in lines[:15]:
150
+ if len(line) <= 60 and any(w in line.lower() for w in title_words):
151
+ return line.title()
152
+ return "Unknown"
153
+
154
+
155
+ def _parse_cv_sections(cv_text: str) -> Dict[str, str]:
156
+ section_headers = {
157
+ "summary": ["summary", "profile", "about me", "objective"],
158
+ "contact": ["contact", "contact information", "personal details", "personal information"],
159
+ "links": ["links", "online profiles", "social media", "web presence", "profiles"],
160
+ "skills": ["skills", "technical skills", "core skills", "competencies"],
161
+ "experience": ["experience", "employment", "work history", "career", "volunteer"],
162
+ "education": ["education", "university", "school"],
163
+ "projects": ["projects", "portfolio", "github"],
164
+ }
165
+ current = "summary"
166
+ sections: Dict[str, List[str]] = {k: [] for k in section_headers}
167
+ for raw_line in cv_text.splitlines():
168
+ line = re.sub(r"^#+\s*", "", raw_line).strip()
169
+ if not line:
170
+ continue
171
+ line_norm = _normalize(line)
172
+ matched = None
173
+ if len(line_norm) <= 40:
174
+ for section, headers in section_headers.items():
175
+ if any(line_norm == h or line_norm.replace(" ", "") == h.replace(" ", "") for h in headers):
176
+ matched = section
177
+ break
178
+ if matched:
179
+ current = matched
180
+ continue
181
+ sections[current].append(line)
182
+ return {k: "\n".join(v).strip() for k, v in sections.items()}
183
+
184
+
185
+ # ---------------------------------------------------------------------------
186
+ # Date / period helpers
187
+ # ---------------------------------------------------------------------------
188
+
189
+ _MONTH = r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*"
190
+ _YEAR = r"\d{4}"
191
+ _DATE = rf"(?:{_MONTH}\s+)?{_YEAR}"
192
+ _PERIOD_RE = re.compile(
193
+ rf"({_DATE})\s*[-–—]\s*({_DATE}|Present|Current|Now|Till date|To date)",
194
+ re.IGNORECASE,
195
+ )
196
+ _YEAR_ONLY_RE = re.compile(
197
+ rf"({_YEAR})\s*[-–—]\s*({_YEAR}|Present|Current|Now)",
198
+ re.IGNORECASE,
199
+ )
200
+
201
+
202
+ def _extract_period(line: str) -> Optional[str]:
203
+ m = _PERIOD_RE.search(line)
204
+ if m:
205
+ return f"{m.group(1)} - {m.group(2)}"
206
+ m = _YEAR_ONLY_RE.search(line)
207
+ if m:
208
+ return f"{m.group(1)} - {m.group(2)}"
209
+ return None
210
+
211
+
212
+ def _strip_period(line: str) -> str:
213
+ line = _PERIOD_RE.sub("", line)
214
+ line = _YEAR_ONLY_RE.sub("", line)
215
+ return re.sub(r"[\|\·•]\s*$", "", line).strip(" |·•–—-")
216
+
217
+
218
+ # ---------------------------------------------------------------------------
219
+ # Experience parser
220
+ # ---------------------------------------------------------------------------
221
+
222
+ _BULLET_RE = re.compile(r"^[-•*▪►▸>]\s+")
223
+
224
+ _ROLE_WORDS = {
225
+ "engineer", "developer", "manager", "designer", "analyst", "intern", "officer",
226
+ "lead", "head", "director", "consultant", "assistant", "specialist", "coordinator",
227
+ "technician", "architect", "programmer", "researcher", "executive",
228
+ }
229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
+ def _split_role_company(text: str) -> Tuple[str, str]:
232
+ """'Role at Company', 'Company | Role', or 'Role, Company'."""
233
+ for pat in [r"\s+(?:at|@)\s+", r"\s*\|\s*", r"\s*,\s+"]:
234
+ parts = re.split(pat, text, maxsplit=1)
235
+ if len(parts) == 2:
236
+ a, b = parts[0].strip(), parts[1].strip()
237
+ a_is_role = any(w in a.lower() for w in _ROLE_WORDS)
238
+ b_is_role = any(w in b.lower() for w in _ROLE_WORDS)
239
+ if a_is_role and not b_is_role:
240
+ return a, b
241
+ if b_is_role and not a_is_role:
242
+ return b, a
243
+ return a, b # default: first=role, second=company
244
+ return "", text
245
+
246
+
247
+ def _parse_experience(raw: str) -> List[Dict[str, Any]]:
248
+ entries: List[Dict[str, Any]] = []
249
+ current: Optional[Dict[str, Any]] = None
250
+
251
+ for raw_line in raw.splitlines():
252
+ line = re.sub(r"^#+\s*", "", raw_line).strip()
253
+ if not line:
254
+ continue
255
+
256
+ period = _extract_period(line)
257
+ is_bullet = bool(_BULLET_RE.match(line))
258
+ clean = _strip_period(_BULLET_RE.sub("", line)).strip()
259
+
260
+ if is_bullet:
261
+ if current is not None and clean:
262
+ current["responsibilities"].append(clean)
263
+ continue
264
+
265
+ if period and not clean:
266
+ # Stand-alone date line
267
+ if current is not None and not current["period"]:
268
+ current["period"] = period
269
+ continue
270
+
271
+ if period:
272
+ # Header line with embedded date
273
+ if current is not None and not current["period"] and not current.get("role") and not current.get("company"):
274
+ current["period"] = period
275
+ role, company = _split_role_company(clean)
276
+ current["role"] = role
277
+ current["company"] = company
278
+ else:
279
+ if current:
280
+ entries.append(current)
281
+ role, company = _split_role_company(clean)
282
+ current = {"role": role, "company": company, "period": period, "responsibilities": []}
283
+ continue
284
+
285
+ # Plain header line (no date)
286
+ if current:
287
+ entries.append(current)
288
+ role, company = _split_role_company(clean)
289
+ current = {"role": role, "company": company, "period": None, "responsibilities": []}
290
+
291
+ if current:
292
+ entries.append(current)
293
+
294
+ return [e for e in entries if e.get("company") or e.get("role")]
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Education parser
299
+ # ---------------------------------------------------------------------------
300
+
301
+ _DEGREE_RE = re.compile(
302
+ r"\b(bachelor|master|phd|doctorate|diploma|certificate|degree|bsc|msc|ba|ma|mba|hnd|kcse|kcpe)\b",
303
+ re.IGNORECASE,
304
+ )
305
+ _INSTITUTION_RE = re.compile(
306
+ r"\b(university|college|school|institute|polytechnic|academy)\b",
307
+ re.IGNORECASE,
308
+ )
309
+
310
+
311
+ def _parse_education(raw: str) -> List[Dict[str, str]]:
312
+ entries: List[Dict[str, str]] = []
313
+ current: Dict[str, str] = {}
314
+
315
+ def _flush() -> None:
316
+ if current.get("institution") or current.get("degree"):
317
+ entries.append({
318
+ "institution": current.get("institution", ""),
319
+ "degree": current.get("degree", ""),
320
+ "period": current.get("period", ""),
321
+ })
322
+ current.clear()
323
+
324
+ for raw_line in raw.splitlines():
325
+ line = re.sub(r"^#+\s*", "", raw_line).strip()
326
+ line = _BULLET_RE.sub("", line).strip()
327
+ if not line:
328
+ continue
329
+
330
+ period = _extract_period(line)
331
+ clean = _strip_period(line).strip()
332
+ if not clean:
333
+ if period and current:
334
+ current["period"] = period
335
+ continue
336
+
337
+ has_degree = bool(_DEGREE_RE.search(clean))
338
+ has_inst = bool(_INSTITUTION_RE.search(clean))
339
+
340
+ if has_degree or has_inst:
341
+ _flush()
342
+ current["degree"] = clean if has_degree else ""
343
+ current["institution"] = "" if has_degree else clean
344
+ current["period"] = period or ""
345
+ elif period:
346
+ # Stand-alone date — attach to open entry or start minimal one
347
+ if current:
348
+ current["period"] = period
349
+ else:
350
+ current["institution"] = clean
351
+ current["period"] = period
352
+ else:
353
+ # Could be a sub-section header (e.g. "VOLUNTEER & LEADERSHIP")
354
+ _flush()
355
+ current["institution"] = clean
356
+ current["period"] = ""
357
 
358
+ _flush()
359
+ return [e for e in entries if e.get("institution") or e.get("degree")]
360
 
 
 
 
361
 
362
+ # ---------------------------------------------------------------------------
363
+ # Contact parser
364
+ # ---------------------------------------------------------------------------
365
 
366
+ _EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}")
367
+ _PHONE_RE = re.compile(r"(?:\+?\d[\d\s().\-]{6,}\d)")
368
+ _LOCATION_RE = re.compile(
369
+ r"\b([A-Z][a-zA-Z]+(?:\s[A-Z][a-zA-Z]+)*)\s*,\s*([A-Z][a-zA-Z]+(?:\s[A-Z][a-zA-Z]+)*)\b"
370
+ )
371
 
 
 
 
 
 
 
372
 
373
+ def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
 
 
 
 
 
374
  """
375
+ Extract email, phone, and location from the contact section.
376
+ Falls back to scanning the full CV text when the section is empty.
377
+ """
378
+ search_text = raw if raw.strip() else cv_full[:800]
379
+
380
+ email_m = _EMAIL_RE.search(search_text)
381
+ phone_m = _PHONE_RE.search(search_text)
382
+ loc_m = _LOCATION_RE.search(search_text)
383
+
384
+ return {
385
+ "email": email_m.group(0).strip() if email_m else "",
386
+ "phone": phone_m.group(0).strip() if phone_m else "",
387
+ "location": loc_m.group(0).strip() if loc_m else "",
388
+ }
389
+
390
+
391
+ # ---------------------------------------------------------------------------
392
+ # Links parser
393
+ # ---------------------------------------------------------------------------
394
+
395
+ _URL_RE = re.compile(
396
+ r"(?:https?://|www\.)[^\s,;\"'>)]+"
397
+ r"|(?:github\.com|linkedin\.com|behance\.net|dribbble\.com|medium\.com|dev\.to)[^\s,;\"'>)]*",
398
+ re.IGNORECASE,
399
+ )
400
+
401
+ _PLATFORM_MAP: List[Tuple[str, str]] = [
402
+ ("github", "GitHub"),
403
+ ("linkedin", "LinkedIn"),
404
+ ("behance", "Behance"),
405
+ ("dribbble", "Dribbble"),
406
+ ("medium", "Medium"),
407
+ ("dev.to", "Dev.to"),
408
+ ("twitter", "Twitter"),
409
+ ("x.com", "X (Twitter)"),
410
+ ("portfolio", "Portfolio"),
411
+ ("website", "Website"),
412
+ ]
413
+
414
+
415
+ def _label_url(url: str, context_line: str) -> str:
416
+ combined = (url + " " + context_line).lower()
417
+ for key, label in _PLATFORM_MAP:
418
+ if key in combined:
419
+ return label
420
+ return "Website"
421
+
422
+
423
+ def _parse_links(raw: str, cv_full: str) -> List[Dict[str, str]]:
424
+ """
425
+ Extract URLs from the links section (or the full CV header as fallback).
426
+ Returns a list of {"label": str, "url": str}.
427
+ """
428
+ search_text = raw if raw.strip() else cv_full[:1200]
429
+ results: List[Dict[str, str]] = []
430
+ seen: set = set()
431
+
432
+ for line in search_text.splitlines():
433
+ for m in _URL_RE.finditer(line):
434
+ url = m.group(0).rstrip(".,:;)")
435
+ if url in seen:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  continue
437
+ seen.add(url)
438
+ # Ensure the URL has a scheme for consistency
439
+ normalised = url if url.startswith("http") else f"https://{url}"
440
+ results.append({"label": _label_url(url, line), "url": normalised})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
+ return results
 
443
 
 
 
 
444
 
445
+ # ---------------------------------------------------------------------------
446
+ # Skills parser
447
+ # ---------------------------------------------------------------------------
 
 
448
 
449
+ def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
450
+ canonical = sorted(_extract_skills(cv_full, DEFAULT_SKILL_ALIASES))
 
 
 
 
 
 
 
 
 
 
 
451
 
452
+ raw_items: List[str] = []
453
+ for line in raw.splitlines():
454
+ line = re.sub(r"^#+\s*", "", line).strip()
455
+ line = _BULLET_RE.sub("", line).strip()
456
+ for item in re.split(r"[,|;/]", line):
457
+ item = item.strip(" ·•-")
458
+ if item and len(item) < 60:
459
+ raw_items.append(item)
460
 
461
+ return {"items": raw_items, "canonical": canonical}
462
 
 
 
 
 
 
 
 
463
 
464
+ # ---------------------------------------------------------------------------
465
+ # Public API
466
+ # ---------------------------------------------------------------------------
467
 
468
+ def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
469
+ """
470
+ Parse a CV markdown string into structured, cleaned chunks.
471
 
472
+ Returns
473
+ -------
474
+ {
475
+ "cv_title": str,
476
+ "seniority": str,
477
+ "years_experience": int,
478
+ "category": str,
479
+ "chunks": {
480
+ "summary": str,
481
+ "experience": [{"role", "company", "period", "responsibilities"}, ...],
482
+ "education": [{"institution", "degree", "period"}, ...],
483
+ "skills": {"items": [...], "canonical": [...]},
484
+ "projects": str,
485
+ }
486
+ }
487
+ """
488
+ sections = _parse_cv_sections(cv_markdown)
489
+
490
+ cv_title = _extract_cv_title(cv_markdown)
491
+ cv_years = _extract_years(cv_markdown)
492
+ seniority_input = cv_title + "\n" + sections.get("experience", "") + "\n" + cv_markdown[:600]
493
+ cv_seniority = _detect_seniority(seniority_input, is_cv=True)
494
+ cv_skills = _extract_skills(cv_markdown, DEFAULT_SKILL_ALIASES)
495
+ cv_category = _infer_category(cv_markdown, cv_skills, DEFAULT_CATEGORY_SKILLS)
496
+
497
+ return {
498
+ "cv_title": cv_title,
499
+ "seniority": cv_seniority,
500
+ "years_experience": cv_years,
501
+ "category": cv_category,
502
+ "chunks": {
503
+ "summary": sections.get("summary", "").strip(),
504
+ "contact": _parse_contact(sections.get("contact", ""), cv_markdown),
505
+ "links": _parse_links(sections.get("links", ""), cv_markdown),
506
+ "skills": _parse_skills(sections.get("skills", ""), cv_markdown),
507
+ "experience": _parse_experience(sections.get("experience", "")),
508
+ "education": _parse_education(sections.get("education", "")),
509
+ "projects": sections.get("projects", "").strip(),
510
+ },
511
+ }
512
+
513
+
514
+ # ---------------------------------------------------------------------------
515
+ # CLI — python cv_chunker.py [file.md]
516
+ # ---------------------------------------------------------------------------
517
+
518
+ if __name__ == "__main__":
519
+ import json, sys
520
+
521
+ if len(sys.argv) > 1:
522
+ with open(sys.argv[1]) as f:
523
+ md = f.read()
524
+ else:
525
+ md = """
526
+ # Jane Doe
527
+ Software Engineer
528
+
529
+ ## Summary
530
+ Results-driven full-stack developer with 4 years of experience.
531
+
532
+ ## Skills
533
+ Python, JavaScript, React, Node.js, PostgreSQL, Docker, Git, REST API
534
+
535
+ ## Experience
536
+ Software Engineer at Safaricom PLC | Jan 2021 - Present
537
+ - Built microservices in Python and Node.js
538
+ - Led migration from monolith to Docker-based deployment
539
+
540
+ Junior Developer, Andela Kenya | Mar 2019 - Dec 2020
541
+ - Developed React dashboards for internal tooling
542
+ - Wrote REST API integrations with PostgreSQL backend
543
+
544
+ ## Education
545
+ Machakos University BACHELOR'S DEGREE, Electrical and Electronics Engineering | Sep 2017 - Apr 2023
546
+ Kisii National Polytechnic CERTIFICATE, Computer Support and Maintenance | Mar 2017 - Aug 2017
547
+
548
+ VOLUNTEER & LEADERSHIP
549
+ Cardinal Otunga High School CERTIFICATE, KCSE | Jan 2013 - Dec 2016
550
+ ELC Machakos Vice President and President | 2018 - 2021
551
+ Kangundo Boys | Mentor Mentored students on academics and career development | 2018 - 2022
552
+
553
+ ## Projects
554
+ Built an open-source CLI tool for job board scraping (github.com/jane/scraper)
555
+ """
556
 
557
+ result = chunk_cv(md)
558
+ print(json.dumps(result, indent=2))