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

update chunker

Browse files
Files changed (2) hide show
  1. main.py +10 -1
  2. services/cv_chunker.py +639 -182
main.py CHANGED
@@ -110,7 +110,16 @@ async def process_cv(file: UploadFile = File(...)):
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,
 
110
  "seniority": chunks["seniority"],
111
  "years_experience": chunks["years_experience"],
112
  "category": chunks["category"],
113
+ "chunks": {
114
+ "summary": chunks["chunks"]["summary"],
115
+ "contact": chunks["chunks"]["contact"],
116
+ "links": chunks["chunks"]["links"],
117
+ "skills": chunks["chunks"]["skills"],
118
+ "experience": chunks["chunks"]["experience"],
119
+ "education": chunks["chunks"]["education"],
120
+ "projects": chunks["chunks"]["projects"],
121
+ "awards": chunks["chunks"]["awards"],
122
+ },
123
  "file_type": conversion.file_type,
124
  "method_used": conversion.method_used,
125
  "is_scanned": conversion.is_scanned,
services/cv_chunker.py CHANGED
@@ -4,7 +4,7 @@ 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]] = {
@@ -42,17 +42,34 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
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]] = {
@@ -64,20 +81,68 @@ DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
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()
@@ -102,14 +167,17 @@ def _infer_category(text: str, skills: Set[str], category_skills: Dict[str, Set[
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
@@ -120,6 +188,7 @@ def _extract_years(text: str) -> int:
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
@@ -139,154 +208,338 @@ def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
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)
@@ -296,16 +549,32 @@ def _parse_experience(raw: str) -> List[Dict[str, Any]]:
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]]:
@@ -315,45 +584,104 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
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")]
@@ -361,104 +689,207 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
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
  # ---------------------------------------------------------------------------
@@ -467,7 +898,7 @@ def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
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
  -------
@@ -477,28 +908,36 @@ def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
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),
@@ -507,6 +946,7 @@ def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
507
  "experience": _parse_experience(sections.get("experience", "")),
508
  "education": _parse_education(sections.get("education", "")),
509
  "projects": sections.get("projects", "").strip(),
 
510
  },
511
  }
512
 
@@ -516,42 +956,59 @@ def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
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)
 
4
  from typing import Any, Dict, List, Optional, Set, Tuple
5
 
6
  # ---------------------------------------------------------------------------
7
+ # Skill taxonomy
8
  # ---------------------------------------------------------------------------
9
 
10
  DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
 
42
  "rest api": ["rest api", "restful api", "api"],
43
  "git": ["git", "github", "gitlab"],
44
  "docker": ["docker"],
45
+ "ui design": ["ui design", "user interface design"],
46
+ "ux design": ["ux design", "user experience design"],
47
  "figma": ["figma"],
48
  "wireframing": ["wireframe", "wireframing"],
49
  "prototyping": ["prototype", "prototyping"],
50
  "seo": ["seo", "search engine optimization"],
51
+ "content writing": ["content writing", "copywriting"],
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
+ "spring boot": ["spring boot", "spring"],
57
+ "ci/cd": ["ci/cd", "ci cd", "github actions", "jenkins", "gitlab ci", "pipelines"],
58
+ "kubernetes": ["kubernetes", "k8s"],
59
+ "aws": ["aws", "amazon web services"],
60
+ "azure": ["azure", "microsoft azure"],
61
+ "gcp": ["gcp", "google cloud"],
62
+ "flutter": ["flutter"],
63
+ "dart": ["dart"],
64
+ "swift": ["swift"],
65
+ "ios": ["ios", "xcode"],
66
+ "c#": ["c#", "csharp", "c sharp"],
67
+ "c++": ["c++", "cpp"],
68
+ "rust": ["rust"],
69
+ "go": ["golang", "go lang"],
70
+ "redis": ["redis"],
71
+ "elasticsearch": ["elasticsearch", "elastic search"],
72
+ "graphql": ["graphql"],
73
  }
74
 
75
  DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
 
81
  "html", "css", "javascript", "typescript", "react", "next.js", "vue", "angular",
82
  "tailwind css", "node.js", "express.js", "python", "java", "kotlin", "android", "php",
83
  "laravel", "mysql", "postgresql", "mongodb", "rest api", "git", "docker",
84
+ "spring boot", "ci/cd", "kubernetes", "aws", "azure", "gcp", "flutter", "dart",
85
+ "swift", "ios", "c#", "c++", "rust", "go", "redis", "graphql",
86
  },
87
  "Design & Creative": {"ui design", "ux design", "figma", "wireframing", "prototyping"},
88
  "Marketing & Growth": {"seo", "content writing", "digital marketing"},
89
+ "Data & Analytics": {"sql", "python", "machine learning", "data analysis", "microsoft excel", "elasticsearch"},
90
  }
91
 
92
  SENIORITY_PATTERNS: Dict[str, List[str]] = {
93
+ "intern": ["intern", "internship", "trainee", "industrial attachment"],
94
+ "junior": ["junior", "entry level", "entry-level", "assistant", "fresh graduate", "graduate"],
95
  "mid": ["mid", "officer", "specialist", "developer", "designer", "engineer"],
96
+ "senior": ["senior", "lead", "manager", "head", "principal", "architect", "director", "vp", "vice president"],
97
  }
98
  SENIORITY_ORDER: Dict[str, int] = {"intern": 0, "junior": 1, "mid": 2, "senior": 3}
