Spaces:
Sleeping
Sleeping
Download experience_classifier.py from m0a9/job_classifier: direct link, hf CLI and curl.
- Browser
- Download file 46.2 kB
-
https://huggingface.co/spaces/m0a9/job_classifier/resolve/main/experience_classifier.py
- Command line
-
hf download hf://spaces/m0a9/job_classifier/experience_classifier.py
-
curl -L -o experience_classifier.py https://huggingface.co/spaces/m0a9/job_classifier/resolve/main/experience_classifier.py
46.2 kB
#!/usr/bin/env python3
"""Hybrid years-of-experience classifier for job postings.
Outputs an integer ``experience_level`` per posting:
1 = 0-2 years (entry / no experience)
2 = 3-5 years (early career)
3 = 6-15 years (mid career)
4 = 16+ years (senior)
Pipeline:
1. Regex first-pass over title + description for explicit "X years" mentions
in an experience-related context. If a confident match is found, map the
extracted minimum to the class above.
2. Otherwise fall back to a TF-IDF + Logistic Regression model that was
trained on the labeled subset (Jobs_1_100.json), with the TF-IDF
vocabulary fit on the full 5000-job corpus (semi-supervised).
3. If the ML top-class probability is below ``ML_CONFIDENCE_THRESHOLD``,
default to class 1 (entry) and flag the row for active-learning review.
CLI:
python experience_classifier.py train [--labeled-path FILE] [--no-pseudo-labels] [--with-title-pseudo-labels]
python experience_classifier.py predict # predict on test_jobs.json + corpus
python experience_classifier.py all [...] # train then predict
"""
from __future__ import annotations
import argparse
import csv
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import joblib
import numpy as np
from scipy.sparse import vstack as sparse_vstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, f1_score, accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
# ---------------------------------------------------------------------------
# Paths and constants
# ---------------------------------------------------------------------------
ROOT = Path(__file__).resolve().parent
LABELED_PATH = ROOT / "Jobs_1_100.json"
CORPUS_PATH = ROOT / "Candogram-5000-random-jobs.csv"
TEST_PATH = ROOT / "test_jobs.json"
PRED_TEST_PATH = ROOT / "predictions_test_jobs.json"
PRED_ALL_PATH = ROOT / "predictions_all.json"
ACTIVE_LEARNING_PATH = ROOT / "active_learning_queue.json"
FLAGGED_REVIEW_PATH = ROOT / "flagged_jobs_for_review.json"
EVAL_REPORT_PATH = ROOT / "eval_report.md"
MODEL_PATH = ROOT / "experience_model.joblib"
CLASS_LABELS = {
1: "entry (0-2 yrs)",
2: "early career (3-5 yrs)",
3: "mid career (6-15 yrs)",
4: "senior (16+ yrs)",
}
ML_CONFIDENCE_THRESHOLD = 0.50
ACTIVE_LEARNING_TOP_N = 100
HUMAN_REVIEW_ML_THRESHOLD = 0.65
# Phase 1 structural upgrades (section extraction, sentence-level regex,
# negation handling, title priors). Set False for legacy behavior.
USE_STRUCTURAL_PHASE1 = True
TITLE_PRIOR_CONFIDENCE = 0.65
NEGATION_CONFIDENCE = 0.90
# Semi-supervised pseudo-labels (regex / negation / optional title) on the corpus.
USE_PSEUDO_LABELS = True
USE_TITLE_PSEUDO_LABELS = False
PSEUDO_WEIGHT_TRUE = 5.0
PSEUDO_WEIGHT_REGEX = 1.0
PSEUDO_WEIGHT_NEGATION = 1.0
PSEUDO_WEIGHT_TITLE = 0.5
# ---------------------------------------------------------------------------
# Class mapping
# ---------------------------------------------------------------------------
def years_to_class(years: float) -> int:
if years <= 2:
return 1
if years <= 5:
return 2
if years <= 15:
return 3
return 4
# ---------------------------------------------------------------------------
# Loaders
# ---------------------------------------------------------------------------
def load_labeled(path: Path = LABELED_PATH) -> list[dict]:
raw = path.read_text(encoding="utf-8")
raw = re.sub(r",(\s*[}\]])", r"\1", raw)
data = json.loads(raw)
# Supports both:
# 1) list[dict] (Jobs_1_100.json legacy format)
# 2) {"labels": list[dict]} (labeled_yoe_auto.json format)
if isinstance(data, dict) and "labels" in data and isinstance(data["labels"], list):
return data["labels"]
if isinstance(data, list):
return data
raise ValueError(f"Unsupported labeled data format in {path}")
def load_corpus(path: Path = CORPUS_PATH) -> list[dict]:
csv.field_size_limit(10_000_000)
rows: list[dict] = []
with path.open(newline="", encoding="utf-8", errors="replace") as f:
reader = csv.DictReader(f)
for r in reader:
rows.append(
{
"UniqueJobAdID": str(r.get("UniqueJobAdID", "")).strip(),
"OrigJobTitle": (r.get("OrigJobTitle") or "").strip(),
"EmployerOrgName": (r.get("EmployerOrgName") or "").strip(),
"JobDescription": (r.get("JobDescription") or "").strip(),
}
)
return rows
def load_test(path: Path = TEST_PATH) -> list[dict]:
return json.loads(path.read_text(encoding="utf-8"))
def build_train_table(labeled: list[dict], corpus: list[dict]) -> list[dict]:
"""Dedupe labels by id and join to corpus job text. Class is re-derived
from ``min_years_experience`` so the threshold mapping is authoritative.
"""
text_by_id = {r["UniqueJobAdID"]: r for r in corpus}
by_id: dict[str, dict] = {}
for row in labeled:
rid = str(row.get("id", "")).strip()
if not rid:
continue
candidate = {
"id": rid,
"min_years_experience": row.get("min_years_experience"),
"max_years_experience": row.get("max_years_experience"),
"signal_type": row.get("signal_type"),
}
prev = by_id.get(rid)
if prev is None:
by_id[rid] = candidate
continue
prev_score = (
prev["signal_type"] == "explicit",
prev["min_years_experience"] is not None,
)
cur_score = (
candidate["signal_type"] == "explicit",
candidate["min_years_experience"] is not None,
)
if cur_score > prev_score:
by_id[rid] = candidate
table: list[dict] = []
level_to_class = {
"entry": 1,
"early": 2,
"early_career": 2,
"mid": 3,
"senior": 4,
}
for rid, row in by_id.items():
text_row = text_by_id.get(rid)
if not text_row:
continue
m = row.get("min_years_experience")
if m is not None:
cls = years_to_class(float(m))
else:
lvl = str(row.get("experience_level", "")).strip().lower()
cls = level_to_class.get(lvl)
if cls is None:
# Drop unknown/unsupported weak labels.
continue
table.append(
{
"id": rid,
"title": text_row["OrigJobTitle"],
"employer": text_row["EmployerOrgName"],
"description": text_row["JobDescription"],
"min_years": m,
"y": cls,
}
)
return table
def make_text(row: dict) -> str:
title = row.get("OrigJobTitle") or row.get("title") or ""
desc = row.get("JobDescription") or row.get("description") or ""
return f"{title}\n\n{desc}".lower()
# ---------------------------------------------------------------------------
# Phase 1: requirements section + sentences + negation + title priors
# ---------------------------------------------------------------------------
SECTION_START_RE = re.compile(
r"(?is)(?:^|\n)\s*(?:[\*#\-\+]+\s*){0,3}"
r"(?:requirements|qualifications|essential\s+skills|minimum\s+qualifications|"
r"required\s+experience|skills\s+(?:and\s+)?(?:requirements|experience)|"
r"what\s+you\s+bring|what\s+we(?:'re|are)\s+looking\s+for)"
r"\s*:?\s*(?:[\*_]+\s*)?(?:\n|$)"
)
SECTION_END_RE = re.compile(
r"(?is)(?:^|\n)\s*(?:[\*#\-\+]+\s*){0,3}"
r"(?:benefits|perks|about\s+(?:us|the\s+company|employer|actalent|target)|"
r"equal\s+opportunity|salary|pay\s+range|compensation|how\s+to\s+apply|"
r"application\s+deadline|job\s+type\s*&|workplace\s+type|"
r"diversity|privacy|overview\b)"
r"\s*:?\s*(?:\n|$)"
)
NEGATION_RX = re.compile(
r"(?is)"
r"(?:no\s+(?:prior\s+)?experience\s+(?:is\s+)?(?:required|needed|necessary))|"
r"(?:experience\s+preferred\s+but\s+not\s+required)|"
r"(?:no\s+experience\s+required)|"
r"(?:entry[-\s]?level\s+role)|"
r"(?:open\s+to\s+(?:current\s+)?students)|"
r"(?:no\s+degree\s+required)|"
r"(?:(?:fresh|recent)\s+graduate)|"
r"(?:\bnew\s+grad\b)"
)
SENTENCE_EXP_KW = re.compile(
r"(?i)\b(?:experience|background|expertise|track\s+record|industry|professional|"
r"work\s+history|hands[-\s]?on)\b"
)
def extract_requirements_section(description: str) -> str | None:
"""Return requirements-style subsection text, or None if no header matched."""
if not description.strip():
return None
m = SECTION_START_RE.search(description)
if not m:
return None
start = m.end()
nxt = SECTION_END_RE.search(description, start)
end = nxt.start() if nxt else len(description)
chunk = description[start:end].strip()
if len(chunk) < 25:
return None
return chunk
def split_sentences(text: str) -> list[str]:
if not text.strip():
return []
parts = re.split(r"(?<=[.!?])\s+|\n\s*\n|;\s+", text)
return [p.strip() for p in parts if p.strip()]
def negation_find_evidence(focus_text: str) -> str | None:
"""First sentence in focus_text matching a no-experience / entry-level phrase."""
if not USE_STRUCTURAL_PHASE1:
return None
for sent in split_sentences(focus_text):
if NEGATION_RX.search(sent):
return sent.strip()
return None
def title_prior_predict(title: str) -> dict | None:
"""Deterministic title keyword prior. Only used when regex did not fire."""
if not USE_STRUCTURAL_PHASE1 or not (title or "").strip():
return None
t = title.lower()
# Most-specific multi-token patterns first (class 4 -> 1).
if re.search(r"(?i)\bvice\s+president\b", t) or re.search(r"(?i)\bvp\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bchief\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bdirector\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bhead\s+of\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bdistinguished\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bfellow\b", t) and not re.search(r"(?i)\bfellowship\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bprincipal\b", t) and not re.search(r"(?i)\bprincipal\s+engineer\b", t):
return {"experience_level": 4, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bprincipal\s+engineer\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bsenior\s+associate\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\b(?:senior|sr\.)\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bstaff\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\blead\b", t) and not re.search(r"(?i)\blead\s+generation\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\blevel\s*(?:iii|3)\b", t) or re.search(r"(?i)\b(?:iii)\b", t):
return {"experience_level": 3, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\b(?:associate\s+(?:ii|2)|level\s*(?:ii|2)|mid[- ]level|"
r"analyst\s+(?:ii|2)|engineer\s+(?:ii|2))\b", t):
return {"experience_level": 2, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\b(?:intern|trainee|apprentice)\b", t):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bsummer\s+associate\b", t):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\b(?:junior|jr\.)\b", t):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\bentry\b", t):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
if re.search(r"(?i)\blevel\s*(?:i|1)\b", t):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
# Associate / Analyst I — avoid false positives when preceded by senior/principal
if re.search(r"(?i)\bassociate\b", t) and not re.search(
r"(?i)\b(?:senior|sr\.?|principal)\s+associate\b", t
):
return {"experience_level": 1, "confidence": TITLE_PRIOR_CONFIDENCE, "evidence": title.strip()}
return None
def row_to_inference_texts(row: dict) -> tuple[str, str, bool]:
"""Returns (focus_lower_for_regex, ml_input_lower, section_extracted).
When Phase 1 is off, both strings equal legacy ``make_text(row)``.
"""
title = (row.get("OrigJobTitle") or row.get("title") or "").strip()
desc = (row.get("JobDescription") or row.get("description") or "").strip()
legacy = f"{title}\n\n{desc}".lower()
if not USE_STRUCTURAL_PHASE1:
return legacy, legacy, False
section = extract_requirements_section(desc)
if section:
focus = section.lower()
ml_text = f"{title}\n\n{section}".lower()
return focus, ml_text, True
focus = desc.lower()
ml_text = legacy
return focus, ml_text, False
def make_ml_input(row: dict) -> str:
"""Text fed to TF-IDF (training + inference). Matches hybrid inference."""
_, ml_text, _ = row_to_inference_texts(row)
return ml_text
# ---------------------------------------------------------------------------
# Regex extractor
# ---------------------------------------------------------------------------
NUMBER_WORDS: dict[str, int] = {
"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,
"twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15,
"sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19,
"twenty": 20,
}
WORD_ALT = "|".join(sorted(NUMBER_WORDS, key=len, reverse=True))
YEAR_UNIT = r"(?:year|yr)s?'?"
# Range: "5-7 years", "5 to 7 years"
RANGE_RX = re.compile(
rf"\b(\d{{1,2}})\s*(?:-|–|—|to)\s*(\d{{1,2}})\s+{YEAR_UNIT}\b",
re.IGNORECASE,
)
# "X+ years"
PLUS_RX = re.compile(rf"\b(\d{{1,2}})\s*\+\s*{YEAR_UNIT}\b", re.IGNORECASE)
# "minimum X years", "at least X years", "no less than X years", "over X years"
MIN_RX = re.compile(
rf"\b(?:minimum(?:\s+of)?|at\s+least|no\s+less\s+than|over|more\s+than)\s+(\d{{1,2}})\s+(?:\+\s*)?{YEAR_UNIT}\b",
re.IGNORECASE,
)
# "X or more years", "X or greater years"
OR_MORE_RX = re.compile(
rf"\b(\d{{1,2}})\s+(?:or\s+more|or\s+greater)\s+{YEAR_UNIT}\b",
re.IGNORECASE,
)
# Generic "X years"
GENERIC_RX = re.compile(rf"\b(\d{{1,2}})\s+{YEAR_UNIT}\b", re.IGNORECASE)
# Word forms
WORD_RANGE_RX = re.compile(
rf"\b({WORD_ALT})\s+to\s+({WORD_ALT})\s+{YEAR_UNIT}\b",
re.IGNORECASE,
)
WORD_RX = re.compile(rf"\b({WORD_ALT})\s+{YEAR_UNIT}\b", re.IGNORECASE)
# Phrases that mention "years" but not work-experience requirements.
BAD_CONTEXT = re.compile(
r"(?i)("
r"warrant|guarant|sentence|prison|olympic|anniversar|"
r"years?\s+of\s+age|years?\s+old|age\s+of\s+\d+|"
r"tenure|year[\s-]?over[\s-]?year|yoy|fiscal\s+year|calendar\s+year|"
r"year\s+contract|year\s+plan|year\s+program|year\s+degree|"
r"in\s+business|grace\s+period|every\s+\d+\s+year|"
r"years?\s+of\s+(?:serving|trusted|protecting|innovation|legacy|operation|"
r"delivering|providing|growth|history|excellence|leadership|service|business|"
r"caring|helping|supporting|empowering|combined)"
r")"
)
GOOD_CONTEXT = re.compile(
r"(?i)("
r"experience|exp\.|background|expertise|industry|professional|"
r"work\s+history|hands[-\s]?on|practitioner|practicing|track\s+record|"
r"supervis|managing|managerial|seniority|yrs\s+of"
r")"
)
# Suppression patterns checked against the text *immediately* after the year
# match (i.e., what completes the phrase). These hard-reject the hit even when
# experience-like words appear elsewhere in the surrounding window.
SUPPRESS_AFTER = re.compile(
r"(?i)^\s*(?:"
r"of\s+age|old|or\s+older|or\s+above|or\s+over|"
r"of\s+(?:serving|trusted|protecting|innovation|legacy|operation|"
r"delivering|providing|growth|history|excellence|leadership|service|business|"
r"caring|helping|supporting|empowering|combined|operating|"
r"trusted\s+service|continuous\s+(?:operation|service))|"
r"contract|plan|program|degree|warrant|anniversar|"
r"after\s+graduation|post\s+graduation|of\s+graduation|from\s+graduation|"
r"after\s+receiving|since\s+graduation|fellow|residency|residencies"
r")\b"
)
# Suppression patterns checked against the text *immediately before* the year
# match. Catches company-tenure brags like "with over 25 years of experience"
# where the GOOD_CONTEXT word appears but it refers to the firm, not the candidate.
SUPPRESS_BEFORE = re.compile(
r"(?i)(?:"
r"\bwith\s+(?:over|more\s+than|nearly|almost)\s*$|"
r"\bfor\s+(?:over|more\s+than|nearly|almost)\s*$|"
r"\bover\s+the\s+(?:last|past)\s*$|"
r"\bin\s+the\s+(?:last|past)\s*$|"
r"\bteam\s+(?:averages?|brings?)\s+(?:over\s+)?$|"
r"\baverages?\s+(?:over\s+)?$|"
r"\bcombined\s+(?:over\s+)?$|"
r"\b(?:has|have|having)\s+been\s+(?:in\s+business|operating|serving|providing)\s+(?:for\s+)?(?:over|more\s+than)?\s*$|"
r"\b(?:we|our\s+team|our\s+firm|our\s+company)\s+(?:have|has|are\s+celebrating)\s+(?:over|more\s+than|been)?\s*$"
r")"
)
CONTEXT_WINDOW = 100
SUPPRESS_LOOKAHEAD = 30
SUPPRESS_LOOKBEHIND = 60
@dataclass
class RegexHit:
min_years: int
max_years: int | None
span: tuple[int, int]
evidence: str
score: int
def _context_score(text: str, span: tuple[int, int]) -> int:
s = max(0, span[0] - CONTEXT_WINDOW)
e = min(len(text), span[1] + CONTEXT_WINDOW)
window = text[s:e]
has_good = bool(GOOD_CONTEXT.search(window))
has_bad = bool(BAD_CONTEXT.search(window))
if has_bad and not has_good:
return -1
if has_good:
return 2
return 1
def _add_hit(hits: list[RegexHit], text: str, m: re.Match, mn: int, mx: int | None, base_score: int) -> None:
after = text[m.end(): m.end() + SUPPRESS_LOOKAHEAD]
if SUPPRESS_AFTER.match(after):
return
before = text[max(0, m.start() - SUPPRESS_LOOKBEHIND): m.start()]
if SUPPRESS_BEFORE.search(before):
return
score = _context_score(text, m.span()) + base_score
if score <= 0:
return
hits.append(
RegexHit(
min_years=mn,
max_years=mx,
span=m.span(),
evidence=text[max(0, m.start() - 30): m.end() + 30].strip(),
score=score,
)
)
def extract_year_hits(raw_text: str) -> list[RegexHit]:
text = raw_text or ""
hits: list[RegexHit] = []
for m in RANGE_RX.finditer(text):
a, b = int(m.group(1)), int(m.group(2))
lo, hi = (a, b) if a <= b else (b, a)
_add_hit(hits, text, m, lo, hi, base_score=2)
for m in WORD_RANGE_RX.finditer(text):
a = NUMBER_WORDS[m.group(1).lower()]
b = NUMBER_WORDS[m.group(2).lower()]
lo, hi = (a, b) if a <= b else (b, a)
_add_hit(hits, text, m, lo, hi, base_score=2)
for m in PLUS_RX.finditer(text):
_add_hit(hits, text, m, int(m.group(1)), None, base_score=2)
for m in MIN_RX.finditer(text):
_add_hit(hits, text, m, int(m.group(1)), None, base_score=2)
for m in OR_MORE_RX.finditer(text):
_add_hit(hits, text, m, int(m.group(1)), None, base_score=2)
for m in WORD_RX.finditer(text):
n = NUMBER_WORDS[m.group(1).lower()]
_add_hit(hits, text, m, n, None, base_score=0)
consumed: list[tuple[int, int]] = [h.span for h in hits]
for m in GENERIC_RX.finditer(text):
if any(s <= m.start() < e or s < m.end() <= e for s, e in consumed):
continue
_add_hit(hits, text, m, int(m.group(1)), None, base_score=0)
return hits
REQUIREMENT_CAP = 25
def regex_predict(raw_text: str) -> dict | None:
"""Return ``None`` if no confident year mention found; otherwise dict with
``experience_level``, ``min_years``, ``max_years``, ``evidence``, ``confidence``.
"""
hits = extract_year_hits(raw_text)
# Discard absurdly large values - real job postings rarely require >25 yrs;
# higher numbers are almost always company tenure ("for over 80 years").
hits = [h for h in hits if h.min_years <= REQUIREMENT_CAP]
if not hits:
return None
hits.sort(key=lambda h: (h.score, h.min_years), reverse=True)
top = hits[0]
if top.score < 2:
return None
return {
"experience_level": years_to_class(top.min_years),
"min_years": top.min_years,
"max_years": top.max_years,
"evidence": top.evidence,
"confidence": min(1.0, 0.6 + 0.1 * top.score),
}
def regex_predict_focus(focus_text: str, *, sentence_level: bool) -> dict | None:
"""Regex pass on ``focus_text``. When ``sentence_level``, only sentences that
contain experience-keywords are scanned; evidence is the full sentence.
"""
if not sentence_level:
return regex_predict(focus_text)
all_hits: list[RegexHit] = []
for sent in split_sentences(focus_text):
if not SENTENCE_EXP_KW.search(sent):
continue
for h in extract_year_hits(sent):
if h.min_years > REQUIREMENT_CAP:
continue
all_hits.append(
RegexHit(
min_years=h.min_years,
max_years=h.max_years,
span=h.span,
evidence=sent.strip(),
score=h.score,
)
)
if not all_hits:
return None
all_hits.sort(key=lambda h: (h.score, h.min_years), reverse=True)
top = all_hits[0]
if top.score < 2:
return None
return {
"experience_level": years_to_class(top.min_years),
"min_years": top.min_years,
"max_years": top.max_years,
"evidence": top.evidence,
"confidence": min(1.0, 0.6 + 0.1 * top.score),
}
def regex_predict_for_row(row: dict) -> dict | None:
"""Regex stage aligned with hybrid inference (section + optional sentence mode)."""
focus, _, _ = row_to_inference_texts(row)
if USE_STRUCTURAL_PHASE1:
return regex_predict_focus(focus, sentence_level=True)
return regex_predict(focus)
def ml_fallback_predict(
ml_text: str,
vec: TfidfVectorizer,
clf: LogisticRegression,
proba_row: np.ndarray | None = None,
classes_arr: np.ndarray | None = None,
) -> tuple[int, float]:
"""Returns (predicted_class, top_probability)."""
if proba_row is None:
top_class, top_prob, _ = ml_predict(vec, clf, ml_text)
return top_class, top_prob
assert classes_arr is not None
top_idx = int(np.argmax(proba_row))
return int(classes_arr[top_idx]), float(proba_row[top_idx])
def predict_row_hybrid(
row: dict,
vec: TfidfVectorizer,
clf: LogisticRegression,
*,
ml_proba_row: np.ndarray | None = None,
ml_classes: np.ndarray | None = None,
) -> dict:
"""Core hybrid logic: regex -> negation -> title prior -> ML/default."""
focus, ml_text, section_used = row_to_inference_texts(row)
title = row.get("OrigJobTitle") or row.get("title") or ""
regex_result = regex_predict_for_row(row)
base_meta = {"experience_section_used": section_used}
if regex_result is not None:
return {
**base_meta,
"experience_level": int(regex_result["experience_level"]),
"experience_source": "regex",
"experience_confidence": round(float(regex_result["confidence"]), 3),
"experience_evidence": regex_result["evidence"],
"experience_min_years": regex_result["min_years"],
"experience_max_years": regex_result["max_years"],
}
if USE_STRUCTURAL_PHASE1:
neg_ev = negation_find_evidence(focus)
if neg_ev:
return {
**base_meta,
"experience_level": 1,
"experience_source": "negation",
"experience_confidence": round(NEGATION_CONFIDENCE, 3),
"experience_evidence": neg_ev,
"experience_min_years": None,
"experience_max_years": None,
}
tp = title_prior_predict(title)
if tp is not None:
return {
**base_meta,
"experience_level": int(tp["experience_level"]),
"experience_source": "title",
"experience_confidence": round(float(tp["confidence"]), 3),
"experience_evidence": tp["evidence"],
"experience_min_years": None,
"experience_max_years": None,
}
top_class, top_prob = ml_fallback_predict(
ml_text, vec, clf, ml_proba_row, ml_classes
)
if top_prob >= ML_CONFIDENCE_THRESHOLD:
return {
**base_meta,
"experience_level": int(top_class),
"experience_source": "ml",
"experience_confidence": round(top_prob, 3),
"experience_evidence": None,
"experience_min_years": None,
"experience_max_years": None,
}
return {
**base_meta,
"experience_level": 1,
"experience_source": "default",
"experience_confidence": round(top_prob, 3),
"experience_evidence": None,
"experience_min_years": None,
"experience_max_years": None,
}
def build_pseudo_label_table(
corpus: list[dict],
true_ids: set[str],
*,
include_title_pseudo: bool,
) -> tuple[list[dict], dict[str, int]]:
"""Weak labels from regex / negation / optional title priors. Skips IDs in ``true_ids``.
Each row is a shallow copy of a corpus record plus ``y``, ``sample_weight``,
and ``pseudo_source`` for training only (stripped before inference).
"""
out: list[dict] = []
stats = {"regex": 0, "negation": 0, "title": 0}
for row in corpus:
jid = str(row.get("UniqueJobAdID", "")).strip()
if not jid or jid in true_ids:
continue
rr = regex_predict_for_row(row)
if rr is not None:
pr = dict(row)
pr["y"] = int(rr["experience_level"])
pr["sample_weight"] = PSEUDO_WEIGHT_REGEX
pr["pseudo_source"] = "regex"
out.append(pr)
stats["regex"] += 1
continue
if USE_STRUCTURAL_PHASE1:
focus, _, _ = row_to_inference_texts(row)
if negation_find_evidence(focus):
pr = dict(row)
pr["y"] = 1
pr["sample_weight"] = PSEUDO_WEIGHT_NEGATION
pr["pseudo_source"] = "negation"
out.append(pr)
stats["negation"] += 1
continue
if include_title_pseudo:
title = row.get("OrigJobTitle") or ""
tp = title_prior_predict(title)
if tp is not None:
pr = dict(row)
pr["y"] = int(tp["experience_level"])
pr["sample_weight"] = PSEUDO_WEIGHT_TITLE
pr["pseudo_source"] = "title"
out.append(pr)
stats["title"] += 1
return out, stats
# ---------------------------------------------------------------------------
# ML model
# ---------------------------------------------------------------------------
def build_vectorizer() -> TfidfVectorizer:
return TfidfVectorizer(
ngram_range=(1, 2),
min_df=2,
max_df=0.95,
sublinear_tf=True,
strip_accents="unicode",
lowercase=True,
max_features=50000,
)
def train_model(
train_rows: list[dict],
corpus_rows: list[dict],
pseudo_rows: list[dict] | None = None,
) -> tuple[TfidfVectorizer, LogisticRegression, dict]:
corpus_texts = [make_ml_input(r) for r in corpus_rows]
vec = build_vectorizer()
vec.fit(corpus_texts)
train_texts = [make_ml_input(r) for r in train_rows]
y_true_only = np.array([r["y"] for r in train_rows])
X_true_only = vec.transform(train_texts)
clf = LogisticRegression(
max_iter=2000,
class_weight="balanced",
C=1.0,
)
# CV only on trusted labels (no pseudo-label leakage).
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
y_pred_cv = cross_val_predict(clf, X_true_only, y_true_only, cv=skf, method="predict")
pseudo_rows = pseudo_rows or []
if pseudo_rows:
pseudo_texts = [make_ml_input(r) for r in pseudo_rows]
X_pseudo = vec.transform(pseudo_texts)
y_pseudo = np.array([int(r["y"]) for r in pseudo_rows])
w_true = np.full(len(train_rows), PSEUDO_WEIGHT_TRUE, dtype=np.float64)
w_pseudo = np.array([float(r["sample_weight"]) for r in pseudo_rows], dtype=np.float64)
X_fit = sparse_vstack([X_true_only, X_pseudo])
y_fit = np.concatenate([y_true_only, y_pseudo])
w_fit = np.concatenate([w_true, w_pseudo])
clf.fit(X_fit, y_fit, sample_weight=w_fit)
pseudo_counts: dict[str, int] = {}
for r in pseudo_rows:
src = str(r.get("pseudo_source", "unknown"))
pseudo_counts[src] = pseudo_counts.get(src, 0) + 1
weighted_mass = float(w_fit.sum())
else:
clf.fit(X_true_only, y_true_only)
pseudo_counts = {}
weighted_mass = float(len(train_rows))
metrics = {
"n_train": int(len(y_true_only)),
"class_distribution": {
int(k): int((y_true_only == k).sum()) for k in sorted(set(y_true_only))
},
"cv_accuracy": float(accuracy_score(y_true_only, y_pred_cv)),
"cv_macro_f1": float(f1_score(y_true_only, y_pred_cv, average="macro", zero_division=0)),
"cv_classification_report": classification_report(
y_true_only, y_pred_cv, zero_division=0, output_dict=True
),
"cv_classification_report_text": classification_report(y_true_only, y_pred_cv, zero_division=0),
"n_pseudo": len(pseudo_rows),
"pseudo_counts_by_source": pseudo_counts,
"weighted_fit_mass": weighted_mass,
"pseudo_weights_scheme": (
f"true={PSEUDO_WEIGHT_TRUE}, regex={PSEUDO_WEIGHT_REGEX}, "
f"negation={PSEUDO_WEIGHT_NEGATION}, title={PSEUDO_WEIGHT_TITLE}"
),
}
return vec, clf, metrics
def ml_predict(vec: TfidfVectorizer, clf: LogisticRegression, raw_text: str) -> tuple[int, float, dict]:
X = vec.transform([raw_text.lower()])
probs = clf.predict_proba(X)[0]
classes = list(clf.classes_)
top_idx = int(np.argmax(probs))
top_class = int(classes[top_idx])
top_prob = float(probs[top_idx])
prob_map = {int(c): float(p) for c, p in zip(classes, probs)}
return top_class, top_prob, prob_map
# ---------------------------------------------------------------------------
# Hybrid inference
# ---------------------------------------------------------------------------
def hybrid_predict(
rows: list[dict],
vec: TfidfVectorizer,
clf: LogisticRegression,
) -> list[dict]:
out: list[dict] = []
for r in rows:
rec = dict(r)
rec.update(predict_row_hybrid(r, vec, clf))
out.append(rec)
return out
# ---------------------------------------------------------------------------
# Reporting
# ---------------------------------------------------------------------------
def regex_coverage(rows: list[dict]) -> dict:
n = len(rows)
hit_count = 0
class_counts = {1: 0, 2: 0, 3: 0, 4: 0}
for r in rows:
result = regex_predict_for_row(r)
if result is not None:
hit_count += 1
class_counts[result["experience_level"]] += 1
return {
"n": n,
"regex_hits": hit_count,
"regex_hit_rate": hit_count / n if n else 0.0,
"class_counts_among_hits": class_counts,
}
def hybrid_eval_on_labeled(
train_rows: list[dict],
vec: TfidfVectorizer,
clf: LogisticRegression,
) -> dict:
"""Score the hybrid pipeline on the labeled set (regex fires freely; ML is
used out-of-fold via cross_val_predict to avoid leakage).
"""
y_true = np.array([r["y"] for r in train_rows])
texts = [make_ml_input(r) for r in train_rows]
X = vec.transform(texts)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
fresh_clf = LogisticRegression(max_iter=2000, class_weight="balanced", C=1.0)
fresh_clf.fit(X, y_true)
classes_arr = fresh_clf.classes_
proba_oof = cross_val_predict(fresh_clf, X, y_true, cv=skf, method="predict_proba")
y_hybrid = np.empty_like(y_true)
sources: list[str] = []
for i, r in enumerate(train_rows):
pred = predict_row_hybrid(
r, vec, clf, ml_proba_row=proba_oof[i], ml_classes=classes_arr
)
y_hybrid[i] = pred["experience_level"]
sources.append(str(pred["experience_source"]))
# Macro-F1 only over labels present in y_true (training set has no class 4 rows).
label_universe = sorted(set(int(x) for x in y_true))
return {
"regex_only_hit_rate": float(np.mean([s == "regex" for s in sources])),
"negation_rate": float(np.mean([s == "negation" for s in sources])),
"title_prior_rate": float(np.mean([s == "title" for s in sources])),
"ml_used_rate": float(np.mean([s == "ml" for s in sources])),
"default_used_rate": float(np.mean([s == "default" for s in sources])),
"hybrid_accuracy": float(accuracy_score(y_true, y_hybrid)),
"hybrid_macro_f1": float(
f1_score(
y_true,
y_hybrid,
average="macro",
labels=label_universe,
zero_division=0,
)
),
"hybrid_report_text": classification_report(y_true, y_hybrid, zero_division=0),
}
def write_eval_report(
path: Path,
train_metrics: dict,
coverage: dict,
hybrid_metrics: dict,
) -> None:
lines: list[str] = []
lines.append("# Experience Classifier - Evaluation Report\n")
lines.append(f"- Training rows: **{train_metrics['n_train']}** unique IDs\n")
lines.append("- Class distribution in training set:\n")
for k, v in sorted(train_metrics["class_distribution"].items()):
lines.append(f" - class {k} ({CLASS_LABELS[k]}): {v}")
lines.append("")
lines.append("## Regex Coverage on 5000-job Corpus\n")
lines.append(f"- Confident regex hits: **{coverage['regex_hits']} / {coverage['n']} "
f"({coverage['regex_hit_rate']*100:.1f}%)**")
lines.append("- Class distribution among regex hits:")
for k, v in sorted(coverage["class_counts_among_hits"].items()):
lines.append(f" - class {k} ({CLASS_LABELS[k]}): {v}")
lines.append("")
if train_metrics.get("n_pseudo", 0):
lines.append("## Pseudo-Label Training\n")
lines.append(
f"- Trusted (hand-labeled) rows: **{train_metrics['n_train']}**; "
f"pseudo-labeled rows: **{train_metrics['n_pseudo']}**"
)
lines.append(f"- Sample-weight scheme: `{train_metrics.get('pseudo_weights_scheme', '')}`")
lines.append(f"- Total weighted training mass: **{train_metrics.get('weighted_fit_mass', 0):.0f}**")
lines.append("- Pseudo-label counts by source:")
for src, cnt in sorted(train_metrics.get("pseudo_counts_by_source", {}).items()):
lines.append(f" - {src}: {cnt}")
lines.append("- **Note:** 5-fold CV metrics below are computed on **trusted labels only** (no pseudo rows).\n")
lines.append("## ML Fallback (TF-IDF + Logistic Regression)\n")
lines.append(f"- 5-fold CV accuracy (trusted labels only): **{train_metrics['cv_accuracy']:.3f}**")
lines.append(f"- 5-fold CV macro-F1 (trusted labels only): **{train_metrics['cv_macro_f1']:.3f}**\n")
lines.append("```")
lines.append(train_metrics["cv_classification_report_text"].rstrip())
lines.append("```\n")
lines.append("## Hybrid Pipeline (regex first, ML fallback) on Labeled Set\n")
lines.append(f"- Regex-fired share: **{hybrid_metrics['regex_only_hit_rate']*100:.1f}%**")
if "negation_rate" in hybrid_metrics:
lines.append(f"- Negation rule share: **{hybrid_metrics['negation_rate']*100:.1f}%**")
if "title_prior_rate" in hybrid_metrics:
lines.append(f"- Title-prior share: **{hybrid_metrics['title_prior_rate']*100:.1f}%**")
lines.append(f"- ML-fallback share: **{hybrid_metrics['ml_used_rate']*100:.1f}%**")
lines.append(f"- Defaulted share: **{hybrid_metrics['default_used_rate']*100:.1f}%**")
lines.append(f"- Hybrid accuracy: **{hybrid_metrics['hybrid_accuracy']:.3f}**")
lines.append(f"- Hybrid macro-F1: **{hybrid_metrics['hybrid_macro_f1']:.3f}**\n")
lines.append("```")
lines.append(hybrid_metrics["hybrid_report_text"].rstrip())
lines.append("```\n")
lines.append("## Class Definition\n")
for k, label in CLASS_LABELS.items():
lines.append(f"- {k} = {label}")
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
def write_active_learning_queue(
path: Path, predictions: list[dict], top_n: int = ACTIVE_LEARNING_TOP_N
) -> None:
fallback = [p for p in predictions if p.get("experience_source") in ("ml", "default")]
fallback.sort(key=lambda p: p.get("experience_confidence") or 0.0)
queue = fallback[:top_n]
out = [
{
"UniqueJobAdID": p.get("UniqueJobAdID"),
"OrigJobTitle": p.get("OrigJobTitle"),
"EmployerOrgName": p.get("EmployerOrgName"),
"predicted_experience_level": p.get("experience_level"),
"experience_source": p.get("experience_source"),
"experience_confidence": p.get("experience_confidence"),
}
for p in queue
]
path.write_text(json.dumps(out, indent=2), encoding="utf-8")
def needs_human_review(pred: dict) -> tuple[bool, str | None]:
source = pred.get("experience_source")
conf = float(pred.get("experience_confidence") or 0.0)
if source == "default":
return True, "default_fallback_low_confidence"
if source == "ml" and conf < HUMAN_REVIEW_ML_THRESHOLD:
return True, "ml_below_review_threshold"
if source == "regex" and pred.get("experience_level") == 4 and (pred.get("experience_min_years") or 0) >= 18:
return True, "senior_regex_needs_spot_check"
return False, None
def write_flagged_jobs_for_review(path: Path, predictions: list[dict]) -> int:
flagged: list[dict] = []
for p in predictions:
should_flag, reason = needs_human_review(p)
if not should_flag:
continue
flagged.append(
{
"UniqueJobAdID": p.get("UniqueJobAdID"),
"OrigJobTitle": p.get("OrigJobTitle"),
"EmployerOrgName": p.get("EmployerOrgName"),
"predicted_experience_level": p.get("experience_level"),
"experience_source": p.get("experience_source"),
"experience_confidence": p.get("experience_confidence"),
"experience_min_years": p.get("experience_min_years"),
"experience_evidence": p.get("experience_evidence"),
"review_reason": reason,
}
)
path.write_text(json.dumps(flagged, indent=2), encoding="utf-8")
return len(flagged)
def annotate_predictions_with_review_flags(predictions: list[dict]) -> None:
"""Annotate predictions in-place with review metadata."""
for p in predictions:
should_flag, reason = needs_human_review(p)
p["needs_human_review"] = bool(should_flag)
p["review_reason"] = reason
# ---------------------------------------------------------------------------
# Top-level commands
# ---------------------------------------------------------------------------
def cmd_train(
labeled_path: Path = LABELED_PATH,
*,
use_pseudo_labels: bool = True,
include_title_pseudo: bool = False,
) -> tuple[TfidfVectorizer, LogisticRegression, list[dict], list[dict]]:
print("[load] labeled rows ...")
labeled = load_labeled(labeled_path)
print("[load] corpus ...")
corpus = load_corpus()
train_rows = build_train_table(labeled, corpus)
print(f"[train] unique training rows: {len(train_rows)} (from {labeled_path.name})")
pseudo_rows: list[dict] | None = None
effective_pseudo = USE_PSEUDO_LABELS and use_pseudo_labels
effective_title = USE_TITLE_PSEUDO_LABELS or include_title_pseudo
if effective_pseudo:
true_ids = {str(r["id"]).strip() for r in train_rows}
pseudo_rows, pstats = build_pseudo_label_table(
corpus, true_ids, include_title_pseudo=effective_title
)
print(
f"[train] pseudo-labels: regex={pstats['regex']}, negation={pstats['negation']}, "
f"title={pstats['title']} (title_pseudo={effective_title})"
)
else:
pseudo_rows = None
print("[train] pseudo-labels: disabled")
vec, clf, metrics = train_model(train_rows, corpus, pseudo_rows)
print(f"[train] CV accuracy: {metrics['cv_accuracy']:.3f}, macro-F1: {metrics['cv_macro_f1']:.3f}")
print("[eval] regex coverage on corpus ...")
coverage = regex_coverage(corpus)
print(f"[eval] regex hit rate: {coverage['regex_hit_rate']*100:.1f}%")
print("[eval] hybrid metrics on labeled set ...")
hybrid_metrics = hybrid_eval_on_labeled(train_rows, vec, clf)
print(
f"[eval] hybrid accuracy: {hybrid_metrics['hybrid_accuracy']:.3f}, "
f"hybrid macro-F1: {hybrid_metrics['hybrid_macro_f1']:.3f}"
)
write_eval_report(EVAL_REPORT_PATH, metrics, coverage, hybrid_metrics)
print(f"[write] {EVAL_REPORT_PATH}")
joblib.dump({"vectorizer": vec, "model": clf}, MODEL_PATH)
print(f"[write] {MODEL_PATH}")
return vec, clf, train_rows, corpus
def cmd_predict(
vec: TfidfVectorizer | None = None,
clf: LogisticRegression | None = None,
corpus: list[dict] | None = None,
) -> None:
if vec is None or clf is None:
bundle = joblib.load(MODEL_PATH)
vec, clf = bundle["vectorizer"], bundle["model"]
if corpus is None:
corpus = load_corpus()
test_rows = load_test()
test_preds = hybrid_predict(test_rows, vec, clf)
annotate_predictions_with_review_flags(test_preds)
PRED_TEST_PATH.write_text(json.dumps(test_preds, indent=2), encoding="utf-8")
print(f"[write] {PRED_TEST_PATH} ({len(test_preds)} rows)")
all_preds = hybrid_predict(corpus, vec, clf)
annotate_predictions_with_review_flags(all_preds)
PRED_ALL_PATH.write_text(json.dumps(all_preds, indent=2), encoding="utf-8")
print(f"[write] {PRED_ALL_PATH} ({len(all_preds)} rows)")
write_active_learning_queue(ACTIVE_LEARNING_PATH, all_preds)
print(f"[write] {ACTIVE_LEARNING_PATH}")
flagged_count = write_flagged_jobs_for_review(FLAGGED_REVIEW_PATH, all_preds)
print(f"[write] {FLAGGED_REVIEW_PATH} ({flagged_count} rows)")
sources = {}
levels = {}
for p in all_preds:
sources[p["experience_source"]] = sources.get(p["experience_source"], 0) + 1
levels[p["experience_level"]] = levels.get(p["experience_level"], 0) + 1
print(f"[summary] sources: {sources}")
print(f"[summary] levels: {dict(sorted(levels.items()))}")
def main(argv: Iterable[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("command", choices=["train", "predict", "all"], help="Pipeline step to run.")
parser.add_argument(
"--labeled-path",
default=str(LABELED_PATH),
help="Path to labeled JSON file (supports list format or {'labels': [...]}).",
)
parser.add_argument(
"--no-pseudo-labels",
action="store_true",
help="Train ML only on trusted labels (disable corpus pseudo-labels).",
)
parser.add_argument(
"--with-title-pseudo-labels",
action="store_true",
help="Include title-prior predictions as weak pseudo-labels (noisier).",
)
args = parser.parse_args(list(argv) if argv is not None else None)
labeled_path = Path(args.labeled_path)
use_pseudo = not args.no_pseudo_labels
if args.command == "train":
cmd_train(labeled_path, use_pseudo_labels=use_pseudo, include_title_pseudo=args.with_title_pseudo_labels)
elif args.command == "predict":
cmd_predict()
else:
vec, clf, _, corpus = cmd_train(
labeled_path,
use_pseudo_labels=use_pseudo,
include_title_pseudo=args.with_title_pseudo_labels,
)
cmd_predict(vec, clf, corpus)
return 0
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
"""Hybrid years-of-experience classifier for job postings.
Outputs an integer ``experience_level`` per posting:
1 = 0-2 years (entry / no experience)
2 = 3-5 years (early career)
3 = 6-15 years (mid career)
4 = 16+ years (senior)
Pipeline:
1. Regex first-pass over title + description for explicit "X years" mentions
in an experience-related context. If a confident match is found, map the
extracted minimum to the class above.
2. Otherwise fall back to a TF-IDF + Logistic Regression model that was
trained on the labeled subset (Jobs_1_100.json), with the TF-IDF
vocabulary fit on the full 5000-job corpus (semi-supervised).
3. If the ML top-class probability is below ``ML_CONFIDENCE_THRESHOLD``,
default to class 1 (entry) and flag the row for active-learning review.
CLI:
python experience_classifier.py train [--labeled-path FILE] [--no-pseudo-labels] [--with-title-pseudo-labels]
python experience_classifier.py predict # predict on test_jobs.json + corpus
python experience_classifier.py all [...] # train then predict
"""
from __future__ import annotations
import argparse
import csv
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import joblib
import numpy as np
from scipy.sparse import vstack as sparse_vstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, f1_score, accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
# ---------------------------------------------------------------------------
# Paths and constants
# ---------------------------------------------------------------------------
ROOT = Path(__file__).resolve().parent
LABELED_PATH = ROOT / "Jobs_1_100.json"
CORPUS_PATH = ROOT / "Candogram-5000-random-jobs.csv"
TEST_PATH = ROOT / "test_jobs.json"
PRED_TEST_PATH = ROOT / "predictions_test_jobs.json"
PRED_ALL_PATH = ROOT / "predictions_all.json"
ACTIVE_LEARNING_PATH = ROOT / "active_learning_queue.json"
FLAGGED_REVIEW_PATH = ROOT / "flagged_jobs_for_review.json"
EVAL_REPORT_PATH = ROOT / "eval_report.md"
MODEL_PATH = ROOT / "experience_model.joblib"
CLASS_LABELS = {
1: "entry (0-2 yrs)",
2: "early career (3-5 yrs)",
3: "mid career (6-15 yrs)",
4: "senior (16+ yrs)",
}
ML_CONFIDENCE_THRESHOLD = 0.50
ACTIVE_LEARNING_TOP_N = 100
HUMAN_REVIEW_ML_THRESHOLD = 0.65
# Phase 1 structural upgrades (section extraction, sentence-level regex,
# negation handling, title priors). Set False for legacy behavior.
USE_STRUCTURAL_PHASE1 = True
TITLE_PRIOR_CONFIDENCE = 0.65
NEGATION_CONFIDENCE = 0.90
# Semi-supervised pseudo-labels (regex / negation / optional title) on the corpus.
USE_PSEUDO_LABELS = True
USE_TITLE_PSEUDO_LABELS = False
PSEUDO_WEIGHT_TRUE = 5.0
PSEUDO_WEIGHT_REGEX = 1.0
PSEUDO_WEIGHT_NEGATION = 1.0
PSEUDO_WEIGHT_TITLE = 0.5
# ---------------------------------------------------------------------------
# Class mapping
# ---------------------------------------------------------------------------
def years_to_class(years: float) -> int:
if years <= 2:
return 1
if years <= 5:
return 2
if years <= 15:
return 3
return 4
# ---------------------------------------------------------------------------