Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import osimport gradio as grimport fitz # PyMuPDFimport docximport numpy as npfrom sentence_transformers import SentenceTransformer# 1. Load a pretrained Sentence Transformer model locallymodel = SentenceTransformer("all-MiniLM-L6-v2")# ---- Text extraction ----def extract_text(file_path, filename):if filename.endswith(".pdf"):text = ""with fitz.open(file_path) as doc:for page in doc:text += page.get_text("text") + "\n"return textelif filename.endswith(".docx"):docf = docx.Document(file_path)return "\n".join(p.text for p in docf.paragraphs)return ""# ---- Local embedding helper ----def get_embedding(text):# Use the locally loaded model to generate embeddingsembedding = model.encode(text)return np.array(embedding)# ---- CV ranking ----def rank_cvs(job_description, files):if not job_description or not files:return "⚠️ Please upload CVs and provide a job description."job_emb = get_embedding(job_description)scores, names = [], []for file_path in files:# Get filename from file pathfilename = os.path.basename(file_path)text = extract_text(file_path, filename)if not text.strip():continuecv_emb = get_embedding(text[:4000]) # limit text lengthsim = np.dot(job_emb, cv_emb) / (np.linalg.norm(job_emb) * np.linalg.norm(cv_emb))scores.append(sim)names.append(filename)top = sorted(zip(names, scores), key=lambda x: x[1], reverse=True)[:10]return "\n\n".join([f"**{i+1}. {n}** — Similarity: `{s:.3f}`" for i, (n, s) in enumerate(top)])# ---- Gradio UI ----demo = gr.Interface(fn=rank_cvs,inputs=[gr.Textbox(label="💼 Job Description", lines=5),gr.File(label="📁 Upload CVs (PDF/DOCX)", file_count="multiple", type="filepath"),],outputs=gr.Markdown(),title="📄 AI CV Ranker (Local Model)",description="Ranks uploaded CVs based on job relevance using local SentenceTransformer model.",)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import osimport fitzimport docximport numpy as npimport gradio as grimport refrom sentence_transformers import SentenceTransformer, CrossEncoderfrom sklearn.metrics.pairwise import cosine_similarity# -----------------------# MODELS (better choices)# -----------------------bi_encoder = SentenceTransformer("BAAI/bge-base-en") # better embeddingscross_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 textif 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 0matched = 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 oncejob_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:continueemb = embed_chunks(text)sim = cosine_similarity([job_emb], [emb])[0][0]candidates.append({"name": name,"text": text,"sim": sim})# shortlist top 20candidates = 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 accuracy0.3 * s_score + # skills0.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()
app.py+159-45