99
 
100
+ # Words that look like "City, Country" but are actually tech terms — excluded from location detection
101
+ _TECH_LOC_BLACKLIST: Set[str] = {
102
+ "java", "spring", "boot", "sql", "python", "node", "react", "angular", "vue", "docker",
103
+ "linux", "windows", "android", "swift", "kotlin", "scala", "ruby", "rails", "django",
104
+ "flask", "express", "mongo", "postgres", "redis", "kafka", "hadoop", "spark", "airflow",
105
+ "jenkins", "gitlab", "github", "bitbucket", "jira", "confluence", "slack", "figma",
106
+ }
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Markdown / HTML cleanup helpers
111
+ # ---------------------------------------------------------------------------
112
+
113
+ # Strips **bold**, *italic*, `code`, keeping visible text; [label](url) → label
114
+ _MD_INLINE_RE = re.compile(
115
+ r"\*{1,3}([^*\n]*?)\*{1,3}" # bold/italic
116
+ r"|_{1,2}([^_\n]*?)_{1,2}" # underscore emphasis
117
+ r"|`([^`\n]+)`" # inline code
118
+ r"|\[([^\]]*)\]\([^)]*\)" # [label](url) → label
119
+ r"|\[([^\]]*)\]\[[^\]]*\]" # [label][ref]
120
+ )
121
+
122
+
123
+ def _strip_md(text: str) -> str:
124
+ def _repl(m: re.Match) -> str:
125
+ return next((g for g in m.groups() if g is not None), "")
126
+ return re.sub(r"\s+", " ", _MD_INLINE_RE.sub(_repl, text)).strip()
127
+
128
+
129
+ def _strip_html(text: str) -> str:
130
+ """Remove HTML tags; replace <br> variants with a space."""
131
+ text = re.sub(r"<br\s*/?>", " ", text, flags=re.IGNORECASE)
132
+ return re.sub(r"<[^>]+>", " ", text)
133
+
134
+
135
+ def _clean_line(raw: str) -> str:
136
+ """Strip heading markers, HTML, and inline markdown from a line."""
137
+ line = re.sub(r"^#+\s*", "", raw)
138
+ line = _strip_html(line)
139
+ line = _strip_md(line)
140
+ return re.sub(r"\s+", " ", line).strip()
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Normalisation & skill helpers
145
+ # ---------------------------------------------------------------------------
146
 
147
  def _normalize(text: str) -> str:
148
  text = (text or "").lower()
 
167
  text_norm = _normalize(text)
168
  title_keywords = {
169
  "Admin & Stock": ["stock", "inventory", "warehouse", "admin", "office", "cashier"],
170
+ "Software Engineering": ["developer", "engineer", "programmer", "frontend", "backend", "full stack", "mobile", "fullstack"],
171
+ "Design & Creative": ["designer", "ui", "ux", "creative", "graphic"],
172
+ "Marketing & Growth": ["marketing", "seo", "content", "social media", "growth"],
173
+ "Data & Analytics": ["data", "analyst", "analytics", "machine learning", "ai", "scientist"],
174
  }
175
  best, best_score = "Other", 0.0
176
  for cat, cat_skills in category_skills.items():
177
+ score = (
178
+ len(skills & cat_skills) * 2.0
179
+ + sum(1 for kw in title_keywords.get(cat, []) if kw in text_norm) * 1.25
180
+ )
181
  if score > best_score:
182
  best_score, best = score, cat
183
  return best
 
188
  patterns = [
189
  r"(\d+)\+?\s*(?:years|year|yrs|yr)\s*(?:of)?\s*(?:experience|exp)",
190
  r"experience\s*(?:of)?\s*(\d+)\+?\s*(?:years|year|yrs|yr)",
191
+ r"(\d+)\+?\s*(?:years|year|yrs|yr)\s+(?:in\s+)?(?:the\s+)?(?:industry|field|software|development)",
192
  ]
193
  years = [int(m.group(1)) for p in patterns for m in re.finditer(p, text_norm)]
194
  return max(years) if years else 0
 
208
  return "junior" if is_cv else "mid"
209
 
210
 
211
+ # ---------------------------------------------------------------------------
212
+ # CV title extractor
213
+ # Handles: standalone title line, title embedded in summary, "Name\nTitle" format
214
+ # ---------------------------------------------------------------------------
 
 
 
 
 
 
 
215
 
216
+ _TITLE_ROLE_WORDS = [
217
+ "officer", "developer", "engineer", "designer", "assistant", "accountant",
218
+ "manager", "marketing", "stock", "cashier", "admin", "student", "intern",
219
+ "analyst", "teacher", "architect", "consultant", "programmer", "researcher",
220
+ "specialist", "technician", "coordinator", "director", "executive", "lead",
221
+ "scientist", "strategist", "advisor", "trainer",
222
+ ]
223
 
