ZainabFatimaa's picture
Update src/app.py
4b8ca84 verified
import streamlit as st
import pandas as pd
import numpy as np
import re
import io
import base64
import os
import requests
import json
from collections import Counter
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
# File processing imports
import PyPDF2
import pdfplumber
import docx
from docx import Document
# NLP imports
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem import WordNetLemmatizer
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, set_seed
# Optional imports with fallbacks
try:
import spacy
SPACY_AVAILABLE = True
except ImportError:
SPACY_AVAILABLE = False
try:
from fuzzywuzzy import fuzz, process
FUZZYWUZZY_AVAILABLE = True
except ImportError:
FUZZYWUZZY_AVAILABLE = False
try:
import language_tool_python
GRAMMAR_TOOL_AVAILABLE = True
except ImportError:
GRAMMAR_TOOL_AVAILABLE = False
# ML imports
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Report generation
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re
from datetime import datetime
from typing import Dict, List
# Set seed for reproducibility
set_seed(42)
# Custom CSS for better UI
def load_custom_css():
st.markdown("""
<style>
.main {
padding-top: 2rem;
}
.metric-card {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 1rem;
margin: 0.5rem 0;
text-align: center;
}
.metric-value {
font-size: 2rem;
font-weight: bold;
color: #28a745;
}
.metric-label {
font-size: 0.9rem;
color: #6c757d;
margin-top: 0.5rem;
}
.warning-box {
background-color: #fff3cd;
border-left: 4px solid #ffc107;
padding: 1rem;
margin: 1rem 0;
}
.success-box {
background-color: #d4edda;
border-left: 4px solid #28a745;
padding: 1rem;
margin: 1rem 0;
}
.error-box {
background-color: #f8d7da;
border-left: 4px solid #dc3545;
padding: 1rem;
margin: 1rem 0;
}
.info-box {
background-color: #d1ecf1;
border-left: 4px solid #17a2b8;
padding: 1rem;
margin: 1rem 0;
}
.skill-tag {
display: inline-block;
background-color: #e9ecef;
border-radius: 4px;
padding: 0.25rem 0.5rem;
margin: 0.25rem;
font-size: 0.875rem;
}
.section-header {
border-bottom: 2px solid #dee2e6;
padding-bottom: 0.5rem;
margin-bottom: 1rem;
}
.nav-pills {
background-color: #f8f9fa;
border-radius: 8px;
padding: 0.5rem;
margin-bottom: 1rem;
}
.sidebar .sidebar-content {
background-color: #f8f9fa;
}
</style>
""", unsafe_allow_html=True)
class ImprovedNLPProcessor:
def __init__(self):
self.setup_nltk()
def setup_nltk(self):
try:
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
nltk.download('wordnet', quiet=True)
self.stop_words = set(stopwords.words('english'))
self.lemmatizer = WordNetLemmatizer()
except:
self.stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'with'}
self.lemmatizer = None
def extract_key_terms(self, text: str, max_terms: int = 5) -> str:
"""Extract key terms without overwhelming the model"""
try:
tokens = word_tokenize(text.lower())
except:
tokens = text.lower().split()
# Focus on resume-relevant terms
resume_keywords = ['resume', 'experience', 'skills', 'education', 'job', 'work', 'ats', 'career']
filtered_tokens = []
for token in tokens:
if (len(token) > 2 and
token not in self.stop_words and
(token.isalpha() or token in resume_keywords)):
filtered_tokens.append(token)
# Return only the most relevant terms
return ' '.join(filtered_tokens[:max_terms])
class ImprovedChatMemory:
def __init__(self):
if 'improved_chat_history' not in st.session_state:
st.session_state.improved_chat_history = []
def add_conversation(self, user_msg: str, bot_response: str):
conversation = {
'user': user_msg,
'bot': bot_response,
'timestamp': datetime.now().strftime("%H:%M:%S")
}
st.session_state.improved_chat_history.append(conversation)
# Keep only last 6 conversations
if len(st.session_state.improved_chat_history) > 6:
st.session_state.improved_chat_history = st.session_state.improved_chat_history[-6:]
def get_simple_context(self) -> str:
"""Get very simple context to avoid confusing the model"""
if not st.session_state.improved_chat_history:
return ""
# Only use the last conversation for context
last_conv = st.session_state.improved_chat_history[-1]
last_topic = last_conv['user'][:30] # First 30 chars only
return f"Previously discussed: {last_topic}"
class ImprovedCPUChatbot:
def __init__(self):
self.model_name = "distilgpt2"
self.model = None
self.tokenizer = None
self.pipeline = None
self.nlp_processor = ImprovedNLPProcessor()
self.memory = ImprovedChatMemory()
self.is_loaded = False
# Predefined responses for common resume questions
self.template_responses = {
'experience': "To improve your experience section: Use bullet points with action verbs, quantify achievements with numbers, focus on results rather than duties, and tailor content to match job requirements.",
'ats': "Make your resume ATS-friendly by: Using standard section headings, including relevant keywords naturally, avoiding images and complex formatting, using common fonts like Arial, and saving as PDF.",
'skills': "Enhance your skills section by: Organizing technical and soft skills separately, matching skills to job descriptions, providing proficiency levels, and including both hard and soft skills relevant to your target role.",
'keywords': "Add relevant keywords by: Studying job descriptions in your field, using industry-specific terms, including both acronyms and full terms, and incorporating them naturally throughout your resume.",
'format': "Improve resume formatting with: Clear section headings, consistent bullet points, readable fonts, appropriate white space, and a clean, professional layout that's easy to scan."
}
@st.cache_resource
def load_model(_self):
"""Load the model with better configuration"""
try:
with st.spinner("Loading AI model (first time may take 2-3 minutes)..."):
tokenizer = AutoTokenizer.from_pretrained(_self.model_name)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
_self.model_name,
torch_dtype=torch.float32,
low_cpu_mem_usage=True
)
# Create pipeline with better parameters
text_generator = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=-1, # CPU only
max_new_tokens=50, # Reduced for better quality
do_sample=True,
temperature=0.8,
top_p=0.85,
top_k=50,
repetition_penalty=1.2, # Reduce repetition
pad_token_id=tokenizer.eos_token_id,
no_repeat_ngram_size=3 # Prevent 3-gram repetition
)
return model, tokenizer, text_generator
except Exception as e:
st.error(f"Failed to load model: {str(e)}")
return None, None, None
def initialize(self):
"""Initialize the chatbot"""
if not self.is_loaded:
result = self.load_model()
if result[0] is not None:
self.model, self.tokenizer, self.pipeline = result
self.is_loaded = True
st.success("AI model loaded successfully!")
return True
else:
return False
return True
def get_template_response(self, user_input: str) -> str:
"""Check if we can use a template response for common questions"""
user_lower = user_input.lower()
# Check for common patterns
if any(word in user_lower for word in ['experience', 'work history', 'job history']):
return self.template_responses['experience']
elif any(word in user_lower for word in ['ats', 'applicant tracking', 'ats-friendly']):
return self.template_responses['ats']
elif any(word in user_lower for word in ['skills', 'technical skills', 'abilities']):
return self.template_responses['skills']
elif any(word in user_lower for word in ['keywords', 'keyword', 'terms']):
return self.template_responses['keywords']
elif any(word in user_lower for word in ['format', 'formatting', 'layout', 'design']):
return self.template_responses['format']
# Add general improvement patterns
elif any(phrase in user_lower for phrase in ['improve my resume', 'better resume', 'hire me', 'get hired', 'land job']):
return "To improve your resume for HR success: Use a clear, professional format with standard headings. Tailor your content to match job descriptions. Quantify achievements with numbers. Include relevant keywords naturally. Keep it to 1-2 pages. Use bullet points with action verbs. Proofread carefully for errors."
elif any(word in user_lower for word in ['help', 'advice', 'tips', 'suggestions']):
return "Key resume tips: Match your resume to each job application. Use metrics to show your impact. Include both technical and soft skills. Write a compelling summary. Use reverse chronological order. Keep formatting clean and simple."
return None
def create_simple_prompt(self, user_input: str, resume_context: str = "") -> str:
"""Create a very simple, clear prompt"""
# Try template response first
template_response = self.get_template_response(user_input)
if template_response:
return template_response
# Extract key terms
key_terms = self.nlp_processor.extract_key_terms(user_input)
# Create simple prompt
if resume_context:
context_snippet = resume_context[:100].replace('\n', ' ')
prompt = f"Resume help: {context_snippet}\nQuestion: {user_input}\nAdvice:"
else:
prompt = f"Resume question: {user_input}\nHelpful advice:"
return prompt
def generate_response(self, user_input: str, resume_context: str = "") -> str:
"""Generate response with better quality control and timeout handling"""
if not self.is_loaded:
return "Please initialize the AI model first by clicking 'Initialize AI'."
# Check for template response first (this should catch most questions)
template_response = self.get_template_response(user_input)
if template_response:
self.memory.add_conversation(user_input, template_response)
return template_response
# For non-template questions, provide a general helpful response instead of using the model
# This avoids the generation loops and stuck behavior
general_response = self.get_comprehensive_advice(user_input)
self.memory.add_conversation(user_input, general_response)
return general_response
def get_comprehensive_advice(self, user_input: str) -> str:
"""Provide comprehensive advice based on user input patterns"""
user_lower = user_input.lower()
# Comprehensive resume improvement advice
if any(phrase in user_lower for phrase in ['improve', 'better', 'enhance', 'optimize']):
return """To improve your resume effectiveness: 1) Tailor it to each job by matching keywords from the job description. 2) Use quantifiable achievements (increased sales by 25%, managed team of 10). 3) Start bullet points with strong action verbs. 4) Keep it concise - ideally 1-2 pages. 5) Use a clean, professional format with consistent styling. 6) Include relevant technical and soft skills. 7) Proofread carefully for any errors."""
# HR/hiring focused advice
elif any(phrase in user_lower for phrase in ['hr', 'hire', 'hiring', 'recruiter', 'employer']):
return """To make your resume appealing to HR and hiring managers: 1) Use standard section headings they expect (Experience, Education, Skills). 2) Include relevant keywords to pass ATS screening. 3) Show clear career progression and achievements. 4) Make it easy to scan with bullet points and white space. 5) Demonstrate value you can bring to their organization. 6) Include measurable results and impacts."""
# Job search and career advice
elif any(phrase in user_lower for phrase in ['job', 'career', 'position', 'role', 'work']):
return """For job search success: 1) Customize your resume for each application. 2) Research the company and role requirements. 3) Highlight relevant experience and skills prominently. 4) Use industry-specific terminology. 5) Show how your background aligns with their needs. 6) Include both technical competencies and soft skills."""
# General help
else:
return """Key resume best practices: Use a professional format with clear headings. Lead with your strongest qualifications. Include relevant keywords naturally. Quantify achievements with specific numbers. Keep descriptions concise but impactful. Ensure error-free writing and consistent formatting. Focus on what value you bring to employers."""
def get_general_advice(self, user_input: str) -> str:
"""Fallback advice for when model fails"""
user_lower = user_input.lower()
if 'experience' in user_lower:
return "Focus on achievements with numbers, use action verbs, and show results."
elif 'skill' in user_lower:
return "List skills that match the job description and organize them by category."
elif 'ats' in user_lower:
return "Use standard headings, include keywords, and avoid complex formatting."
else:
return "Make sure your resume is clear, relevant to the job, and easy to read."
def clean_response_thoroughly(self, response: str, user_input: str) -> str:
"""Thoroughly clean the generated response"""
if not response or len(response.strip()) < 5:
return self.get_general_advice(user_input)
# Remove common problematic patterns
response = re.sub(r'\|[^|]*\|', '', response) # Remove pipe-separated content
response = re.sub(r'Advice:\s*', '', response) # Remove "Advice:" repetition
response = re.sub(r'\s+', ' ', response) # Replace multiple spaces
response = re.sub(r'[.]{2,}', '.', response) # Replace multiple periods
# Split into sentences and filter
sentences = [s.strip() for s in response.split('.') if s.strip()]
good_sentences = []
seen_content = set()
for sentence in sentences[:2]: # Max 2 sentences
if (len(sentence) > 15 and
sentence.lower() not in seen_content and
not sentence.lower().startswith(('you are', 'i am', 'as a', 'how do')) and
'advice' not in sentence.lower()):
good_sentences.append(sentence)
seen_content.add(sentence.lower())
if good_sentences:
response = '. '.join(good_sentences)
if not response.endswith('.'):
response += '.'
else:
response = self.get_general_advice(user_input)
return response.strip()
def create_improved_chat_interface(resume_context: str = ""):
"""Create improved chat interface"""
st.header("AI Resume Assistant")
# Initialize chatbot
if 'improved_chatbot' not in st.session_state:
st.session_state.improved_chatbot = ImprovedCPUChatbot()
chatbot = st.session_state.improved_chatbot
# Model initialization
col1, col2 = st.columns([3, 1])
with col1:
st.info("Using DistilGPT2 with improved response quality")
with col2:
if st.button("Initialize AI", type="primary"):
chatbot.initialize()
# Chat interface
if chatbot.is_loaded:
st.success("AI Ready")
# Quick questions
st.subheader("Quick Questions")
col1, col2 = st.columns(2)
with col1:
if st.button("How to improve experience section?"):
st.session_state.quick_question = "What's wrong with my experience section?"
with col2:
if st.button("Make resume ATS-friendly?"):
st.session_state.quick_question = "How do I make it more ATS-friendly?"
col3, col4 = st.columns(2)
with col3:
if st.button("Add better keywords?"):
st.session_state.quick_question = "What keywords should I add?"
with col4:
if st.button("Improve skills section?"):
st.session_state.quick_question = "How can I improve my skills section?"
# Chat input
user_question = st.text_input(
"Ask about your resume:",
value=st.session_state.get('quick_question', ''),
placeholder="How can I improve my resume?",
key="improved_chat_input"
)
# Send button and clear
col1, col2 = st.columns([1, 3])
with col1:
send_clicked = st.button("Send", type="primary")
with col2:
if st.button("Clear Chat"):
st.session_state.improved_chat_history = []
if 'quick_question' in st.session_state:
del st.session_state.quick_question
st.experimental_rerun()
# Generate response
if send_clicked and user_question.strip():
with st.spinner("Generating advice..."):
response = chatbot.generate_response(user_question, resume_context)
if 'quick_question' in st.session_state:
del st.session_state.quick_question
st.experimental_rerun()
# Display chat history
if st.session_state.improved_chat_history:
st.subheader("💬 Conversation")
for conv in reversed(st.session_state.improved_chat_history[-3:]): # Show last 3
st.markdown(f"**You:** {conv['user']}")
st.markdown(f"**AI:** {conv['bot']}")
st.caption(f"Time: {conv['timestamp']}")
st.divider()
else:
st.warning("Click 'Initialize AI' to start chatting")
with st.expander("Improved Features"):
st.markdown("""
**Model**: DistilGPT2 with enhanced parameters
**Response time**: 1-3 seconds
**Quality**: Significantly improved over basic version
""")
@st.cache_resource
def download_nltk_data():
try:
nltk.data.find('tokenizers/punkt')
nltk.data.find('corpora/stopwords')
nltk.data.find('corpora/wordnet')
except LookupError:
with st.spinner("Downloading NLTK data..."):
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
nltk.download('wordnet', quiet=True)
nltk.download('punkt_tab', quiet=True)
@st.cache_resource
def init_tools():
download_nltk_data()
nlp = None
if SPACY_AVAILABLE:
try:
nlp = spacy.load("en_core_web_sm")
except OSError:
try:
import subprocess
import sys
with st.spinner("Downloading spaCy model..."):
subprocess.run([sys.executable, "-m", "spacy", "download", "en_core_web_sm"],
check=True, capture_output=True)
nlp = spacy.load("en_core_web_sm")
except Exception as e:
nlp = None
grammar_tool = None
if GRAMMAR_TOOL_AVAILABLE:
try:
with st.spinner("Initializing grammar checker..."):
grammar_tool = language_tool_python.LanguageTool('en-US')
except Exception as e:
grammar_tool = None
return nlp, grammar_tool
def simple_fuzzy_match(keyword, text):
"""Simple fuzzy matching fallback when fuzzywuzzy is not available"""
keyword_lower = keyword.lower()
text_lower = text.lower()
if keyword_lower in text_lower:
return 100
keyword_words = keyword_lower.split()
matches = sum(1 for word in keyword_words if word in text_lower)
return (matches / len(keyword_words)) * 100 if keyword_words else 0
def basic_grammar_check(text):
"""Basic grammar check when language_tool_python is not available"""
issues = []
sentences = sent_tokenize(text)
for i, sentence in enumerate(sentences):
if len(sentence.split()) > 30:
issues.append(f"Sentence {i+1} might be too long ({len(sentence.split())} words)")
words = sentence.lower().split()
for j in range(len(words) - 1):
if words[j] == words[j + 1] and len(words[j]) > 3:
issues.append(f"Repeated word '{words[j]}' in sentence {i+1}")
return [type('MockError', (), {'message': issue}) for issue in issues]
def display_metric_card(title, value, description=""):
"""Display a metric in a card format"""
st.markdown(f"""
<div class="metric-card">
<div class="metric-value">{value}</div>
<div class="metric-label">{title}</div>
{f"<small>{description}</small>" if description else ""}
</div>
""", unsafe_allow_html=True)
def display_alert_box(message, alert_type="info"):
"""Display alert box with different types"""
box_class = f"{alert_type}-box"
st.markdown(f"""
<div class="{box_class}">
{message}
</div>
""", unsafe_allow_html=True)
class ResumeAnalyzer:
def __init__(self):
self.nlp, self.grammar_tool = init_tools()
self.chatbot = ImprovedCPUChatbot()
try:
self.stop_words = set(stopwords.words('english'))
except LookupError:
self.stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could', 'can', 'may', 'might', 'must'}
self.lemmatizer = WordNetLemmatizer()
# Job role keywords dictionary
self.job_keywords = {
"Data Scientist": ["python", "machine learning", "statistics", "pandas", "numpy", "scikit-learn",
"tensorflow", "pytorch", "sql", "data analysis", "visualization", "jupyter", "r", "statistics", "deep learning"],
"Software Engineer": ["programming", "java", "python", "javascript", "react", "node.js", "database",
"git", "agile", "testing", "debugging", "api", "frontend", "backend", "algorithms", "data structures"],
"Product Manager": ["product", "strategy", "roadmap", "stakeholder", "analytics", "user experience",
"market research", "agile", "scrum", "requirements", "metrics", "wireframes", "user stories"],
"Marketing Manager": ["marketing", "digital marketing", "seo", "social media", "analytics", "campaigns",
"brand", "content", "advertising", "growth", "conversion", "roi", "crm"],
"Data Analyst": ["sql", "excel", "python", "tableau", "power bi", "statistics", "reporting",
"data visualization", "business intelligence", "analytics", "dashboards", "kpi"],
"DevOps Engineer": ["docker", "kubernetes", "aws", "azure", "gcp", "jenkins", "ci/cd", "terraform",
"ansible", "monitoring", "linux", "bash", "infrastructure", "deployment"],
"UI/UX Designer": ["figma", "sketch", "adobe xd", "prototyping", "wireframes", "user research",
"usability testing", "design systems", "responsive design", "accessibility", "typography"],
"Cybersecurity Analyst": ["security", "penetration testing", "vulnerability assessment", "siem", "firewall",
"incident response", "compliance", "risk assessment", "cryptography", "network security"],
"Business Analyst": ["requirements gathering", "process improvement", "stakeholder management", "documentation",
"business process", "gap analysis", "user stories", "workflow", "project management"],
"Full Stack Developer": ["html", "css", "javascript", "react", "angular", "vue", "node.js", "express",
"mongodb", "postgresql", "rest api", "graphql", "version control", "responsive design"],
"Machine Learning Engineer": [
"python", "tensorflow", "pytorch", "scikit-learn", "pandas", "numpy", "machine learning",
"deep learning", "neural networks", "computer vision", "nlp", "data science", "algorithms",
"statistics", "linear algebra", "calculus", "regression", "classification", "clustering",
"feature engineering", "model deployment", "mlops", "docker", "kubernetes", "aws", "gcp"
],
"AI Engineer": [
"artificial intelligence", "machine learning", "deep learning", "neural networks", "python",
"tensorflow", "pytorch", "computer vision", "nlp", "natural language processing", "opencv",
"transformers", "bert", "gpt", "reinforcement learning", "generative ai", "llm", "chatbot",
"model optimization", "ai ethics", "edge ai", "quantization", "onnx", "tensorrt"
]
}
# Common skills database
self.technical_skills = [
"python", "java", "javascript", "c++", "c#", "php", "ruby", "go", "rust", "swift",
"sql", "html", "css", "react", "angular", "vue", "node.js", "express", "django", "flask",
"machine learning", "deep learning", "tensorflow", "pytorch", "pandas", "numpy",
"docker", "kubernetes", "aws", "azure", "gcp", "git", "jenkins", "ci/cd", "mongodb", "postgresql",
"redis", "elasticsearch", "spark", "hadoop", "tableau", "power bi", "excel", "figma", "sketch",
"linux", "bash", "terraform", "ansible", "selenium", "junit", "jira", "confluence"
]
self.soft_skills = [
"leadership", "communication", "teamwork", "problem solving", "critical thinking",
"project management", "time management", "adaptability", "creativity", "analytical",
"collaboration", "innovation", "strategic thinking", "customer service", "negotiation",
"presentation", "mentoring", "conflict resolution", "decision making", "emotional intelligence"
]
def extract_text_from_pdf(self, file):
"""Extract text from PDF file"""
try:
with pdfplumber.open(file) as pdf:
text = ""
for page in pdf.pages:
text += page.extract_text() or ""
return text
except:
try:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text()
return text
except:
return "Error extracting PDF text"
def extract_text_from_docx(self, file):
"""Extract text from DOCX file"""
try:
doc = Document(file)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text
except:
return "Error extracting DOCX text"
def extract_text_from_txt(self, file):
"""Extract text from TXT file"""
try:
return str(file.read(), "utf-8")
except:
return "Error extracting TXT text"
def extract_sections(self, text):
"""Extract different sections from resume"""
sections = {}
section_patterns = {
'education': r'(education|academic|qualification|degree|university|college)',
'experience': r'(experience|employment|work|career|professional|job|position)',
'skills': r'(skills|technical|competencies|expertise|abilities|technologies)',
'projects': r'(projects|portfolio|work samples|personal projects)',
'certifications': r'(certifications?|certificates?|licensed?|credentials)',
'summary': r'(summary|objective|profile|about|overview)'
}
text_lower = text.lower()
lines = text.split('\n')
for section_name, pattern in section_patterns.items():
section_content = []
capturing = False
for i, line in enumerate(lines):
if re.search(pattern, line.lower()):
capturing = True
continue
if capturing:
if any(re.search(p, line.lower()) for p in section_patterns.values() if p != pattern):
break
if line.strip():
section_content.append(line.strip())
sections[section_name] = '\n'.join(section_content)
return sections
def extract_skills(self, text):
"""Extract technical and soft skills"""
text_lower = text.lower()
found_technical = []
found_soft = []
for skill in self.technical_skills:
if skill.lower() in text_lower:
found_technical.append(skill)
for skill in self.soft_skills:
skill_words = skill.lower().split()
if all(word in text_lower for word in skill_words):
found_soft.append(skill)
return found_technical, found_soft
def keyword_matching(self, text, job_role):
"""Match keywords for specific job role"""
if job_role not in self.job_keywords:
return [], 0
keywords = self.job_keywords[job_role]
text_lower = text.lower()
found_keywords = []
for keyword in keywords:
if FUZZYWUZZY_AVAILABLE:
if fuzz.partial_ratio(keyword, text_lower) > 80:
found_keywords.append(keyword)
else:
if simple_fuzzy_match(keyword, text_lower) > 80:
found_keywords.append(keyword)
match_percentage = (len(found_keywords) / len(keywords)) * 100
return found_keywords, match_percentage
def grammar_check(self, text):
"""Check grammar and language quality"""
if self.grammar_tool and GRAMMAR_TOOL_AVAILABLE:
try:
matches = self.grammar_tool.check(text[:5000])
return matches
except:
return basic_grammar_check(text)
else:
return basic_grammar_check(text)
def calculate_ats_score(self, text, sections):
"""Calculate ATS friendliness score"""
score = 0
# Check for key sections (40 points)
required_sections = ['experience', 'education', 'skills']
for section in required_sections:
if sections.get(section) and len(sections[section]) > 50:
score += 13.33
# Check text length (20 points)
word_count = len(text.split())
if 300 <= word_count <= 800:
score += 20
elif word_count > 200:
score += 10
# Check for contact information (20 points)
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
phone_pattern = r'(\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
if re.search(email_pattern, text):
score += 10
if re.search(phone_pattern, text):
score += 10
# Check for bullet points (20 points)
bullet_patterns = [r'•', r'◦', r'\*', r'-\s', r'→']
bullet_count = sum(len(re.findall(pattern, text)) for pattern in bullet_patterns)
if bullet_count >= 5:
score += 20
elif bullet_count >= 2:
score += 10
return min(score, 100)
def create_pdf_report(self, text, sections, ats_score, match_percentage, selected_role, tech_skills, soft_skills, found_keywords):
"""Create a PDF report using ReportLab"""
buffer = io.BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Title
story.append(Paragraph("Resume Analysis Report", styles['Title']))
story.append(Spacer(1, 12))
# Date
story.append(Paragraph(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal']))
story.append(Spacer(1, 12))
# Overview section
story.append(Paragraph("Overview", styles['Heading1']))
story.append(Paragraph(f"ATS Score: {ats_score}/100", styles['Normal']))
story.append(Paragraph(f"Role Match for {selected_role}: {match_percentage:.1f}%", styles['Normal']))
story.append(Paragraph(f"Overall Score: {(ats_score + match_percentage) / 2:.1f}/100", styles['Normal']))
story.append(Spacer(1, 12))
# Skills section
story.append(Paragraph("Skills Analysis", styles['Heading1']))
if tech_skills:
story.append(Paragraph(f"Technical Skills: {', '.join(tech_skills)}", styles['Normal']))
if soft_skills:
story.append(Paragraph(f"Soft Skills: {', '.join(soft_skills)}", styles['Normal']))
if found_keywords:
story.append(Paragraph(f"Role-specific Keywords Found: {', '.join(found_keywords)}", styles['Normal']))
story.append(Spacer(1, 12))
# Recommendations
story.append(Paragraph("Recommendations", styles['Heading1']))
recommendations = []
if ats_score < 70:
recommendations.extend([
"• Add more bullet points to improve readability",
"• Include contact information (email, phone)",
"• Ensure all major sections are present"
])
if match_percentage < 60:
recommendations.append(f"• Include more {selected_role}-specific keywords")
for rec in recommendations:
story.append(Paragraph(rec, styles['Normal']))
# Build PDF
doc.build(story)
buffer.seek(0)
return buffer
def main():
st.set_page_config(
page_title="Professional Resume Analyzer",
page_icon="📄",
layout="wide",
initial_sidebar_state="expanded"
)
# Load custom CSS
load_custom_css()
# Header section
st.title("Professional Resume Analyzer")
st.markdown("**Comprehensive resume analysis with AI-powered insights and personalized recommendations**")
# Initialize analyzer
try:
analyzer = ResumeAnalyzer()
except Exception as e:
st.error(f"Error initializing analyzer: {str(e)}")
return
# Sidebar configuration
with st.sidebar:
st.header("Analysis Configuration")
job_roles = list(analyzer.job_keywords.keys())
selected_role = st.selectbox(
"Target Job Role:",
job_roles,
help="Select the job role you're targeting to get relevant keyword analysis"
)
st.divider()
st.header("Analysis Features")
st.markdown("""
**Comprehensive Analysis:**
- ATS Compatibility Score
- Skills Detection & Matching
- Section Structure Analysis
- Grammar & Language Check
- Keyword Optimization
- PDF Report Generation
**AI Assistant:**
- Personalized Resume Advice
- Quick Expert Recommendations
- Interactive Q&A
""")
# Initialize session state
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "resume_context" not in st.session_state:
st.session_state.resume_context = ""
if "analysis_done" not in st.session_state:
st.session_state.analysis_done = False
# Main content area
st.markdown('<h2 class="section-header">Upload Resume</h2>', unsafe_allow_html=True)
uploaded_file = st.file_uploader(
"Select your resume file",
type=['pdf', 'docx', 'txt'],
help="Supported formats: PDF, DOCX, TXT (Maximum size: 200MB)"
)
if uploaded_file is not None:
# Show file information
file_details = {
"Filename": uploaded_file.name,
"File size": f"{uploaded_file.size / 1024:.1f} KB",
"File type": uploaded_file.type
}
with st.expander("File Information", expanded=False):
for key, value in file_details.items():
st.write(f"**{key}:** {value}")
# Extract text based on file type
file_type = uploaded_file.type
with st.spinner("Processing your resume..."):
try:
if file_type == "application/pdf":
text = analyzer.extract_text_from_pdf(uploaded_file)
elif file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
text = analyzer.extract_text_from_docx(uploaded_file)
else: # txt
text = analyzer.extract_text_from_txt(uploaded_file)
except Exception as e:
st.error(f"Error extracting text: {str(e)}")
return
if "Error" not in text and text.strip():
st.success("Resume processed successfully!")
# Store resume context for chatbot
st.session_state.resume_context = text
try:
# Extract data for analysis
sections = analyzer.extract_sections(text)
tech_skills, soft_skills = analyzer.extract_skills(text)
found_keywords, match_percentage = analyzer.keyword_matching(text, selected_role)
ats_score = analyzer.calculate_ats_score(text, sections)
# Create navigation tabs
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
"Summary", "Skills Analysis", "Section Review",
"ATS Analysis", "Recommendations", "AI Assistant"
])
with tab1:
st.markdown('<h3 class="section-header">Resume Summary</h3>', unsafe_allow_html=True)
# Key metrics row
metric_cols = st.columns(4)
with metric_cols[0]:
display_metric_card("ATS Score", f"{ats_score}/100")
with metric_cols[1]:
display_metric_card("Role Match", f"{match_percentage:.1f}%")
with metric_cols[2]:
word_count = len(text.split())
display_metric_card("Word Count", f"{word_count}")
with metric_cols[3]:
sections_found = len([s for s in sections.values() if s])
display_metric_card("Sections", f"{sections_found}/6")
st.divider()
# Overall assessment
overall_score = (ats_score + match_percentage) / 2
if overall_score >= 80:
display_alert_box("Excellent resume! Your resume shows strong alignment with the target role and good ATS compatibility.", "success")
elif overall_score >= 60:
display_alert_box("Good foundation with room for improvement. Focus on adding more role-specific keywords and optimizing for ATS.", "warning")
else:
display_alert_box("Significant improvements needed. Consider restructuring sections, adding relevant keywords, and improving ATS compatibility.", "error")
# Quick insights
col1, col2 = st.columns(2)
with col1:
st.subheader("Strengths Identified")
strengths = []
if ats_score >= 70:
strengths.append("Good ATS compatibility")
if match_percentage >= 60:
strengths.append("Strong role alignment")
if len(tech_skills) >= 5:
strengths.append("Rich technical skills")
if len(soft_skills) >= 3:
strengths.append("Good soft skills coverage")
if strengths:
for strength in strengths:
st.write(f"✓ {strength}")
else:
st.write("Focus on the recommendations to improve your resume")
with col2:
st.subheader("Keywords Found")
if found_keywords:
# Display as tags
keyword_html = ""
for keyword in found_keywords[:10]: # Show first 10
keyword_html += f'<span class="skill-tag">{keyword}</span>'
st.markdown(keyword_html, unsafe_allow_html=True)
else:
st.write("No role-specific keywords detected")
with tab2:
st.markdown('<h3 class="section-header">Skills Analysis</h3>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.subheader("Technical Skills Detected")
if tech_skills:
# Create skill tags
tech_html = ""
for skill in tech_skills:
tech_html += f'<span class="skill-tag">{skill}</span>'
st.markdown(tech_html, unsafe_allow_html=True)
st.metric("Technical Skills Count", len(tech_skills))
else:
display_alert_box("No technical skills detected. Consider adding a dedicated skills section.", "warning")
with col2:
st.subheader("Soft Skills Detected")
if soft_skills:
# Create skill tags
soft_html = ""
for skill in soft_skills:
soft_html += f'<span class="skill-tag">{skill}</span>'
st.markdown(soft_html, unsafe_allow_html=True)
st.metric("Soft Skills Count", len(soft_skills))
else:
display_alert_box("Limited soft skills detected. Consider highlighting leadership, communication, and teamwork skills.", "info")
st.divider()
# Role-specific analysis
st.subheader(f"Analysis for {selected_role}")
progress_col, details_col = st.columns([1, 2])
with progress_col:
# Create a progress bar for match percentage
st.metric("Match Percentage", f"{match_percentage:.1f}%")
st.progress(match_percentage / 100)
with details_col:
if match_percentage >= 70:
display_alert_box("Excellent match for this role! Your skills align well with industry expectations.", "success")
elif match_percentage >= 50:
display_alert_box("Good match with opportunities for improvement. Consider adding more role-specific skills.", "warning")
else:
display_alert_box("Limited match detected. Focus on adding more relevant skills and keywords for this role.", "error")
# Missing keywords
missing_keywords = [kw for kw in analyzer.job_keywords[selected_role]
if kw not in found_keywords]
if missing_keywords:
st.subheader("Suggested Keywords to Add")
missing_html = ""
for keyword in missing_keywords[:15]: # Show top 15
missing_html += f'<span class="skill-tag" style="background-color: #fff3cd;">{keyword}</span>'
st.markdown(missing_html, unsafe_allow_html=True)
with tab3:
st.markdown('<h3 class="section-header">Section Structure Review</h3>', unsafe_allow_html=True)
# Section status overview
st.subheader("Section Completeness")
section_status = []
for section_name, section_content in sections.items():
status = "Complete" if section_content and len(section_content) > 50 else "Missing/Incomplete"
section_status.append({
"Section": section_name.title(),
"Status": status,
"Length": len(section_content) if section_content else 0
})
status_df = pd.DataFrame(section_status)
st.dataframe(status_df, use_container_width=True, hide_index=True)
st.divider()
# Detailed section content
st.subheader("Section Content")
for section_name, section_content in sections.items():
with st.expander(f"{section_name.title()} Section", expanded=False):
if section_content:
st.text_area(
f"{section_name.title()} content:",
section_content,
height=150,
disabled=True,
key=f"section_{section_name}"
)
else:
st.warning(f"No {section_name} section found or content is too brief")
with tab4:
st.markdown('<h3 class="section-header">ATS Compatibility Analysis</h3>', unsafe_allow_html=True)
# ATS score breakdown
col1, col2 = st.columns([1, 2])
with col1:
st.metric("Overall ATS Score", f"{ats_score}/100")
st.progress(ats_score / 100)
# Score interpretation
if ats_score >= 80:
st.success("Excellent ATS compatibility")
elif ats_score >= 60:
st.warning("Good ATS compatibility")
else:
st.error("Needs ATS optimization")
with col2:
st.subheader("ATS Checklist")
# Check various ATS factors
checklist_items = []
# Section check
required_sections = ['experience', 'education', 'skills']
sections_present = sum(1 for section in required_sections
if sections.get(section) and len(sections[section]) > 50)
checklist_items.append(("Essential sections present", sections_present >= 2))
# Content length check
word_count = len(text.split())
checklist_items.append(("Appropriate length (300-800 words)", 300 <= word_count <= 800))
# Contact information
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
phone_pattern = r'(\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
has_email = bool(re.search(email_pattern, text))
has_phone = bool(re.search(phone_pattern, text))
checklist_items.append(("Contact information included", has_email or has_phone))
# Bullet points
bullet_patterns = [r'•', r'◦', r'\*', r'-\s', r'→']
bullet_count = sum(len(re.findall(pattern, text)) for pattern in bullet_patterns)
checklist_items.append(("Uses bullet points", bullet_count >= 2))
# Keywords
checklist_items.append(("Contains relevant keywords", len(found_keywords) >= 3))
for item, passed in checklist_items:
status = "✓" if passed else "✗"
color = "green" if passed else "red"
st.markdown(f"<span style='color:{color}'>{status} {item}</span>", unsafe_allow_html=True)
st.divider()
# Grammar analysis
col1, col2 = st.columns(2)
with col1:
st.subheader("Language Quality Check")
grammar_issues = analyzer.grammar_check(text)
if len(grammar_issues) == 0:
display_alert_box("No grammar issues detected", "success")
else:
display_alert_box(f"{len(grammar_issues)} potential issues found", "warning")
with col2:
if grammar_issues:
st.subheader("Issues Detected")
for issue in grammar_issues[:5]: # Show first 5
st.write(f"• {issue.message}")
# ATS optimization tips
st.subheader("ATS Optimization Recommendations")
tips = [
"Use standard section headings: Experience, Education, Skills, etc.",
"Include relevant keywords naturally throughout your resume",
"Use bullet points to improve readability and scanning",
"Avoid images, graphics, tables, and complex formatting",
"Use standard fonts like Arial, Calibri, or Times New Roman",
"Save your resume as a PDF to preserve formatting",
"Include your contact information prominently at the top",
"Use consistent formatting throughout the document"
]
for i, tip in enumerate(tips, 1):
st.write(f"{i}. {tip}")
with tab5:
st.markdown('<h3 class="section-header">Personalized Recommendations</h3>', unsafe_allow_html=True)
# Generate specific recommendations
recommendations = []
# ATS-based recommendations
if ats_score < 70:
recommendations.extend([
"Improve ATS compatibility by adding more bullet points throughout your resume",
"Ensure your contact information (email and phone) is clearly visible at the top",
"Use standard section headings that ATS systems can easily recognize"
])
# Role matching recommendations
if match_percentage < 60:
recommendations.append(f"Increase your match for {selected_role} by incorporating more industry-specific keywords")
# Skills recommendations
if not tech_skills:
recommendations.append("Add a dedicated Technical Skills section to highlight your capabilities")
if not soft_skills:
recommendations.append("Incorporate more soft skills like leadership, communication, and teamwork throughout your experience descriptions")
# Section recommendations
missing_sections = [name for name, content in sections.items() if not content]
if missing_sections:
recommendations.append(f"Consider adding these missing sections: {', '.join(missing_sections)}")
if not sections.get('projects'):
recommendations.append("Add a Projects section to showcase hands-on experience and technical skills")
# Display recommendations
if recommendations:
for i, rec in enumerate(recommendations, 1):
st.write(f"**{i}.** {rec}")
else:
display_alert_box("Your resume looks great! Minor tweaks based on specific job applications can further improve your success rate.", "success")
st.divider()
# Action plan
st.subheader("Priority Action Plan")
action_items = []
if ats_score < 60:
action_items.append("**High Priority:** Improve ATS compatibility - focus on formatting and standard sections")
if match_percentage < 50:
action_items.append("**High Priority:** Add more role-specific keywords and skills")
if not tech_skills and selected_role in ["Data Scientist", "Software Engineer", "DevOps Engineer"]:
action_items.append("**Medium Priority:** Add comprehensive technical skills section")
if len([s for s in sections.values() if s]) < 4:
action_items.append("**Medium Priority:** Ensure all essential sections are complete and substantial")
action_items.append("**Ongoing:** Customize your resume for each job application by matching keywords")
for action in action_items:
st.markdown(action)
st.divider()
# PDF report generation
st.subheader("Download Detailed Report")
col1, col2 = st.columns([2, 1])
with col1:
st.write("Generate a comprehensive PDF report with all analysis results, recommendations, and action items.")
with col2:
if st.button("Generate PDF Report", type="primary", use_container_width=True):
try:
with st.spinner("Generating report..."):
pdf_buffer = analyzer.create_pdf_report(
text, sections, ats_score, match_percentage,
selected_role, tech_skills, soft_skills, found_keywords
)
st.download_button(
label="Download Report",
data=pdf_buffer.getvalue(),
file_name=f"resume_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
mime="application/pdf",
use_container_width=True
)
except Exception as e:
st.error(f"Error generating PDF: {str(e)}")
with tab6:
# AI Chat Interface
create_improved_chat_interface(st.session_state.get('resume_context', ''))
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
st.error("Please check your resume format and try again.")
else:
st.error("Could not extract text from the uploaded file. Please check the file format and try again.")
else:
# Instructions and information when no file is uploaded
st.markdown('<h3 class="section-header">Getting Started</h3>', unsafe_allow_html=True)
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("How It Works")
st.markdown("""
**1. Upload Your Resume**
Upload your resume in PDF, DOCX, or TXT format using the file uploader above.
**2. Select Target Role**
Choose your target job role from the sidebar to get relevant keyword analysis.
**3. Get Comprehensive Analysis**
Review detailed analysis across multiple categories including ATS compatibility, skills matching, and section structure.
**4. Get AI-Powered Recommendations**
Use the AI assistant for personalized advice and answers to your specific questions.
**5. Download Report**
Generate and download a comprehensive PDF report with all findings and recommendations.
""")
with col2:
st.subheader("Analysis Features")
features = [
"ATS Compatibility Scoring",
"Skills Detection & Matching",
"Keyword Optimization",
"Section Structure Analysis",
"Grammar & Language Check",
"Role-Specific Recommendations",
"AI-Powered Chat Assistant",
"Downloadable PDF Reports"
]
for feature in features:
st.write(f"✓ {feature}")
# Sample analysis preview
with st.expander("Preview: What You'll Get", expanded=False):
st.subheader("Sample Analysis Output")
sample_cols = st.columns(3)
with sample_cols[0]:
display_metric_card("ATS Score", "85/100")
with sample_cols[1]:
display_metric_card("Role Match", "72%")
with sample_cols[2]:
display_metric_card("Overall", "A-")
st.markdown("""
**You'll receive detailed analysis including:**
- Comprehensive scoring and metrics
- Section-by-section breakdown
- Specific improvement recommendations
- Missing keywords identification
- ATS optimization checklist
- AI-powered personalized advice
""")
if __name__ == "__main__":
main()