File size: 4,333 Bytes
58a5fa0 362982f 58a5fa0 7d2d686 362982f c519b34 362982f 58a5fa0 362982f 58a5fa0 265e52e 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f 58a5fa0 362982f |
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 |
import os
import fitz
import docx
import numpy as np
import gradio as gr
import re
from sentence_transformers import SentenceTransformer, CrossEncoder
from sklearn.metrics.pairwise import cosine_similarity
# -----------------------
# MODELS (better choices)
# -----------------------
bi_encoder = SentenceTransformer("BAAI/bge-base-en") # better embeddings
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
# -----------------------
# TEXT EXTRACTION
# -----------------------
def extract_text(file_path):
if file_path.endswith(".pdf"):
text = ""
with fitz.open(file_path) as doc:
for page in doc:
text += page.get_text()
return text
if file_path.endswith(".docx"):
d = docx.Document(file_path)
return "\n".join(p.text for p in d.paragraphs)
return ""
# -----------------------
# CLEANING
# -----------------------
def clean_text(t):
t = t.lower()
t = re.sub(r"\s+", " ", t)
return t
# -----------------------
# CHUNK EMBEDDINGS (IMPORTANT)
# -----------------------
def embed_chunks(text, size=400):
chunks = [text[i:i+size] for i in range(0, len(text), size)]
embs = bi_encoder.encode(chunks)
return np.mean(embs, axis=0)
# -----------------------
# SKILL MATCHING
# -----------------------
SKILLS = [
"python","java","sql","aws","docker","kubernetes",
"machine learning","pytorch","tensorflow",
"react","node","linux"
]
def skill_score(job, cv):
job_skills = [s for s in SKILLS if s in job]
if not job_skills:
return 0
matched = sum(s in cv for s in job_skills)
return matched / len(job_skills)
# -----------------------
# EXPERIENCE EXTRACTION (simple rule)
# -----------------------
def extract_years(text):
nums = re.findall(r"(\d+)\+?\s+years?", text)
return max([int(n) for n in nums], default=0)
# -----------------------
# MAIN RANKING
# -----------------------
def rank_cvs(job_description, files):
if not files:
return "Upload CVs."
job_description = clean_text(job_description)
# embed job once
job_emb = embed_chunks(job_description)
candidates = []
# ----------------
# Stage 1: Fast retrieval
# ----------------
for f in files:
name = os.path.basename(f)
text = clean_text(extract_text(f))
if not text:
continue
emb = embed_chunks(text)
sim = cosine_similarity([job_emb], [emb])[0][0]
candidates.append({
"name": name,
"text": text,
"sim": sim
})
# shortlist top 20
candidates = sorted(candidates, key=lambda x: x["sim"], reverse=True)[:20]
# ----------------
# Stage 2: Cross-encoder rerank (accuracy boost)
# ----------------
pairs = [[job_description, c["text"][:3000]] for c in candidates]
ce_scores = cross_encoder.predict(pairs)
for c, ce in zip(candidates, ce_scores):
c["ce"] = ce
# ----------------
# Stage 3: Business logic scoring
# ----------------
for c in candidates:
s_score = skill_score(job_description, c["text"])
years = extract_years(c["text"])
final = (
0.5 * c["ce"] + # semantic accuracy
0.3 * s_score + # skills
0.2 * min(years/10,1) # experience
)
c["final"] = final
# ----------------
# sort final
# ----------------
candidates = sorted(candidates, key=lambda x: x["final"], reverse=True)
# ----------------
# Explainable output
# ----------------
output = ""
for i, c in enumerate(candidates[:10]):
output += (
f"### {i+1}. {c['name']}\n"
f"- Final Score: {c['final']:.3f}\n"
f"- Semantic: {c['ce']:.3f}\n"
f"- Skill Match: {skill_score(job_description,c['text']):.2f}\n"
f"- Years: {extract_years(c['text'])}\n\n"
)
return output
# -----------------------
# UI
# -----------------------
demo = gr.Interface(
fn=rank_cvs,
inputs=[
gr.Textbox(label="Job Description", lines=6),
gr.File(file_count="multiple", type="filepath")
],
outputs=gr.Markdown(),
title="Production CV Ranker"
)
if __name__ == "__main__":
demo.launch()
|