224
+ _TITLE_PHRASE_RE = re.compile(
225
+ r"\b((?:(?:full[\s\-]?stack|front[\s\-]?end|back[\s\-]?end|senior|junior|lead|"
226
+ r"mid[\s\-]?level|entry[\s\-]?level)\s+)?(?:[\w\-]+\s){0,3}"
227
+ r"(?:developer|engineer|designer|analyst|manager|specialist|consultant|architect|"
228
+ r"programmer|researcher|officer|director|executive|scientist|trainer))\b",
229
+ re.IGNORECASE,
230
+ )
231
+
232
+
233
+ def _extract_cv_title(cv_text: str) -> str:
234
+ clean_lines = [_clean_line(x) for x in cv_text.splitlines() if x.strip()]
235
+
236
+ # Pass 1: short standalone line with a role keyword (skip the very first line — usually the name)
237
+ for line in clean_lines[1:16]:
238
+ stripped = line.strip("| \t")
239
+ if (
240
+ len(stripped) <= 80
241
+ and any(w in stripped.lower() for w in _TITLE_ROLE_WORDS)
242
+ # Must not look like a contact / URL / date line
243
+ and not re.search(r"[@http://|+\d{6}]", stripped)
244
+ and not re.search(r"\d{4}\s*[-–]\s*(?:\d{4}|present)", stripped, re.IGNORECASE)
245
+ ):
246
+ return stripped.title()
247
+
248
+ # Pass 2: extract role phrase from the first ~600 chars of visible text
249
+ head = " ".join(clean_lines[:30])[:600]
250
+ m = _TITLE_PHRASE_RE.search(head)
251
+ if m:
252
+ return m.group(1).strip().title()
253
+
254
+ return "Unknown"
255
 
256
 
257
  # ---------------------------------------------------------------------------
258
+ # Date helpers (shared across parsers)
259
  # ---------------------------------------------------------------------------
260
 
261
+ _MONTH_PAT = r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)"
262
+ _YEAR_PAT = r"\d{4}"
263
+ _DATE_PAT = rf"(?:{_MONTH_PAT}\s+)?{_YEAR_PAT}"
264
+
265
  _PERIOD_RE = re.compile(
266
+ rf"({_DATE_PAT})\s*[-–—to]+\s*({_DATE_PAT}|Present|Current|Now|Till\s+date|To\s+date|Ongoing)",
267
  re.IGNORECASE,
268
  )
269
  _YEAR_ONLY_RE = re.compile(
270
+ rf"({_YEAR_PAT})\s*[-–—to]+\s*({_YEAR_PAT}|Present|Current|Now|Ongoing)",
271
  re.IGNORECASE,
272
  )
273
 
274
 
275
+ def _extract_period(text: str) -> Optional[str]:
276
+ m = _PERIOD_RE.search(text)
277
  if m:
278
  return f"{m.group(1)} - {m.group(2)}"
279
+ m = _YEAR_ONLY_RE.search(text)
280
  if m:
281
  return f"{m.group(1)} - {m.group(2)}"
282
  return None
283
 
284
 
285
+ def _strip_period(text: str) -> str:
286
+ text = _PERIOD_RE.sub("", text)
287
+ text = _YEAR_ONLY_RE.sub("", text)
288
+ return re.sub(r"[\|·•]\s*$", "", text).strip(" |·•–—-,()")
289
 
290
 
291
  # ---------------------------------------------------------------------------
292
+ # Section splitter
293
+ # Guards against false positives: bullets, digits, date lines, long prose
294
  # ---------------------------------------------------------------------------
295
 
296
+ _SECTION_KEYWORDS: Dict[str, List[str]] = {
297
+ "summary": [
298
+ "summary", "profile", "about me", "objective", "career summary",
299
+ "professional summary", "executive summary", "personal statement",
300
+ "about", "bio", "career objective", "professional profile",
301
+ ],
302
+ "contact": [
303
+ "contact", "contact information", "contact details", "personal details",
304
+ "personal information", "details", "reach me",
305
+ ],
306
+ "links": [
307
+ "links", "online profiles", "social media", "web presence",
308
+ "profiles", "social profiles", "online presence", "web profiles",
309
+ ],
310
+ "skills": [
311
+ "skills", "technical skills", "core skills", "competencies",
312
+ "key skills", "areas of expertise", "technologies", "tech stack",
313
+ "tools", "expertise", "capabilities", "core competencies",
314
+ "technical expertise", "skills & tools",
315
+ ],
316
+ "experience": [
317
+ "experience", "work experience", "professional experience", "employment",
318
+ "work history", "career history", "career", "employment history",
319
+ "relevant experience", "professional background", "internship",
320
+ "internships", "volunteer", "volunteering",
321
+ ],
322
+ "education": [
323
+ "education", "academic background", "academic history", "qualifications",
324
+ "educational background", "academics", "training", "certifications",
325
+ "degrees", "academic qualifications", "schools",
326
+ ],
327
+ "projects": [
328
+ "projects", "personal projects", "key projects", "notable projects",
329
+ "open source", "portfolio", "side projects", "selected projects",
330
+ "technical projects",
331
+ ],
332
+ "awards": [
333
+ "awards", "honors", "honours", "achievements", "accomplishments",
334
+ "recognition", "publications", "research",
335
+ ],
336
+ "languages": [
337
+ "languages spoken", "spoken languages", "human languages",
338
+ "language proficiency",
339
+ ],
340
+ }
341
+
342
  _BULLET_RE = re.compile(r"^[-•*▪►▸>]\s+")
343
 
