OptiHire / app.py
AdithyaSNair's picture
Update app.py
3019fd8 verified
raw
history blame
7.58 kB
import streamlit as st
from streamlit_option_menu import option_menu
from langchain_groq import ChatGroq
from langchain_core.prompts import PromptTemplate
import fitz
import requests
from bs4 import BeautifulSoup
import uuid
llm = ChatGroq(
temperature=0,
groq_api_key='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', # Replace with your Groq API key
model_name="llama-3.1-70b-versatile"
)
def extract_text_from_pdf(pdf_file):
text = ""
try:
with fitz.open(stream=pdf_file.read(), filetype="pdf") as doc:
for page in doc:
text += page.get_text()
return text
except Exception as e:
st.error(f"Error extracting text from resume: {e}")
return ""
def extract_job_description(job_link):
try:
response = requests.get(job_link)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# You might need to adjust the selectors based on the website's structure
job_description = soup.get_text(separator='\n')
return job_description.strip()
except Exception as e:
st.error(f"Error fetching job description: {e}")
return ""
def extract_requirements(job_description):
prompt_text = f"""
The following is a job description:
{job_description}
Extract the list of job requirements, qualifications, and skills from the job description. Provide them as a numbered list.
Requirements:
"""
prompt = PromptTemplate.from_template(prompt_text)
chain = prompt | llm
response = chain.invoke({})
requirements = response.content.strip()
return requirements
def generate_email(job_description, requirements, resume_text):
prompt_text = f"""
Given the following job description:
{job_description}
And the following extracted requirements:
{requirements}
And the following resume text:
{resume_text}
Write a cold email as Adithya S Nair, a recent graduate in Computer Science with a focus on Artificial Intelligence and Machine Learning.
Highlight your relevant skills and experiences from the resume, emphasizing how you, as a fresher, can bring value to the client’s company.
Mention key projects, internships, and any leadership experiences that align with the job description and requirements.
Ensure the email is concise and professional.
Email:
"""
prompt = PromptTemplate.from_template(prompt_text)
chain = prompt | llm
response = chain.invoke({})
email_text = response.content.strip()
return email_text
# -------------------------------
# Page Functions
# -------------------------------
def email_generator_page():
st.header("Automated Email Generator")
st.write("""
This application generates a personalized email based on a job posting and your resume.
""")
# Input fields
job_link = st.text_input("Enter the job link:")
uploaded_file = st.file_uploader("Upload your resume (PDF format):", type="pdf")
if st.button("Generate Email"):
if not job_link:
st.error("Please enter a job link.")
return
if not uploaded_file:
st.error("Please upload your resume.")
return
with st.spinner("Processing..."):
# Extract job description
job_description = extract_job_description(job_link)
if not job_description:
st.error("Failed to extract job description.")
return
# Extract requirements
requirements = extract_requirements(job_description)
if not requirements:
st.error("Failed to extract requirements.")
return
# Extract resume text
resume_text = extract_text_from_pdf(uploaded_file)
if not resume_text:
st.error("Failed to extract text from resume.")
return
# Generate email
email_text = generate_email(job_description, requirements, resume_text)
if email_text:
st.subheader("Generated Email:")
st.write(email_text)
else:
st.error("Failed to generate email.")
def resume_analysis_page():
st.header("Resume Analysis and Optimization")
uploaded_file = st.file_uploader("Upload your resume (PDF format):", type="pdf")
if uploaded_file:
resume_text = extract_text_from_pdf(uploaded_file)
if resume_text:
st.success("Resume uploaded successfully!")
# Perform analysis
st.subheader("Extracted Information")
# Example: Extracted skills
skills = extract_skills(resume_text)
st.write("**Skills:**", ', '.join(skills))
# Provide optimization suggestions
st.subheader("Optimization Suggestions")
st.write("- **Keyword Optimization:** Consider adding more industry-specific keywords relevant to your desired roles.")
st.write("- **Formatting:** Ensure consistent formatting for headings and bullet points to enhance readability.")
st.write("- **Experience Details:** Provide specific achievements and quantify your accomplishments where possible.")
else:
st.error("Failed to extract text from resume.")
def job_recommendations_page():
st.header("Job Recommendations")
uploaded_file = st.file_uploader("Upload your resume (PDF format):", type="pdf")
if uploaded_file:
resume_text = extract_text_from_pdf(uploaded_file)
if resume_text:
st.success("Resume uploaded successfully!")
# Fetch job recommendations
st.subheader("Recommended Jobs")
jobs = get_job_recommendations(resume_text)
for job in jobs:
st.write(f"**{job['title']}** at {job['company']}")
st.markdown(f"[Apply Here]({job['link']})")
else:
st.error("Failed to extract text from resume.")
# Placeholder for job recommendations - Replace with actual implementation
def get_job_recommendations(resume_text):
# Implement job fetching logic, possibly integrating with job APIs
# This is a placeholder example
return [
{"title": "Data Scientist", "company": "TechCorp", "link": "https://example.com/job1"},
{"title": "Machine Learning Engineer", "company": "InnovateX", "link": "https://example.com/job2"},
]
def extract_skills(text):
# Implement advanced skill extraction logic
# For demonstration, using a predefined skill list
skills_list = ["Python", "Machine Learning", "Data Analysis", "SQL", "Communication", "Leadership"]
extracted_skills = [skill for skill in skills_list if skill.lower() in text.lower()]
return extracted_skills
# -------------------------------
# Main App with Sidebar Navigation
# -------------------------------
def main():
st.set_page_config(page_title="Job Application Assistant", layout="wide")
with st.sidebar:
selected = option_menu(
"Main Menu",
["Email Generator", "Resume Analysis", "Job Recommendations"],
icons=["envelope", "file-person", "briefcase"],
menu_icon="cast",
default_index=0,
)
if selected == "Email Generator":
email_generator_page()
elif selected == "Resume Analysis":
resume_analysis_page()
elif selected == "Job Recommendations":
job_recommendations_page()
if __name__ == "__main__":
main()