Eng-Musa commited on
Commit
4d27703
Β·
1 Parent(s): 4b64bed

update job martching logic

Browse files
__pycache__/main.cpython-312.pyc CHANGED
Binary files a/__pycache__/main.cpython-312.pyc and b/__pycache__/main.cpython-312.pyc differ
 
services/__pycache__/cv_chunker.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/cv_chunker.cpython-312.pyc and b/services/__pycache__/cv_chunker.cpython-312.pyc differ
 
services/__pycache__/job_matcher.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/job_matcher.cpython-312.pyc and b/services/__pycache__/job_matcher.cpython-312.pyc differ
 
services/__pycache__/processor_utils.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/processor_utils.cpython-312.pyc and b/services/__pycache__/processor_utils.cpython-312.pyc differ
 
services/cv_chunker.py CHANGED
@@ -927,12 +927,28 @@ def chunk_cv(cv_markdown: str, embedder=None) -> Dict[str, Any]:
927
  if not skills_chunk["items"]:
928
  skills_chunk["items"] = sorted(list(cv_skills))
929
  experience_entries = _parse_experience(sections.get("experience", ""))
 
 
 
 
 
 
930
  education_entries = _parse_education(sections.get("education", ""))
931
  projects_entries = _parse_projects(sections.get("projects", ""))
932
  awards_entries = _parse_awards(sections.get("awards", ""))
933
 
934
- # ── Years of experience: date-ranges primary, text mention fallback ────
935
  computed_years = compute_years_from_experience(experience_entries)
 
 
 
 
 
 
 
 
 
 
936
  text_years = _extract_years(cv_markdown)
937
  cv_years = computed_years if computed_years > 0 else text_years
938
 
 
927
  if not skills_chunk["items"]:
928
  skills_chunk["items"] = sorted(list(cv_skills))
929
  experience_entries = _parse_experience(sections.get("experience", ""))
930
+
931
+ # If title extraction from header yielded Unknown, fallback to most recent job role
932
+ if (not cv_title or cv_title == "Unknown") and experience_entries:
933
+ first_role = (experience_entries[0].get("role") or "").strip()
934
+ if first_role and len(first_role.split()) <= 6:
935
+ cv_title = first_role.title()
936
  education_entries = _parse_education(sections.get("education", ""))
937
  projects_entries = _parse_projects(sections.get("projects", ""))
938
  awards_entries = _parse_awards(sections.get("awards", ""))
939
 
940
+ # ── Years of experience: date-ranges primary, raw experience scan secondary, text fallback ────
941
  computed_years = compute_years_from_experience(experience_entries)
942
+ if computed_years <= 0 and experience_entries:
943
+ # Fallback: scan experience section for distinct 4-digit calendar years
944
+ exp_raw = sections.get("experience", "")
945
+ found_years = sorted(set(int(y) for y in re.findall(r"\b(19\d{2}|20\d{2})\b", exp_raw)))
946
+ if len(found_years) >= 2:
947
+ min_y = min(found_years)
948
+ from datetime import datetime as _dt
949
+ max_y = _dt.now().year if re.search(r"present|current|now|ongoing", exp_raw, re.IGNORECASE) else max(found_years)
950
+ if 0 < (max_y - min_y) <= 45:
951
+ computed_years = max_y - min_y
952
  text_years = _extract_years(cv_markdown)
953
  cv_years = computed_years if computed_years > 0 else text_years
954
 
services/job_matcher.py CHANGED
@@ -1,6 +1,7 @@
1
  from __future__ import annotations
2
 
3
  import hashlib
 
4
  import json
5
  import threading
6
  from typing import Any, Dict, List, Optional, Set, Tuple
@@ -488,7 +489,7 @@ class JobMatcher:
488
  job_vecs = self._embed_batch_texts(job_texts)
489
 
490
  # ---- Batch 2: job title embeddings, ONE encode() call ----
491
- job_title_vecs = self._embed_title_batch([j.job_title for j in job_objs])
492
 
493
  # ---- Precompute exact skill matches + collect missing technical
494
  # skills across ALL jobs for a single batched semantic pass ----
@@ -519,7 +520,7 @@ class JobMatcher:
519
  individual_skills_vecs = cv_data["individual_skills_vecs"]