344
+
345
+ def _detect_section(stripped_line: str, raw_line: str) -> Optional[str]:
346
+ """
347
+ Return the section key if this line is a section header, else None.
348
+
349
+ Heuristics applied before keyword matching to prevent false positives:
350
+ - Bullet lines are never headers
351
+ - Lines starting with digits (dates, phone numbers) are never headers
352
+ - Lines containing date ranges are never headers
353
+ - Lines longer than 60 normalised chars are likely prose, not headers
354
+ - Lines with more than 7 words are likely prose
355
+ """
356
+ if _BULLET_RE.match(raw_line.strip()):
357
+ return None
358
+
359
+ line_norm = _normalize(_strip_md(_strip_html(stripped_line)))
360
+
361
+ if not line_norm:
362
+ return None
363
+ if re.match(r"^\d", line_norm): # starts with digit
364
+ return None
365
+ if _PERIOD_RE.search(stripped_line): # contains date range
366
+ return None
367
+ if _YEAR_ONLY_RE.search(stripped_line): # year-only range
368
+ return None
369
+ if len(line_norm) > 60: # too long to be a header
370
+ return None
371
+ if len(line_norm.split()) > 7: # too many words
372
+ return None
373
+ # Must contain at least one alphabetic character
374
+ if not re.search(r"[a-z]", line_norm):
375
+ return None
376
+
377
+ for section, keywords in _SECTION_KEYWORDS.items():
378
+ for kw in keywords:
379
+ if (
380
+ line_norm == kw
381
+ or line_norm.replace(" ", "") == kw.replace(" ", "")
382
+ or kw in line_norm
383
+ ):
384
+ return section
385
+
386
+ return None
387
+
388
+
389
+ def _parse_cv_sections(cv_text: str) -> Dict[str, str]:
390
+ current = "summary"
391
+ sections: Dict[str, List[str]] = {k: [] for k in _SECTION_KEYWORDS}
392
+
393
+ for raw_line in cv_text.splitlines():
394
+ stripped = re.sub(r"^#+\s*", "", raw_line).strip()
395
+ if not stripped:
396
+ continue
397
+
398
+ section = _detect_section(stripped, raw_line)
399
+ if section:
400
+ current = section
401
+ continue
402
+
403
+ sections[current].append(raw_line)
404
+
405
+ return {k: "\n".join(v).strip() for k, v in sections.items()}
406
+
407
+
408
+ # ---------------------------------------------------------------------------
409
+ # Experience parser
410
+ # Handles:
411
+ # A) "Role at Company | Date" (single line)
412
+ # B) "### Company\n**Role** | Date" (company header, role sub-header)
413
+ # C) "Company\nRole\nDate" (three separate lines)
414
+ # D) Table rows with pipe separators
415
+ # ---------------------------------------------------------------------------
416
+
417
  _ROLE_WORDS = {
418
  "engineer", "developer", "manager", "designer", "analyst", "intern", "officer",
419
  "lead", "head", "director", "consultant", "assistant", "specialist", "coordinator",
420
+ "technician", "architect", "programmer", "researcher", "executive", "trainer",
421
+ "scientist", "strategist", "advisor", "supervisor", "associate", "fellow",
422
  }
423
 
424
 
425
  def _split_role_company(text: str) -> Tuple[str, str]:
426
+ """
427
+ Split 'Role at Company', 'Company | Role', 'Role — Company', etc.
428
+ Returns (role, company). If unclear, treats first part as role.
429
+ """
430
+ # Try various separators in priority order
431
+ for pat in [r"\s+(?:at|@|with)\s+", r"\s*\|\s*", r"\s*[—–,]\s+"]:
432
  parts = re.split(pat, text, maxsplit=1)
433
  if len(parts) == 2:
434
+ a, b = parts[0].strip().rstrip(","), parts[1].strip()
435
  a_is_role = any(w in a.lower() for w in _ROLE_WORDS)
436
  b_is_role = any(w in b.lower() for w in _ROLE_WORDS)
437
  if a_is_role and not b_is_role:
438
  return a, b
439
  if b_is_role and not a_is_role:
440
  return b, a
441
+ # Both or neither match — assume role | company order
442
+ return a, b
443
  return "", text
444
 
445
 
446
  def _parse_experience(raw: str) -> List[Dict[str, Any]]:
447
  entries: List[Dict[str, Any]] = []
448
+
449
+ def _new() -> Dict[str, Any]:
450
+ return {"role": "", "company": "", "period": None, "responsibilities": []}
451
+
452
  current: Optional[Dict[str, Any]] = None
453
 
454
  for raw_line in raw.splitlines():
455
+ line = _clean_line(raw_line)
456
  if not line:
457
  continue
458
 
459
+ # Skip lines that are obviously sub-section labels (e.g. "Key Achievements:")
460
+ if re.match(r"^[\w\s]+:\s*$", line) and len(line) < 40:
461
+ continue
462
+
463
+ period = _extract_period(line)
464
+ is_bullet = bool(_BULLET_RE.match(line))
465
+ clean = _strip_period(_BULLET_RE.sub("", line)).strip()
466
 
467
+ # ── Bullet / responsibility line ──────────────────────────────────
468
  if is_bullet:
469
  if current is not None and clean:
470
  current["responsibilities"].append(clean)
471
  continue
472
 
473
+ # ── Stand-alone date line ─────────────────────────────────────────
474
  if period and not clean:
 
475
  if current is not None and not current["period"]:
476
  current["period"] = period
477
  continue
478
 
