Spaces:
Running on Zero
Running on Zero
Download scripts/bm25_query_strategy_compare.py from aseemlais/ats-engine: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/spaces/aseemlais/ats-engine/resolve/main/scripts/bm25_query_strategy_compare.py
- Command line
-
hf download hf://spaces/aseemlais/ats-engine/scripts/bm25_query_strategy_compare.py
-
curl -L -o bm25_query_strategy_compare.py https://huggingface.co/spaces/aseemlais/ats-engine/resolve/main/scripts/bm25_query_strategy_compare.py
12.6 kB
| """Compare three BM25 query strategies on the SAME corpus (reproducible, no embedding model needed). | |
| raw the full raw JD text as the query | |
| structured build_bm25_query(jd, "structured") - existing baseline (skills + admin-filtered responsibilities) | |
| filtered build_bm25_query(jd, "filtered") - baseline + generic boilerplate words removed from free text | |
| Corpus = the 64 real resumes stored in data/ats_metadata.db + the full trainee resume fixture + synthetic resumes | |
| (tests/fixtures/bm25_study/data.py). The reference index is built in a TEMP file from that same corpus, so | |
| data/bm25_index.pkl is never modified. Identifiers only (no candidate names) are written to the report. | |
| This is MECHANICAL evidence (query terms, score levels, rank stability, sensitivity to generic text). There are no | |
| human relevance labels, so it cannot show that any strategy ranks better. | |
| Usage (project root): python scripts/bm25_query_strategy_compare.py [--out reports/BM25_QUERY_STRATEGY_COMPARISON.md] [--reps 15] | |
| """ | |
| import argparse, math, statistics, sys, tempfile, time | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| sys.path.insert(0, str(ROOT)) | |
| try: | |
| import pydantic # noqa: F401 | |
| except ImportError: # offline sandbox only: labelled test shim, same as tests/run_offline.py | |
| sys.path.insert(0, str(ROOT / "tests" / "_offline_shims")); print("[note] pydantic missing: using offline shim") | |
| from app.database.storage import MetadataStorage | |
| from app.services.bm25_query import GENERIC_TERMS, build_bm25_query | |
| from app.services.bm25_search import BM25SearchService | |
| from app.services.jd_parser import JDParserService | |
| from app.utils.text_cleaner import tokenize_for_bm25 | |
| from tests.fixtures.bm25_study.data import JD_SPECS, SYN_RESUMES | |
| STRATEGIES = ("raw", "structured", "filtered") | |
| parse = lambda t: JDParserService().parse_job_description(t, job_id="STUDY") | |
| def read_spec(spec): | |
| return (ROOT / spec[5:]).read_text(encoding="utf-8") if spec.startswith("FILE:") else spec | |
| def query_for(strategy, jd): | |
| return jd.raw_text if strategy == "raw" else build_bm25_query(jd, strategy).text | |
| def kendall_tau(a: dict, b: dict) -> float: | |
| ids = sorted(a); con = dis = 0 | |
| for i in range(len(ids)): | |
| for j in range(i + 1, len(ids)): | |
| x = a[ids[i]] - a[ids[j]]; y = b[ids[i]] - b[ids[j]] | |
| if abs(x) < 1e-12 or abs(y) < 1e-12: | |
| continue | |
| con += (x > 0) == (y > 0); dis += (x > 0) != (y > 0) | |
| return (con - dis) / (con + dis) if con + dis else float("nan") | |
| def auc(norm: dict, pos: set, neg: set) -> float: | |
| if not pos or not neg: | |
| return float("nan") | |
| wins = sum((norm[p] > norm[n]) + 0.5 * (norm[p] == norm[n]) for p in pos for n in neg) | |
| return wins / (len(pos) * len(neg)) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", default=str(ROOT / "reports" / "BM25_QUERY_STRATEGY_COMPARISON.md")) | |
| ap.add_argument("--reps", type=int, default=15) | |
| a = ap.parse_args() | |
| docs = {r.candidate_id: r.cleaned_text for r in MetadataStorage().get_all_resumes()} | |
| n_real = len(docs) | |
| docs["USER_TRAINEE_FULL"] = (ROOT / "tests/fixtures/resume_user_trainee_full.txt").read_text(encoding="utf-8") | |
| for k, (_dom, t) in SYN_RESUMES.items(): | |
| docs[k] = t | |
| ids = list(docs); texts = [docs[i] for i in ids] | |
| domain = {k: d for k, (d, _t) in SYN_RESUMES.items()} | |
| tmp = Path(tempfile.mkdtemp()) / "study_index.pkl" | |
| svc = BM25SearchService(index_path=tmp) | |
| svc.build_index(ids, texts, persist=True) | |
| ref_df = {} | |
| for toks in svc.reference_corpus.values(): | |
| for t in set(toks): | |
| ref_df[t] = ref_df.get(t, 0) + 1 | |
| N = len(svc.reference_corpus) | |
| idf = lambda t: math.log((N + 1) / ref_df[t]) if ref_df.get(t) else 0.0 | |
| L = ["# BM25 query-strategy comparison (generated by scripts/bm25_query_strategy_compare.py)", "", | |
| f"Corpus: {n_real} real resumes (DB, identifiers only) + 1 full trainee resume + {len(SYN_RESUMES)} SYNTHETIC resumes = {len(ids)} documents; " | |
| f"reference index built from the same corpus ({svc.reference_info()['reliability']} reliability, normalisation `theoretical_bound`). " | |
| "Mechanical evidence only: no human relevance labels exist.", ""] | |
| summary = [] | |
| for jd_key, (spec, pos_domains) in JD_SPECS.items(): | |
| jd = parse(read_spec(spec)) | |
| skill_tokens = set() | |
| for s in jd.required_skills + jd.preferred_skills + jd.supporting_skills: | |
| skill_tokens.update(tokenize_for_bm25(s, query=True)) | |
| res, times, q = {}, {}, {} | |
| for st in STRATEGIES: | |
| q[st] = query_for(st, jd) | |
| ts = [] | |
| for _ in range(a.reps): | |
| t0 = time.perf_counter(); qq = query_for(st, jd) | |
| svc.score_documents(qq, ids, texts, method="theoretical_bound"); ts.append(time.perf_counter() - t0) | |
| times[st] = statistics.median(ts) * 1000 | |
| res[st] = svc.score_documents(q[st], ids, texts, method="theoretical_bound") | |
| build_us = {} | |
| for st in STRATEGIES: | |
| t0 = time.perf_counter() | |
| for _ in range(200): | |
| query_for(st, jd) | |
| build_us[st] = (time.perf_counter() - t0) / 200 * 1e6 | |
| base = res["structured"] | |
| base_rank = sorted(ids, key=lambda c: (-base.normalized[c], c)); base_pos = {c: i + 1 for i, c in enumerate(base_rank)} | |
| L += [f"## JD: {jd_key} - parsed title `{jd.title}`", "", | |
| f"required={jd.required_skills} preferred={jd.preferred_skills} supporting={jd.supporting_skills} nonmandatory={jd.nonmandatory_skills}; " | |
| f"responsibility lines parsed: {len([l for l in jd.responsibilities.splitlines() if l.strip()])}", ""] | |
| qb, qf = build_bm25_query(jd, "structured"), build_bm25_query(jd, "filtered") | |
| L += [f"Structured query method `{qb.method}`; filtered query method `{qf.method}`; generic terms removed by filter: {sorted(set(qf.removed_terms))}", ""] | |
| L += ["| strategy | query tokens | unique terms | unseen | generic share of denominator | median norm (real) | mean norm (all) | query build us | runtime ms (build+score all docs) |", | |
| "|---|---|---|---|---|---|---|---|---|"] | |
| for st in STRATEGIES: | |
| r = res[st]; seen = [t for t in r.unique_terms if t not in r.unseen_terms] | |
| tot = sum(idf(t) for t in seen) or 1.0 | |
| gen = sum(idf(t) for t in seen if t in GENERIC_TERMS and t not in skill_tokens) | |
| real = [r.normalized[c] for c in ids[:n_real]] | |
| L.append(f"| {st} | {len(r.query_tokens)} | {len(r.unique_terms)} | {len(r.unseen_terms)} | {gen / tot:.1%} | {statistics.median(real):.3f} | " | |
| f"{statistics.mean(r.normalized.values()):.3f} | {build_us[st]:.0f} | {times[st]:.2f} |") | |
| L.append("") | |
| L += ["| strategy | top-10 overlap with structured (all docs) | Kendall tau vs structured (all docs) | top-10 overlap, 64 REAL resumes only | Kendall tau, REAL only | max rank shift in structured top-10 (all docs) | AUC positives-vs-unrelated (synthetic) | mean percentile of generic-only resumes |", | |
| "|---|---|---|---|---|---|---|---|"] | |
| real_ids = ids[:n_real] | |
| real_rank = lambda r: sorted(real_ids, key=lambda c: (-r.normalized[c], c)) | |
| pos = {c for c in ids if domain.get(c) in pos_domains} | |
| if jd_key == "fresher_technical": | |
| pos.add("USER_TRAINEE_FULL") | |
| neg = {c for c in SYN_RESUMES if c not in pos} | |
| gen_ids = [c for c in SYN_RESUMES if domain[c] == "generic_only"] | |
| for st in STRATEGIES: | |
| r = res[st]; rank = sorted(ids, key=lambda c: (-r.normalized[c], c)); rp = {c: i + 1 for i, c in enumerate(rank)} | |
| ov = len(set(rank[:10]) & set(base_rank[:10])) | |
| shift = max(abs(rp[c] - base_pos[c]) for c in base_rank[:10]) | |
| gp = statistics.mean(1 - (rp[c] - 1) / len(ids) for c in gen_ids) | |
| rov = len(set(real_rank(r)[:10]) & set(real_rank(base)[:10])) | |
| rtau = kendall_tau({c: r.raw[c] for c in real_ids}, {c: base.raw[c] for c in real_ids}) | |
| L.append(f"| {st} | {ov}/10 | {kendall_tau(r.raw, base.raw):.3f} | {rov}/10 | {rtau:.3f} | {shift} | {auc(r.normalized, pos, neg):.3f} | {gp:.1%} |") | |
| L.append("") | |
| L += ["Top-10 by strategy (normalised score):", ""] | |
| for st in STRATEGIES: | |
| r = res[st]; rank = sorted(ids, key=lambda c: (-r.normalized[c], c))[:10] | |
| L.append(f"- **{st}**: " + ", ".join(f"{c} ({r.normalized[c]:.3f})" for c in rank)) | |
| L.append("") | |
| # Why do rankings change? BM25 raw is a sum over unique terms with fixed reference statistics, so | |
| # raw(structured) - raw(filtered) is EXACTLY the evidence contributed by the terms the filter removed. | |
| rs_, rf_ = res["structured"], res["filtered"] | |
| top_s = sorted(ids, key=lambda c: (-rs_.normalized[c], c))[:10]; top_f = sorted(ids, key=lambda c: (-rf_.normalized[c], c))[:10] | |
| left = [c for c in top_s if c not in top_f] | |
| if left: | |
| L += ["Documents that leave the top-10 when generic words are removed (share of their structured raw score that came from the removed terms):", "", | |
| "| document | structured raw | filtered raw | share from removed generic terms |", "|---|---|---|---|"] | |
| for c in left: | |
| L.append(f"| {c} | {rs_.raw[c]:.3f} | {rf_.raw[c]:.3f} | {(rs_.raw[c] - rf_.raw[c]) / rs_.raw[c]:.1%} |") | |
| L.append("") | |
| L += ["Query terms (unique):", ""] | |
| for st in STRATEGIES: | |
| L.append(f"- **{st}** ({len(res[st].unique_terms)}): `{' '.join(res[st].unique_terms)}`") | |
| L.append("") | |
| # consistency: re-tokenising the final query must be a no-op for model-built queries; no duplicated candidates | |
| for st in ("structured", "filtered"): | |
| toks = tokenize_for_bm25(q[st], query=True) | |
| assert tokenize_for_bm25(" ".join(toks), query=True) == toks, f"{jd_key}/{st}: query tokenisation not idempotent" | |
| for st in STRATEGIES: | |
| assert len(res[st].normalized) == len(ids) == len(set(ids)), "duplicated or missing candidates" | |
| if jd_key == "fresher_technical": | |
| u = "USER_TRAINEE_FULL" | |
| L += ["Trainee resume (fixture) under each strategy:", "", "| strategy | raw | normalised | matched terms | unmatched query terms |", "|---|---|---|---|---|"] | |
| for st in STRATEGIES: | |
| r = res[st]; L.append(f"| {st} | {r.raw[u]:.3f} | {r.normalized[u]:.3f} | {len(r.matched_terms[u])} | {len(r.unmatched_terms[u])}: {' '.join(r.unmatched_terms[u][:25])} |") | |
| L.append("") | |
| summary.append((jd_key, {st: (len(res[st].unique_terms), statistics.median([res[st].normalized[c] for c in ids[:n_real]])) for st in STRATEGIES})) | |
| # Production-reference view: the SHIPPED index (64 real resumes, read only), user's trainee JD + full resume | |
| prod = BM25SearchService() | |
| jd1 = parse(read_spec(JD_SPECS["fresher_technical"][0])) | |
| L += ["## Trainee resume vs the SHIPPED production reference index (read only)", "", | |
| f"Reference = data/bm25_index.pkl ({prod.reference_info()['documents']} documents, tokenizer v{prod.reference_info()['tokenizer_version']}, stale={prod.reference_info()['stale']}). " | |
| "This is the lexical component only; the hybrid score also needs the embedding model, so it is NOT reproduced here.", "", | |
| "| strategy | raw | normalised (theoretical_bound) | percentile vs reference |", "|---|---|---|---|"] | |
| for st in STRATEGIES: | |
| r = prod.score_documents(query_for(st, jd1), ["USER_TRAINEE_FULL"], [docs["USER_TRAINEE_FULL"]], method="theoretical_bound") | |
| L.append(f"| {st} | {r.raw['USER_TRAINEE_FULL']:.3f} | {r.normalized['USER_TRAINEE_FULL']:.3f} | {r.percentile['USER_TRAINEE_FULL']:.1%} |") | |
| L.append("") | |
| L += ["## Consistency checks", "", "- Final model-built queries (structured, filtered) re-tokenise to themselves (idempotent) for every JD above: PASS (asserted).", | |
| f"- Every strategy returned exactly {len(ids)} unique candidates (no duplication, none missing): PASS (asserted).", | |
| "- The temporary reference index was written outside `data/`; `data/bm25_index.pkl` was not modified.", ""] | |
| out = Path(a.out); out.parent.mkdir(parents=True, exist_ok=True); out.write_text("\n".join(L), encoding="utf-8") | |
| print("\n".join(L)); print(f"\n[written to {out}]") | |
| if __name__ == "__main__": | |
| main() | |