520
  if all_missing_skills and len(individual_skills_vecs) > 0:
521
  unique_missing = sorted(all_missing_skills)
522
- contextualized = [f"software development skill {s}" for s in unique_missing]
523
  vecs = self._model.encode(
524
  contextualized,
525
  normalize_embeddings=True,
@@ -663,9 +664,7 @@ class JobMatcher:
663
 
664
  individual_skills_list = list(cv_skills_technical_set | cv_skills_soft_set)
665
  if individual_skills_list:
666
- contextualized_cv = [
667
- f"software development skill {s}" for s in individual_skills_list
668
- ]
669
  individual_skills_vecs = self._model.encode(
670
  contextualized_cv,
671
  normalize_embeddings=True,
@@ -730,7 +729,7 @@ class JobMatcher:
730
  missing_technical,
731
  missing_skill_vecs,
732
  individual_skills_vecs,
733
- threshold=0.88,
734
  )
735
  if semantic_matches:
736
  matched_technical = sorted(set(matched_technical) | semantic_matches)
@@ -762,29 +761,53 @@ class JobMatcher:
762
  cv_skills, job.category, self._category_skills
763
  )
764
 
765
- seniority, sen_reason = _seniority_fit(cv_seniority, job.seniority)
 
 
 
 
 
 
 
 
 
 
 
766
  title = self._title_similarity_precomputed(
767
  cv_title, cv_title_vec, job_title_vec
768
  )
769
- experience = _experience_fit(cv_years, job.min_years_experience)
 
 
 
 
 
 
 
 
770
 
771
  # ── Weighted aggregation ─────────────────────────────────────────
 
 
 
772
  base_final = (
773
- 0.42 * skill
774
- + 0.23 * semantic
775
  + 0.12 * title
776
- + 0.11 * cat_score
777
- + 0.07 * seniority
778
  + 0.05 * experience
779
  ) * 100
780
 
781
- # Smooth Modifier applies universally
782
  if cat_score < 0.75:
783
  cat_modifier = -20.0 + ((cat_score - 0.30) / 0.45) * 20.0
784
  cat_modifier = max(-20.0, min(0.0, cat_modifier))
785
  else:
786
- cat_modifier = ((cat_score - 0.75) / 0.25) * 10.0
787
- cat_modifier = max(0.0, min(10.0, cat_modifier))
 
 
788
 
789
  final = base_final + cat_modifier
790
 
@@ -853,6 +876,14 @@ class JobMatcher:
853
  # Private helpers
854
  # ------------------------------------------------------------------
855
 
 
 
 
 
 
 
 
 
856
  def _build_job_index_text(self, job: JobInput) -> str:
857
  """Build the semantic index text for a job (same as before, factored out)."""
