ARCP / app.py
MerlinValanarasu's picture
Create app.py
4819ead verified
Raw History Blame Contribute Delete
17 kB
# For Hugging Face Spaces with Streamlit
import streamlit as st
import pdfplumber
import docx2txt
import spacy
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
import matplotlib.pyplot as plt
import nltk
from nltk.corpus import stopwords
from collections import Counter
import base64
import os
# Download spaCy model
try:
nlp = spacy.load("en_core_web_sm")
except OSError:
os.system("python -m spacy download en_core_web_sm")
# Download NLTK data
@st.cache_resource
def download_nltk_data():
nltk.download('stopwords')
return True
# Load spaCy model
@st.cache_resource
def load_spacy():
try:
return spacy.load("en_core_web_sm")
except OSError:
import os
os.system("python -m spacy download en_core_web_sm")
return spacy.load("en_core_web_sm")
# Initialize
download_nltk_data()
nlp = load_spacy()
# Resume parsing functions
def extract_text_from_pdf(file):
with pdfplumber.open(file) as pdf:
text = " ".join([page.extract_text() or "" for page in pdf.pages])
return text
def extract_text_from_docx(file):
text = docx2txt.process(file)
return text
def extract_text(file):
file_name = file.name.lower()
if file_name.endswith('.pdf'):
return extract_text_from_pdf(file)
elif file_name.endswith('.docx'):
return extract_text_from_docx(file)
else:
return "Unsupported file format. Please upload a PDF or DOCX file."
# ATS Scoring functions
def preprocess_text(text):
text = text.lower()
text = re.sub(r'[^\w\s]', ' ', text)
text = re.sub(r'\d+', ' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text
def calculate_similarity_score(resume_text, job_desc_text):
resume_processed = preprocess_text(resume_text)
job_processed = preprocess_text(job_desc_text)
vectorizer = TfidfVectorizer(stop_words='english')
try:
tfidf_matrix = vectorizer.fit_transform([resume_processed, job_processed])
similarity = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]
return similarity * 100
except:
return 0
def extract_skills_from_text(text):
doc = nlp(text.lower())
potential_skills = [token.text for token in doc if token.pos_ in ["NOUN", "PROPN"]]
stop_words = set(stopwords.words('english'))
skills = [skill for skill in potential_skills
if skill not in stop_words and len(skill) > 2]
skill_freq = Counter(skills)
return skill_freq
def get_missing_keywords(resume_text, job_desc_text, threshold=2):
job_skills = extract_skills_from_text(job_desc_text)
resume_skills = extract_skills_from_text(resume_text)
missing_skills = {skill: count for skill, count in job_skills.items()
if count >= threshold and skill not in resume_skills}
sorted_missing = sorted(missing_skills.items(), key=lambda x: x[1], reverse=True)
return sorted_missing
def check_ats_formatting(resume_text):
formatting_issues = []
important_sections = ['experience', 'education', 'skills', 'projects']
found_sections = []
for section in important_sections:
pattern = re.compile(r'\b' + section + r'\b', re.IGNORECASE)
if pattern.search(resume_text):
found_sections.append(section)
missing_sections = set(important_sections) - set(found_sections)
if missing_sections:
formatting_issues.append(f"Missing key sections: {', '.join(missing_sections)}")
if 'โ€ข' not in resume_text and '*' not in resume_text and '-' not in resume_text:
formatting_issues.append("No bullet points detected - consider using them for listing skills and responsibilities")
if '|' in resume_text or '\t' in resume_text:
formatting_issues.append("Possible tables detected - avoid tables as they may not parse correctly")
contact_patterns = [
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # Email
r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', # Phone number
r'linkedin\.com' # LinkedIn
]
missing_contact = []
for i, pattern in enumerate(['email', 'phone', 'linkedin']):
if not re.search(contact_patterns[i], resume_text, re.IGNORECASE):
missing_contact.append(pattern)
if missing_contact:
formatting_issues.append(f"Missing contact information: {', '.join(missing_contact)}")
paragraphs = resume_text.split('\n\n')
long_paragraphs = [p for p in paragraphs if len(p.split()) > 40]
if long_paragraphs:
formatting_issues.append(f"Found {len(long_paragraphs)} long paragraphs - consider breaking them into bullet points")
return formatting_issues if formatting_issues else ["No major formatting issues detected!"]
# Resume advice function
def get_resume_advice(query, resume_score=None, missing_keywords=None, formatting_issues=None):
query_lower = query.lower()
context = ""
if resume_score is not None:
context += f"Based on your ATS score of {resume_score:.1f}%: "
if any(word in query_lower for word in ['ats', 'score', 'improve score']):
return context + "To improve your ATS score, tailor your resume to match the job description by incorporating relevant keywords naturally. Use a clean, simple format and standard section headings like 'Experience', 'Education', and 'Skills'."
elif any(word in query_lower for word in ['keyword', 'keywords', 'missing']):
keyword_info = ""
if missing_keywords and len(missing_keywords) > 0:
top_keywords = [k for k, _ in missing_keywords[:5]]
keyword_info = f"Consider adding these missing keywords: {', '.join(top_keywords)}. "
return context + keyword_info + "Add missing keywords from the job description to your resume, but do it naturally. Include them in your skills section and work experience bullets. Don't just list them - show how you've used these skills in previous roles."
elif any(word in query_lower for word in ['format', 'formatting', 'layout']):
format_info = ""
if formatting_issues and len(formatting_issues) > 0:
format_info = f"Your specific formatting issues: {formatting_issues[0] if len(formatting_issues) == 1 else ', '.join(formatting_issues[:2]) + '...'}. "
return context + format_info + "For ATS-friendly formatting: 1) Use standard section headings, 2) Avoid tables, images, and complex layouts, 3) Use bullet points for work experience, 4) Include your contact information at the top, 5) Save as a .docx or simple PDF file."
elif any(word in query_lower for word in ['bullet', 'bullets', 'point']):
return context + "Effective bullet points follow the STAR method: Situation, Task, Action, Result. Start with strong action verbs, include specific metrics where possible, and keep each bullet to 1-2 lines. Make sure they highlight achievements, not just responsibilities."
elif any(word in query_lower for word in ['experience', 'work history', 'job']):
return context + "When describing work experience, focus on achievements rather than duties. Use metrics and numbers to quantify your impact. Tailor each bullet to highlight skills relevant to the job you're applying for. Use past tense for previous jobs and present tense for current roles."
elif any(word in query_lower for word in ['education', 'degree']):
return context + "In your education section, list your most recent degree first. Include your degree, major, university name, location, and graduation year. If you're a recent graduate, you can also include relevant coursework, GPA (if above 3.5), and academic achievements."
elif any(word in query_lower for word in ['skill', 'skills']):
return context + "For your skills section, categorize them (Technical, Software, Soft Skills, etc.) and prioritize those mentioned in the job description. Be specific with technical skills - instead of 'Programming', list specific languages like 'Python' or 'Java'."
elif any(word in query_lower for word in ['interview', 'prepare']):
return context + "To prepare for interviews: 1) Research the company thoroughly, 2) Practice answering common questions using the STAR method, 3) Prepare examples that showcase the skills in the job description, 4) Have questions ready to ask the interviewer, 5) Review your resume and be ready to elaborate on any point."
else:
return context + "I'm here to help with your resume and job application questions. For best results, ask specific questions about improving your ATS score, formatting, keywords, or different resume sections. I can also help with interview preparation and career advice."
# Create a download link for the results
def get_table_download_link(df):
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}" download="resume_analysis.csv">Download results as CSV</a>'
return href
# Streamlit UI
st.set_page_config(page_title="AI Resume Checker", page_icon="๐Ÿ“", layout="wide")
st.title("๐Ÿ“ AI Resume Checker")
st.markdown("### Optimize your resume for Applicant Tracking Systems (ATS)")
# Sidebar with instructions
with st.sidebar:
st.header("How it works")
st.write("1. Upload your resume (PDF or DOCX)")
st.write("2. Enter the job description")
st.write("3. Get instant ATS compatibility analysis")
st.write("4. Ask questions to improve your resume")
st.markdown("---")
st.markdown("### About")
st.write("This tool helps you optimize your resume for ATS systems by analyzing keyword matching, formatting, and providing personalized advice.")
st.write("Your data is processed locally and not stored.")
# Create tabs
tab1, tab2, tab3 = st.tabs(["Upload & Analyze", "Results", "Resume Assistant"])
# Global variables to store state
if 'resume_text' not in st.session_state:
st.session_state.resume_text = None
if 'job_desc' not in st.session_state:
st.session_state.job_desc = None
if 'ats_score' not in st.session_state:
st.session_state.ats_score = None
if 'missing_keywords' not in st.session_state:
st.session_state.missing_keywords = None
if 'formatting_issues' not in st.session_state:
st.session_state.formatting_issues = None
if 'analysis_complete' not in st.session_state:
st.session_state.analysis_complete = False
# Tab 1: Upload & Analyze
with tab1:
col1, col2 = st.columns(2)
with col1:
st.subheader("Upload Resume")
uploaded_resume = st.file_uploader("Choose a resume file", type=["pdf", "docx"])
if uploaded_resume is not None:
st.session_state.resume_text = extract_text(uploaded_resume)
if st.session_state.resume_text == "Unsupported file format. Please upload a PDF or DOCX file.":
st.error(st.session_state.resume_text)
else:
st.success(f"Resume loaded successfully! ({len(st.session_state.resume_text)} characters)")
with col2:
st.subheader("Job Description")
st.session_state.job_desc = st.text_area("Paste the job description here", height=300)
if st.button("Analyze Resume") and st.session_state.resume_text and st.session_state.job_desc:
with st.spinner("Analyzing your resume..."):
# Calculate ATS score
st.session_state.ats_score = calculate_similarity_score(st.session_state.resume_text, st.session_state.job_desc)
# Get missing keywords
st.session_state.missing_keywords = get_missing_keywords(st.session_state.resume_text, st.session_state.job_desc)
# Check formatting
st.session_state.formatting_issues = check_ats_formatting(st.session_state.resume_text)
st.session_state.analysis_complete = True
st.success("Analysis complete! Check the Results tab.")
st.balloons()
# Tab 2: Results
with tab2:
if st.session_state.analysis_complete:
st.subheader("ATS Compatibility Analysis")
# ATS Score
col1, col2 = st.columns([1, 2])
with col1:
st.metric("ATS Score", f"{st.session_state.ats_score:.1f}%")
if st.session_state.ats_score >= 70:
st.success("Great match! Your resume is well-aligned with this job.")
elif st.session_state.ats_score >= 50:
st.warning("Moderate match. Some improvements could help.")
else:
st.error("Low match. Significant tailoring recommended.")
with col2:
# Create a gauge chart
fig, ax = plt.subplots(figsize=(4, 0.8))
ax.barh(0, 100, color='#e0e0e0', height=0.5)
ax.barh(0, st.session_state.ats_score, color='#2e6ca4' if st.session_state.ats_score >= 70 else '#f9a825' if st.session_state.ats_score >= 50 else '#d32f2f', height=0.5)
ax.set_xlim(0, 100)
ax.set_yticks([])
ax.set_xticks([0, 25, 50, 75, 100])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.tight_layout()
st.pyplot(fig)
# Formatting Check
st.subheader("Formatting Check")
for issue in st.session_state.formatting_issues:
if "No major" in issue:
st.success(issue)
else:
st.warning(issue)
# Missing Keywords
st.subheader("Missing Keywords")
if st.session_state.missing_keywords:
# Create dataframe for keywords
keywords_df = pd.DataFrame(st.session_state.missing_keywords[:15], columns=["Keyword", "Frequency"])
col1, col2 = st.columns([3, 2])
with col1:
# Plot missing keywords
fig, ax = plt.subplots(figsize=(10, min(8, 0.5*min(15, len(st.session_state.missing_keywords)))))
keywords = keywords_df["Keyword"].tolist()
counts = keywords_df["Frequency"].tolist()
ax.barh(keywords, counts, color='#2e6ca4')
ax.set_xlabel('Frequency in Job Description')
ax.set_title('Top Missing Keywords')
plt.tight_layout()
st.pyplot(fig)
with col2:
st.dataframe(keywords_df)
st.markdown(get_table_download_link(keywords_df), unsafe_allow_html=True)
else:
st.success("Great job! Your resume already contains key terms from the job description.")
# Improvement suggestions
st.subheader("Improvement Suggestions")
if st.session_state.ats_score < 50:
st.error("Your resume needs significant improvements to pass ATS systems. Focus on adding more relevant keywords and improving formatting.")
elif st.session_state.ats_score < 70:
st.warning("Your resume may pass some ATS systems but could be improved. Try to incorporate more of the missing keywords.")
else:
st.success("Your resume is well-optimized for ATS systems! Make minor adjustments to incorporate any missing keywords.")
else:
st.info("Please upload your resume and job description, then click 'Analyze Resume' to see results here.")
# Tab 3: Resume Assistant
with tab3:
st.subheader("Ask the Resume AI Assistant")
st.write("Ask questions about improving your resume, job applications, or interview preparation.")
user_question = st.text_input("Your question:", placeholder="How can I improve my ATS score?")
if user_question:
response = get_resume_advice(
user_question,
st.session_state.ats_score,
st.session_state.missing_keywords,
st.session_state.formatting_issues
)
st.markdown(f"### Answer")
st.markdown(response)
# Sample questions
st.markdown("### Sample questions")
questions = [
"How can I improve my ATS score?",
"What keywords am I missing?",
"How should I format my resume?",
"How do I write good bullet points?",
"How should I describe my work experience?"
]
cols = st.columns(3)
for i, question in enumerate(questions):
if cols[i % 3].button(question):
response = get_resume_advice(
question,
st.session_state.ats_score,
st.session_state.missing_keywords,
st.session_state.formatting_issues
)
st.markdown(f"### Answer")
st.markdown(response)