479
+ # ── Line with both content and a date ────────────────────────────
480
+ if period and clean:
481
+ role, company = _split_role_company(clean)
482
+
483
+ # If current entry is incomplete (missing period), fill it in
484
+ if (
485
+ current is not None
486
+ and not current["period"]
487
+ and (current["role"] or current["company"])
488
+ ):
489
+ # The date belongs to the already-open entry; the content may
490
+ # supply the missing role or company
491
+ if not current["role"] and role:
492
+ current["role"] = role
493
+ if not current["company"] and company:
494
+ current["company"] = company
495
  current["period"] = period
 
 
 
496
  else:
497
  if current:
498
  entries.append(current)
499
+ current = _new()
500
+ current["role"] = role
501
+ current["company"] = company
502
+ current["period"] = period
503
  continue
504
 
505
+ # ── Plain header line (no date, no bullet) ────────────────────────
506
+ # Could be company name, job title, or continuation of previous header
507
+ is_role_line = any(w in clean.lower() for w in _ROLE_WORDS)
508
+
509
+ if current is None:
510
+ # Start first entry
511
+ role, company = _split_role_company(clean)
512
+ current = _new()
513
+ current["role"] = role
514
+ current["company"] = company
515
+
516
+ elif not current["role"] and not current["company"]:
517
+ # Completely empty entry — fill it
518
+ role, company = _split_role_company(clean)
519
+ current["role"] = role
520
+ current["company"] = company
521
+
522
+ elif (not current["role"] or not current["company"]) and not current["period"]:
523
+ # Incomplete entry (only company OR only role) — try to complete it
524
+ if not current["role"] and is_role_line:
525
+ current["role"] = clean
526
+ elif not current["company"] and not is_role_line:
527
+ current["company"] = clean
528
+ else:
529
+ # Ambiguous — start a new entry
530
+ entries.append(current)
531
+ role, company = _split_role_company(clean)
532
+ current = _new()
533
+ current["role"] = role
534
+ current["company"] = company
535
+
536
+ else:
537
+ # Current entry already complete — start a new one
538
  entries.append(current)
539
+ role, company = _split_role_company(clean)
540
+ current = _new()
541
+ current["role"] = role
542
+ current["company"] = company
543
 
544
  if current:
545
  entries.append(current)
 
549
 
550
  # ---------------------------------------------------------------------------
551
  # Education parser
552
+ # Handles:
553
+ # A) "University DEGREE, Field | Date" (all on one line)
554
+ # B) "University\nBSc Computer Science\n2018-2022" (three lines)
555
+ # C) Markdown table rows "| University | Degree | Date |"
556
+ # D) Degree then institution on separate lines
557
  # ---------------------------------------------------------------------------
558
 
559
  _DEGREE_RE = re.compile(
560
+ r"\b(bachelor(?:'s)?|master(?:'s)?|phd|ph\.d|doctorate|diploma|certificate|"
561
+ r"degree|bsc|msc|b\.sc|m\.sc|ba|ma|mba|hnd|hons|honours|kcse|kcpe|btec|"
562
+ r"associate(?:'s)?|advanced\s+diploma)\b",
563
  re.IGNORECASE,
564
  )
565
  _INSTITUTION_RE = re.compile(
566
+ r"\b(university|college|school|institute|polytechnic|academy|"
567
+ r"institution|faculty|campus)\b",
568
+ re.IGNORECASE,
569
+ )
570
+ # Sub-section labels to skip (volunteer, leadership, etc. within education block)
571
+ _EDU_SKIP_RE = re.compile(
572
+ r"^(volunteer|leadership|activities|honors?|awards?|publications?|"
573
+ r"extracurricular|memberships?|certifications?)\b",
574
  re.IGNORECASE,
575
  )
576
+ # Table separator rows like "| --- | --- |"
577
+ _TABLE_SEP_RE = re.compile(r"^\|[\s\-|:]+\|$")
578
 
579
 
580
  def _parse_education(raw: str) -> List[Dict[str, str]]:
 
584
  def _flush() -> None:
585
  if current.get("institution") or current.get("degree"):
586
  entries.append({
587
+ "institution": current.get("institution", "").strip(),
588
+ "degree": current.get("degree", "").strip(),
589
+ "period": current.get("period", "").strip(),
590
  })
591
  current.clear()
592
 
593
  for raw_line in raw.splitlines():
594
+ # Strip table separators
595
+ stripped_raw = raw_line.strip()
596
+ if _TABLE_SEP_RE.match(stripped_raw):
597
+ continue
598
+
599
+ # Handle pipe-delimited table cells: split, clean each cell
600
+ if stripped_raw.startswith("|") and stripped_raw.endswith("|"):
601
+ cells = [_clean_line(c) for c in stripped_raw.strip("|").split("|")]
602
+ cells = [c for c in cells if c]
603
+ if not cells:
604
+ continue
605
+ # Treat first cell as institution/degree, last cell as period
606
+ line = cells[0]
607
+ extra_period = _extract_period(cells[-1]) if len(cells) > 1 else None
608
+ else:
609
+ line = _clean_line(raw_line)
610
+ extra_period = None
611
+
612
  line = _BULLET_RE.sub("", line).strip()
613
  if not line:
614
  continue
615
 
616
+ # Skip volunteer/leadership sub-sections embedded in education
617
+ if _EDU_SKIP_RE.match(line) and len(line) < 60:
618
+ _flush()
619
+ continue
620
+
621
+ period = _extract_period(line) or extra_period
622
+ clean = _strip_period(line).strip()
623
  if not clean:
