Spaces:
Running
Running
Added character to the write up and moved functions to the helpers file.
Browse filesFiles changed (3)
- app.py+22-97
- llamallms.pngAdded
- resume_helpers.pyAdded+131
19 unmodified lines2021222324253 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913015 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716819 unmodified linesimport timeimport os# Set the LANGCHAIN_TRACING_V2 environment variable to 'true'os.environ['LANGCHAIN_TRACING_V2'] = 'true'3 unmodified linesload_dotenv()def pdf_to_string(file):"""Convert a PDF file to a string.Parameters:file (io.BytesIO): A file-like object representing the PDF file.Returns:str: The extracted text from the PDF."""pdf_reader = PyPDF2.PdfReader(file)num_pages = len(pdf_reader.pages)text = ''for i in range(num_pages):page = pdf_reader.pages[i]text += page.extract_text()file.close()return textclass CustomOutputParserException(Exception):passdef extract_resume_fields(full_text, model):"""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 filewith open("prompts/resume_extraction.prompt", "r") as f:template = f.read()parser = PydanticOutputParser(pydantic_object=Resume)prompt_template = PromptTemplate(template=template,input_variables=["resume"],partial_variables={"response_template": parser.get_format_instructions()},)llm = llm_dict.get(model, ChatOpenAI(temperature=0, model=model))chain = prompt_template | llm | parsermax_attempts = 3attempt = 1while attempt <= max_attempts:try:output = chain.invoke(full_text)print(output)return outputexcept (CustomOutputParserException, ValidationError) as e:if attempt == max_attempts:raise eelse:print(f"Parsing error occurred. Retrying (attempt {attempt + 1}/{max_attempts})...")attempt += 1return Nonedef display_extracted_fields(obj, section_title=None, indent=0):if section_title:st.subheader(section_title)for field_name, field_value in obj:if field_name in ["personal_details", "education", "work_experience", "projects", "skills", "certifications", "publications", "awards", "additional_sections"]:st.write(" " * indent + f"**{field_name.replace('_', ' ').title()}**:")if isinstance(field_value, BaseModel):display_extracted_fields(field_value, None, indent + 1)elif isinstance(field_value, list):for item in field_value:if isinstance(item, BaseModel):display_extracted_fields(item, None, indent + 1)else:st.write(" " * (indent + 1) + "- " + str(item))else:st.write(" " * (indent + 1) + str(field_value))else:st.write(" " * indent + f"{field_name.replace('_', ' ').title()}: " + str(field_value))def get_json_download_link(json_str, download_name):# Convert the JSON string back to a dictionarydata = json.loads(json_str)# Convert the dictionary back to a JSON string with 4 spaces indentationjson_str_formatted = json.dumps(data, indent=4)b64 = base64.b64encode(json_str_formatted.encode()).decode()href = f'<a href="data:file/json;base64,{b64}" download="{download_name}.json">Click here to download the JSON file</a>'return hrefst.set_page_config(layout="wide")st.title("Resume Parser")llm_dict = {"GPT 3.5 turbo": ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo"),15 unmodified linesselected_model2 = st.selectbox("Select Model 2", list(llm_dict.keys()), index=list(llm_dict.keys()).index("Mixtral 8x7b"))if uploaded_file is not None:text = pdf_to_string(uploaded_file)if st.button("Extract Resume Fields"):col1, col2 = st.columns(2)with col1:start_time = time.time()extracted_fields1 = extract_resume_fields(text, selected_model1)end_time = time.time()elapsed_time = end_time - start_timest.write(f"Extraction completed in {elapsed_time:.2f} seconds")display_extracted_fields(extracted_fields1, f"{selected_model1} Extracted Fields ")with col2:start_time = time.time()extracted_fields2 = extract_resume_fields(text, selected_model2)end_time = time.time()elapsed_time = end_time - start_timest.write(f"Extraction completed in {elapsed_time:.2f} seconds")display_extracted_fields(extracted_fields2, f"{selected_model2} Extracted Fields ")19 unmodified lines20212223242526273 unmodified lines3132333435363738394041424344454647484950515253545515 unmodified lines717273747576777879808182838485868788899091929319 unmodified linesimport timeimport osimport resume_helpers# Set the LANGCHAIN_TRACING_V2 environment variable to 'true'os.environ['LANGCHAIN_TRACING_V2'] = 'true'3 unmodified linesload_dotenv()st.set_page_config(layout="wide")st.title("Resume Parser")col1, col2 = st.columns([1,6])with col1:st.image("llamallms.png", use_column_width=True)with col2:st.write("""## 📝 Unlocking the Power of LLMs 🔓Welcome to the Resume Parser, a powerful tool designed to extract structured information from resumes using the magic of Language Models (LLMs)! 🪄📄 As a data scientist and military veteran, I understand the importance of efficiency and accuracy when it comes to processing information. That's why I've created this app to showcase how different LLMs can help us parse resumes with ease. 💪Resumes come in all shapes and sizes, and standardization is often a distant dream. 😴 But with the right LLM by your side, you can extract key information like personal details, education, work experience, and more, all with just a few clicks! 🖱️ Plus, by comparing the performance of various models, you can find the perfect balance of speed, accuracy, and cost for your specific use case. 💰So, whether you're a recruiter looking to streamline your hiring process, or a data enthusiast curious about the capabilities of LLMs, the Resume Parser has got you covered! 🙌 Upload a resume, select your models, and watch the magic happen. 🎩✨ Let's unlock the full potential of LLMs together and make resume parsing a breeze! 😎""")llm_dict = {"GPT 3.5 turbo": ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo"),15 unmodified linesselected_model2 = st.selectbox("Select Model 2", list(llm_dict.keys()), index=list(llm_dict.keys()).index("Mixtral 8x7b"))if uploaded_file is not None:text = resume_helpers.pdf_to_string(uploaded_file)if st.button("Extract Resume Fields"):col1, col2 = st.columns(2)with col1:start_time = time.time()extracted_fields1 = resume_helpers.extract_resume_fields(text, selected_model1)end_time = time.time()elapsed_time = end_time - start_timest.write(f"Extraction completed in {elapsed_time:.2f} seconds")resume_helpers.display_extracted_fields(extracted_fields1, f"{selected_model1} Extracted Fields ")with col2:start_time = time.time()extracted_fields2 = resume_helpers.extract_resume_fields(text, selected_model2)end_time = time.time()elapsed_time = end_time - start_timest.write(f"Extraction completed in {elapsed_time:.2f} seconds")resume_helpers.display_extracted_fields(extracted_fields2, f"{selected_model2} Extracted Fields ")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131from dotenv import load_dotenvimport ioimport streamlit as stimport streamlit.components.v1 as componentsimport base64
from langchain.prompts import PromptTemplatefrom langchain_core.output_parsers import PydanticOutputParserfrom langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAIfrom langchain_groq import ChatGroqfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.exceptions import OutputParserExceptionfrom pydantic import ValidationErrorfrom langchain_core.pydantic_v1 import BaseModel, Fieldfrom resume_template import Resumefrom json import JSONDecodeErrorimport PyPDF2import jsonimport timeimport os
# Set the LANGCHAIN_TRACING_V2 environment variable to 'true'os.environ['LANGCHAIN_TRACING_V2'] = 'true'
# Set the LANGCHAIN_PROJECT environment variable to the desired project nameos.environ['LANGCHAIN_PROJECT'] = 'Resume_Project'
load_dotenv()llm_dict = { "GPT 3.5 turbo": ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo"), "Anthropic Sonnet": ChatAnthropic(model_name="claude-3-sonnet-20240229"), "Llama 3 8b": ChatGroq(model_name="llama3-8b-8192"), "Llama 3 70b": ChatGroq(model_name="llama3-70b-8192"), "Gemma 7b": ChatGroq(model_name="gemma-7b-it"), "Mixtral 8x7b": ChatGroq(model_name="mixtral-8x7b-32768"), # "Gemini 1.5 Pro": ChatGoogleGenerativeAI(model_name="gemini-1.5-pro-latest"),}def pdf_to_string(file): """ Convert a PDF file to a string.
Parameters: file (io.BytesIO): A file-like object representing the PDF file.
Returns: str: The extracted text from the PDF. """ pdf_reader = PyPDF2.PdfReader(file) num_pages = len(pdf_reader.pages) text = '' for i in range(num_pages): page = pdf_reader.pages[i] text += page.extract_text() file.close() return text
class CustomOutputParserException(Exception): pass
def extract_resume_fields(full_text, model): """ 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()
parser = PydanticOutputParser(pydantic_object=Resume)
prompt_template = PromptTemplate( template=template, input_variables=["resume"], partial_variables={"response_template": parser.get_format_instructions()}, ) llm = llm_dict.get(model, ChatOpenAI(temperature=0, model=model))
chain = prompt_template | llm | parser max_attempts = 3 attempt = 1
while attempt <= max_attempts: try: output = chain.invoke(full_text) print(output) return output except (CustomOutputParserException, ValidationError) as e: if attempt == max_attempts: raise e else: print(f"Parsing error occurred. Retrying (attempt {attempt + 1}/{max_attempts})...") attempt += 1
return None
def display_extracted_fields(obj, section_title=None, indent=0): if section_title: st.subheader(section_title) for field_name, field_value in obj: if field_name in ["personal_details", "education", "work_experience", "projects", "skills", "certifications", "publications", "awards", "additional_sections"]: st.write(" " * indent + f"**{field_name.replace('_', ' ').title()}**:") if isinstance(field_value, BaseModel): display_extracted_fields(field_value, None, indent + 1) elif isinstance(field_value, list): for item in field_value: if isinstance(item, BaseModel): display_extracted_fields(item, None, indent + 1) else: st.write(" " * (indent + 1) + "- " + str(item)) else: st.write(" " * (indent + 1) + str(field_value)) else: st.write(" " * indent + f"{field_name.replace('_', ' ').title()}: " + str(field_value))
def get_json_download_link(json_str, download_name): # Convert the JSON string back to a dictionary data = json.loads(json_str) # Convert the dictionary back to a JSON string with 4 spaces indentation json_str_formatted = json.dumps(data, indent=4) b64 = base64.b64encode(json_str_formatted.encode()).decode() href = f'<a href="data:file/json;base64,{b64}" download="{download_name}.json">Click here to download the JSON file</a>' return hrefapp.py+22-97
llamallms.pngAdded

resume_helpers.pyAdded+131