Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +280 -410
src/streamlit_app.py
CHANGED
|
@@ -1,432 +1,302 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
from PyPDF2 import PdfReader
|
| 6 |
-
import docx2txt
|
| 7 |
-
from langchain_community.llms import HuggingFaceHub
|
| 8 |
-
from langchain.chains import LLMChain
|
| 9 |
-
from langchain.prompts import PromptTemplate
|
| 10 |
from sentence_transformers import SentenceTransformer
|
| 11 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
if
|
| 31 |
-
with
|
| 32 |
-
|
| 33 |
-
text = " ".join([page.extract_text() or "" for page in reader.pages])
|
| 34 |
-
if not text.strip():
|
| 35 |
-
raise ValueError("PDF appears to be image-based. Try converting to text first.")
|
| 36 |
-
return clean_text(text)
|
| 37 |
-
elif file.name.endswith('.docx'):
|
| 38 |
-
with st.spinner("Extracting Word document..."):
|
| 39 |
-
return clean_text(docx2txt.process(file))
|
| 40 |
-
raise ValueError("Unsupported file format")
|
| 41 |
-
except Exception as e:
|
| 42 |
-
st.error(f"Error processing {file.name}: {str(e)}")
|
| 43 |
-
raise
|
| 44 |
-
|
| 45 |
-
def clean_text(text):
|
| 46 |
-
"""Advanced text cleaning"""
|
| 47 |
-
# Remove non-printable characters
|
| 48 |
-
text = re.sub(r'[^\x20-\x7E\u2013\u2014\u2018\u2019\u201C\u201D]', ' ', text)
|
| 49 |
-
# Normalize whitespace and bullet points
|
| 50 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
| 51 |
-
# Standardize common resume section headers
|
| 52 |
-
text = re.sub(r'(?i)\b(?:work\s*history|employment\s*history)\b', 'EXPERIENCE', text)
|
| 53 |
-
return text
|
| 54 |
-
|
| 55 |
-
# ----------------------------
|
| 56 |
-
# 3. Optimized DeepSeek Integration
|
| 57 |
-
# ----------------------------
|
| 58 |
-
@st.cache_resource
|
| 59 |
-
def init_deepseek_llm():
|
| 60 |
-
"""Cached model initialization"""
|
| 61 |
-
return HuggingFaceHub(
|
| 62 |
-
repo_id=DEEPSEEK_MODEL,
|
| 63 |
-
model_kwargs={
|
| 64 |
-
"temperature": 0.1,
|
| 65 |
-
"max_new_tokens": 1024,
|
| 66 |
-
"repetition_penalty": 1.1,
|
| 67 |
-
"top_p": 0.9
|
| 68 |
-
}
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
def analyze_with_deepseek(prompt_template, input_text):
|
| 72 |
-
"""Robust analysis with retry logic"""
|
| 73 |
-
llm = init_deepseek_llm()
|
| 74 |
-
prompt = PromptTemplate.from_template(prompt_template)
|
| 75 |
-
chain = LLMChain(llm=llm, prompt=prompt)
|
| 76 |
-
|
| 77 |
-
max_retries = 2
|
| 78 |
-
for attempt in range(max_retries):
|
| 79 |
-
try:
|
| 80 |
-
response = chain.run(text=input_text)
|
| 81 |
-
# Improved JSON extraction with fallback
|
| 82 |
-
try:
|
| 83 |
-
return json.loads(response.strip())
|
| 84 |
-
except json.JSONDecodeError:
|
| 85 |
-
# Handle cases where response includes markdown code blocks
|
| 86 |
-
cleaned = re.sub(r'^```json|```$', '', response, flags=re.MULTILINE)
|
| 87 |
-
return json.loads(cleaned.strip())
|
| 88 |
-
except Exception as e:
|
| 89 |
-
if attempt == max_retries - 1:
|
| 90 |
-
st.error(f"Analysis failed after {max_retries} attempts: {str(e)}")
|
| 91 |
-
return {"error": str(e)}
|
| 92 |
-
continue
|
| 93 |
-
|
| 94 |
-
# ----------------------------
|
| 95 |
-
# 4. Enhanced Prompt Templates
|
| 96 |
-
# ----------------------------
|
| 97 |
-
JD_ANALYSIS_PROMPT = """[INST] <<SYS>>
|
| 98 |
-
You are an expert HR analyst. Extract these details as valid JSON:
|
| 99 |
-
{
|
| 100 |
-
"required_skills": ["list", "specific", "technical", "skills"],
|
| 101 |
-
"preferred_skills": ["list", "of", "nice-to-have", "skills"],
|
| 102 |
-
"min_experience": number,
|
| 103 |
-
"certifications": ["list", "of", "required", "certifications"],
|
| 104 |
-
"keywords": ["industry", "specific", "terms"],
|
| 105 |
-
"education_level": "degree requirement"
|
| 106 |
-
}
|
| 107 |
-
Important:
|
| 108 |
-
- Be specific with skills (e.g., "Python (Pandas, NumPy)" not just "Python")
|
| 109 |
-
- Convert experience requirements to years (e.g., "5+ years" → 5)
|
| 110 |
-
- Include only concrete requirements
|
| 111 |
-
<</SYS>>
|
| 112 |
-
Job description:
|
| 113 |
-
{text} [/INST]"""
|
| 114 |
-
|
| 115 |
-
RESUME_ANALYSIS_PROMPT = """[INST] <<SYS>>
|
| 116 |
-
You are a professional resume parser. Extract as valid JSON:
|
| 117 |
-
{
|
| 118 |
-
"skills": ["specific", "technical", "skills"],
|
| 119 |
-
"experience": [
|
| 120 |
-
{
|
| 121 |
-
"role": "position title",
|
| 122 |
-
"years": number,
|
| 123 |
-
"achievements": ["quantified", "accomplishments"]
|
| 124 |
-
}
|
| 125 |
-
],
|
| 126 |
-
"education": [
|
| 127 |
-
{
|
| 128 |
-
"degree": "degree name",
|
| 129 |
-
"field": "field of study",
|
| 130 |
-
"institution": "school name"
|
| 131 |
-
}
|
| 132 |
-
],
|
| 133 |
-
"certifications": ["certificate", "names"]
|
| 134 |
-
}
|
| 135 |
-
Rules:
|
| 136 |
-
- Estimate years of experience for each role
|
| 137 |
-
- Include only hard skills (no "teamwork" etc.)
|
| 138 |
-
- Quantify achievements where possible
|
| 139 |
-
<</SYS>>
|
| 140 |
-
Resume text:
|
| 141 |
-
{text} [/INST]"""
|
| 142 |
-
|
| 143 |
-
# ----------------------------
|
| 144 |
-
# 5. Advanced Matching Algorithm
|
| 145 |
-
# ----------------------------
|
| 146 |
-
@st.cache_data
|
| 147 |
-
def calculate_match(jd_data, resume_data):
|
| 148 |
-
"""Comprehensive matching with skill clustering"""
|
| 149 |
-
# Initialize embedding model
|
| 150 |
-
model = SentenceTransformer('BAAI/bge-small-en-v1.5')
|
| 151 |
-
|
| 152 |
-
# Skill matching with clustering
|
| 153 |
-
jd_skills = [skill.lower() for skill in jd_data["required_skills"] + jd_data["preferred_skills"]]
|
| 154 |
-
resume_skills = [skill.lower() for skill in resume_data["skills"]]
|
| 155 |
-
|
| 156 |
-
# Create skill embeddings
|
| 157 |
-
jd_embeddings = model.encode(jd_skills)
|
| 158 |
-
resume_embeddings = model.encode(resume_skills)
|
| 159 |
-
|
| 160 |
-
# Calculate similarity matrix
|
| 161 |
-
similarity_matrix = cosine_similarity(jd_embeddings, resume_embeddings)
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
if similarity_matrix[i][best_match_idx] > 0.65: # Threshold for valid match
|
| 168 |
-
matched_skills[jd_skill] = {
|
| 169 |
-
"resume_skill": resume_skills[best_match_idx],
|
| 170 |
-
"similarity": float(similarity_matrix[i][best_match_idx])
|
| 171 |
-
}
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
)[0][0] > 0.5
|
| 209 |
-
]
|
| 210 |
-
missing_skills.append({
|
| 211 |
-
"required": skill,
|
| 212 |
-
"similar_in_resume": similar_in_resume[:3] # Top 3 similar
|
| 213 |
-
})
|
| 214 |
-
|
| 215 |
-
return {
|
| 216 |
-
"match_score": score,
|
| 217 |
-
"missing_skills": missing_skills,
|
| 218 |
-
"skill_coverage": f"{exact_match * 100:.1f}%",
|
| 219 |
-
"experience_adequacy": f"{min(exp_ratio, 1.0) * 100:.1f}%",
|
| 220 |
-
"matched_skills": matched_skills
|
| 221 |
-
}
|
| 222 |
-
|
| 223 |
-
# ----------------------------
|
| 224 |
-
# 6. Streamlit UI with Performance Optimizations
|
| 225 |
-
# ----------------------------
|
| 226 |
-
def main():
|
| 227 |
-
st.set_page_config(
|
| 228 |
-
page_title="DeepSeek Resume Analyzer Pro",
|
| 229 |
-
layout="wide",
|
| 230 |
-
initial_sidebar_state="expanded"
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
# Custom CSS
|
| 234 |
-
st.markdown("""
|
| 235 |
-
<style>
|
| 236 |
-
.stProgress > div > div > div > div {
|
| 237 |
-
background-color: #4CAF50;
|
| 238 |
-
}
|
| 239 |
-
.st-b7 {
|
| 240 |
-
color: white;
|
| 241 |
-
}
|
| 242 |
-
.st-c0 {
|
| 243 |
-
background-color: #2E86AB;
|
| 244 |
}
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
}
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
key="jd_upload"
|
| 282 |
-
)
|
| 283 |
-
jd_text = ""
|
| 284 |
-
else:
|
| 285 |
-
jd_text = st.text_area(
|
| 286 |
-
"Paste Job Description",
|
| 287 |
-
height=300,
|
| 288 |
-
placeholder="Paste the full job description here...",
|
| 289 |
-
key="jd_text"
|
| 290 |
-
)
|
| 291 |
-
jd_file = None
|
| 292 |
-
|
| 293 |
-
with col2:
|
| 294 |
-
st.subheader("Resume")
|
| 295 |
-
resume_source = st.radio(
|
| 296 |
-
"Resume Input Method",
|
| 297 |
-
["Upload", "Paste"],
|
| 298 |
-
horizontal=True,
|
| 299 |
-
key="resume_source"
|
| 300 |
-
)
|
| 301 |
-
if resume_source == "Upload":
|
| 302 |
-
resume_file = st.file_uploader(
|
| 303 |
-
"Upload Resume (PDF/DOCX)",
|
| 304 |
-
type=["pdf", "docx"],
|
| 305 |
-
key="resume_upload"
|
| 306 |
-
)
|
| 307 |
-
resume_text = ""
|
| 308 |
else:
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
try:
|
| 324 |
-
#
|
| 325 |
-
with
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
)
|
| 332 |
-
jd_text_clean, resume_text_clean = future_jd.result(), future_resume.result()
|
| 333 |
-
|
| 334 |
-
# Analysis
|
| 335 |
-
with st.status("DeepSeek AI is processing...", expanded=True) as status:
|
| 336 |
-
st.write("Parsing Job Description...")
|
| 337 |
-
jd_data = analyze_with_deepseek(JD_ANALYSIS_PROMPT, jd_text_clean)
|
| 338 |
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
status.update(label="Analysis Complete!", state="complete")
|
| 345 |
-
|
| 346 |
-
# Display Results
|
| 347 |
-
st.subheader(f"Overall Match Score: {results['match_score']}%")
|
| 348 |
-
st.progress(results['match_score'] / 100)
|
| 349 |
-
|
| 350 |
-
# Metrics
|
| 351 |
-
col1, col2, col3 = st.columns(3)
|
| 352 |
-
col1.metric(
|
| 353 |
-
"Skill Coverage",
|
| 354 |
-
results["skill_coverage"],
|
| 355 |
-
help="Percentage of required skills matched"
|
| 356 |
-
)
|
| 357 |
-
col2.metric(
|
| 358 |
-
"Experience Adequacy",
|
| 359 |
-
results["experience_adequacy"],
|
| 360 |
-
help="Years of experience vs requirement"
|
| 361 |
-
)
|
| 362 |
-
col3.metric(
|
| 363 |
-
"Certification Match",
|
| 364 |
-
f"{len(set(jd_data.get('certifications', [])) & set(resume_data.get('certifications', []))}/{len(jd_data.get('certifications', [])) or 'N/A'}",
|
| 365 |
-
help="Matching certifications"
|
| 366 |
-
)
|
| 367 |
-
|
| 368 |
-
# Improvement Recommendations
|
| 369 |
-
with st.expander("🔍 Detailed Skill Matching", expanded=True):
|
| 370 |
-
if results["matched_skills"]:
|
| 371 |
-
st.write("**Strong Matches:**")
|
| 372 |
-
for jd_skill, match in list(results["matched_skills"].items())[:10]:
|
| 373 |
-
st.write(f"- ✅ {jd_skill} → {match['resume_skill']} (similarity: {match['similarity']:.2f})")
|
| 374 |
|
| 375 |
-
if results["missing_skills"]:
|
| 376 |
-
st.write("**Skills to Add:**")
|
| 377 |
-
for item in results["missing_skills"]:
|
| 378 |
-
if item["similar_in_resume"]:
|
| 379 |
-
st.write(f"- ⚠️ {item['required']} (You have similar: {', '.join(item['similar_in_resume'])})")
|
| 380 |
-
else:
|
| 381 |
-
st.write(f"- ❌ {item['required']}")
|
| 382 |
-
|
| 383 |
-
# AI Suggestions
|
| 384 |
-
if analysis_mode == "Advanced" and results["match_score"] < 80:
|
| 385 |
-
with st.expander("🤖 AI Improvement Suggestions", expanded=True):
|
| 386 |
-
llm = init_deepseek_llm()
|
| 387 |
-
prompt = f"""Suggest specific improvements for this resume to better match the job:
|
| 388 |
-
Job Requirements: {jd_data['required_skills'][:5]}
|
| 389 |
-
Resume Gaps: {[m['required'] for m in results['missing_skills']][:5]}
|
| 390 |
-
Provide 3-5 concrete suggestions in bullet points:"""
|
| 391 |
-
suggestions = llm(prompt)
|
| 392 |
-
st.write(suggestions)
|
| 393 |
-
|
| 394 |
-
# Raw Data
|
| 395 |
-
with st.expander("📊 View Analysis Data"):
|
| 396 |
-
tab_jd, tab_resume = st.tabs(["Job Analysis", "Resume Analysis"])
|
| 397 |
-
with tab_jd:
|
| 398 |
-
st.json(jd_data)
|
| 399 |
-
with tab_resume:
|
| 400 |
-
st.json(resume_data)
|
| 401 |
-
|
| 402 |
except Exception as e:
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
with tab2:
|
| 407 |
-
st.markdown("""
|
| 408 |
-
## How This Analyzer Works
|
| 409 |
-
|
| 410 |
-
**1. Document Processing**
|
| 411 |
-
- Extracts and cleans text from PDF/DOCX files
|
| 412 |
-
- Handles complex layouts and normalizes formatting
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
- Certification verification
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
|
|
|
|
| 431 |
if __name__ == "__main__":
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
import pdfplumber
|
| 4 |
+
import spacy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
from typing import List, Dict, Tuple
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import pickle
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
from docx import Document
|
| 14 |
|
| 15 |
+
class ResumeScreener:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
# Load models
|
| 18 |
+
self.nlp = spacy.load("en_core_web_lg")
|
| 19 |
+
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 20 |
+
self.embedding_cache = {}
|
| 21 |
+
self.cache_file = Path("embedding_cache.pkl")
|
| 22 |
+
self._load_cache()
|
| 23 |
+
|
| 24 |
+
# Configure thresholds
|
| 25 |
+
self.semantic_threshold = 0.65
|
| 26 |
+
self.keyword_threshold = 0.6
|
| 27 |
+
self.min_skill_coverage = 0.5
|
| 28 |
+
|
| 29 |
+
def _load_cache(self):
|
| 30 |
+
"""Load cached embeddings from disk"""
|
| 31 |
+
if self.cache_file.exists():
|
| 32 |
+
with open(self.cache_file, 'rb') as f:
|
| 33 |
+
self.embedding_cache = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
def _save_cache(self):
|
| 36 |
+
"""Save embeddings to disk for future runs"""
|
| 37 |
+
with open(self.cache_file, 'wb') as f:
|
| 38 |
+
pickle.dump(self.embedding_cache, f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
def _get_embedding(self, text: str) -> np.ndarray:
|
| 41 |
+
"""Get or compute embedding for text with caching"""
|
| 42 |
+
text_hash = hash(text)
|
| 43 |
+
if text_hash not in self.embedding_cache:
|
| 44 |
+
embedding = self.embedding_model.encode(text, convert_to_tensor=False)
|
| 45 |
+
self.embedding_cache[text_hash] = embedding
|
| 46 |
+
self._save_cache()
|
| 47 |
+
return self.embedding_cache[text_hash]
|
| 48 |
|
| 49 |
+
def extract_text(self, file_path: str) -> str:
|
| 50 |
+
"""Extract text from PDF, DOCX, or plain text"""
|
| 51 |
+
if file_path.lower().endswith('.pdf'):
|
| 52 |
+
with pdfplumber.open(file_path) as pdf:
|
| 53 |
+
return "\n".join([page.extract_text() for page in pdf.pages])
|
| 54 |
+
elif file_path.lower().endswith(('.docx', '.doc')):
|
| 55 |
+
doc = Document(file_path)
|
| 56 |
+
return "\n".join([para.text for para in doc.paragraphs])
|
| 57 |
+
else: # Assume plain text
|
| 58 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 59 |
+
return f.read()
|
| 60 |
|
| 61 |
+
def parse_job_description(self, jd_text: str) -> Dict:
|
| 62 |
+
"""Analyze and structure job description"""
|
| 63 |
+
doc = self.nlp(jd_text)
|
| 64 |
+
|
| 65 |
+
# Extract entities
|
| 66 |
+
skills = list(set(ent.text.lower() for ent in doc.ents if ent.label_ == "SKILL"))
|
| 67 |
+
experience_requirements = [
|
| 68 |
+
sent.text for sent in doc.sents
|
| 69 |
+
if any(token.text in ['experience', 'exp.'] for token in sent)
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
# Generate embeddings
|
| 73 |
+
jd_embedding = self._get_embedding(jd_text)
|
| 74 |
+
skill_embeddings = {skill: self._get_embedding(skill) for skill in skills}
|
| 75 |
+
|
| 76 |
+
return {
|
| 77 |
+
'raw_text': jd_text,
|
| 78 |
+
'skills': skills,
|
| 79 |
+
'experience_requirements': experience_requirements,
|
| 80 |
+
'embedding': jd_embedding,
|
| 81 |
+
'skill_embeddings': skill_embeddings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
}
|
| 83 |
+
|
| 84 |
+
def parse_resume(self, resume_text: str) -> Dict:
|
| 85 |
+
"""Extract structured information from resume"""
|
| 86 |
+
doc = self.nlp(resume_text)
|
| 87 |
+
|
| 88 |
+
# Extract sections (simplified - would use more sophisticated parsing in production)
|
| 89 |
+
skills = list(set(ent.text.lower() for ent in doc.ents if ent.label_ == "SKILL"))
|
| 90 |
+
experience = [ent.text for ent in doc.ents if ent.label_ == "ORG"]
|
| 91 |
+
education = [ent.text for ent in doc.ents if ent.label_ == "EDU"]
|
| 92 |
+
|
| 93 |
+
# Generate embeddings
|
| 94 |
+
full_embedding = self._get_embedding(resume_text)
|
| 95 |
+
experience_embedding = self._get_embedding(" ".join(experience)) if experience else None
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
'raw_text': resume_text,
|
| 99 |
+
'skills': skills,
|
| 100 |
+
'experience': experience,
|
| 101 |
+
'education': education,
|
| 102 |
+
'full_embedding': full_embedding,
|
| 103 |
+
'experience_embedding': experience_embedding
|
| 104 |
}
|
| 105 |
+
|
| 106 |
+
def calculate_similarity(self, resume: Dict, jd: Dict) -> Dict:
|
| 107 |
+
"""Compute multiple similarity metrics between resume and JD"""
|
| 108 |
+
# Full text semantic similarity
|
| 109 |
+
semantic_sim = cosine_similarity(
|
| 110 |
+
[resume['full_embedding']],
|
| 111 |
+
[jd['embedding']]
|
| 112 |
+
)[0][0]
|
| 113 |
+
|
| 114 |
+
# Skill matching (exact + semantic)
|
| 115 |
+
matched_skills = []
|
| 116 |
+
missing_skills = []
|
| 117 |
+
skill_similarities = []
|
| 118 |
+
|
| 119 |
+
for jd_skill, jd_skill_emb in jd['skill_embeddings'].items():
|
| 120 |
+
# Check exact match first
|
| 121 |
+
if jd_skill in resume['skills']:
|
| 122 |
+
matched_skills.append(jd_skill)
|
| 123 |
+
skill_similarities.append(1.0)
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
# Find best semantic match among resume skills
|
| 127 |
+
max_sim = 0
|
| 128 |
+
for resume_skill in resume['skills']:
|
| 129 |
+
resume_skill_emb = self._get_embedding(resume_skill)
|
| 130 |
+
sim = cosine_similarity([jd_skill_emb], [resume_skill_emb])[0][0]
|
| 131 |
+
if sim > max_sim:
|
| 132 |
+
max_sim = sim
|
| 133 |
+
|
| 134 |
+
if max_sim > 0.7: # Semantic match threshold
|
| 135 |
+
matched_skills.append(f"{jd_skill} (≈{resume_skill})")
|
| 136 |
+
skill_similarities.append(max_sim)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
else:
|
| 138 |
+
missing_skills.append(jd_skill)
|
| 139 |
+
|
| 140 |
+
skill_coverage = len(matched_skills) / len(jd['skills']) if jd['skills'] else 0
|
| 141 |
+
avg_skill_sim = np.mean(skill_similarities) if skill_similarities else 0
|
| 142 |
+
|
| 143 |
+
# Experience matching
|
| 144 |
+
exp_sim = 0
|
| 145 |
+
if resume['experience_embedding'] is not None:
|
| 146 |
+
exp_sim = cosine_similarity(
|
| 147 |
+
[resume['experience_embedding']],
|
| 148 |
+
[jd['embedding']]
|
| 149 |
+
)[0][0]
|
| 150 |
+
|
| 151 |
+
# Composite score
|
| 152 |
+
composite_score = (
|
| 153 |
+
0.5 * semantic_sim +
|
| 154 |
+
0.3 * skill_coverage +
|
| 155 |
+
0.2 * exp_sim
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return {
|
| 159 |
+
'semantic_similarity': semantic_sim,
|
| 160 |
+
'skill_coverage': skill_coverage,
|
| 161 |
+
'average_skill_similarity': avg_skill_sim,
|
| 162 |
+
'experience_similarity': exp_sim,
|
| 163 |
+
'composite_score': composite_score,
|
| 164 |
+
'matched_skills': matched_skills,
|
| 165 |
+
'missing_skills': missing_skills
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
def process_resumes(self, zip_path: str, jd_text: str) -> pd.DataFrame:
|
| 169 |
+
"""Main pipeline: process JD and all resumes in ZIP"""
|
| 170 |
+
# Process JD
|
| 171 |
+
jd = self.parse_job_description(jd_text)
|
| 172 |
+
|
| 173 |
+
results = []
|
| 174 |
+
|
| 175 |
+
# Process each resume in ZIP
|
| 176 |
+
with zipfile.ZipFile(zip_path) as z:
|
| 177 |
+
for filename in z.namelist():
|
| 178 |
+
if not filename.lower().endswith(('.pdf', '.docx', '.doc', '.txt')):
|
| 179 |
+
continue
|
| 180 |
+
|
| 181 |
try:
|
| 182 |
+
# Extract to temp file
|
| 183 |
+
with z.open(filename) as file:
|
| 184 |
+
temp_path = f"temp_{filename}"
|
| 185 |
+
with open(temp_path, 'wb') as f:
|
| 186 |
+
f.write(file.read())
|
| 187 |
+
|
| 188 |
+
# Parse resume
|
| 189 |
+
resume_text = self.extract_text(temp_path)
|
| 190 |
+
resume = self.parse_resume(resume_text)
|
| 191 |
+
|
| 192 |
+
# Compare to JD
|
| 193 |
+
comparison = self.calculate_similarity(resume, jd)
|
| 194 |
+
|
| 195 |
+
# Determine selection
|
| 196 |
+
is_selected = (
|
| 197 |
+
comparison['composite_score'] >= self.semantic_threshold and
|
| 198 |
+
comparison['skill_coverage'] >= self.min_skill_coverage
|
| 199 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
results.append({
|
| 202 |
+
'filename': filename,
|
| 203 |
+
'name': self._extract_name(resume_text),
|
| 204 |
+
'email': self._extract_email(resume_text),
|
| 205 |
+
'selection_status': "✅ Selected" if is_selected else "❌ Rejected",
|
| 206 |
+
'composite_score': comparison['composite_score'],
|
| 207 |
+
'semantic_similarity': comparison['semantic_similarity'],
|
| 208 |
+
'skill_coverage': f"{comparison['skill_coverage']:.0%}",
|
| 209 |
+
'matched_skills': ", ".join(comparison['matched_skills']),
|
| 210 |
+
'missing_skills': ", ".join(comparison['missing_skills']),
|
| 211 |
+
})
|
| 212 |
|
| 213 |
+
# Clean up
|
| 214 |
+
os.remove(temp_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
except Exception as e:
|
| 217 |
+
print(f"Error processing {filename}: {str(e)}")
|
| 218 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
+
# Create DataFrame and sort
|
| 221 |
+
df = pd.DataFrame(results)
|
| 222 |
+
df = df.sort_values('composite_score', ascending=False)
|
| 223 |
+
return df
|
| 224 |
+
|
| 225 |
+
def _extract_name(self, text: str) -> str:
|
| 226 |
+
"""Simple name extraction (would use more sophisticated NLP in production)"""
|
| 227 |
+
doc = self.nlp(text)
|
| 228 |
+
for ent in doc.ents:
|
| 229 |
+
if ent.label_ == "PERSON":
|
| 230 |
+
return ent.text
|
| 231 |
+
return "Unknown"
|
| 232 |
+
|
| 233 |
+
def _extract_email(self, text: str) -> str:
|
| 234 |
+
"""Basic email extraction"""
|
| 235 |
+
import re
|
| 236 |
+
email = re.search(r'[\w\.-]+@[\w\.-]+', text)
|
| 237 |
+
return email.group(0) if email else ""
|
| 238 |
+
|
| 239 |
+
def generate_report(self, df: pd.DataFrame, output_path: str = "report"):
|
| 240 |
+
"""Generate visual report and save to files"""
|
| 241 |
+
# CSV Export
|
| 242 |
+
df.to_csv(f"{output_path}.csv", index=False)
|
| 243 |
|
| 244 |
+
# PDF Report
|
| 245 |
+
import matplotlib.pyplot as plt
|
| 246 |
+
from matplotlib.backends.backend_pdf import PdfPages
|
|
|
|
| 247 |
|
| 248 |
+
with PdfPages(f"{output_path}.pdf") as pdf:
|
| 249 |
+
# Score Distribution
|
| 250 |
+
plt.figure(figsize=(10, 6))
|
| 251 |
+
plt.hist(df['composite_score'], bins=20, color='skyblue')
|
| 252 |
+
plt.title("Distribution of Composite Scores")
|
| 253 |
+
plt.xlabel("Score")
|
| 254 |
+
plt.ylabel("Number of Candidates")
|
| 255 |
+
pdf.savefig()
|
| 256 |
+
plt.close()
|
| 257 |
+
|
| 258 |
+
# Top Candidates
|
| 259 |
+
plt.figure(figsize=(10, 6))
|
| 260 |
+
top_candidates = df.head(10)
|
| 261 |
+
plt.barh(top_candidates['name'], top_candidates['composite_score'], color='green')
|
| 262 |
+
plt.title("Top 10 Candidates by Score")
|
| 263 |
+
plt.xlabel("Composite Score")
|
| 264 |
+
plt.tight_layout()
|
| 265 |
+
pdf.savefig()
|
| 266 |
+
plt.close()
|
| 267 |
+
|
| 268 |
+
# Skill Coverage
|
| 269 |
+
plt.figure(figsize=(10, 6))
|
| 270 |
+
df['skill_coverage_num'] = df['skill_coverage'].str.rstrip('%').astype('float') / 100
|
| 271 |
+
plt.scatter(df['composite_score'], df['skill_coverage_num'], alpha=0.5)
|
| 272 |
+
plt.title("Skill Coverage vs Composite Score")
|
| 273 |
+
plt.xlabel("Composite Score")
|
| 274 |
+
plt.ylabel("Skill Coverage")
|
| 275 |
+
plt.axhline(y=self.min_skill_coverage, color='r', linestyle='--')
|
| 276 |
+
pdf.savefig()
|
| 277 |
+
plt.close()
|
| 278 |
|
| 279 |
+
# Example Usage
|
| 280 |
if __name__ == "__main__":
|
| 281 |
+
# Initialize screener
|
| 282 |
+
screener = ResumeScreener()
|
| 283 |
+
|
| 284 |
+
# Example JD
|
| 285 |
+
jd_text = """
|
| 286 |
+
Data Scientist Position
|
| 287 |
+
Requirements:
|
| 288 |
+
- 3+ years experience in machine learning
|
| 289 |
+
- Strong Python programming skills
|
| 290 |
+
- Experience with TensorFlow or PyTorch
|
| 291 |
+
- Knowledge of SQL and data visualization
|
| 292 |
+
- Degree in Computer Science or related field
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
# Process resumes
|
| 296 |
+
results_df = screener.process_resumes("resumes.zip", jd_text)
|
| 297 |
+
|
| 298 |
+
# Generate reports
|
| 299 |
+
screener.generate_report(results_df)
|
| 300 |
+
|
| 301 |
+
# Display top candidates
|
| 302 |
+
print(results_df.head())
|