624
  if period and current:
625
  current["period"] = period
626
  continue
627
 
628
  has_degree = bool(_DEGREE_RE.search(clean))
629
+ has_inst = bool(_INSTITUTION_RE.search(clean))
630
 
631
+ if has_degree and has_inst:
632
+ # Both on same line → split at degree keyword boundary
633
+ deg_m = _DEGREE_RE.search(clean)
634
+ institution = clean[:deg_m.start()].strip(" ,–—|") if deg_m else ""
635
+ degree = clean[deg_m.start():].strip() if deg_m else clean
636
  _flush()
637
+ current["institution"] = institution
638
+ current["degree"] = degree
639
+ current["period"] = period or ""
640
+
641
+ elif has_degree:
642
+ if current.get("institution") and not current.get("degree"):
643
+ # Institution already collected → complement it with degree
644
+ current["degree"] = clean
645
+ if period:
646
+ current["period"] = period
647
+ else:
648
+ _flush()
649
+ current["degree"] = clean
650
+ current["institution"] = ""
651
+ current["period"] = period or ""
652
+
653
+ elif has_inst:
654
+ if current.get("degree") and not current.get("institution"):
655
+ # Degree already collected → complement it with institution
656
+ current["institution"] = clean
657
+ if period:
658
+ current["period"] = period
659
+ else:
660
+ _flush()
661
+ current["institution"] = clean
662
+ current["degree"] = ""
663
+ current["period"] = period or ""
664
+
665
  elif period:
666
+ # Date-only or plain line with date
667
  if current:
668
  current["period"] = period
669
+ if clean and not current.get("degree"):
670
+ current["degree"] = clean
671
  else:
672
  current["institution"] = clean
673
+ current["period"] = period
674
+
675
  else:
676
+ # Plain line — could be field of study, GPA, or institution continuation
677
+ if current and not current.get("institution") and not has_degree:
678
+ current["institution"] = clean
679
+ elif current and not current.get("degree"):
680
+ current["degree"] = clean
681
+ else:
682
+ _flush()
683
+ current["institution"] = clean
684
+ current["period"] = ""
685
 
686
  _flush()
687
  return [e for e in entries if e.get("institution") or e.get("degree")]
 
689
 
690
  # ---------------------------------------------------------------------------
691
  # Contact parser
692
+ # Handles various contact line formats:
693
+ # "email | phone | City, Country"
694
+ # "Email: ...", "Phone: ...", "Location: ..."
695
+ # Contact info embedded in CV header
696
  # ---------------------------------------------------------------------------
697
 
698
  _EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}")
699
+ _PHONE_RE = re.compile(r"(?:\+?[\d][\d\s().\-]{6,}\d)")
700
  _LOCATION_RE = re.compile(
701
+ r"\b([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\s*,\s*([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\b"
702
+ )
703
+ # Labelled patterns: "Location: Nairobi, Kenya"
704
+ _LABELLED_RE = re.compile(
705
+ r"\b(?:location|address|city|based\s+in|residing\s+in|located\s+in)\s*[:\-]?\s*([^\n|•·,]+(?:,\s*[^\n|•·]+)?)",
706
+ re.IGNORECASE,
707
  )
708
 
709
 
710
  def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
711
  """
712
+ Extract email, phone, and location.
713
+
714
+ Strategy:
715
+ - Email/phone: search the dedicated contact section, or the first 600 chars of the CV.
716
+ - Location: first try labelled patterns ("Location: X"), then "City, Country" pattern
717
+ restricted to the contact section or first 8 header lines to avoid
718
+ false positives from technical skills text.
719
  """
720
+ search_text = raw if raw.strip() else cv_full[:600]
721
+
722
+ email_m = _EMAIL_RE.search(search_text)
723
+ phone_m = _PHONE_RE.search(search_text)
724
+
725
+ # Location search area — never scan deep into CV body
726
+ if raw.strip():
727
+ loc_text = raw
728
+ else:
729
+ header_lines = [ln for ln in cv_full.splitlines() if ln.strip()][:8]
730
+ loc_text = "\n".join(header_lines)
731
 
732
+ location = ""
733
+
734
+ # 1. Labelled location ("Location: Nairobi, Kenya")
735
+ lbl_m = _LABELLED_RE.search(loc_text)
736
+ if lbl_m:
737
+ location = lbl_m.group(1).strip()
738
+ else:
739
+ # 2. "City, Country" pattern — exclude tech blacklist words
740
+ loc_m = _LOCATION_RE.search(loc_text)
741
+ if loc_m:
742
+ word1 = (loc_m.group(1) or "").lower()
743
+ word2 = (loc_m.group(2) or "").lower()
744
+ if word1 not in _TECH_LOC_BLACKLIST and word2 not in _TECH_LOC_BLACKLIST:
745
+ location = loc_m.group(0).strip()
746
 
747
  return {
748
+ "email": email_m.group(0).strip() if email_m else "",
749
+ "phone": phone_m.group(0).strip() if phone_m else "",
750
+ "location": location,
751
  }
752
 
753
 
754
  # ---------------------------------------------------------------------------
755
  # Links parser
756
+ # Handles: full URLs, bare domains, mailto: links, markdown [label](url) links
757
  # ---------------------------------------------------------------------------
758
 
