Spaces:
Sleeping
Sleeping
Download solution/src/scoring.py from javaliajayakumar/redrob-ranker: direct link, hf CLI and curl.
- Browser
- Download file 23.5 kB
-
https://huggingface.co/spaces/javaliajayakumar/redrob-ranker/resolve/main/solution/src/scoring.py
- Command line
-
hf download hf://spaces/javaliajayakumar/redrob-ranker/solution/src/scoring.py
-
curl -L -o scoring.py https://huggingface.co/spaces/javaliajayakumar/redrob-ranker/resolve/main/solution/src/scoring.py
23.5 kB
| """Hybrid scoring: semantic fit + structured fit, modified by behavior. | |
| Final score per candidate: | |
| base = w_sem*semantic + w_title*title + w_skill*skill | |
| + w_exp*experience + w_edu*education + w_loc*location | |
| + w_cert*certification + w_prog*progression | |
| score = base * behavioral_modifier * trust_multiplier + availability_bonus | |
| Each structured component is in [0, 1] and is computed against the parsed | |
| ``JobRequirements`` so the ranking reflects what the role actually needs. | |
| A short human-readable reason is emitted per candidate for recruiter | |
| transparency. | |
| v3 improvements | |
| --------------- | |
| * Skill alias/synonym map: "nlp" <-> "natural language processing", | |
| "llm" <-> "large language model", etc. β catches real skills missed by | |
| naive substring match. | |
| * Bidirectional skill matching: JD vocab checked against candidate names | |
| AND candidate names checked against JD vocab (both directions). | |
| * Token-level overlap for multi-word skills (e.g. "vector search" in | |
| "Weaviate vector search"). | |
| * Richer reasoning string with per-component breakdown. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from dataclasses import dataclass | |
| from typing import Any, Dict, List, Set, Tuple | |
| from .jd import JobRequirements | |
| from .profile_text import candidate_skill_names | |
| from .signals import ( | |
| availability_bonus, | |
| behavioral_modifier, | |
| trust_multiplier, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Scoring weights β must sum to 1.0 | |
| # --------------------------------------------------------------------------- | |
| WEIGHTS: Dict[str, float] = { | |
| "semantic": 0.30, # full-text cosine similarity (JD β profile) | |
| "title": 0.20, # job title / headline alignment | |
| "skill": 0.20, # core skill coverage + depth | |
| "experience": 0.14, # years-of-experience band fit | |
| "education": 0.05, # institution tier + STEM field | |
| "location": 0.05, # geo / work-mode match | |
| "certification": 0.03, # relevant ML/AI certifications | |
| "progression": 0.03, # career trajectory | |
| } | |
| assert abs(sum(WEIGHTS.values()) - 1.0) < 1e-9, "Weights must sum to 1" | |
| TIER_SCORE: Dict[str, float] = { | |
| "tier_1": 1.00, | |
| "tier_2": 0.82, | |
| "tier_3": 0.62, | |
| "tier_4": 0.42, | |
| "unknown": 0.50, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Skill alias / synonym table | |
| # Key: canonical JD vocab term β values: accepted candidate skill variants | |
| # --------------------------------------------------------------------------- | |
| SKILL_ALIASES: Dict[str, List[str]] = { | |
| # NLP / LLM | |
| "nlp": ["nlp", "natural language processing", "text analytics"], | |
| "natural language processing": ["nlp", "natural language processing", "text classification", | |
| "named entity recognition", "ner", "text analytics"], | |
| "llm": ["llm", "large language model", "gpt", "gpt-4", "chatgpt", | |
| "claude", "gemini", "palm", "openai", "llama", "mistral", | |
| "fine-tuning llms", "finetuning"], | |
| "large language model": ["llm", "large language model", "gpt", "fine-tuning llms", | |
| "instruction tuning", "rlhf", "llama", "mistral"], | |
| "transformers": ["transformers", "bert", "gpt", "t5", "roberta", "distilbert", | |
| "hugging face", "huggingface", "attention mechanism"], | |
| "embeddings": ["embeddings", "word2vec", "sentence embeddings", | |
| "text embeddings", "semantic embeddings", "dense retrieval"], | |
| "vector search": ["vector search", "vector database", "milvus", "pinecone", | |
| "weaviate", "qdrant", "faiss", "chroma", "annoy", | |
| "approximate nearest neighbor", "ann", "semantic search"], | |
| "rag": ["rag", "retrieval augmented generation", | |
| "retrieval-augmented", "knowledge retrieval", | |
| "document qa", "document retrieval"], | |
| "semantic search": ["semantic search", "dense retrieval", "bi-encoder", | |
| "cross-encoder", "faiss", "vector search"], | |
| # ML frameworks | |
| "pytorch": ["pytorch", "torch", "libtorch"], | |
| "tensorflow": ["tensorflow", "tf", "keras", "tf2"], | |
| "scikit-learn": ["scikit-learn", "sklearn", "scikit learn"], | |
| "sklearn": ["sklearn", "scikit-learn", "scikit learn"], | |
| "xgboost": ["xgboost", "xgb", "gradient boosting"], | |
| "lightgbm": ["lightgbm", "lgbm", "light gbm"], | |
| "gradient boosting": ["gradient boosting", "gbm", "xgboost", "lightgbm", | |
| "catboost", "boosting"], | |
| # MLOps | |
| "mlops": ["mlops", "ml ops", "model deployment", "model serving", | |
| "ml pipeline", "kubeflow", "mlflow", "bentoml", | |
| "model registry", "model monitoring", "seldon", | |
| "weights & biases", "wandb"], | |
| "model deployment": ["model deployment", "model serving", "fastapi ml", | |
| "bentoml", "torchserve", "triton", "seldon", | |
| "sagemaker", "vertex ai", "mlflow"], | |
| "feature engineering": ["feature engineering", "feature extraction", | |
| "feature selection", "data preprocessing"], | |
| # Deep learning | |
| "deep learning": ["deep learning", "neural network", "neural networks", | |
| "cnn", "rnn", "lstm", "gru", "transformer", | |
| "convolutional", "recurrent"], | |
| "machine learning": ["machine learning", "ml", "supervised learning", | |
| "unsupervised learning", "reinforcement learning", | |
| "classification", "regression", "clustering"], | |
| "computer vision": ["computer vision", "cv", "image classification", | |
| "object detection", "image segmentation", | |
| "yolo", "resnet", "vgg", "image recognition"], | |
| "recommendation": ["recommendation", "recommender", "collaborative filtering", | |
| "content-based filtering", "matrix factorization"], | |
| "ranking": ["ranking", "learning to rank", "ltr", "pairwise ranking", | |
| "listwise", "pointwise", "reranking"], | |
| "neural network": ["neural network", "neural networks", "deep learning", | |
| "ann", "mlp", "perceptron"], | |
| "hugging face": ["hugging face", "huggingface", "transformers library", | |
| "datasets library", "peft", "lora"], | |
| "fine-tuning": ["fine-tuning", "fine tuning", "finetuning", | |
| "instruction tuning", "rlhf", "lora", "qlora", | |
| "fine-tuning llms", "domain adaptation"], | |
| "prompt engineering": ["prompt engineering", "prompt design", "chain of thought", | |
| "few-shot", "zero-shot", "prompt tuning"], | |
| # Python ecosystem | |
| "python": ["python", "python3", "pyspark", "jupyter"], | |
| "pandas": ["pandas", "dataframe", "data wrangling"], | |
| "numpy": ["numpy", "numerical computing", "scipy"], | |
| "docker": ["docker", "containerization", "dockerfile"], | |
| "kubernetes": ["kubernetes", "k8s", "container orchestration", "helm"], | |
| "aws": ["aws", "amazon web services", "s3", "ec2", "sagemaker", | |
| "lambda", "emr", "bedrock"], | |
| "gcp": ["gcp", "google cloud", "bigquery", "vertex ai", | |
| "google cloud platform", "dataflow"], | |
| "azure": ["azure", "microsoft azure", "azure ml", | |
| "azure openai", "cosmos db"], | |
| "spark": ["spark", "apache spark", "pyspark", "spark streaming", | |
| "databricks"], | |
| "airflow": ["airflow", "apache airflow", "dag", "workflow orchestration"], | |
| "fastapi": ["fastapi", "fast api"], | |
| "flask": ["flask", "flask api"], | |
| "sql": ["sql", "postgresql", "mysql", "sqlite", "snowflake", | |
| "bigquery sql", "t-sql", "plsql"], | |
| "git": ["git", "github", "gitlab", "version control"], | |
| "ci/cd": ["ci/cd", "cicd", "continuous integration", | |
| "github actions", "jenkins", "gitlab ci"], | |
| "data pipeline": ["data pipeline", "etl", "data engineering", | |
| "data workflow", "pipeline"], | |
| "model monitoring": ["model monitoring", "data drift", "model drift", | |
| "model observability", "evidently", "great expectations"], | |
| "a/b testing": ["a/b testing", "ab testing", "experimentation", | |
| "statistical testing", "hypothesis testing"], | |
| # Speech / audio | |
| "speech recognition": ["speech recognition", "asr", "automatic speech recognition", | |
| "whisper", "wav2vec", "deepspeech", "tts", | |
| "text to speech", "speech processing"], | |
| } | |
| def _normalize(text: str) -> str: | |
| return re.sub(r"[^a-z0-9+#.\-/ ]", " ", text.lower()).strip() | |
| def _skill_tokens(name: str) -> Set[str]: | |
| """Return the skill name and all its known aliases as a set of strings.""" | |
| key = _normalize(name) | |
| aliases = SKILL_ALIASES.get(key, [key]) | |
| return {_normalize(a) for a in aliases} | {key} | |
| def _candidate_matches_jd_skill( | |
| candidate_skill_name: str, jd_skill: str | |
| ) -> bool: | |
| """True if the candidate's skill name matches a JD skill term (with aliases).""" | |
| csk = _normalize(candidate_skill_name) | |
| jsk = _normalize(jd_skill) | |
| # Direct or alias hit | |
| csk_aliases = _skill_tokens(csk) | |
| jsk_aliases = _skill_tokens(jsk) | |
| # Any overlap between candidate aliases and JD aliases | |
| if csk_aliases & jsk_aliases: | |
| return True | |
| # Token-level overlap: at least 2 tokens shared (for multi-word skills) | |
| c_toks = set(csk.split()) | |
| j_toks = set(jsk.split()) | |
| if len(c_toks) >= 2 and len(c_toks & j_toks) >= min(2, len(j_toks)): | |
| return True | |
| # Single important token: one of the JD skill tokens appears in candidate name | |
| if len(j_toks) == 1 and list(j_toks)[0] in c_toks: | |
| return True | |
| return False | |
| # Cert keywords that indicate genuine ML/AI relevance | |
| RELEVANT_CERT_TOKENS: List[str] = [ | |
| "machine learning", "deep learning", "tensorflow", "pytorch", | |
| "aws certified machine learning", "google professional ml", | |
| "azure ai", "nlp", "neural", "data science", "mlops", | |
| "hugging face", "deeplearning.ai", "fast.ai", | |
| "professional data engineer", "databricks", "spark", | |
| "certified ai", "artificial intelligence", "data scientist", | |
| "aws machine learning", "google cloud ml", "vertex", | |
| ] | |
| class ScoredCandidate: | |
| candidate_id: str | |
| score: float | |
| reasoning: str | |
| components: Dict[str, float] | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Sub-scorers | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _title_score(candidate: Dict[str, Any], jd: JobRequirements) -> float: | |
| title = str(candidate.get("profile", {}).get("current_title", "")).lower() | |
| head = str(candidate.get("profile", {}).get("headline", "")).lower() | |
| hist = " ".join( | |
| str(j.get("title", "")).lower() | |
| for j in candidate.get("career_history", []) | |
| ) | |
| hay = f"{title} {head} {hist}" | |
| if any(kw in title for kw in jd.title_keywords): | |
| return 1.0 | |
| if any(kw in head for kw in jd.title_keywords): | |
| return 0.88 | |
| if any(kw in hist for kw in jd.title_keywords): | |
| return 0.65 | |
| # Partial-match fallback for AI/ML adjacent roles | |
| strong_ai_tokens = ( | |
| "ml engineer", "machine learning", "data scientist", "ai engineer", | |
| "nlp engineer", "research engineer", "applied scientist", | |
| "computer vision", "recommendation", "ranking engineer", | |
| ) | |
| if any(tok in hay for tok in strong_ai_tokens): | |
| return 0.50 | |
| moderate_tokens = ( | |
| "ml", " ai ", "data engineer", "data analyst", | |
| "analytics engineer", "cloud engineer", "platform engineer", | |
| ) | |
| if any(tok in hay for tok in moderate_tokens): | |
| return 0.28 | |
| if any(tok in hay for tok in ("engineer", "developer", "scientist")): | |
| return 0.10 | |
| return 0.03 | |
| def _skill_score( | |
| candidate: Dict[str, Any], jd: JobRequirements | |
| ) -> Tuple[float, int]: | |
| """Score skill coverage using alias-aware bidirectional matching.""" | |
| raw_skills = candidate.get("skills", []) or [] | |
| skill_names = [str(s.get("name", "")) for s in raw_skills if s.get("name")] | |
| # For each JD core skill, check if any candidate skill matches it. | |
| core_hits = 0 | |
| matched_core_indices: List[int] = [] # index into raw_skills | |
| for jd_skill in jd.core_skills: | |
| for idx, sk_name in enumerate(skill_names): | |
| if _candidate_matches_jd_skill(sk_name, jd_skill): | |
| core_hits += 1 | |
| matched_core_indices.append(idx) | |
| break | |
| support_hits = 0 | |
| for jd_skill in jd.support_skills: | |
| for sk_name in skill_names: | |
| if _candidate_matches_jd_skill(sk_name, jd_skill): | |
| support_hits += 1 | |
| break | |
| core_cov = core_hits / max(1, len(jd.core_skills)) | |
| support_cov = support_hits / max(1, len(jd.support_skills)) | |
| # Proficiency + endorsement + duration quality on matched core skills | |
| prof_w = {"beginner": 0.35, "intermediate": 0.65, "advanced": 0.88, "expert": 1.0} | |
| quality, matched = 0.0, 0 | |
| for idx in matched_core_indices: | |
| sk = raw_skills[idx] | |
| q = prof_w.get(sk.get("proficiency", ""), 0.55) | |
| end = int(sk.get("endorsements", 0) or 0) | |
| dur = int(sk.get("duration_months", 0) or 0) | |
| # Endorsements β€20 β 1, duration β€36m β 1 | |
| q *= (0.60 + 0.25 * min(1.0, end / 20.0) + 0.15 * min(1.0, dur / 36.0)) | |
| quality += q | |
| matched += 1 | |
| quality = quality / matched if matched else 0.0 | |
| # Bonus for Redrob-assessed core skills (verified platform proof) | |
| assessments = (candidate.get("redrob_signals", {}) or {}).get( | |
| "skill_assessment_scores", {}) or {} | |
| assess_bonus = 0.0 | |
| if assessments: | |
| rel_scores = [] | |
| for k, v in assessments.items(): | |
| for jd_skill in jd.core_skills: | |
| if _candidate_matches_jd_skill(k, jd_skill): | |
| rel_scores.append(float(v) / 100.0) | |
| break | |
| if rel_scores: | |
| assess_bonus = min(0.10, 0.10 * (sum(rel_scores) / len(rel_scores))) | |
| # Nice-to-have: small uplift | |
| nice_hits = 0 | |
| for jd_skill in jd.nice_to_have: | |
| for sk_name in skill_names: | |
| if _candidate_matches_jd_skill(sk_name, jd_skill): | |
| nice_hits += 1 | |
| break | |
| nice_bonus = min(0.05, 0.015 * nice_hits) | |
| score = ( | |
| 0.50 * core_cov + | |
| 0.18 * support_cov + | |
| 0.22 * quality + | |
| assess_bonus + | |
| nice_bonus | |
| ) | |
| return min(1.0, score), core_hits | |
| def _experience_score(candidate: Dict[str, Any], jd: JobRequirements) -> float: | |
| yrs = float(candidate.get("profile", {}).get("years_of_experience", 0) or 0) | |
| if yrs <= 0: | |
| return 0.10 | |
| if jd.min_years <= yrs <= jd.max_years: | |
| return 1.0 | |
| if yrs < jd.min_years: | |
| return max(0.15, yrs / max(1.0, jd.min_years)) | |
| # Over-qualified: gentle decay | |
| over = yrs - jd.max_years | |
| return max(0.55, 1.0 - 0.04 * over) | |
| def _education_score(candidate: Dict[str, Any]) -> float: | |
| edus = candidate.get("education", []) or [] | |
| if not edus: | |
| return 0.38 | |
| best = 0.0 | |
| for e in edus: | |
| t = TIER_SCORE.get(e.get("tier", "unknown"), 0.50) | |
| field = str(e.get("field_of_study", "")).lower() | |
| deg = str(e.get("degree", "")).lower() | |
| if any(k in field for k in ( | |
| "computer", "data", "machine", "statistic", | |
| "math", "ai", "electr", "information", "physics", "science", | |
| )): | |
| t = min(1.0, t + 0.10) | |
| if any(k in deg for k in ("ph.d", "phd", "m.tech", "m.s.", "master", "m.e.")): | |
| t = min(1.0, t + 0.08) | |
| best = max(best, t) | |
| return best | |
| def _location_score(candidate: Dict[str, Any], jd: JobRequirements) -> float: | |
| if not jd.locations and not jd.work_modes: | |
| return 0.70 | |
| country = str(candidate.get("profile", {}).get("country", "")).lower() | |
| loc = str(candidate.get("profile", {}).get("location", "")).lower() | |
| sig = candidate.get("redrob_signals", {}) or {} | |
| mode = str(sig.get("preferred_work_mode", "")).lower() | |
| relocate = bool(sig.get("willing_to_relocate")) | |
| score = 0.40 | |
| if jd.locations: | |
| if any(l in country or l in loc for l in jd.locations): | |
| score = 1.0 | |
| elif relocate: | |
| score = max(score, 0.72) | |
| if "remote" in jd.work_modes and mode in ("remote", "flexible"): | |
| score = max(score, 0.90) | |
| if "hybrid" in jd.work_modes and mode in ("hybrid", "flexible"): | |
| score = max(score, 0.85) | |
| return score | |
| def _certification_score(candidate: Dict[str, Any]) -> float: | |
| certs = candidate.get("certifications", []) or [] | |
| if not certs: | |
| return 0.0 | |
| hits = 0 | |
| for cert in certs: | |
| name = str(cert.get("name", "")).lower() | |
| issuer = str(cert.get("issuer", "")).lower() | |
| blob = name + " " + issuer | |
| if any(tok in blob for tok in RELEVANT_CERT_TOKENS): | |
| hits += 1 | |
| # 1 cert β 0.50, 2 β 0.75, 3+ β 1.0 | |
| return min(1.0, 0.50 + 0.25 * (hits - 1)) if hits >= 1 else 0.0 | |
| def _progression_score(candidate: Dict[str, Any]) -> float: | |
| """Reward upward career trajectory.""" | |
| history = list(candidate.get("career_history", []) or []) | |
| if len(history) < 2: | |
| return 0.5 | |
| seniority_rank = { | |
| "director": 7, "vp": 7, "head": 6, "lead": 5, "principal": 5, | |
| "staff": 5, "senior": 4, "sr": 4, "mid": 3, "engineer": 2, | |
| "analyst": 2, "associate": 2, "junior": 1, "jr": 1, "intern": 0, | |
| } | |
| def _rank(title: str) -> int: | |
| t = title.lower() | |
| for tok, r in seniority_rank.items(): | |
| if tok in t: | |
| return r | |
| return 2 | |
| try: | |
| ordered = sorted(history, key=lambda j: j.get("start_date", "") or "") | |
| except TypeError: | |
| ordered = history | |
| ranks = [_rank(j.get("title", "")) for j in ordered] | |
| if not ranks: | |
| return 0.5 | |
| latest = ranks[-1] | |
| avg_earlier = sum(ranks[:-1]) / len(ranks[:-1]) if len(ranks) > 1 else latest | |
| if latest >= avg_earlier: | |
| return min(1.0, 0.5 + 0.1 * latest) | |
| return max(0.2, 0.5 - 0.1 * (avg_earlier - latest)) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Reasoning string | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _reason( | |
| candidate: Dict[str, Any], | |
| comp: Dict[str, float], | |
| core_hits: int, | |
| jd: JobRequirements, | |
| ) -> str: | |
| p = candidate.get("profile", {}) or {} | |
| title = p.get("current_title", "?") | |
| yrs = float(p.get("years_of_experience", 0) or 0) | |
| sig = candidate.get("redrob_signals", {}) or {} | |
| rr = float(sig.get("recruiter_response_rate", 0) or 0) | |
| gh = float(sig.get("github_activity_score", -1) or -1) | |
| otw = "open-to-work" if sig.get("open_to_work_flag") else "not open-to-work" | |
| sem = comp.get("semantic", 0) | |
| skill = comp.get("skill", 0) | |
| exp = comp.get("experience", 0) | |
| cert = comp.get("certification", 0) | |
| gh_str = f"; GitHub {gh:.0f}/100" if gh >= 0 else "" | |
| cert_str = "; certified" if cert > 0.4 else "" | |
| text = ( | |
| f"{title} | {yrs:.1f} yrs | {core_hits}/{len(jd.core_skills)} core skills | " | |
| f"semantic {sem:.2f} | skill {skill:.2f} | exp {exp:.2f} | " | |
| f"rr {rr:.2f}{gh_str}{cert_str} | {otw}" | |
| ) | |
| return text.replace("\n", " ").replace('"', "'")[:300] | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Main scorer | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def score_candidate( | |
| candidate: Dict[str, Any], | |
| jd: JobRequirements, | |
| semantic: float, | |
| ) -> ScoredCandidate: | |
| title = _title_score(candidate, jd) | |
| skill, core_hits = _skill_score(candidate, jd) | |
| exp = _experience_score(candidate, jd) | |
| edu = _education_score(candidate) | |
| loc = _location_score(candidate, jd) | |
| cert = _certification_score(candidate) | |
| prog = _progression_score(candidate) | |
| # Map cosine sim [-1, 1] β [0, 1] | |
| sem = max(0.0, min(1.0, (semantic + 1.0) / 2.0)) | |
| comp = { | |
| "semantic": sem, | |
| "title": title, | |
| "skill": skill, | |
| "experience": exp, | |
| "education": edu, | |
| "location": loc, | |
| "certification": cert, | |
| "progression": prog, | |
| } | |
| base = sum(WEIGHTS[k] * comp[k] for k in WEIGHTS) | |
| mod = behavioral_modifier(candidate) | |
| trust = trust_multiplier(candidate, core_hits) | |
| avail = availability_bonus(candidate) | |
| final = base * mod * trust + avail | |
| final = max(0.0, min(1.0, final)) | |
| cid = candidate.get("candidate_id", "") | |
| return ScoredCandidate( | |
| candidate_id=cid, | |
| score=final, | |
| reasoning=_reason(candidate, comp, core_hits, jd), | |
| components=comp, | |
| ) | |