Spaces:
Runtime error
Runtime error
File size: 10,020 Bytes
c1ae082 5e45ce5 2a4f6b6 c1ae082 2a4f6b6 91ec250 2a4f6b6 3165716 c1ae082 5e45ce5 a6a290e 91ec250 2a4f6b6 91ec250 c693b05 c1ae082 c693b05 c1ae082 c693b05 c1ae082 c693b05 c1ae082 c693b05 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c1ae082 09b79a1 c693b05 c1ae082 c693b05 c1ae082 c693b05 09b79a1 c1ae082 | 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | import io
import os
from json import JSONDecodeError
from typing import Union
import PyPDF2
from dotenv import load_dotenv
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain_community.callbacks import get_openai_callback
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
from langchain_openai import ChatOpenAI
from langchain_community.llms import HuggingFaceEndpoint
from langchain_core.messages import BaseMessage
from pydantic import ValidationError
from resume_template import Resume
load_dotenv()
def pdf_to_string(file:Union[io.BytesIO, str, bytes]):
"""
Convert a PDF file to a string.
Parameters:
file: A file-like object representing the PDF file (io.BytesIO, or file Path, or bytes)
Returns:
str: The extracted text from the PDF.
"""
f = io.BytesIO(file) if isinstance(file, bytes) else file
pdf_reader = PyPDF2.PdfReader(f)
num_pages = len(pdf_reader.pages)
text = ''
for i in range(num_pages):
page = pdf_reader.pages[i]
text += page.extract_text()
if isinstance(f, io.BytesIO):
f.close()
return text
class ResumeParser:
list_llm = [
"mistralai/mistral-7b-instruct-v0.2",
"mistralai/Mixtral-8x7B-Instruct-v0.1",
"microsoft/phi-2",
"google/gemma-7b-it",
"HuggingFaceH4/zephyr-7b-beta",
"HuggingFaceH4/zephyr-7b-gemma-v0.1",
]
def __init__(self, use_openai=False, openai_key=""):
self.use_openai = use_openai
self.openai_key = ""
self.model = None
self.hf_model_name = self.list_llm[0]
self.openai_model_name = "gpt-3.5-turbo" #"gpt-4-1106-preview"
self.set_key(openai_key)
self.set_model()
def set_key(self, openai_key=""):
self.openai_key = openai_key
if len(self.openai_key) == 0 and "OPENAI_API_KEY" in os.environ:
self.openai_key = os.environ["OPENAI_API_KEY"]
def set_model(self, hf_model_name=""):
if self.use_openai:
print(f"using OpenAI Model {self.openai_model_name}")
self.model = ChatOpenAI(temperature=0, model=self.openai_model_name, max_tokens=2500, openai_api_key=self.openai_key)
else:
if hf_model_name != "" and hf_model_name in self.list_llm:
self.hf_model_name = hf_model_name
print(f"using HF Model {self.hf_model_name}")
self.model = HuggingFaceEndpoint(repo_id=self.hf_model_name, temperature=0.001, max_new_tokens=4000)
#self.model = HuggingFacePipeline.from_model_id(model_id=self.hf_model_name, task="text-generation",
# device=0,
# pipeline_kwargs={"max_new_tokens": 4000},
# model_kwargs={"temperature": 0.001, "max_length": 8000})
def extract_resume_fields(self, full_text):
"""
Analyze a resume text and extract structured information using a specified language model.
Parameters:
full_text (str): The text content of the resume.
model (str): The language model object to use for processing the text.
Returns:
dict: A dictionary containing structured information extracted from the resume.
"""
# The Resume object is imported from the local resume_template file
with open("prompts/resume_extraction.prompt", "r") as f:
template = f.read()
with open("prompts/json.schema", "r") as f:
json_schema = f.read()
parser = PydanticOutputParser(pydantic_object=Resume)
prompt_template = PromptTemplate(
template=template,
input_variables=["resume"],
partial_variables={"json_schema": json_schema},
)
# Invoke the language model and process the resume
formatted_input = prompt_template.format_prompt(resume=full_text)
llm = self.model
# print("llm", llm)
with get_openai_callback() as cb:
output = llm.invoke(formatted_input.to_string())
print(cb)
#print(output) # Print the output object for debugging
if isinstance(output, BaseMessage):
output = output.content
try:
parsed_output = parser.parse(output)
#json_output = parsed_output.json()
#print(json_output)
return parsed_output
except ValidationError as e:
print(f"Validation error: {e}")
#print(output)
return output
except JSONDecodeError as e:
print(f"JSONDecodeError error: {e}")
#print(output)
return output
except Exception as e:
print(f"Exception: {e}")
#print(output)
return output
def match_resume_with_job_description(self, resume_txt, job_description):
with open("prompts/job_description_matching.prompt", "r") as f:
template = f.read()
prompt_template = PromptTemplate(
template=template,
input_variables=["resume", "job_description"],
)
# Invoke the language model and process the resume
formatted_input = prompt_template.format_prompt(resume=resume_txt, job_description=job_description)
llm = self.model
# print("llm", llm)
with get_openai_callback() as cb:
output = llm.invoke(formatted_input.to_string())
print(cb)
# print(output) # Print the output object for debugging
if isinstance(output, BaseMessage):
output = output.content
return output
class StructuredResumeParser:
list_llm = [
"mistralai/Mixtral-8x7B-Instruct-v0.1",
"mistralai/mistral-7b-instruct-v0.2",
"microsoft/phi-2",
"google/gemma-7b-it",
"HuggingFaceH4/zephyr-7b-beta",
"HuggingFaceH4/zephyr-7b-gemma-v0.1",
]
def __init__(self, use_openai=False, openai_key=""):
self.use_openai = use_openai
self.openai_key = ""
self.model = None
self.hf_model_name = self.list_llm[0]
self.openai_model_name = "gpt-3.5-turbo" #"gpt-4-1106-preview"
self.set_key(openai_key)
self.set_model()
def set_key(self, openai_key=""):
self.openai_key = openai_key
if len(self.openai_key) == 0 and "OPENAI_API_KEY" in os.environ:
self.openai_key = os.environ["OPENAI_API_KEY"]
def set_model(self, hf_model_name=""):
if self.use_openai:
print(f"using OpenAI Model {self.openai_model_name}")
self.model = ChatOpenAI(temperature=0, model=self.openai_model_name, max_tokens=2500, openai_api_key=self.openai_key)
else:
if hf_model_name != "" and hf_model_name in self.list_llm:
self.hf_model_name = hf_model_name
print(f"using Together Model {self.hf_model_name}")
self.model = ChatOpenAI(
base_url="https://api.together.xyz/v1",
api_key=os.environ["TOGETHER_API_KEY"],
model=self.hf_model_name,
)
def extract_resume_fields(self, full_text):
"""
Analyze a resume text and extract structured information using a specified language model.
Parameters:
full_text (str): The text content of the resume.
model (str): The language model object to use for processing the text.
Returns:
dict: A dictionary containing structured information extracted from the resume.
"""
# The Resume object is imported from the local resume_template file
with open("prompts/resume_extraction_structured.prompt", "r") as f:
template = f.read()
prompt_template = PromptTemplate(
template=template,
input_variables=["resume"]
)
# Invoke the language model and process the resume
formatted_input = prompt_template.format_prompt(resume=full_text)
llm = self.model.with_structured_output(Resume)
with get_openai_callback() as cb:
output = llm.invoke(formatted_input.to_string())
print(cb)
return output
def match_resume_with_job_description(self, resume_txt, job_description):
with open("prompts/job_description_matching.prompt", "r") as f:
template = f.read()
prompt_template = PromptTemplate(
template=template,
input_variables=["resume", "job_description"],
)
# Invoke the language model and process the resume
formatted_input = prompt_template.format_prompt(resume=resume_txt, job_description=job_description)
llm = self.model
# print("llm", llm)
with get_openai_callback() as cb:
output = llm.invoke(formatted_input.to_string())
print(cb)
# print(output) # Print the output object for debugging
if isinstance(output, BaseMessage):
output = output.content
return output
if __name__ == "__main__":
resume_file = "samples/0.pdf"
text = pdf_to_string(resume_file)
p = StructuredResumeParser(use_openai=False)
resume_data = p.extract_resume_fields(text)
'''
model = ChatOpenAI(
base_url="https://api.together.xyz/v1",
api_key=os.environ["TOGETHER_API_KEY"],
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
)
model_with_structure = model.with_structured_output(Resume)
with open("prompts/resume_extraction_structured.prompt", "r") as f:
template = f.read()
prompt_template = PromptTemplate(
template=template,
input_variables=["resume"]
)
formatted_input = prompt_template.format_prompt(resume=text)
with get_openai_callback() as cb:
resume_data = model_with_structure.invoke(formatted_input.to_string())
print(cb)
'''
print(resume_data)
|