759
+ _URL_RE = re.compile(r"(?:https?://|www\.)[^\s,;\"'>()\]]+", re.IGNORECASE)
760
+ _BARE_DOMAIN_RE = re.compile(
761
+ r"(?:github\.com|linkedin\.com|behance\.net|dribbble\.com|medium\.com"
762
+ r"|dev\.to|twitter\.com|x\.com|gitlab\.com|bitbucket\.org)"
763
+ r"[^\s,;\"'>()\]]*",
764
  re.IGNORECASE,
765
  )
766
+ _MAILTO_RE = re.compile(r"mailto:([\w.+-]+@[\w-]+\.[a-zA-Z]{2,})", re.IGNORECASE)
767
 
768
  _PLATFORM_MAP: List[Tuple[str, str]] = [
769
+ ("github.com", "GitHub"),
770
+ ("gitlab.com", "GitLab"),
771
+ ("bitbucket.org", "Bitbucket"),
772
+ ("linkedin.com", "LinkedIn"),
773
+ ("behance.net", "Behance"),
774
+ ("dribbble.com", "Dribbble"),
775
+ ("medium.com", "Medium"),
776
+ ("dev.to", "Dev.to"),
777
+ ("twitter.com", "Twitter"),
778
+ ("x.com", "X (Twitter)"),
779
+ ("vercel.app", "Portfolio"),
780
+ ("netlify.app", "Portfolio"),
781
+ ("github.io", "Portfolio"),
782
  ]
783
 
784
+ _LABEL_HINTS = {
785
+ "github": "GitHub", "gitlab": "GitLab", "bitbucket": "Bitbucket",
786
+ "linkedin": "LinkedIn", "behance": "Behance", "dribbble": "Dribbble",
787
+ "medium": "Medium", "twitter": "Twitter", "portfolio": "Portfolio",
788
+ "website": "Website", "blog": "Blog", "personal": "Portfolio",
789
+ }
790
+
791
 
792
  def _label_url(url: str, context_line: str) -> str:
793
+ """Identify platform from URL first, then from markdown label text."""
794
+ url_lower = url.lower()
795
+
796
+ # 1. Match by URL domain (most reliable — avoids cross-contamination)
797
+ for domain, label in _PLATFORM_MAP:
798
+ if domain in url_lower:
799
+ return label
800
+
801
+ # 2. Match by markdown link label text: [Label](url)
802
+ escaped = re.escape(url.split("?")[0].rstrip("/"))
803
+ md_m = re.search(r"\[([^\]]+)\]\s*\(" + escaped, context_line, re.IGNORECASE)
804
+ if md_m:
805
+ label_text = md_m.group(1).lower()
806
+ for hint, label in _LABEL_HINTS.items():
807
+ if hint in label_text:
808
+ return label
809
+
810
+ # 3. Infer from surrounding context text on the same line
811
+ ctx = context_line.lower()
812
+ for hint, label in _LABEL_HINTS.items():
813
+ if hint in ctx:
814
  return label
815
+
816
  return "Website"
817
 
818
 
819
  def _parse_links(raw: str, cv_full: str) -> List[Dict[str, str]]:
820
  """
821
+ Extract URLs from the dedicated links section or the CV header.
822
+ Handles full URLs, bare domains, and mailto: links.
823
+ Returns [{"label": str, "url": str}, ...].
824
  """
825
+ # Search dedicated links section first; fall back to first 1500 chars of CV
826
+ search_text = raw if raw.strip() else cv_full[:1500]
827
  results: List[Dict[str, str]] = []
828
+ seen: Set[str] = set()
829
 
830
  for line in search_text.splitlines():
831
+ # Collect URLs from this line — process each independently so labels don't bleed
832
+ found: List[str] = []
833
+
834
  for m in _URL_RE.finditer(line):
835
+ found.append(m.group(0).rstrip(".,:;)\"'"))
836
+
837
+ # Bare domain links not already captured by full URL regex
838
+ for m in _BARE_DOMAIN_RE.finditer(line):
839
+ url = m.group(0).rstrip(".,:;)\"'")
840
+ if not any(url in u for u in found):
841
+ found.append(url)
842
+
843
+ for url in found:
844
  normalised = url if url.startswith("http") else f"https://{url}"
845
+ if normalised in seen:
846
+ continue
847
+ seen.add(normalised)
848
+ results.append({"label": _label_url(normalised, line), "url": normalised})
849
 
850
  return results
851
 
852
 
853
  # ---------------------------------------------------------------------------
854
  # Skills parser
855
+ # Handles: comma-separated, pipe-separated, bullet per skill, "Category: x, y, z"
856
  # ---------------------------------------------------------------------------
857
 
858
+ # Strip "Languages:", "**Frameworks:**", "Tools & Technologies:" prefixes
859
+ _SKILL_PREFIX_RE = re.compile(r"^\*{0,2}[\w][\w\s&/()+\-]+:\*{0,2}\s*")
860
+
861
+
862
  def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
863
  canonical = sorted(_extract_skills(cv_full, DEFAULT_SKILL_ALIASES))
864
 
865
  raw_items: List[str] = []
866
  for line in raw.splitlines():
867
+ line = _clean_line(line) # strip #, HTML, markdown
868
  line = _BULLET_RE.sub("", line).strip()