858
  text = (
 
1
  from __future__ import annotations
2
 
3
  import hashlib
4
+ import re
5
  import json
6
  import threading
7
  from typing import Any, Dict, List, Optional, Set, Tuple
 
489
  job_vecs = self._embed_batch_texts(job_texts)
490
 
491
  # ---- Batch 2: job title embeddings, ONE encode() call ----
492
+ job_title_vecs = self._embed_title_batch([self._clean_job_title(j.job_title) for j in job_objs])
493
 
494
  # ---- Precompute exact skill matches + collect missing technical
495
  # skills across ALL jobs for a single batched semantic pass ----
 
520
  individual_skills_vecs = cv_data["individual_skills_vecs"]
521
  if all_missing_skills and len(individual_skills_vecs) > 0:
522
  unique_missing = sorted(all_missing_skills)
523
+ contextualized = unique_missing
524
  vecs = self._model.encode(
525
  contextualized,
526
  normalize_embeddings=True,
 
664
 
665
  individual_skills_list = list(cv_skills_technical_set | cv_skills_soft_set)
666
  if individual_skills_list:
667
+ contextualized_cv = individual_skills_list
 
 
668
  individual_skills_vecs = self._model.encode(
669
  contextualized_cv,
670
  normalize_embeddings=True,
 
729
  missing_technical,
730
  missing_skill_vecs,
731
  individual_skills_vecs,
732
+ threshold=0.85, # was 0.88 β€” lowered to catch synonyms (k8s/kubernetes, postgres/postgresql)
733
  )
734
  if semantic_matches:
735
  matched_technical = sorted(set(matched_technical) | semantic_matches)
 
761
  cv_skills, job.category, self._category_skills
762
  )
763
 
764
+ # If job seniority is defaulted to 'mid' by the caller but the title clearly specifies seniority:
765
+ job_effective_seniority = job.seniority
766
+ if job_effective_seniority == "mid" and job.job_title:
767
+ t_lower = job.job_title.lower()
768
+ if re.search(r"\b(senior|sr\.?|lead|principal|staff|head)\b", t_lower):
769
+ job_effective_seniority = "senior"
770
+ elif re.search(r"\b(junior|jr\.?|entry|trainee|apprentice)\b", t_lower):
771
+ job_effective_seniority = "junior"
772
+ elif re.search(r"\b(intern|internship)\b", t_lower):
773
+ job_effective_seniority = "intern"
774
+
775
+ seniority, sen_reason = _seniority_fit(cv_seniority, job_effective_seniority)
776
  title = self._title_similarity_precomputed(
777
  cv_title, cv_title_vec, job_title_vec
778
  )
779
+ # Use seniority as a proxy for years when date parsing yielded 0.
780
+ # Prevents CV formatting failures (no parseable date ranges) from
781
+ # zeroing experience_score for an otherwise qualified candidate.
782
+ effective_cv_years = cv_years
783
+ if effective_cv_years == 0 and cv_seniority:
784
+ _seniority_year_proxy = {"senior": 7, "mid": 4, "junior": 2, "intern": 0}
785
+ effective_cv_years = _seniority_year_proxy.get(cv_seniority, 0)
786
+
787
+ experience = _experience_fit(effective_cv_years, job.min_years_experience)
788
 
789
  # ── Weighted aggregation ─────────────────────────────────────────
790
+ # Rebalanced: skill 42β†’35% (taxonomy-dependent, noisiest signal),
791
+ # semantic 23β†’30% (more robust, captures fit beyond exact skill labels),
792
+ # seniority 7β†’9% (was under-weighted for its actual impact on fit).
793
  base_final = (
794
+ 0.35 * skill
795
+ + 0.30 * semantic
796
  + 0.12 * title
797
+ + 0.09 * cat_score
798
+ + 0.09 * seniority
799
  + 0.05 * experience
800
  ) * 100
801
 
802
+ # Category modifier: penalize category mismatch, but earn positive bonus through skill fit
803
  if cat_score < 0.75:
804
  cat_modifier = -20.0 + ((cat_score - 0.30) / 0.45) * 20.0
805
  cat_modifier = max(-20.0, min(0.0, cat_modifier))
806
  else:
807
+ # Positive modifier is earned based on skill overlap (scales up to +6.0)
808
+ max_boost = 6.0 * skill
809
+ cat_modifier = ((cat_score - 0.75) / 0.25) * max_boost
810
+ cat_modifier = max(0.0, min(6.0, cat_modifier))
811
 
812
  final = base_final + cat_modifier
813
 
 
876
  # Private helpers
877
  # ------------------------------------------------------------------
878
 
879
+ @staticmethod
880
+ def _clean_job_title(title: str) -> str:
881
+ """Strip scraper noise like 'Job <Company>' or 'at <Company>' before embedding."""
882
+ t = (title or "").strip()
883
+ t = re.sub(r"\s+(?:Job|at|@|\|)\s+.*$", "", t, flags=re.IGNORECASE)
884
+ t = re.sub(r"\s*\([^)]*?(?:safaricom|zeraki|kenya|remote|ltd|group|plc)[^)]*?\)", "", t, flags=re.IGNORECASE)
885
+ return t.strip() or title
886
+
887
  def _build_job_index_text(self, job: JobInput) -> str:
888
  """Build the semantic index text for a job (same as before, factored out)."""
889
  text = (
services/processor_utils.py CHANGED
@@ -197,7 +197,7 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
197
  "process documentation",
198
  "sop",
199
  ],
200
- "c": ["c language", "c programming", "embedded c"],
201
  "c#": ["c#", "csharp", "c sharp"],
202
  "c++": ["c++", "cpp", "c plus plus"],
203
  "call centre": [
@@ -612,6 +612,7 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
612
  "paid social",
613
  ],
614
  "fastapi": ["fastapi", "fast api"],
 
615
  "figma": ["figma"],
616
  "filing": [
617
  "filing",
@@ -690,7 +691,7 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
690
  "version control",
691
  "source control",
692
  ],
693
- "go": ["golang", "go lang", "go programming"],
694
  "google ads": [
695
  "google ads",
696
  "google adwords",
@@ -1288,7 +1289,7 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
1288
  "total quality management",
1289
  ],
1290
  "quickbooks": ["quickbooks", "quick books"],
1291
- "r": ["r programming", "r language", "rstudio"],
1292
  "rabbitmq": ["rabbitmq", "rabbit mq", "amqp", "message queue"],
1293
  "radiology": [
1294
  "radiology",
@@ -1550,7 +1551,7 @@ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
1550
  "swift": ["swift", "swiftui", "swift ui"],
1551
  "symfony": ["symfony"],
1552
  "tableau": ["tableau", "tableau desktop"],
1553
- "tailwind css": ["tailwind", "tailwind css"],
1554
  "talent management": [
1555
  "talent management",
1556
  "talent strategy",
@@ -2356,6 +2357,10 @@ TITLE_ROLE_WORDS: List[str] = [
2356
  "director",
2357
  "executive",
2358
  "lead",
 
 
 
 
2359
  "scientist",
2360
  "strategist",
2361
  "advisor",
@@ -2475,6 +2480,43 @@ def _get_skill_pattern():
2475
  return _SKILL_PATTERN, _ALIAS_TO_CANONICAL
2476
 
2477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2478
  def _extract_skills(
2479
  text: str,
2480
  aliases: Optional[Dict[str, List[str]]] = None,
@@ -2483,7 +2525,12 @@ def _extract_skills(
2483
 
2484
  if aliases is None or aliases is DEFAULT_SKILL_ALIASES:
2485
  pattern, alias_map = _get_skill_pattern()
2486
- return {alias_map[match.group(1)] for match in pattern.finditer(text_norm)}
 
 
 
 
 
2487
 
2488
  return {
2489
  canon
@@ -2705,19 +2752,51 @@ def _infer_category(
2705
  skills: Set[str],
2706
  category_skills: Optional[Dict[str, Set[str]]] = None,
2707
  ) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
2708
  if category_skills is None:
2709
  category_skills = DEFAULT_CATEGORY_SKILLS
 
2710
  text_norm = _normalize(text)
2711
- best, best_score = "Other", 0.0
 
 
 
2712
  category_order = [cat for cat in _CATEGORY_ORDER if cat in category_skills]
2713
  category_order.extend(cat for cat in category_skills if cat not in _CATEGORY_ORDER)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2714
  for cat in category_order:
2715
  cat_skills = category_skills[cat]
2716
  skill_overlap = len(skills & cat_skills)
2717
  kw_hits = sum(
2718
  1 for kw in _CATEGORY_TITLE_KEYWORDS.get(cat, []) if kw in text_norm
2719
  )
2720
- score = skill_overlap * 2.0 + kw_hits * 1.25
2721
  if score > best_score:
2722
  best_score, best = score, cat
2723
  return best
@@ -2783,7 +2862,7 @@ def compute_years_from_experience(entries: List[Dict[str, Any]]) -> int:
2783
  period = (entry.get("period") or "").strip()
2784
  if not period:
2785
  continue
2786
- parts = re.split(r"\s*[-–—]\s*", period, maxsplit=1)
2787
  if len(parts) != 2:
2788
  continue
2789
  start = _parse_date_token(parts[0])
@@ -2799,29 +2878,50 @@ def compute_years_from_experience(entries: List[Dict[str, Any]]) -> int:
2799
  # ---------------------------------------------------------------------------
2800
 
2801
 
2802
- def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
2803
- """Detect seniority: title zone first, then body (guards against
2804
- false positives from advice/boilerplate text in job descriptions)."""
2805
- title_zone = text[:300]
2806
- title_norm = _normalize(title_zone)
2807
- text_norm = _normalize(text)
 
2808
 
2809
- order = (
2810
- ["senior", "junior", "intern", "mid"]
2811
- if is_cv
2812
- else ["senior", "intern", "junior", "mid"]
2813
- )
2814
 
2815
- for level in order:
2816
- if any(_has_alias(title_norm, term) for term in SENIORITY_PATTERNS[level]):
2817
- return level
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2818
 
2819
- for level in order:
2820
- if level == "senior" and not is_cv:
2821
- continue # already checked title zone; skip body re-check to avoid boilerplate inflation
2822
- if any(_has_alias(text_norm, term) for term in SENIORITY_PATTERNS[level]):
2823
- return level
2824
 
 
2825
  years = _extract_years(text)
2826
  if years >= 7:
2827
  return "senior"
@@ -2853,32 +2953,61 @@ def refine_seniority_with_years(detected: str, years: int) -> str:
2853
  # ---------------------------------------------------------------------------
2854
 
2855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2856
  def _extract_cv_title(cv_text: str, clean_line_fn=None) -> str:
 
 
 
 
 
 
 
2857
  def _simple_clean(raw: str) -> str:
2858
  line = re.sub(r"^#+\s*", "", raw)
2859
  line = re.sub(r"\*{1,3}|\_{1,2}|`", "", line)
2860
  return re.sub(r"\s+", " ", line).strip()
2861
 
2862
  clean = clean_line_fn or _simple_clean
2863
- clean_lines = [clean(x) for x in cv_text.splitlines() if x.strip()]
 
 
2864
 
2865
  _role_wb_re = re.compile(
2866
  r"\b(" + "|".join(re.escape(w) for w in TITLE_ROLE_WORDS) + r")\b",
2867
  re.IGNORECASE,
2868
  )
2869
- for line in clean_lines[1:30]:
 
 
2870
  stripped = line.strip("| \t")
2871
- if (
2872
- len(stripped) <= 80
2873
- and bool(_role_wb_re.search(stripped))
2874
- and "|" not in stripped
2875
- and not re.search(r"[@http]", stripped)
2876
- and not re.search(
2877
- r"\d{4}\s*[-–]\s*(?:\d{4}|present)", stripped, re.IGNORECASE
2878
- )
2879
- ):
2880
- return stripped.title()
 
2881
 
 
2882
  _SECTION_HDR_RE = re.compile(
2883
  r"^(career\s*summary|professional\s*summary|executive\s*summary|"
2884
  r"personal\s*statement|career\s*objective|professional\s*profile|"
@@ -2892,8 +3021,10 @@ def _extract_cv_title(cv_text: str, clean_line_fn=None) -> str:
2892
  )
2893
  non_header = [
2894
  ln
2895
- for ln in clean_lines[:40]
2896
  if not _SECTION_HDR_RE.match(re.sub(r"[^a-zA-Z\s&]", " ", ln).strip())
 
 
2897
  ]
2898
  head = ". ".join(non_header)[:1000]
2899
  m = TITLE_PHRASE_RE.search(head)
 
197
  "process documentation",
198
  "sop",
199
  ],
200
+ "c": ["c", "c language", "c programming", "embedded c"],
201
  "c#": ["c#", "csharp", "c sharp"],
202
  "c++": ["c++", "cpp", "c plus plus"],
203
  "call centre": [
 
612
  "paid social",
613
  ],
614
  "fastapi": ["fastapi", "fast api"],
615
+ "solidity": ["solidity", "smart contracts", "evm"],
616
  "figma": ["figma"],
617
  "filing": [
618
  "filing",
 
691
  "version control",
692
  "source control",
693
  ],
694
+ "go": ["go", "golang", "go lang", "go programming"],
695
  "google ads": [
696
  "google ads",
697
  "google adwords",
 
1289
  "total quality management",
1290
  ],
1291
  "quickbooks": ["quickbooks", "quick books"],
1292
+ "r": ["r", "r programming", "r language", "rstudio"],
1293
  "rabbitmq": ["rabbitmq", "rabbit mq", "amqp", "message queue"],
1294
  "radiology": [
1295
  "radiology",
 
1551
  "swift": ["swift", "swiftui", "swift ui"],
1552
  "symfony": ["symfony"],
1553
  "tableau": ["tableau", "tableau desktop"],
1554
+ "tailwind css": ["tailwind", "tailwind css", "tailwindcss"],
1555
  "talent management": [
1556
  "talent management",
1557
  "talent strategy",
 
2357
  "director",
2358
  "executive",
2359
  "lead",
2360
+ "principal",
2361
+ "head",
2362
+ "vp",
2363
+ "chief",
2364
  "scientist",
2365
  "strategist",
2366
  "advisor",
 
2480
  return _SKILL_PATTERN, _ALIAS_TO_CANONICAL
2481
 
2482
 
2483
+ # Context words required near a short/ambiguous alias before it is accepted
2484
+ # as a real skill. Prevents "c" matching inside "practice", "science", etc.
2485
+ # and "go" matching inside "going", "ago", "goal".
2486
+ _AMBIGUOUS_SKILL_CONTEXT: Dict[str, List[str]] = {
2487
+ "c": [
2488
+ "programming", "language", "embedded", "microcontroller", "firmware",
2489
+ "code", "developer", "engineer", "software", "skills", "c++", "linux",
2490
+ "systems", "kernel", "assembly", "rtos"
2491
+ ],
2492
+ "r": [
2493
+ "statistical", "programming", "rstudio", "analytics", "tidyverse", "cran",
2494
+ "data", "analysis", "statistics", "python", "biostatistics", "econometrics",
2495
+ "modeling", "machine learning"
2496
+ ],
2497
+ "go": [
2498
+ "golang", "backend", "microservice", "programming", "language", "concurrent",
2499
+ "developer", "engineer", "software", "docker", "kubernetes", "python",
2500
+ "grpc", "distributed", "api", "cloud"
2501
+ ],
2502
+ }
2503
+
2504
+ # Window (characters) around the match to scan for context words
2505
+ _CONTEXT_WINDOW = 120
2506
+
2507
+
2508
+ def _has_skill_context(text_norm: str, match_start: int, match_end: int,
2509
+ canonical: str) -> bool:
2510
+ """Return True unless the canonical skill needs context and none is found."""
2511
+ ctx_words = _AMBIGUOUS_SKILL_CONTEXT.get(canonical)
2512
+ if not ctx_words:
2513
+ return True # no context required β€” accept as-is
2514
+ window_start = max(0, match_start - _CONTEXT_WINDOW)
2515
+ window_end = min(len(text_norm), match_end + _CONTEXT_WINDOW)
2516
+ window = text_norm[window_start:window_end]
2517
+ return any(cw in window for cw in ctx_words)
2518
+
2519
+
2520
  def _extract_skills(
2521
  text: str,
2522
  aliases: Optional[Dict[str, List[str]]] = None,
 
2525
 
2526
  if aliases is None or aliases is DEFAULT_SKILL_ALIASES:
2527
  pattern, alias_map = _get_skill_pattern()
2528
+ found: Set[str] = set()
2529
+ for match in pattern.finditer(text_norm):
2530
+ canon = alias_map[match.group(1)]
2531
+ if _has_skill_context(text_norm, match.start(1), match.end(1), canon):
2532
+ found.add(canon)
2533
+ return found
2534
 
2535
  return {
2536
  canon
 
2752
  skills: Set[str],
2753
  category_skills: Optional[Dict[str, Set[str]]] = None,
2754
  ) -> str:
2755
+ """Infer job/CV category from skills and text keywords.
2756
+
2757
+ Fast path: if the first line of text (job title or CV title) contains
2758
+ two or more category-specific keywords it is treated as decisive and
2759
+ returned immediately. This prevents cross-domain misclassification
2760
+ where a small number of coincidental soft-skill overlaps would otherwise
2761
+ override a clear title signal (e.g. a Data Engineer whose CV mentions
2762
+ 'communication' being classified as 'Admin & Office').
2763
+
2764
+ Full path: weighted scoring over the entire text when the fast path
2765
+ does not fire.
2766
+ """
2767
  if category_skills is None:
2768
  category_skills = DEFAULT_CATEGORY_SKILLS
2769
+
2770
  text_norm = _normalize(text)
2771
+ # First line of text before whitespace collapsing is the title signal
2772
+ raw_lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
2773
+ first_line_norm = _normalize(raw_lines[0]) if raw_lines else ""
2774
+
2775
  category_order = [cat for cat in _CATEGORY_ORDER if cat in category_skills]
2776
  category_order.extend(cat for cat in category_skills if cat not in _CATEGORY_ORDER)
2777
+
2778
+ # ── Fast path: specific multi-word title keyword is decisive ─────────────
2779
+ # e.g. "data engineer", "software engineer", "data analyst", "account manager"
2780
+ for cat in category_order:
2781
+ kws = _CATEGORY_TITLE_KEYWORDS.get(cat, [])
2782
+ if any(len(kw.split()) >= 2 and kw in first_line_norm for kw in kws):
2783
+ return cat
2784
+
2785
+ # Single-word title hits earn a strong +5.0 bonus in full scoring
2786
+ title_bonus: Dict[str, float] = {
2787
+ cat: 5.0 * sum(1 for kw in _CATEGORY_TITLE_KEYWORDS.get(cat, []) if kw in first_line_norm)
2788
+ for cat in category_order
2789
+ }
2790
+
2791
+ # ── Full scoring path ─────────────────────────────────────────────────────
2792
+ best, best_score = "Other", 0.0
2793
  for cat in category_order:
2794
  cat_skills = category_skills[cat]
2795
  skill_overlap = len(skills & cat_skills)
2796
  kw_hits = sum(
2797
  1 for kw in _CATEGORY_TITLE_KEYWORDS.get(cat, []) if kw in text_norm
2798
  )
2799
+ score = skill_overlap * 2.0 + kw_hits * 1.25 + title_bonus.get(cat, 0.0)
2800
  if score > best_score:
2801
  best_score, best = score, cat
2802
  return best
 
2862
  period = (entry.get("period") or "").strip()
2863
  if not period:
2864
  continue
2865
+ parts = re.split(r"\s*(?:[-–—]|to)\s*", period, maxsplit=1, flags=re.IGNORECASE)
2866
  if len(parts) != 2:
2867
  continue
2868
  start = _parse_date_token(parts[0])
 
2878
  # ---------------------------------------------------------------------------
2879
 
2880
 
2881
+ # Regex to mask managerial mentions of junior/intern so they are not counted
2882
+ # as the job's own seniority level (e.g. "will mentor junior engineers").
2883
+ _SENIORITY_MGMT_RE = re.compile(
2884
+ r"\b(?:manag|mentor|supervis|guid|train|lead|support|coach|assist)\w*"
2885
+ r"\s+(?:\w+\s+){0,3}(?:junior|intern)\b",
2886
+ re.IGNORECASE,
2887
+ )
2888
 
 
 
 
 
 
2889
 
2890
+ def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
2891
+ """Zone-weighted seniority detection with negation guard.
2892
+
2893
+ Scores each level across three non-overlapping text zones with
2894
+ decreasing weights (title 3x, summary 2x, body 1x) and picks the
2895
+ highest-scoring level rather than stopping at the first match.
2896
+ This avoids false positives from boilerplate phrases like
2897
+ 'manage junior staff' or 'for senior stakeholders'.
2898
+
2899
+ For job descriptions (is_cv=False), managerial mentions of 'junior'
2900
+ and 'intern' (e.g. 'mentor junior engineers') are masked before
2901
+ scoring so they do not inflate the detected level downward.
2902
+ """
2903
+ # Mask managerial junior/intern mentions for job descriptions only
2904
+ if not is_cv:
2905
+ text = _SENIORITY_MGMT_RE.sub(" ", text)
2906
+
2907
+ # Three non-overlapping zones, higher weight = stronger signal
2908
+ zones = [
2909
+ (_normalize(text[:300]), 3), # title / header
2910
+ (_normalize(text[300:1000]), 2), # summary / intro
2911
+ (_normalize(text[1000:]), 1), # body / requirements
2912
+ ]
2913
+
2914
+ scores: Dict[str, int] = {level: 0 for level in SENIORITY_PATTERNS}
2915
+ for zone_norm, weight in zones:
2916
+ for level, patterns in SENIORITY_PATTERNS.items():
2917
+ hits = sum(1 for p in patterns if _has_alias(zone_norm, p))
2918
+ scores[level] += hits * weight
2919
 
2920
+ best = max(scores, key=lambda k: (scores[k], SENIORITY_ORDER.get(k, 1)))
2921
+ if scores[best] > 0:
2922
+ return best
 
 
2923
 
2924
+ # No keyword signal β€” fall back to years of experience
2925
  years = _extract_years(text)
2926
  if years >= 7:
2927
  return "senior"
 
2953
  # ---------------------------------------------------------------------------
2954
 
2955
 
2956
+ # Regexes to guard CV title extraction against degrees, contacts, and dates
2957
+ _EDU_LINE_RE = re.compile(
2958
+ r"\b(bachelor|master|phd|diploma|degree|bsc|msc|ba|ma|mba|hons|honours|kcse|"
2959
+ r"university|college|school|faculty|campus|polytechnic|institute|academy|curriculum)\b",
2960
+ re.IGNORECASE,
2961
+ )
2962
+ _CONTACT_LINE_RE = re.compile(
2963
+ r"@|https?://|www\.|\+?\d[\d\s\-()]{6,}\d|\b(?:github|linkedin|portfolio|twitter|phone|email)\b",
2964
+ re.IGNORECASE,
2965
+ )
2966
+ _DATE_LINE_RE = re.compile(
2967
+ r"\b\d{4}\s*[-–—to]+\s*(?:\d{4}|present|current|now)\b",
2968
+ re.IGNORECASE,
2969
+ )
2970
+
2971
+
2972
  def _extract_cv_title(cv_text: str, clean_line_fn=None) -> str:
2973
+ """Extract professional title from CV header area with high precision.
2974
+
2975
+ 1. Checks the top 20 lines for title candidates.
2976
+ 2. Strips out education/degree lines, contact info, dates, and names.
2977
+ 3. Supports modern pipe-separated headlines (e.g. 'Software Engineer | Full Stack').
2978
+ 4. Falls back to section-aware regex matching over the header summary.
2979
+ """
2980
  def _simple_clean(raw: str) -> str:
2981
  line = re.sub(r"^#+\s*", "", raw)
2982
  line = re.sub(r"\*{1,3}|\_{1,2}|`", "", line)
2983
  return re.sub(r"\s+", " ", line).strip()
2984
 
2985
  clean = clean_line_fn or _simple_clean
2986
+ raw_lines = [clean(x) for x in cv_text.splitlines() if x.strip()]
2987
+ if not raw_lines:
2988
+ return "Unknown"
2989
 
2990
  _role_wb_re = re.compile(
2991
  r"\b(" + "|".join(re.escape(w) for w in TITLE_ROLE_WORDS) + r")\b",
2992
  re.IGNORECASE,
2993
  )
2994
+
2995
+ # Scan the header lines (up to 20 lines)
2996
+ for line in raw_lines[:20]:
2997
  stripped = line.strip("| \t")
2998
+ if not stripped or len(stripped) > 90:
2999
+ continue
3000
+ # Skip lines that are contacts, urls, dates, or degrees
3001
+ if _CONTACT_LINE_RE.search(stripped) or _DATE_LINE_RE.search(stripped) or _EDU_LINE_RE.search(stripped):
3002
+ continue
3003
+
3004
+ # Split on pipes or bullets to support multi-part headlines
3005
+ segments = [s.strip() for s in re.split(r"\s*[|Β·β€’]\s*", stripped) if s.strip()]
3006
+ for seg in segments:
3007
+ if bool(_role_wb_re.search(seg)) and len(seg.split()) <= 6:
3008
+ return seg.title()
3009
 
3010
+ # Fallback: scan text before major section headers
3011
  _SECTION_HDR_RE = re.compile(
3012
  r"^(career\s*summary|professional\s*summary|executive\s*summary|"
3013
  r"personal\s*statement|career\s*objective|professional\s*profile|"
 
3021
  )
3022
  non_header = [
3023
  ln
3024
+ for ln in raw_lines[:30]
3025
  if not _SECTION_HDR_RE.match(re.sub(r"[^a-zA-Z\s&]", " ", ln).strip())
3026
+ and not _EDU_LINE_RE.search(ln)
3027
+ and not _CONTACT_LINE_RE.search(ln)
3028
  ]
3029
  head = ". ".join(non_header)[:1000]
3030
  m = TITLE_PHRASE_RE.search(head)