File size: 7,382 Bytes
3387453
5189c42
 
 
 
 
 
 
 
 
 
 
 
 
3bafd3b
 
5189c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bafd3b
5189c42
 
 
 
 
 
 
 
 
 
 
 
44234c3
1b6beae
44234c3
 
 
 
 
 
 
5189c42
 
44234c3
5189c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import os
OR_API_KEY = os.getenv("OR_API_KEY")
# HELICON_API_KEY = os.getenv("HELICON_API_KEY")
# SUPABASE_USER = os.environ['SUPABASE_USER']
# SUPABASE_PASSWORD = os.environ['SUPABASE_PASSWORD']

import fitz  # PyMuPDF for PDFs
import docx  # python-docx for Word documents
import requests
from bs4 import BeautifulSoup
import json
import re
import sys
from pydantic import HttpUrl
import json
from openai import OpenAI

SysPromptOpt = """
**You are a professional resume optimization expert. You have been optimizing resumes for over 20 years, helping thousands of job seekers secure their dream jobs across various industries. Your expertise lies in aligning resumes perfectly with job descriptions to highlight relevant skills, experience, and accomplishments.**

**Objective:**
Optimize the user's resume by tailoring it to a specific job description. Ensure that the final resume showcases the most relevant skills, experience, and achievements in a way that aligns perfectly with the requirements and preferences outlined in the job description. The goal is to significantly increase the user's chances of landing an interview for this position.

**Steps:**

1. **Analyze the Job Description:**
   - Carefully read the provided job description.
   - Identify and list the key skills, qualifications, and experiences the employer is seeking.
   - Highlight any specific keywords, phrases, or technical skills that are emphasized.

2. **Review the User's Resume:**
   - Examine the user's current resume thoroughly.
   - Identify and list the skills, experiences, and accomplishments that are most relevant to the job description.
   - Note any gaps or areas that could be better aligned with the job description.

3. **Optimize the Resume:**
   - Rewrite sections of the resume to better match the job description, incorporating relevant keywords and phrases.
   - Emphasize the user’s most pertinent skills and experiences in a way that demonstrates their suitability for the role.
   - Ensure the resume is formatted professionally, with clear and concise language, and free of any errors.

4. **Finalize and Review:**
   - Review the optimized resume for coherence and alignment with the job description.
   - Make any necessary adjustments to improve clarity and impact.
   - Ensure the final resume is compelling and effectively tailored to the job description.

ONLY OUTPUT THE FOLLOWING IN THE FOLLOWING FORMAT:
<optimized_resume>.....</optimized_resume>
<changes_made>......</changes_made>             
"""


or_client = OpenAI(api_key=OR_API_KEY, base_url = "https://openrouter.ai/api/v1")

def together_response(messages,model="openai/gpt-4o-mini",SysPrompt=SysPromptOpt):
    response = or_client.chat.completions.create(
            model=model,
            messages=messages,
            max_tokens=4096,
        )
        
    response_message = response.choices[0].message.content

    return response_message

import tiktoken # Used to limit tokens
encoding = tiktoken.encoding_for_model("gpt-4o") 

def limit_tokens(input_string, token_limit=7500):
    """
    Limit tokens sent to the model
    """
    return encoding.decode(encoding.encode(input_string)[:token_limit])

# Function to optimize the resume using OpenAI
def optimize_resume_api(resume, job_desc):
    prompt = f"Optimize the following Resume:\n ## RESUME:{limit_tokens(resume, token_limit=4000)}\n\n for the:## JOB DESCRIPTION:{limit_tokens(job_desc,token_limit=4000)}\n\n"
    messages = [{"role": "assistant", "content": SysPromptOpt},
                {"role": "user", "content": prompt}]
    response = together_response(messages, model = "openai/gpt-4o-mini")
    return response

# Function to extract text from a Word document
def extract_text_from_word(docx_file):
    doc = docx.Document(docx_file)
    return "\n".join([para.text for para in doc.paragraphs])

# Function to extract text from a PDF file
def extract_text_from_pdf(pdf_file):
    doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
    text = ""
    for page in doc:
        text += page.get_text()
    return text

# Function to read text from a plain text file
def read_text_file(text_file):
    return text_file.read().decode("utf-8")

# Function to scrape a website and extract content
def scrape_website(url):
    response = requests.post(
        'https://pvanand-web-scraping.hf.space/scrape',
        headers={
            'accept': 'application/json',
            'Content-Type': 'application/json'
        },
        json={'url': url}
    )
    return response.json()

# Function to extract main content from HTML
def extract_main_content(html):
    if html:
        soup = BeautifulSoup(html, 'lxml')
        plain_text = soup.get_text(separator=" ", strip=True)
        return clean_paragraph(plain_text)
    return ""

# Function to extract JSON from script tags in HTML
def extract_json_from_script(html):
    if html:
        soup = BeautifulSoup(html, 'lxml')
        script_tags = soup.find_all('script')
        
        json_objects = []
        
        for tag in script_tags:
            if tag.string and '{' in tag.string and '}' in tag.string:
                script_content = tag.string.strip()
                
                json_like_content = re.search(r'\{.*\}', script_content, re.DOTALL)
                if json_like_content:
                    json_text = json_like_content.group(0)
                    try:
                        data = json.loads(json_text)
                        json_objects.append(data)
                    except json.JSONDecodeError:
                        continue  # Skip this script if JSON parsing fails

        if json_objects:
            return json.dumps(json_objects, indent=4)  # Pretty-print the JSON data
        
        return "No suitable JSON script tag found."
    return "No HTML content."

# Function to fetch and parse job description from a link
def fetch_job_description(link: HttpUrl):
    # Convert the Url object to a string
    link_str = str(link)
    response = scrape_website(link_str)["content"]
    job_desc = extract_main_content(response)
    if len(job_desc) < 100:
        job_desc = extract_main_content(extract_json_from_script(response))
    return job_desc

# Function to read file content based on file type
def read_file(file):
    if not file or not file.filename:
        raise ValueError("No file uploaded or filename is empty")
    
    if file.filename.endswith(".pdf"):
        return extract_text_from_pdf(file.file)
    elif file.filename.endswith(".docx"):
        return extract_text_from_word(file.file)
    elif file.filename.endswith(".txt"):
        return read_text_file(file.file)
    else:
        raise ValueError(f"Unsupported file type: {file.filename}")
    
def clean_paragraph(paragraph, n=4):
    """
    Clean a paragraph of text by removing words that occur more than n times.
    """
    # Split the paragraph into words
    words = re.findall(r'\b\w+\b', paragraph)

    # Create a dictionary to count the occurrences of each word
    word_count = {}
    for word in words:
        word_count[word] = word_count.get(word, 0) + 1

    # Filter out words that occur more than n times
    cleaned_words = [word for word in words if word_count[word] <= n]

    # Join the cleaned words back into a paragraph
    cleaned_paragraph = ' '.join(cleaned_words)

    return cleaned_paragraph