{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#!pip install langchain openai python-docx beautifulsoup4 requests gradio langchain-community tiktoken fake-useragent langchain_openai pypdf" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "import os\n", "import requests\n", "\n", "#Ensure you already set up openai_api_key as an environment parameter before use the model\n", "openai_api_key = os.getenv(\"openai_api_key\")\n", "#os.environ[\"openai_api_key\"] = openai_api_key\n", "#os.environ[\"OPENAI_MODEL_NAME\"]=\"gpt-4o\"\n", "# Check if the API key was retrieved successfully\n", "\n", "if openai_api_key is None:\n", " raise ValueError(\"OpenAI API key not found in environment variables.\")" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "#from langchain.chat_models import ChatOpenAI\n", "#from langchain_community.chat_models import ChatOpenAI\n", "from langchain_openai import ChatOpenAI\n", "from langchain.prompts import ChatPromptTemplate\n", "from langchain.chains import LLMChain\n", "from langchain.chains import SequentialChain\n", "#from langchain.document_loaders import PyPDFLoader\n", "from langchain_community.document_loaders import PyPDFLoader\n", "import docx\n", "from bs4 import BeautifulSoup\n", "import logging\n", "\n", "import tiktoken\n", "from openai import OpenAIError # Make sure you handle exceptions from OpenAI\n", "import openai\n", "from fake_useragent import UserAgent\n", "import random\n", "import time" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "llm_model = \"gpt-4o\"\n", "llm = ChatOpenAI(temperature=0.0, model=llm_model, openai_api_key=openai_api_key)\n", "\n", "# Token counting function with a check for non-string inputs\n", "def count_tokens(text, model=llm_model):\n", " if not isinstance(text, str):\n", " return 0 # Return 0 tokens for non-string inputs\n", " encoding = tiktoken.encoding_for_model(model)\n", " return len(encoding.encode(text))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "#Define prompt template\n", "prompt_job_description = ChatPromptTemplate.from_template(\n", " \"Your role is a tech job researcher. Your goal is to make sure to do amazing analysis on \"\n", " \"{job_description} to help job applicants.\"\n", " \"As a Job Researcher, your prowess in \"\n", " \"navigating and extracting critical \"\n", " \"information from job postings is unmatched.\"\n", " \"Your skills help pinpoint the necessary \"\n", " \"qualifications and skills sought \"\n", " \"by employers, forming the foundation for \"\n", " \"effective application tailoring.\"\n", ")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "prompt_profiler = ChatPromptTemplate.from_template(\n", " \"Your role is a Personal Profiler for Job Candidate. Your goal is to do incredible research on job candidates\"\n", " \"to help them stand out in the job market\"\n", " \"Equipped with analytical prowess, you dissect \"\n", " \"and synthesize information \"\n", " \"from diverse sources to craft comprehensive \"\n", " \"personal and professional profiles, laying the \"\n", " \"groundwork for personalized cover letter enhancements. \"\n", " \"The sources of the information you are gonna use \" \n", " \"are candidate's resume and Linkedin profile. \\n\\n\"\n", " \"Resume: {resume} \"\n", " \"Linkedin profile: {linkedin} \"\n", " \"If Linkedin is missing, use ONLY resume to craft the profile. \"\n", ")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "prompt_cover_letter_composer = ChatPromptTemplate.from_template(\n", " \"Your role is a Cover Letter Writer for Job Candidates. \"\n", " \"Your goal is to compose a cover letter that is factually correct for the job application. \"\n", " \"With a strategic mind and an eye for detail, you \"\n", " \"excel at composing cover letters for applicants to tech companies. \"\n", " \"You understand what is important to recruiters \"\n", " \"in the tech space. \"\n", " \"You know how to highlight relevant skills and experiences, ensuring they \"\n", " \"resonate perfectly with the job's requirements. \"\n", " \"You are gonna use candidate's Personal Profile and the Job Description to craft an exceptional cover letter by using the Cover Letter Template provided below. \\n\\n\"\n", " \"Personal Profile: {personal_profile} \\n \"\n", " \"Job Description: {job_summary} \\n \"\n", " \"Cover Letter Template: {cover_letter_format} \\n \"\n", " \"If Linkedin is missing, use ONLY resume to craft the profile. If Cover Letter Template is missing, you decide an appropriate format to use. \"\n", ")" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "prompt_proof_reader = ChatPromptTemplate.from_template(\n", " \"Your role is to proofread cover letters. \"\n", " \"Your goal is to ensure there are no grammatical errors \"\n", " \"and that the meaning of the cover letter is concise. \"\n", " \"With an eye for detail, you are the final gatekeeper \" \n", " \"to ensure a high-quality cover letter is generated for job applications. \"\n", " \"You will use the Cover Letter Draft from previous work to complete your work. \"\n", " \"You will also ensure that the final cover letter follows the Cover Letter Template as closely as possibl. \\n\\n\"\n", " \"Cover Letter Draft: {cover_letter_draft} \\n \"\n", " \"Cover Letter Template: {cover_letter_format} \"\n", " \"If Cover Letter Template is missing, you decide an appropriate format to use. \"\n", ")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "#Define individual chain and chain of thoughts\n", "chain_one = LLMChain(llm=llm, prompt=prompt_job_description, output_key=\"job_summary\")\n", "chain_two = LLMChain(llm=llm, prompt=prompt_profiler, output_key=\"personal_profile\")\n", "chain_three = LLMChain(llm=llm, prompt=prompt_cover_letter_composer, output_key=\"cover_letter_draft\")\n", "chain_four = LLMChain(llm=llm, prompt= prompt_proof_reader, output_key=\"cover_letter_final\")\n", "#result = chain.run(input)\n", "sequential_chain = SequentialChain(\n", " chains=[chain_one, chain_two, chain_three, chain_four],\n", " input_variables=[\"resume\", \"linkedin\", \"job_description\", \"cover_letter_format\"],\n", " output_variables=[\"job_summary\", \"personal_profile\", \"cover_letter_draft\", \"cover_letter_final\"],\n", " verbose=True\n", ")" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "# Function to extract text from PDF\n", "def extract_text_from_pdf(file):\n", " try:\n", " # Assuming 'file' is a file-like object\n", " file_path = file.name\n", " loader = PyPDFLoader(file_path)\n", " text = loader.load()\n", " return text\n", " except Exception as e:\n", " logging.error(\"Error extracting text from PDF\", exc_info=True)\n", " return str(e)\n", "\n", "# Function to extract text from DOCX\n", "def extract_text_from_docx(file):\n", " doc = docx.Document(file)\n", " text = \"\"\n", " for paragraph in doc.paragraphs:\n", " text += paragraph.text + \"\\n\"\n", " return text\n", "\n", "# Rate limiter to slow down requests\n", "def rate_limiter(min_wait=2, max_wait=5):\n", " delay = random.uniform(min_wait, max_wait) # Random delay between requests\n", " time.sleep(delay)\n", " print(f\"Rate limiter: Delaying for {delay:.2f} seconds.\")\n", "\n", "# Function to fetch job description from URL\n", "def fetch_job_description(url):\n", " try:\n", " response = requests.get(url)\n", " response.raise_for_status()\n", " soup = BeautifulSoup(response.content, 'html.parser')\n", " job_description = soup.get_text(strip=True)\n", " # Check if the fetched content is too short to be meaningful\n", " if len(job_description) < 100:\n", " raise ValueError(\"Fetched job description content is too short.\")\n", " return job_description\n", " except (requests.exceptions.RequestException, ValueError) as e:\n", " print(f\"Error fetching job description: {e}\")\n", " return None\n", "\n", "# Function to fetch LinkedIn profile from URL\n", "def fetch_linkedin_profile(url):\n", " ua = UserAgent() # Create a UserAgent object\n", " headers = {\n", " 'User-Agent': ua.random # Randomly select a User-Agent for each request\n", " }\n", " try:\n", " # Apply rate limiter before making the request\n", " rate_limiter() # Add a delay before each request\n", " \n", " response = requests.get(url, headers=headers)\n", " response.raise_for_status() # Will raise an HTTPError for bad responses\n", " soup = BeautifulSoup(response.content, 'html.parser')\n", " \n", " # Extract LinkedIn profile text - adjust based on the structure of the LinkedIn profile page\n", " linkedin_profile = soup.get_text()\n", " return linkedin_profile\n", " except requests.exceptions.RequestException as e:\n", " print(f\"Error fetching LinkedIn profile: {e}\")\n", " return None" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "def cover_letter_gen(resume_file, linkedin_url, job_description_url, manual_job_description, cover_letter_file):\n", " # Extract text from the uploaded resume PDF\n", " resume_content = extract_text_from_pdf(resume_file)\n", "\n", " # Fetch job description from URL\n", " job_description = fetch_job_description(job_description_url)\n", " if not job_description: # Check if job description is empty or too short\n", " job_description = manual_job_description.strip()\n", " if not job_description:\n", " return None, \"Error: Job description could not be fetched and manual input is empty. Please provide a valid job description.\", \"\", \"\"\n", " \n", " # Fetch LinkedIn profile from URL\n", " linkedin_profile = fetch_linkedin_profile(linkedin_url)\n", " if linkedin_profile is None or not linkedin_profile.strip():\n", " linkedin_profile = \"LinkedIn profile could not be fetched.\"\n", " message = \"Warning: LinkedIn profile could not be fetched. Continuing without LinkedIn profile data.\"\n", " else:\n", " message = \"LinkedIn profile fetched successfully.\"\n", " \n", " \n", " # Check if cover letter file is provided\n", " if cover_letter_file is not None:\n", " # Determine the file type and extract text accordingly\n", " cover_letter_format = \"\"\n", " cover_letter_file_path = cover_letter_file.name\n", " if cover_letter_file_path.endswith(\".pdf\"):\n", " cover_letter_format = extract_text_from_pdf(cover_letter_file_path)\n", " elif cover_letter_file_path.endswith(\".docx\"):\n", " cover_letter_format = extract_text_from_docx(cover_letter_file)\n", " else:\n", " return None, \"Error: Unsupported file format for cover letter. Please upload a .pdf or .docx file.\"\n", " else:\n", " cover_letter_format = \"\"\n", " \n", " \n", " inputs = {\n", " \"resume\": resume_content,\n", " \"linkedin\": linkedin_profile,\n", " \"job_description\": job_description,\n", " \"cover_letter_format\": cover_letter_format\n", " }\n", " \n", " # Calculate input tokens\n", " resume_tokens = count_tokens(resume_content)\n", " linkedin_tokens = count_tokens(linkedin_profile)\n", " job_description_tokens = count_tokens(job_description)\n", " cover_letter_format_tokens = count_tokens(cover_letter_format)\n", " input_tokens = resume_tokens + linkedin_tokens + job_description_tokens + cover_letter_format_tokens\n", "\n", " # Run the sequential chain\n", " try:\n", " outputs = sequential_chain(inputs)\n", " cover_letter_final = outputs[\"cover_letter_final\"]\n", " output_tokens = count_tokens(cover_letter_final)\n", " except Exception as e:\n", " return None, f\"Error during processing: {e}\"\n", " \n", " # Total tokens\n", " total_tokens = input_tokens + output_tokens\n", "\n", "\n", " # Return the outputs: cover letter final, message, and LinkedIn profile content\n", " return cover_letter_final, message, input_tokens, output_tokens, total_tokens" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Use Gradio to generate web UI\n", "import gradio as gr\n", "\n", "gr.close_all()\n", "demo = gr.Interface(fn=cover_letter_gen, \n", " inputs=[gr.File(label=\"Upload Resume (PDF) (Required)\"),\n", " gr.Textbox(lines=1, placeholder=\"Enter LinkedIn profile URL (Optional)\", label=\"LinkedIn Profile URL\"),\n", " gr.Textbox(lines=1, placeholder=\"Enter job description URL (Required)\", label=\"Job Description URL\"),\n", " gr.Textbox(lines=5, placeholder=\"Enter job description manually (if URL fetch fails)\", label=\"Manual Job Description\"),\n", " gr.File(label=\"Upload Cover Letter Format (PDF or DOCX) (Optional)\")\n", " ],\n", " outputs=[gr.Textbox(label=\"Cover Letter Final\"),\n", " gr.Textbox(label=\"Message\"),\n", " gr.Textbox(label=\"Input Tokens\"),\n", " gr.Textbox(label=\"Output Tokens\"),\n", " gr.Textbox(label=\"Total Tokens\")\n", " ],\n", " title=\"Cover Letter Generator\",\n", " description=\"Upload your resume, Linkedin profile, and job description URL to generate your customized cover letter\"\n", " )\n", "#demo.launch(share=True)\n", "demo.launch()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 }