Spaces:
Sleeping
Sleeping
import os | |
import io | |
import streamlit as st | |
import docx | |
import docx2txt | |
import tempfile | |
from transformers import pipeline | |
import numpy as np | |
from scipy.spatial.distance import cosine | |
import time | |
# Set page title and hide sidebar | |
st.set_page_config( | |
page_title="Resume Analyzer and Company Suitability Checker", | |
initial_sidebar_state="collapsed" | |
) | |
# Hide sidebar completely with custom CSS | |
st.markdown(""" | |
<style> | |
[data-testid="collapsedControl"] {display: none;} | |
section[data-testid="stSidebar"] {display: none;} | |
</style> | |
""", unsafe_allow_html=True) | |
##################################### | |
# Preload Models | |
##################################### | |
def load_models(): | |
"""Load models at startup""" | |
with st.spinner("Loading AI models... This may take a minute on first run."): | |
models = {} | |
# Load summarization model | |
models['summarizer'] = pipeline("summarization", model="t5-base") | |
# Load feature extraction model for similarity | |
models['feature_extractor'] = pipeline("feature-extraction", model="bert-base-uncased") | |
return models | |
# Preload models immediately when app starts | |
models = load_models() | |
##################################### | |
# Function: Extract Text from File | |
##################################### | |
def extract_text_from_file(file_obj): | |
""" | |
Extract text from .docx and .doc files. | |
Returns the extracted text or an error message if extraction fails. | |
""" | |
filename = file_obj.name | |
ext = os.path.splitext(filename)[1].lower() | |
text = "" | |
if ext == ".docx": | |
try: | |
document = docx.Document(file_obj) | |
text = "\n".join(para.text for para in document.paragraphs if para.text.strip()) | |
except Exception as e: | |
text = f"Error processing DOCX file: {e}" | |
elif ext == ".doc": | |
try: | |
# For .doc files, we need to save to a temp file | |
with tempfile.NamedTemporaryFile(delete=False, suffix='.doc') as temp_file: | |
temp_file.write(file_obj.getvalue()) | |
temp_path = temp_file.name | |
# Use docx2txt which is generally faster | |
try: | |
text = docx2txt.process(temp_path) | |
except Exception: | |
text = "Could not process .doc file. Please convert to .docx format." | |
# Clean up temp file | |
os.unlink(temp_path) | |
except Exception as e: | |
text = f"Error processing DOC file: {e}" | |
elif ext == ".txt": | |
try: | |
text = file_obj.getvalue().decode("utf-8") | |
except Exception as e: | |
text = f"Error processing TXT file: {e}" | |
else: | |
text = "Unsupported file type. Please upload a .docx, .doc, or .txt file." | |
return text | |
##################################### | |
# Function: Summarize Resume Text | |
##################################### | |
def summarize_resume_text(resume_text, models): | |
""" | |
Generates a structured summary of the resume text including name, age, | |
expected job industry, and skills of the candidate. | |
""" | |
start_time = time.time() | |
summarizer = models['summarizer'] | |
# Handle long text | |
max_input_length = 1024 # Model limit | |
# Append instructions to guide the model to extract structured information | |
prompt = f"Summarize this resume and include the candidate's name, age, expected job industry, and skills: {resume_text[:max_input_length]}" | |
if len(resume_text) > max_input_length: | |
# Process in chunks if text is too long | |
chunks = [resume_text[i:i+max_input_length] for i in range(0, min(len(resume_text), 3*max_input_length), max_input_length)] | |
summaries = [] | |
for chunk in chunks: | |
chunk_summary = summarizer(chunk, max_length=100, min_length=30, do_sample=False)[0]['summary_text'] | |
summaries.append(chunk_summary) | |
candidate_summary = " ".join(summaries) | |
if len(candidate_summary) > max_input_length: | |
candidate_summary = summarizer(f"Provide name, age, expected job industry, and skills of the candidate: {candidate_summary[:max_input_length]}", | |
max_length=150, min_length=40, do_sample=False)[0]['summary_text'] | |
else: | |
candidate_summary = summarizer(prompt, max_length=150, min_length=40, do_sample=False)[0]['summary_text'] | |
# Format the summary to ensure it contains the required information | |
# If the model doesn't extract all required information, we'll add placeholders | |
formatted_summary = candidate_summary | |
# Check if the summary contains the required information and add labels if needed | |
if "name:" not in formatted_summary.lower() and "name " not in formatted_summary.lower(): | |
formatted_summary = "Name: [Not explicitly mentioned in resume]\n" + formatted_summary | |
if "age:" not in formatted_summary.lower() and "age " not in formatted_summary.lower(): | |
formatted_summary += "\nAge: [Not explicitly mentioned in resume]" | |
if "industry:" not in formatted_summary.lower() and "expected job" not in formatted_summary.lower(): | |
formatted_summary += "\nExpected Job Industry: [Based on resume content]" | |
if "skills:" not in formatted_summary.lower() and "skills " not in formatted_summary.lower(): | |
formatted_summary += "\nSkills: [Key skills extracted from resume]" | |
execution_time = time.time() - start_time | |
return formatted_summary, execution_time | |
##################################### | |
# Function: Compare Candidate Summary to Company Prompt | |
##################################### | |
def compute_suitability(candidate_summary, company_prompt, models): | |
""" | |
Compute the similarity between candidate summary and company prompt. | |
Returns a score in the range [0, 1] and execution time. | |
""" | |
start_time = time.time() | |
feature_extractor = models['feature_extractor'] | |
# Extract features (embeddings) | |
candidate_features = feature_extractor(candidate_summary) | |
company_features = feature_extractor(company_prompt) | |
# Convert to numpy arrays and flatten if needed | |
candidate_vec = np.mean(np.array(candidate_features[0]), axis=0) | |
company_vec = np.mean(np.array(company_features[0]), axis=0) | |
# Compute cosine similarity (1 - cosine distance) | |
similarity = 1 - cosine(candidate_vec, company_vec) | |
execution_time = time.time() - start_time | |
return similarity, execution_time | |
##################################### | |
# Main Streamlit Interface | |
##################################### | |
st.title("Resume Analyzer and Company Suitability Checker") | |
st.markdown( | |
""" | |
Upload your resume file in **.docx**, **.doc**, or **.txt** format. The app performs the following tasks: | |
1. Extracts text from the resume. | |
2. Uses a transformer-based model to generate a structured candidate summary with name, age, expected job industry, and skills. | |
3. Compares the candidate summary with a company profile to produce a suitability score. | |
""" | |
) | |
# File uploader | |
uploaded_file = st.file_uploader("Upload your resume (.docx, .doc, or .txt)", type=["docx", "doc", "txt"]) | |
# Company description text area | |
company_prompt = st.text_area( | |
"Enter the company description or job requirements:", | |
height=150, | |
help="Enter a detailed description of the company culture, role requirements, and desired skills.", | |
) | |
# Process button | |
if uploaded_file is not None and company_prompt and st.button("Analyze Resume"): | |
with st.spinner("Processing..."): | |
# Extract text from resume | |
resume_text = extract_text_from_file(uploaded_file) | |
if resume_text.startswith("Error") or resume_text == "Unsupported file type. Please upload a .docx, .doc, or .txt file.": | |
st.error(resume_text) | |
else: | |
# Generate summary | |
summary, summarization_time = summarize_resume_text(resume_text, models) | |
# Display summary | |
st.subheader("Candidate Summary") | |
st.markdown(summary) | |
st.info(f"Summarization completed in {summarization_time:.2f} seconds") | |
# Only compute similarity if company description is provided | |
if company_prompt: | |
similarity_score, similarity_time = compute_suitability(summary, company_prompt, models) | |
# Display similarity score | |
st.subheader("Suitability Assessment") | |
st.markdown(f"**Matching Score:** {similarity_score:.2%}") | |
st.info(f"Similarity computation completed in {similarity_time:.2f} seconds") | |
# Provide interpretation | |
if similarity_score >= 0.85: | |
st.success("Excellent match! This candidate's profile is strongly aligned with the company requirements.") | |
elif similarity_score >= 0.70: | |
st.success("Good match! This candidate shows strong potential for the position.") | |
elif similarity_score >= 0.50: | |
st.warning("Moderate match. The candidate meets some requirements but there may be gaps.") | |
else: | |
st.error("Low match. The candidate's profile may not align well with the requirements.") |