File size: 7,002 Bytes
1689e06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python3
"""
Redrob Hackathon β€” Scoring Explainer
=====================================
Prints a rich per-candidate breakdown showing every scoring component,
behavioral modifier, trust multiplier, and matched skills.

Usage
-----
    python solution/explain.py \\
        --candidates sample_candidates.json \\
        [--jd solution/job_description.txt] \\
        [--top 10]

Useful for:
  * Debugging the ranker
  * Generating content for the submission deck
  * Verifying that genuine ML candidates rank above irrelevant ones
"""
from __future__ import annotations

import os
import argparse
import json
import sys

os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

from src.embedding import SemanticEncoder, cosine_similarity
from src.jd import parse_job_description
from src.profile_text import build_document
from src.scoring import (
    WEIGHTS,
    _certification_score,
    _education_score,
    _experience_score,
    _location_score,
    _progression_score,
    _skill_score,
    _title_score,
    score_candidate,
)
from src.signals import behavioral_modifier, trust_multiplier, availability_bonus


COLS = 90
LINE = "─" * COLS


def _header(text: str) -> None:
    print(f"\n{'━' * COLS}")
    print(f"  {text}")
    print("━" * COLS)


def _bar(value: float, width: int = 20) -> str:
    filled = int(round(value * width))
    return f"[{'β–ˆ' * filled}{'β–‘' * (width - filled)}] {value:.3f}"


def explain(candidates_path: str, jd_path: str | None, top_n: int = 10) -> None:
    # Load
    text = Path(candidates_path).read_text(encoding="utf-8").strip()
    candidates = json.loads(text) if text.startswith("[") else \
        [json.loads(l) for l in text.splitlines() if l.strip()]

    jd_raw = (Path(jd_path) if jd_path else HERE / "job_description.txt"
              ).read_text(encoding="utf-8")
    jd = parse_job_description(jd_raw)

    _header(f"JOB DESCRIPTION ANALYSIS")
    print(f"  Role family   : {jd.role_family}")
    print(f"  Seniority     : {jd.seniority}")
    print(f"  Experience    : {jd.min_years:.0f} – {jd.max_years:.0f} years")
    print(f"  Core skills   : {', '.join(jd.core_skills[:8])} …")
    print(f"  Locations     : {', '.join(jd.locations) or 'any'}")
    print(f"  Work modes    : {', '.join(jd.work_modes) or 'any'}")

    # Encode
    corpus = [build_document(c) for c in candidates] + [jd.raw_text]
    enc = SemanticEncoder()
    enc.fit(corpus)
    jd_vec   = enc.encode([jd.raw_text])[0]
    cand_vecs = enc.encode(corpus[:-1])
    sims = cosine_similarity(jd_vec, cand_vecs)

    # Score all
    scored = [score_candidate(c, jd, float(s)) for c, s in zip(candidates, sims)]
    ranked = sorted(scored, key=lambda x: (-x.score, x.candidate_id))

    _header(f"TOP {min(top_n, len(ranked))} CANDIDATES β€” DETAILED BREAKDOWN")

    cand_map = {c["candidate_id"]: c for c in candidates}

    for rank_pos, sc in enumerate(ranked[:top_n], 1):
        c  = cand_map[sc.candidate_id]
        p  = c.get("profile", {})
        sig = c.get("redrob_signals", {}) or {}

        title = p.get("current_title", "?")
        yrs   = p.get("years_of_experience", 0)
        loc   = p.get("location", "?")
        country = p.get("country", "?")

        sem_raw = float(sims[[c["candidate_id"] for c in candidates].index(sc.candidate_id)])
        sem_01  = max(0.0, min(1.0, (sem_raw + 1.0) / 2.0))

        _, core_hits = _skill_score(c, jd)
        skill_s  = _skill_score(c, jd)[0]
        title_s  = _title_score(c, jd)
        exp_s    = _experience_score(c, jd)
        edu_s    = _education_score(c)
        loc_s    = _location_score(c, jd)
        cert_s   = _certification_score(c)
        prog_s   = _progression_score(c)
        beh_mod  = behavioral_modifier(c)
        trust    = trust_multiplier(c, core_hits)
        avail    = availability_bonus(c)

        print(f"\n{'─' * COLS}")
        print(f"  #{rank_pos:>2}  {sc.candidate_id}   FINAL SCORE: {sc.score:.4f}")
        print(f"       {title}  |  {yrs} yrs  |  {loc}, {country}")
        print(f"{'─' * COLS}")

        # Component table
        print(f"  {'COMPONENT':<18} {'WEIGHT':>7}  {'RAW SCORE':>10}  {'WEIGHTED':>9}  BAR")
        print(f"  {'─' * 65}")
        comps = [
            ("semantic",      WEIGHTS["semantic"],      sem_01),
            ("title",         WEIGHTS["title"],         title_s),
            ("skill",         WEIGHTS["skill"],         skill_s),
            ("experience",    WEIGHTS["experience"],    exp_s),
            ("education",     WEIGHTS["education"],     edu_s),
            ("location",      WEIGHTS["location"],      loc_s),
            ("certification", WEIGHTS["certification"], cert_s),
            ("progression",   WEIGHTS["progression"],   prog_s),
        ]
        base = 0.0
        for name, w, raw in comps:
            weighted = w * raw
            base += weighted
            bar = _bar(raw, 16)
            print(f"  {name:<18} {w:>7.0%}  {raw:>10.3f}  {weighted:>9.4f}  {bar}")

        print(f"  {'─' * 65}")
        print(f"  {'BASE SCORE':<18} {'':>7}  {'':>10}  {base:>9.4f}")
        print(f"  {'behavioral mod':<18} {'Γ—':>7}  {beh_mod:>10.4f}")
        print(f"  {'trust mult':<18} {'Γ—':>7}  {trust:>10.4f}")
        print(f"  {'avail bonus':<18} {'+':>7}  {avail:>10.4f}")
        print(f"  {'FINAL':<18} {'':>7}  {'':>10}  {sc.score:>9.4f}")

        # Skills detail
        skill_names = [s.get("name", "") for s in c.get("skills", [])]
        print(f"\n  Core skill hits : {core_hits}/{len(jd.core_skills)}")
        print(f"  Candidate skills: {', '.join(skill_names[:10])}"
              + (" …" if len(skill_names) > 10 else ""))

        # Signals detail
        rr   = sig.get("recruiter_response_rate", 0)
        gh   = sig.get("github_activity_score", -1)
        otw  = sig.get("open_to_work_flag", False)
        np_d = sig.get("notice_period_days", "?")
        print(f"  Response rate   : {rr:.0%}  |  "
              f"GitHub: {gh if gh >= 0 else 'N/A'}/100  |  "
              f"Open-to-work: {otw}  |  Notice: {np_d} days")

        certs = c.get("certifications", [])
        if certs:
            print(f"  Certifications  : {', '.join(x.get('name', '') for x in certs)}")

    _header("SCORING WEIGHT SUMMARY")
    for k, w in WEIGHTS.items():
        print(f"  {k:<18} {w:.0%}")
    print(f"\n  Behavioral modifier range : [0.78 – 1.20]")
    print(f"  Trust multiplier range    : [0.65 – 1.00]")
    print(f"  Semantic encoder backend  : {enc.backend}\n")


def _args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Redrob Scoring Explainer")
    p.add_argument("--candidates", default="sample_candidates.json")
    p.add_argument("--jd", default=None)
    p.add_argument("--top", type=int, default=10)
    return p.parse_args()


if __name__ == "__main__":
    a = _args()
    explain(a.candidates, a.jd, a.top)