869
+ line = _SKILL_PREFIX_RE.sub("", line).strip() # strip "Languages: " etc.
870
+
871
+ # Split on common skill delimiters including bullet-like separators
872
+ for item in re.split(r"[,|;•·/]", line):
873
+ item = re.sub(r"^\W+|\W+$", "", item).strip() # strip leading/trailing non-word chars
874
+ # Skip empty, too-long, or obviously non-skill strings
875
+ if (
876
+ item
877
+ and 1 < len(item) < 60
878
+ and not re.match(r"^\d+$", item) # pure numbers
879
+ and not re.search(r"@|http|www\.", item) # emails/URLs
880
+ ):
881
  raw_items.append(item)
882
 
883
+ # Deduplicate while preserving order
884
+ seen_items: Set[str] = set()
885
+ deduped: List[str] = []
886
+ for item in raw_items:
887
+ key = item.lower()
888
+ if key not in seen_items:
889
+ seen_items.add(key)
890
+ deduped.append(item)
891
+
892
+ return {"items": deduped, "canonical": canonical}
893
 
894
 
895
  # ---------------------------------------------------------------------------
 
898
 
899
  def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
900
  """
901
+ Parse any CV markdown string into structured, cleaned chunks.
902
 
903
  Returns
904
  -------
 
908
  "years_experience": int,
909
  "category": str,
910
  "chunks": {
911
+ "summary": str,
912
+ "contact": {"email", "phone", "location"},
913
+ "links": [{"label", "url"}, ...],
914
+ "skills": {"items": [...], "canonical": [...]},
915
  "experience": [{"role", "company", "period", "responsibilities"}, ...],
916
+ "education": [{"institution", "degree", "period"}, ...],
917
+ "projects": str,
918
+ "awards": str,
919
  }
920
  }
921
  """
922
  sections = _parse_cv_sections(cv_markdown)
923
 
924
+ cv_title = _extract_cv_title(cv_markdown)
925
+ cv_years = _extract_years(cv_markdown)
 
 
926
  cv_skills = _extract_skills(cv_markdown, DEFAULT_SKILL_ALIASES)
927
  cv_category = _infer_category(cv_markdown, cv_skills, DEFAULT_CATEGORY_SKILLS)
928
 
929
+ seniority_text = (
930
+ cv_title + "\n"
931
+ + sections.get("experience", "")
932
+ + "\n" + cv_markdown[:600]
933
+ )
934
+ cv_seniority = _detect_seniority(seniority_text, is_cv=True)
935
+
936
  return {
937
+ "cv_title": cv_title,
938
+ "seniority": cv_seniority,
939
  "years_experience": cv_years,
940
+ "category": cv_category,
941
  "chunks": {
942
  "summary": sections.get("summary", "").strip(),
943
  "contact": _parse_contact(sections.get("contact", ""), cv_markdown),
 
946
  "experience": _parse_experience(sections.get("experience", "")),
947
  "education": _parse_education(sections.get("education", "")),
948
  "projects": sections.get("projects", "").strip(),
949
+ "awards": sections.get("awards", "").strip(),
950
  },
951
  }
952
 
 
956
  # ---------------------------------------------------------------------------
957
 
958
  if __name__ == "__main__":
959
+ import json
960
+ import sys
961
 
962
  if len(sys.argv) > 1:
963
+ with open(sys.argv[1], encoding="utf-8") as f:
964
  md = f.read()
965
  else:
966
+ md = """\
967
  # Jane Doe
968
+ Senior Software Engineer
969
+ jane@example.com | +254 712 345 678 | Nairobi, Kenya
970
+ https://github.com/jane | https://linkedin.com/in/jane | https://jane.dev
971
 
972
  ## Summary
973
+ Results-driven full-stack engineer with 6 years of experience building
974
+ scalable APIs and cloud-native applications.
975
+
976
+ ## Technical Skills
977
+ - **Languages:** Python, JavaScript, TypeScript, Go
978
+ - **Frameworks:** Django, FastAPI, React, Next.js
979
+ - **Databases:** PostgreSQL, MongoDB, Redis
980
+ - **DevOps:** Docker, Kubernetes, GitHub Actions (CI/CD), AWS
981
+ - **Tools:** Git, Figma, Jira
982
 
983
+ ## Professional Experience
 
984
 
985
+ ### Safaricom PLC
986
+ **Senior Software Engineer** | Jan 2021 – Present
987
+ - Led migration of monolithic payment service to microservices, reducing p99 latency by 40 %
988
+ - Designed and shipped REST API used by 2 M+ customers
989
 
990
+ Andela — Software Engineer | Mar 2019 – Dec 2020
991
+ - Built React dashboards for internal analytics
992
+ - Wrote integration tests with Jest, achieving 90 % coverage
993
+
994
+ ### Freelance
995
+ Junior Developer | Jan 2018 – Feb 2019
996
+ - Delivered 5 client websites using WordPress and PHP
997
 
998
  ## Education
999
+ University of Nairobi
1000
+ BSc Computer Science | 2014 – 2018
1001
 
1002
+ Strathmore University
1003
+ Certificate, Data Science | 2019
 
 
1004
 
1005
  ## Projects
1006
+ - **PayLink**: Real-time payment gateway built with Node.js and Stripe API
1007
+ - **JobScraper**: Open-source CLI tool — github.com/jane/jobscraper
1008
+
1009
+ ## Awards
1010
+ - Andela Fellowship Recipient, 2019
1011
+ - Finalist, Safaricom Hackathon, 2022
1012
  """
1013
 
1014
  result = chunk_cv(md)