Spaces:
Runtime error
Runtime error
Commit ·
f3adfbf
1
Parent(s): 1a1a2a1
Add HF Spaces deployment and fix broken app
Browse files- Fix LangChain imports (langchain_classic for ConversationChain/Memory)
- Fix variable scoping bugs and duplicate methods
- Make JD optional, support text input for JD
- Add app.py + requirements.txt + README metadata for HF Spaces
- Add .streamlit config at project root
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (4)
- Code+Folder/src/resume_suggestions.py+80-71
- README.md+28
- app.pyAdded+254
- requirements.txtAdded+15
28 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989933 unmodified lines1331341351361371381391401411421431441451461471481491502 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918028 unmodified linesllm = Noneresume_chain = None# Add API key input in the sidebarwith st.sidebar:st.title('Resume Reviewer')st.write("Upload your resume and JD for my recommendations.")# API Key handling - cleaner UIst.write("---") # Add a separatorst.write("### OpenAI API Key")st.write("Enter your API key to use the application. Get one at [OpenAI](https://platform.openai.com/api-keys)")api_key = st.text_input("API Key", type="password", help="Your API key will not be stored")if api_key:os.environ['OPENAI_API_KEY'] = api_keyllm = ChatOpenAI(temperature=0.0, model=OPENAI_MODEL_NAME)else:st.info("👆 Please enter your OpenAI API key to start")llm = None# Add upload method selectionupload_method = st.radio("Choose input method:", ["File Upload", "Text Input"])# Initialize variables to avoid NameErrorresume_file = Nonejd_file = Noneresume_content = Nonejob_description_content = Nonewith st.sidebar:if upload_method == "File Upload":st.write("Note: File size should be less than 5MB")resume_file = st.file_uploader("Upload your resume (pdf file only)", type=["pdf"], accept_multiple_files=False)jd_file = st.file_uploader("Upload your JD (txt file only)", type=["txt"], accept_multiple_files=False)else:resume_text = st.text_area("Paste your resume content here:", height=200)jd_text = st.text_area("Paste your job description here:", height=200)if resume_text and jd_text:resume_content = resume_textjob_description_content = jd_textst.sidebar.success("Text content received successfully!")if upload_method == "File Upload" and resume_file is not None and jd_file is not None and api_key:try:with st.spinner("Processing resume file..."):directory_reader = DirectoryReader("", "")resume_content = directory_reader.extract_text_from_pdf(resume_file)st.sidebar.success("Resume processed successfully!")with st.spinner("Processing job description file..."):if jd_file.type == 'text/plain':try:from io import StringIOstringio = StringIO(jd_file.getvalue().decode('utf-8'))read_data = stringio.read()job_description_content = read_datast.sidebar.success("JD processed successfully!")except Exception as e:st.sidebar.error(f"Error processing JD file: {str(e)}")job_description_content = Noneexcept Exception as e:st.sidebar.error(f"Error processing resume file: {str(e)}")resume_content = Nonejob_description_content = NoneSYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT + "<RESUME STARTS HERE> {}. <RESUME ENDS HERE> with the job description: <JOB DESCRIPTION STARTS HERE> {}.<JOB DESCRIPTION ENDS HERE>\n\nBe crisp and clear in response.DO NOT provide the resume and job description in the response\n\n".format(resume_content, job_description_content)# Store LLM generated responses33 unmodified linesdef generate_report():user_message = {"role": "user", "content": "Generate a Report!"}st.session_state.messages.append(user_message)if resume_content is not None and job_description_content is not None:with st.chat_message("assistant"):with st.spinner("Just a moment..."):comparison_analysis = generate_response(comparison_prompt.format(resume_content, job_description_content))resume_analysis = generate_response(resume_analysis_prompt.format(resume_content))job_description_analysis = generate_response(job_description_analysis_prompt.format(job_description_content))gap_analysis = generate_response(gap_analysis_prompt.format(resume_content,job_description_content))actionable_steps_analysis = generate_response(actionable_steps_prompt.format(resume_content, job_description_content))experience_enhancement_analysis = generate_response(experience_enhancement_prompt.format(resume_content, job_description_content))additional_qualifications_analysis = generate_response(2 unmodified linesresume_tailoring_prompt.format(resume_content, job_description_content))relevant_skills_highlight_analysis = generate_response(relevant_skills_highlight_prompt.format(resume_content, job_description_content))resume_formatting_analysis = generate_response(resume_formatting_prompt.format(resume_content, job_description_content))resume_length_analysis = generate_response(resume_length_prompt.format(resume_content, job_description_content))# Compile the reportreport = f"Comparison Analysis:\n{comparison_analysis}\n\n" \f"Resume Analysis:\n{resume_analysis}\n\n" \f"Job Description Analysis:\n{job_description_analysis}\n" \f"\nGap Analysis:\n{gap_analysis} \n\n" \f"Actionable Steps:\n{actionable_steps_analysis}\n\n" \f"Experience Enhancement:\n{experience_enhancement_analysis}\n\n" \f"Additional Qualifications:\n{additional_qualifications_analysis}\n\n" \f"Resume Tailoring:\n{resume_tailoring_analysis}\n\n" \f"Relevant Skills Highlight:\n{relevant_skills_highlight_analysis}\n\n" \f"Resume Formatting:\n{resume_formatting_analysis}\n\n" \f"Resume Length:\n{resume_length_analysis} "report_message = {"role": "assistant", "content": report}st.session_state.messages.append(report_message)else:st.error("Please upload a resume and enter a job description!")# Setup the system message and prompt template28 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410533 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651662 unmodified lines16917017117217317417517617717817918018118218318418518618718818928 unmodified linesllm = Noneresume_chain = None# Initialize variablesresume_content = Nonejob_description_content = None# Sidebarwith st.sidebar:st.title('Resume Reviewer')st.write("Upload your resume for my recommendations. Job description is optional.")# API Keyst.write("---")st.write("### OpenAI API Key")st.write("Enter your API key to use the application. Get one at [OpenAI](https://platform.openai.com/api-keys)")api_key = st.text_input("API Key", type="password", help="Your API key will not be stored")if api_key:os.environ['OPENAI_API_KEY'] = api_keyllm = ChatOpenAI(temperature=0.0, model=OPENAI_MODEL_NAME)else:st.info("Please enter your OpenAI API key to start")llm = None# Resume upload (file only)st.write("---")st.write("### Resume")st.write("Note: File size should be less than 5MB")resume_file = st.file_uploader("Upload your resume (PDF)", type=["pdf"], accept_multiple_files=False)# JD input (file or text, optional)st.write("---")st.write("### Job Description (optional)")jd_file = st.file_uploader("Upload a JD (txt file)", type=["txt"], accept_multiple_files=False)jd_text = st.text_area("Or paste the job description here:", height=150)# Process resumeif resume_file is not None and api_key:try:with st.spinner("Processing resume file..."):directory_reader = DirectoryReader("", "")resume_content = directory_reader.extract_text_from_pdf(resume_file)st.sidebar.success("Resume processed successfully!")except Exception as e:st.sidebar.error(f"Error processing resume file: {str(e)}")resume_content = None# Process JD - prefer file upload, fall back to text inputif jd_file is not None:try:from io import StringIOstringio = StringIO(jd_file.getvalue().decode('utf-8'))job_description_content = stringio.read()st.sidebar.success("JD processed successfully!")except Exception as e:st.sidebar.error(f"Error processing JD file: {str(e)}")elif jd_text:job_description_content = jd_text# Build system prompt based on what's providedif resume_content and job_description_content:SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT + \"<RESUME STARTS HERE> {}. <RESUME ENDS HERE> with the job description: " \"<JOB DESCRIPTION STARTS HERE> {}.<JOB DESCRIPTION ENDS HERE>\n\n" \"Be crisp and clear in response. DO NOT provide the resume and job description in the response.\n\n".format(resume_content, job_description_content)elif resume_content:SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT + \"<RESUME STARTS HERE> {}. <RESUME ENDS HERE>\n\n" \"No job description was provided. Focus on general resume feedback, strengths, and areas for improvement. " \"Be crisp and clear in response. DO NOT provide the resume in the response.\n\n".format(resume_content)else:SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT# Store LLM generated responses33 unmodified linesdef generate_report():user_message = {"role": "user", "content": "Generate a Report!"}st.session_state.messages.append(user_message)if resume_content is None:st.error("Please upload a resume first!")returnwith st.chat_message("assistant"):with st.spinner("Just a moment..."):resume_analysis = generate_response(resume_analysis_prompt.format(resume_content))resume_formatting_analysis = generate_response(resume_formatting_prompt.format(resume_content, "N/A"))report = f"**Resume Analysis:**\n{resume_analysis}\n\n" \f"**Resume Formatting:**\n{resume_formatting_analysis}"if job_description_content is not None:comparison_analysis = generate_response(comparison_prompt.format(resume_content, job_description_content))job_description_analysis = generate_response(job_description_analysis_prompt.format(job_description_content))gap_analysis = generate_response(gap_analysis_prompt.format(resume_content, job_description_content))actionable_steps_analysis = generate_response(actionable_steps_prompt.format(resume_content, job_description_content))experience_enhancement_analysis = generate_response(experience_enhancement_prompt.format(resume_content, job_description_content))additional_qualifications_analysis = generate_response(2 unmodified linesresume_tailoring_prompt.format(resume_content, job_description_content))relevant_skills_highlight_analysis = generate_response(relevant_skills_highlight_prompt.format(resume_content, job_description_content))resume_length_analysis = generate_response(resume_length_prompt.format(resume_content, job_description_content))report += f"\n\n**Comparison Analysis:**\n{comparison_analysis}\n\n" \f"**Job Description Analysis:**\n{job_description_analysis}\n\n" \f"**Gap Analysis:**\n{gap_analysis}\n\n" \f"**Actionable Steps:**\n{actionable_steps_analysis}\n\n" \f"**Experience Enhancement:**\n{experience_enhancement_analysis}\n\n" \f"**Additional Qualifications:**\n{additional_qualifications_analysis}\n\n" \f"**Resume Tailoring:**\n{resume_tailoring_analysis}\n\n" \f"**Relevant Skills Highlight:**\n{relevant_skills_highlight_analysis}\n\n" \f"**Resume Length:**\n{resume_length_analysis}"report_message = {"role": "assistant", "content": report}st.session_state.messages.append(report_message)# Setup the system message and prompt template
12345678910111213141516171819202122232425262728---title: Resume Revieweremoji: 📄colorFrom: bluecolorTo: indigosdk: streamlitsdk_version: "1.54.0"app_file: app.pypinned: false---# Resume ReviewerAI-powered resume analyzer that reviews your resume and compares it against job descriptions using OpenAI.## Features- Upload a PDF resume for instant analysis- Optionally provide a job description (file or text) for targeted feedback- Get a full report: gap analysis, tailoring suggestions, formatting tips, and more- Chat with the AI for follow-up questions about your resume## Usage1. Enter your OpenAI API key in the sidebar2. Upload your resume (PDF)3. Optionally add a job description (upload .txt or paste text)4. Click **Generate Report** or ask questions in the chat
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254import osimport sys
# Add source directory to path so sibling imports worksys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "Code+Folder", "src"))
import streamlit as st
try: from streamlit_feedback import streamlit_feedback FEEDBACK_AVAILABLE = Trueexcept ImportError: FEEDBACK_AVAILABLE = False
from langchain_classic.chains import ConversationChainfrom langchain_classic.memory import ConversationBufferWindowMemoryfrom langchain_core.messages import SystemMessagefrom langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplatefrom langchain_openai import ChatOpenAIfrom constants import OPENAI_MODEL_NAME, TEMPLATE_CONTENT, comparison_prompt, resume_analysis_prompt, \ job_description_analysis_prompt, gap_analysis_prompt, actionable_steps_prompt, experience_enhancement_prompt, \ additional_qualifications_prompt, resume_tailoring_prompt, relevant_skills_highlight_prompt, \ resume_formatting_prompt, resume_length_promptfrom directory_reader import DirectoryReader
st.set_page_config(page_title="Resume Reviewer")
# Initialize llm as None at the top levelllm = Noneresume_chain = None
# Initialize variablesresume_content = Nonejob_description_content = None
# Sidebarwith st.sidebar: st.title('Resume Reviewer') st.write("Upload your resume for my recommendations. Job description is optional.")
# API Key st.write("---") st.write("### OpenAI API Key") st.write("Enter your API key to use the application. Get one at [OpenAI](https://platform.openai.com/api-keys)") api_key = st.text_input("API Key", type="password", help="Your API key will not be stored")
if api_key: os.environ['OPENAI_API_KEY'] = api_key llm = ChatOpenAI(temperature=0.0, model=OPENAI_MODEL_NAME) else: st.info("Please enter your OpenAI API key to start") llm = None
# Resume upload (file only) st.write("---") st.write("### Resume") st.write("Note: File size should be less than 5MB") resume_file = st.file_uploader("Upload your resume (PDF)", type=["pdf"], accept_multiple_files=False)
# JD input (file or text, optional) st.write("---") st.write("### Job Description (optional)") jd_file = st.file_uploader("Upload a JD (txt file)", type=["txt"], accept_multiple_files=False) jd_text = st.text_area("Or paste the job description here:", height=150)
# Process resumeif resume_file is not None and api_key: try: with st.spinner("Processing resume file..."): directory_reader = DirectoryReader("", "") resume_content = directory_reader.extract_text_from_pdf(resume_file) st.sidebar.success("Resume processed successfully!") except Exception as e: st.sidebar.error(f"Error processing resume file: {str(e)}") resume_content = None
# Process JD - prefer file upload, fall back to text inputif jd_file is not None: try: from io import StringIO stringio = StringIO(jd_file.getvalue().decode('utf-8')) job_description_content = stringio.read() st.sidebar.success("JD processed successfully!") except Exception as e: st.sidebar.error(f"Error processing JD file: {str(e)}")elif jd_text: job_description_content = jd_text
# Build system prompt based on what's providedif resume_content and job_description_content: SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT + \ "<RESUME STARTS HERE> {}. <RESUME ENDS HERE> with the job description: " \ "<JOB DESCRIPTION STARTS HERE> {}.<JOB DESCRIPTION ENDS HERE>\n\n" \ "Be crisp and clear in response. DO NOT provide the resume and job description in the response.\n\n".format( resume_content, job_description_content)elif resume_content: SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT + \ "<RESUME STARTS HERE> {}. <RESUME ENDS HERE>\n\n" \ "No job description was provided. Focus on general resume feedback, strengths, and areas for improvement. " \ "Be crisp and clear in response. DO NOT provide the resume in the response.\n\n".format(resume_content)else: SYSTEM_PROMPT = "\n\n" + TEMPLATE_CONTENT
# Store LLM generated responsesif "messages" not in st.session_state.keys(): st.session_state.messages = [{"role": "assistant", "content": "How may I assist you today?"}]
# Display or clear chat messagesfor message in st.session_state.messages: if message["role"] != "feedback": with st.chat_message(message["role"]): st.write(message["content"])
def clear_chat_history(): global resume_chain st.session_state.messages = [{"role": "assistant", "content": "How may I help you today?"}] if llm is not None: resume_chain = ConversationChain( llm=llm, prompt=prompt_template, memory=memory, verbose=False )
def generate_report(): user_message = {"role": "user", "content": "Generate a Report!"} st.session_state.messages.append(user_message) if resume_content is None: st.error("Please upload a resume first!") return
with st.chat_message("assistant"): with st.spinner("Just a moment..."): resume_analysis = generate_response(resume_analysis_prompt.format(resume_content)) resume_formatting_analysis = generate_response( resume_formatting_prompt.format(resume_content, "N/A"))
report = f"**Resume Analysis:**\n{resume_analysis}\n\n" \ f"**Resume Formatting:**\n{resume_formatting_analysis}"
if job_description_content is not None: comparison_analysis = generate_response( comparison_prompt.format(resume_content, job_description_content)) job_description_analysis = generate_response( job_description_analysis_prompt.format(job_description_content)) gap_analysis = generate_response( gap_analysis_prompt.format(resume_content, job_description_content)) actionable_steps_analysis = generate_response( actionable_steps_prompt.format(resume_content, job_description_content)) experience_enhancement_analysis = generate_response( experience_enhancement_prompt.format(resume_content, job_description_content)) additional_qualifications_analysis = generate_response( additional_qualifications_prompt.format(resume_content, job_description_content)) resume_tailoring_analysis = generate_response( resume_tailoring_prompt.format(resume_content, job_description_content)) relevant_skills_highlight_analysis = generate_response( relevant_skills_highlight_prompt.format(resume_content, job_description_content)) resume_length_analysis = generate_response( resume_length_prompt.format(resume_content, job_description_content))
report += f"\n\n**Comparison Analysis:**\n{comparison_analysis}\n\n" \ f"**Job Description Analysis:**\n{job_description_analysis}\n\n" \ f"**Gap Analysis:**\n{gap_analysis}\n\n" \ f"**Actionable Steps:**\n{actionable_steps_analysis}\n\n" \ f"**Experience Enhancement:**\n{experience_enhancement_analysis}\n\n" \ f"**Additional Qualifications:**\n{additional_qualifications_analysis}\n\n" \ f"**Resume Tailoring:**\n{resume_tailoring_analysis}\n\n" \ f"**Relevant Skills Highlight:**\n{relevant_skills_highlight_analysis}\n\n" \ f"**Resume Length:**\n{resume_length_analysis}"
report_message = {"role": "assistant", "content": report} st.session_state.messages.append(report_message)
# Setup the system message and prompt templatesystem_message = SystemMessage(content=TEMPLATE_CONTENT)human_message = HumanMessagePromptTemplate.from_template("{history} User:{input} Assistant:")prompt_template = ChatPromptTemplate(messages=[system_message, human_message])memory = ConversationBufferWindowMemory(k=2)
# Initialize the chain if llm is availableif llm is not None: resume_chain = ConversationChain( llm=llm, prompt=prompt_template, memory=memory, verbose=False )
def generate_response(prompt_input): if resume_chain is None: return "Please enter your OpenAI API key to use this application" output = resume_chain.predict(input=prompt_input) return output
st.sidebar.button('Clear Chat History', on_click=clear_chat_history)st.sidebar.button('Generate Report', on_click=generate_report)
def get_feedback(): st.session_state.messages.append({"role": "feedback", "content": st.session_state.fbk})
# At the beginning of your script, initialize the prompt in session stateif "current_prompt" not in st.session_state: st.session_state.current_prompt = ""
# When user enters a promptif prompt := st.chat_input(): st.session_state.current_prompt = prompt st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.write(prompt)
def get_llm_response(): with st.chat_message("assistant"): with st.spinner("Thinking..."): response = generate_response(st.session_state.current_prompt + SYSTEM_PROMPT) placeholder = st.empty() placeholder.markdown(response) full_response = response message = {"role": "assistant", "content": full_response} st.session_state.messages.append(message)
# Only show feedback form if the feature is available if FEEDBACK_AVAILABLE: with st.form("form"): streamlit_feedback(feedback_type="thumbs", optional_text_label="[Optional] Please provide an explanation", key="fbk") st.form_submit_button('Save feedback', on_click=get_feedback)
# Generate a new response if last message is not from assistantif st.session_state.messages[-1]["role"] not in ["assistant", "feedback"]: get_llm_response()
if st.session_state.messages[-1]["role"] in ["feedback"]: try: feedback_response = st.session_state.messages[-1]["content"] score_mappings = { "thumbs": {"thumbs_up": 1, "thumbs_down": 0}, } score = score_mappings[feedback_response["type"]][feedback_response["score"]] if score == 0: feedback = st.session_state.messages[-1]["content"]['text'] prompt = "Please respond according to feedback '{0}' on the previous response on \n".format(feedback) \ + st.session_state.messages[-3]["content"] get_llm_response() except: pass123456789101112131415streamlit>=1.31.0langchain>=0.3.0langchain-classic>=1.0.0langchain-community>=0.3.0langchain-core>=0.3.0langchain-openai>=0.2.0openai>=1.10.0streamlit-feedback>=0.1.3PyPDF2>=3.0.1pypdf>=3.17.1numpy>=1.26.3pandas>=2.1.4scikit-learn>=1.3.2tqdm>=4.66.1python-dotenv>=1.0.0Code+Folder/src/resume_suggestions.py+80-71
README.md+28
app.pyAdded+254
requirements.txtAdded+15