Skip to content

Instantly share code, notes, and snippets.

@tonydzi
Last active October 8, 2026 17:30
Show Gist options
  • Select an option

  • Save tonydzi/7ee108dca7f8ae324501c8ea97b6e5c4 to your computer and use it in GitHub Desktop.

Select an option

Save tonydzi/7ee108dca7f8ae324501c8ea97b6e5c4 to your computer and use it in GitHub Desktop.
JD keywords -> resume gaps: advisory three-bucket scorer (covered / missing_in_cv / unknown_hot), stdlib only, 12 offline tests
r"""jd_skills_gap.py - JD keywords -> gaps in a resume. Advisory, offline-testable, stdlib only.
Why this shape: ATS filters and recruiters match on words taken FROM THE JOB DESCRIPTION.
A tailoring pipeline that optimises a single percentage will happily "gain" skills the
person never had, and a score that moves 62% -> 88% by inventing Azure Functions is worse
than no score. So this reports three buckets instead of one number:
covered terms in the JD that the SELECTED resume variant already carries
(this is the evidence of a match, not a promise of one)
missing_in_cv terms in the JD that exist in a lexicon built from the union of the
user's OWN resume variants, but are absent from the selected variant
-> either weave it in (the experience is real, it lives in another
variant) or the wrong variant was selected for this role
unknown_hot frequent technical terms in the JD (3+ occurrences) present in NO
variant at all -> candidates to ask the human about, never to auto-insert
The lexicon bound is the whole point: `missing_in_cv` is by construction a subset of what
the person already wrote about themselves somewhere.
This module is ADVISORY. It writes nothing into a resume and never blocks a submission;
callers wrap it in try/except and log one SKIP line when the network is unavailable.
Resume variants: any directory of markdown files. The filename stem is the variant key,
and the lexicon is seeded from each file's `## Skills` section, then each term is
confirmed against the FULL text of every variant (a term can be proven by a bullet in
the experience section even when it is missing from that variant's Skills line).
CLI:
python3 jd_skills_gap.py --variants ./resumes <url> <variant> [ats]
python3 jd_skills_gap.py --variants ./resumes --lexicon
Tests: test_jd_skills_gap.py (offline, network mocked).
No LLM calls: matching words is a job for code.
"""
import html
import json
import re
import sys
import urllib.request
from pathlib import Path
UA = "Mozilla/5.0 (X11; Linux x86_64) jd-gap/1.0"
# Words that look like terms but are not: generic prose, recruiter boilerplate, and the
# hub cities that appear capitalised mid-sentence in almost every posting.
STOP = {
"the", "and", "for", "you", "our", "with", "will", "are", "this", "that",
"team", "role", "work", "who", "what", "how", "your", "their", "about",
"job", "jobs", "apply", "candidate", "candidates", "experience", "years",
"requirements", "responsibilities", "benefits", "equal", "opportunity",
"employer", "please", "must", "have", "strong", "ability", "skills",
"knowledge", "including", "across", "within", "using", "from", "into",
"more", "than", "such", "well", "all", "any", "new",
"join", "bonus", "salary", "compensation", "equity", "hybrid", "remote",
"onsite", "location", "locations", "company", "mission", "vision",
"san", "francisco", "york", "london", "toronto", "seattle", "austin",
"boston", "denver", "chicago", "dublin", "berlin", "paris", "zurich",
"singapore", "tokyo", "sydney", "vancouver", "amsterdam", "angeles",
"mountain", "view", "alto", "palo", "diego", "jose", "states", "united",
"america", "europe", "canada", "monday", "friday", "january", "december",
}
def _http(url, timeout=25):
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"})
with urllib.request.urlopen(req, timeout=timeout) as x:
return x.read().decode("utf-8", "replace")
def _strip_tags(markup):
txt = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", markup)
txt = re.sub(r"(?s)<[^>]+>", " ", txt)
return re.sub(r"\s+", " ", html.unescape(txt)).strip()
def _jsonld_description(page):
"""Most career pages carry a schema.org JobPosting block with the full description."""
for m in re.finditer(r'(?is)<script[^>]+ld\+json[^>]*>(.*?)</script>', page):
try:
data = json.loads(m.group(1).strip())
except Exception:
continue
items = data if isinstance(data, list) else [data]
for it in items:
if isinstance(it, dict) and it.get("@type") == "JobPosting":
d = it.get("description") or ""
if len(d) > 200:
return _strip_tags(d)
return ""
def fetch_jd(url, ats=""):
"""JD text. Order: the board's own API -> the page's JSON-LD -> stripped HTML.
Fetching beats scraping: Lever and Greenhouse hand back clean JSON, so the
HTML path is the fallback, not the default.
"""
ats = (ats or "").lower()
m = re.search(r"jobs\.lever\.co/([^/]+)/([0-9a-f-]{36})", url)
if m and ats in ("lever", ""):
try:
data = json.loads(_http(f"https://api.lever.co/v0/postings/{m.group(1)}/{m.group(2)}"))
parts = [data.get("descriptionPlain", "")]
for lst in data.get("lists", []):
parts.append(lst.get("text", ""))
parts.append(_strip_tags(lst.get("content", "")))
txt = " ".join(p for p in parts if p)
if len(txt) > 200:
return txt
except Exception:
pass
m = re.search(r"boards\.greenhouse\.io/(?:embed/job_app\?for=)?([A-Za-z0-9_-]+)/jobs/(\d+)", url) \
or re.search(r"job-boards\.greenhouse\.io/([A-Za-z0-9_-]+)/jobs/(\d+)", url)
slug_jid = [(m.group(1), m.group(2))] if m else []
if not slug_jid:
# Greenhouse embedded on the company's own site: ?gh_jid=N, slug guessed from the host.
m = re.search(r"[?&]gh_jid=(\d+)", url)
h = re.search(r"https?://(?:www\.)?([^/]+)", url)
if m and h:
# The board slug is usually the company, which is rarely the FIRST label:
# careers.acme.com -> "careers" is wrong, "acme" is right. Try every label
# except the obvious subdomain words and the TLD, longest-first.
labels = [p for p in h.group(1).split(".")
if p not in ("careers", "jobs", "job", "work", "hire", "hiring",
"boards", "apply", "www", "com", "io", "co", "net",
"org", "ai", "dev", "app")]
cands = []
for p in labels:
cands += [p, p.replace("-", "")]
seen = set()
slug_jid = [(c, m.group(1)) for c in cands
if not (c in seen or seen.add(c))]
for slug, jid in slug_jid:
try:
data = json.loads(_http(f"https://boards-api.greenhouse.io/v1/boards/{slug}/jobs/{jid}"))
txt = _strip_tags(data.get("content", ""))
if len(txt) > 200:
return txt
except Exception:
continue
try:
page = _http(url)
except Exception:
return ""
txt = _jsonld_description(page)
if txt:
return txt
# Ashby ships the posting as JSON in the page under "descriptionHtml".
m = re.search(r'"descriptionHtml"\s*:\s*"((?:[^"\\]|\\.)*)"', page)
if m:
try:
return _strip_tags(json.loads(f'"{m.group(1)}"'))
except Exception:
pass
return _strip_tags(page)
def _skills_line(md_text):
"""Body of the `## Skills` section, and nothing else.
An EMPTY Skills section used to swallow the following section, because `(.+?)`
cannot match empty text and happily ran past the next `##` header - producing
terms like "## experience kubernetes". Cut at the first header line instead.
"""
m = re.search(r"(?m)^##\s+Skills\s*$", md_text)
if not m:
return ""
body = []
for line in md_text[m.end():].splitlines():
if line.lstrip().startswith("##"):
break
body.append(line)
return "\n".join(body)
def _norm(term):
return re.sub(r"\s+", " ", term.strip().lower())
def _word_rx(term):
"""Word-boundary match that survives '+' and '#': plain \b makes 'Go' match 'Google'
and 'C++' match nothing."""
return re.compile(r"(?<![a-z0-9])" + re.escape(term) + r"(?![a-z0-9])")
def load_lexicon(variants_dir):
"""Skill lexicon from every resume variant in a directory.
Returns (terms: {term -> set(variant keys whose FULL text proves it)},
full_texts: {variant key -> normalised full text}).
"""
src = Path(variants_dir)
per_variant_text, terms = {}, {}
for p in sorted(src.glob("*.md")):
raw = p.read_text(encoding="utf-8")
per_variant_text[p.stem] = " " + _norm(raw) + " "
for t in _skills_line(raw).split(","):
t = _norm(t)
if len(t) >= 2 and t not in STOP:
terms.setdefault(t, set())
for t in terms:
rx = _word_rx(t)
for variant, txt in per_variant_text.items():
if rx.search(txt):
terms[t].add(variant)
return terms, per_variant_text
def _hot_unknown(jd_text, all_cv_text, top=10):
"""Frequent technical terms in the JD that appear in no variant at all.
Three shapes count: acronyms (RLHF), CamelCase (PyTorch), and Capitalised words
MID-SENTENCE (Kubernetes). A capital at the start of a sentence carries no
information, so it is skipped - otherwise every posting reports "We" and "Our".
"""
freq = {}
for m in re.finditer(
# The symbol branch comes first: "C++", "C#", "F#" have ONE capital and end
# in characters that \b cannot follow, so the word branches never see them.
r"(?:(?<![A-Za-z0-9])[A-Z](?:\+\+|\#)(?![A-Za-z0-9])"
r"|\b(?:[A-Z]{2,}[A-Za-z0-9+#.]*[A-Za-z0-9+#]"
r"|[A-Z][a-z]+[A-Z][A-Za-z0-9]*|[A-Z][a-z]{2,})\b)",
jd_text):
w = m.group(0)
wl = w.lower()
# Substring containment here is the same defect the lexicon path already guards
# against: a resume mentioning "trust" silently suppressed "Rust" in the JD.
if wl in STOP or len(w) < 2 or _word_rx(wl).search(all_cv_text):
continue
if re.fullmatch(r"[A-Z][a-z]{2,}", w):
head = jd_text[max(0, m.start() - 2):m.start()]
if not head.strip() or head.rstrip()[-1:] in ".!?:;":
continue
freq[w] = freq.get(w, 0) + 1
hot = [(w, n) for w, n in freq.items() if n >= 3]
hot.sort(key=lambda x: (-x[1], x[0]))
return [w for w, _ in hot[:top]]
def gap(url, variant, variants_dir, ats="", jd_text=None):
"""The report. Pass jd_text directly to run fully offline."""
terms, cv_texts = load_lexicon(variants_dir)
if variant not in cv_texts:
raise KeyError(f"unknown variant: {variant!r} (have: {sorted(cv_texts)})")
blank = {"url": url, "variant": variant, "lexicon_terms": len(terms),
"covered": [], "missing_in_cv": [], "unknown_hot": []}
if not terms:
# An empty lexicon produces an empty report that reads exactly like "no gaps".
# Say so instead: every bucket is a claim about the lexicon, and there isn't one.
return dict(blank, jd_chars=0, error="empty-lexicon")
text = jd_text if jd_text is not None else fetch_jd(url, ats)
if len(text) < 200:
return dict(blank, jd_chars=len(text), error="jd-too-short")
jd_norm = " " + _norm(text) + " "
covered, missing = [], []
for t, variants in terms.items():
if not _word_rx(t).search(jd_norm):
continue
(covered if variant in variants else missing).append(t)
return {"url": url, "variant": variant, "jd_chars": len(text),
"lexicon_terms": len(terms),
"covered": sorted(covered), "missing_in_cv": sorted(missing),
"unknown_hot": _hot_unknown(text, " ".join(cv_texts.values()))}
def report_line(rep):
"""One line for an application log. Counts, not a percentage: the buckets mean
different things and averaging them away is how the invented-skill failure hides."""
if rep.get("error"):
return f"JD-GAP: {rep['error']} ({rep['jd_chars']} chars)"
return ("JD-GAP: covered=%d missing_in_cv=%s unknown_hot=%s"
% (len(rep["covered"]), rep["missing_in_cv"][:8], rep["unknown_hot"][:5]))
def _main(argv):
if "--variants" not in argv:
return "usage: jd_skills_gap.py --variants DIR URL VARIANT [ATS] | --variants DIR --lexicon"
i = argv.index("--variants")
vdir = argv[i + 1]
rest = argv[:i] + argv[i + 2:]
if rest[:1] == ["--lexicon"]:
terms, _ = load_lexicon(vdir)
for t in sorted(terms):
print(f"{t} -> {sorted(terms[t])}")
print(f"{len(terms)} terms")
return 0 if terms else 3 # an empty lexicon is a failure, not a quiet success
if len(rest) < 2:
return "usage: jd_skills_gap.py --variants DIR URL VARIANT [ATS]"
rep = gap(rest[0], rest[1], vdir, rest[2] if len(rest) > 2 else "")
print(json.dumps(rep, ensure_ascii=False, indent=1))
print(report_line(rep))
return 0
if __name__ == "__main__":
sys.exit(_main(sys.argv[1:]))
"""Mutation check: each mutation must make the suite RED, or the test is decorative."""
import pathlib
import shutil
import subprocess
import sys
import tempfile
HERE = pathlib.Path(__file__).resolve().parent
SRC = HERE / "jd_skills_gap.py"
TST = HERE / "test_jd_skills_gap.py"
MUTANTS = [
("invert covered/missing split",
"(covered if variant in variants else missing).append(t)",
"(missing if variant in variants else covered).append(t)"),
("drop sentence-start guard in _hot_unknown",
" if not head.strip() or head.rstrip()[-1:] in \".!?:;\":\n continue",
" pass"),
("word boundary -> plain substring",
'return re.compile(r"(?<![a-z0-9])" + re.escape(term) + r"(?![a-z0-9])")',
'return re.compile(re.escape(term))'),
("unknown_hot frequency floor 3 -> 1",
"hot = [(w, n) for w, n in freq.items() if n >= 3]",
"hot = [(w, n) for w, n in freq.items() if n >= 1]"),
("lexicon seeded from Skills only, never confirmed against full text",
" if rx.search(txt):\n terms[t].add(variant)",
" pass"),
]
def run(d):
return subprocess.run([sys.executable, "test_jd_skills_gap.py"], cwd=d,
capture_output=True, text=True)
def main():
with tempfile.TemporaryDirectory() as d:
shutil.copy(SRC, d)
shutil.copy(TST, d)
base = run(d)
print(f"BASELINE: {'GREEN' if base.returncode == 0 else 'RED'} "
f"{base.stderr.strip().splitlines()[-1] if base.stderr else ''}")
if base.returncode != 0:
print(base.stderr)
return 1
src_text = SRC.read_text(encoding="utf-8")
survivors = 0
for name, old, new in MUTANTS:
if old not in src_text:
print(f" !! MUTANT NOT APPLIED (anchor missing): {name}")
survivors += 1
continue
(pathlib.Path(d) / "jd_skills_gap.py").write_text(
src_text.replace(old, new, 1), encoding="utf-8")
r = run(d)
killed = r.returncode != 0
print(f" {'KILLED ' if killed else 'SURVIVED'} {name}")
if not killed:
survivors += 1
(pathlib.Path(d) / "jd_skills_gap.py").write_text(src_text, encoding="utf-8")
print(f"\n{len(MUTANTS) - survivors}/{len(MUTANTS)} mutants killed")
return 1 if survivors else 0
if __name__ == "__main__":
sys.exit(main())
r"""Offline tests for jd_skills_gap: network mocked, resume variants are fixtures in a tmpdir.
These were shown red before they were shown green. Two of the mutations used:
inverting `variant in variants` in gap() fails test_missing_vs_covered; dropping the
sentence-start guard in _hot_unknown() fails test_unknown_hot_finds_rlhf on "Run"/"Ship".
"""
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import jd_skills_gap as g
CV_A = """# Research Engineer
## Skills
python, c++, evals, eval harness, distributed systems, reproducibility
## Experience
**Technical Lead - Lab** (2023 - Present)
Built eval harness in python and c++ for distributed systems; reproducibility work.
"""
CV_B = """# DevRel
## Skills
developer relations, sdk, api design, community, python
## Experience
**Advocate** (2023 - Present)
SDK and api design tutorials in python for the community. Kubernetes mentioned once.
"""
JD = ("We need a Research Engineer. Requirements: python, eval harness, api design, "
"RLHF pipelines and RLHF experience required, RLHF at scale. "
"Run workloads on Kubernetes clusters, deploy with Kubernetes daily, love Kubernetes. "
"Ship services on Terraform stacks, manage Terraform state, review Terraform plans. "
"You will own distributed systems reliability. " * 3)
class Base(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
src = Path(self.tmp.name)
(src / "research.md").write_text(CV_A, encoding="utf-8")
(src / "devrel.md").write_text(CV_B, encoding="utf-8")
self.addCleanup(self.tmp.cleanup)
self.src = self.tmp.name
class TestLexicon(Base):
def test_terms_union_and_membership(self):
terms, _ = g.load_lexicon(self.src)
self.assertIn("eval harness", terms)
self.assertIn("api design", terms)
self.assertEqual(terms["eval harness"], {"research"})
# "python" is proven by the FULL text of both variants, not just one Skills line
self.assertEqual(terms["python"], {"research", "devrel"})
def test_word_boundary_no_substring_match(self):
rep = g.gap("u", "research", self.src,
jd_text="We use msdk and ac++b nothing real. " * 20)
self.assertNotIn("sdk", rep["covered"] + rep["missing_in_cv"])
self.assertNotIn("c++", rep["covered"])
class TestGap(Base):
def test_missing_vs_covered(self):
rep = g.gap("u", "research", self.src, jd_text=JD)
self.assertIn("python", rep["covered"])
self.assertIn("eval harness", rep["covered"])
self.assertIn("distributed systems", rep["covered"])
# in the JD and in our own lexicon (via devrel), but NOT in the research variant
self.assertIn("api design", rep["missing_in_cv"])
self.assertNotIn("api design", rep["covered"])
def test_unknown_hot_finds_rlhf(self):
rep = g.gap("u", "research", self.src, jd_text=JD)
self.assertIn("RLHF", rep["unknown_hot"]) # acronym
self.assertIn("Terraform", rep["unknown_hot"]) # capitalised mid-sentence
# Kubernetes appears in the devrel variant -> not unknown
self.assertNotIn("Kubernetes", rep["unknown_hot"])
# ordinary words that merely start a sentence must not leak through
self.assertNotIn("Run", rep["unknown_hot"])
self.assertNotIn("Ship", rep["unknown_hot"])
def test_unknown_hot_needs_three_occurrences(self):
# A term named once is a mention, not a requirement: the floor is what keeps
# the bucket worth reading. Jenkins appears once, Datadog three times.
jd = ("We run Datadog dashboards, alert from Datadog, page from Datadog. "
"The platform team owns reliability and on-call. " * 3
+ "Some of the build still runs on Jenkins today.")
rep = g.gap("u", "research", self.src, jd_text=jd)
self.assertIn("Datadog", rep["unknown_hot"])
self.assertNotIn("Jenkins", rep["unknown_hot"])
def test_short_jd_reports_error_not_crash(self):
rep = g.gap("u", "research", self.src, jd_text="tiny")
self.assertEqual(rep["error"], "jd-too-short")
def test_unknown_variant_raises_keyerror(self):
with self.assertRaises(KeyError):
g.gap("u", "no-such-variant", self.src, jd_text=JD)
def test_offline_fetch_reports_error(self):
with mock.patch.object(g, "fetch_jd", return_value=""):
rep = g.gap("https://x", "research", self.src)
self.assertEqual(rep["error"], "jd-too-short")
def test_report_line_shape(self):
line = g.report_line(g.gap("u", "research", self.src, jd_text=JD))
self.assertTrue(line.startswith("JD-GAP: covered="))
self.assertIn("unknown_hot=", line)
class TestReviewRegressions(Base):
"""Five defects found by an external reviewer after the first publish, each
reproduced as a wrong output before it was fixed."""
def test_unknown_hot_uses_word_boundaries_not_substrings(self):
# "trust" anywhere in a resume used to suppress "Rust" in the job description
jd = ("The service is written in Rust end to end, we love Rust, "
"and Rust experience is required. " * 3)
src = tempfile.mkdtemp()
Path(src, "research.md").write_text(
"# Eng\n## Skills\npython\n## Experience\nI build trust daily.\n",
encoding="utf-8")
self.assertIn("Rust", g.gap("u", "research", src, jd_text=jd)["unknown_hot"])
def test_symbol_terms_survive(self):
# Deliberately NOT self.src: that fixture lists c++, where suppressing it is right.
jd = ("The stack is C++ throughout, we write C++ daily, C++ is required. " * 6)
src = tempfile.mkdtemp()
Path(src, "research.md").write_text(
"# Eng\n## Skills\npython, sql\n## Experience\nPython services only.\n",
encoding="utf-8")
self.assertIn("C++", g.gap("u", "research", src, jd_text=jd)["unknown_hot"])
def test_empty_skills_section_does_not_swallow_next_section(self):
src = tempfile.mkdtemp()
Path(src, "research.md").write_text(
"# Eng\n## Skills\n\n## Experience\nkubernetes, terraform, postgres\n",
encoding="utf-8")
terms, _ = g.load_lexicon(src)
self.assertEqual(terms, {})
def test_greenhouse_slug_tries_company_label_not_just_the_first(self):
asked = []
def spy(url, timeout=25):
asked.append(url)
raise OSError("offline")
with mock.patch.object(g, "_http", spy):
g.fetch_jd("https://careers.acme.com/job?gh_jid=42", "greenhouse")
tried = [u.split("/boards/")[1].split("/")[0] for u in asked if "/boards/" in u]
self.assertIn("acme", tried)
def test_empty_lexicon_is_an_error_not_a_clean_report(self):
src = tempfile.mkdtemp()
Path(src, "research.md").write_text("# Eng\nno skills section\n", encoding="utf-8")
rep = g.gap("u", "research", src, jd_text=JD)
self.assertEqual(rep["error"], "empty-lexicon")
class TestFetchParsers(unittest.TestCase):
def test_lever_api_parsed(self):
payload = json.dumps({"descriptionPlain": "Long role text " * 30,
"lists": [{"text": "Requirements",
"content": "<li>python</li>"}]})
with mock.patch.object(g, "_http", return_value=payload):
txt = g.fetch_jd("https://jobs.lever.co/acme/"
"12345678-1234-1234-1234-123456789abc", "lever")
self.assertIn("python", txt)
def test_jsonld_jobposting_extracted(self):
page = ('<html><script type="application/ld+json">'
+ json.dumps({"@type": "JobPosting",
"description": "<p>" + "Real JD text here. " * 30 + "</p>"})
+ "</script><body>chrome shell</body></html>")
with mock.patch.object(g, "_http", return_value=page):
txt = g.fetch_jd("https://company.com/hr/job?gh_jid=1", "greenhouse")
self.assertIn("Real JD text here", txt)
self.assertNotIn("chrome shell", txt)
def test_network_dead_returns_empty(self):
with mock.patch.object(g, "_http", side_effect=OSError("net down")):
self.assertEqual(g.fetch_jd("https://jobs.lever.co/a/b", "lever"), "")
if __name__ == "__main__":
unittest.main(verbosity=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment