Manas281 commited on
Commit
8f1528c
Β·
verified Β·
1 Parent(s): ca27b7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +309 -239
app.py CHANGED
@@ -1,239 +1,309 @@
1
- import streamlit as st
2
- from langchain.chains import create_history_aware_retriever, create_retrieval_chain
3
- from langchain.chains.combine_documents import create_stuff_documents_chain
4
-
5
- from langchain_core.prompts import ChatPromptTemplate
6
- from langchain_groq import ChatGroq
7
-
8
- from langchain_huggingface import HuggingFaceEmbeddings
9
- from langchain_text_splitters import RecursiveCharacterTextSplitter
10
- from langchain_community.document_loaders import PyPDFLoader
11
- from langchain.vectorstores import FAISS
12
- import os
13
- from dotenv import load_dotenv
14
- import google.generativeai as genai
15
- import pandas as pd
16
- import json
17
- from io import BytesIO
18
- import tempfile
19
-
20
- # Load environment variables
21
- load_dotenv()
22
-
23
- # Set up embeddings
24
- HF_TOKEN = os.getenv('HF_TOKEN')
25
- embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
26
-
27
- # API keys
28
- api_key = os.getenv('API_KEY')
29
- GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
30
- genai.configure(api_key=GEMINI_API_KEY)
31
-
32
- # Set up generative model
33
- model = genai.GenerativeModel('gemini-pro')
34
-
35
-
36
- def create_job_post(job_title, location, exp):
37
- prompt = (
38
- f"Create a job opening post for platforms like Internshala, LinkedIn, and Naukri.com. "
39
- f"The post should include the job title: {job_title}, location: {location}, and required experience: {exp}. "
40
- f"Make it attractive, include skills (if possible but the skills in boxes and highlight them) required, who can apply, benefits, and other necessary details. "
41
- f"The post should be 100-200 words."
42
- )
43
-
44
- try:
45
- # Replace 'model.generate_content' with the actual method to generate content
46
- response = model.generate_content(prompt) # assuming 'model' is defined elsewhere
47
- return response.text
48
- except Exception as e:
49
- return f"Error generating response: {e}"
50
-
51
-
52
- # Streamlit app title
53
- st.title("Recruitment AI")
54
-
55
- # Job title, location, and experience input fields
56
- job_title = st.text_input("Enter the job title you are looking for")
57
- location = st.text_input("Enter the location you are looking for")
58
- exp = st.text_input("Enter the experience you are looking for")
59
-
60
- # Button to generate job post
61
- if st.button("Create Job Post"):
62
- if job_title and location and exp:
63
- job_post = create_job_post(job_title, location, exp)
64
- st.write(job_post)
65
- else:
66
- st.warning("Please fill in all fields to generate the job post.")
67
-
68
- job_post = create_job_post(job_title, location, exp)
69
- # Resume scoring section
70
-
71
- llm = ChatGroq(groq_api_key=api_key, model_name="llama-3.1-8b-instant")
72
- llm_2 = ChatGroq(groq_api_key=api_key, model_name="gemma-7b-it")
73
-
74
-
75
-
76
- jd=st.file_uploader("Upload Job Description", type="pdf")
77
- def get_jd(jd):
78
- try:
79
- # Use a temporary file to save the uploaded file
80
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
81
- temp_pdf.write(jd.getvalue())
82
- temp_pdf_path = temp_pdf.name
83
-
84
- # Load the PDF using PyPDFLoader
85
- loader = PyPDFLoader(temp_pdf_path)
86
- docs = loader.load()
87
-
88
- finally:
89
- # Remove the temporary file after processing
90
- if os.path.exists(temp_pdf_path):
91
- os.remove(temp_pdf_path)
92
-
93
- # Text splitting for embeddings
94
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)
95
- splits = text_splitter.split_documents(docs)
96
-
97
- # Create FAISS vectorstore for retrieval
98
- vectorstore = FAISS.from_documents(splits, embeddings)
99
- retriever = vectorstore.as_retriever()
100
-
101
- # Define prompt and QA chain
102
- system_prompt = (
103
- f"Extract the Job description from the uploaded file in proper format."
104
- )
105
-
106
- qa_prompt = ChatPromptTemplate.from_messages(
107
- [
108
- ("system", system_prompt),
109
- ("human", "{context}\n{input}"),
110
- ]
111
- )
112
-
113
- # Create question-answering chain
114
- question_answer_chain = create_stuff_documents_chain(llm_2, qa_prompt)
115
- rag_chain = create_retrieval_chain(retriever, question_answer_chain)
116
-
117
- try:
118
- # Retrieve the job description using the chain
119
- response = rag_chain.invoke({
120
- "input": "Describe the job description in proper format"
121
- })
122
- job_description = response["answer"]
123
-
124
- return job_description
125
-
126
- except Exception as e:
127
- raise RuntimeError(f"Error retrieving job description: {e}")
128
-
129
- if jd:
130
- job_description = get_jd(jd)
131
-
132
-
133
-
134
- # File uploader for PDF resumes
135
- uploaded_files = st.file_uploader("Choose PDF files", type="pdf", accept_multiple_files=True)
136
-
137
-
138
- # Function to process PDFs in batches of 4
139
-
140
-
141
-
142
-
143
- def process_pdfs_in_batches(files):
144
- batch_size = 4
145
- num_batches = (len(files) // batch_size) + (1 if len(files) % batch_size != 0 else 0)
146
- all_json_data = []
147
-
148
- for i in range(num_batches):
149
- batch = files[i * batch_size: (i + 1) * batch_size] # Select a batch of files
150
- documents = [] # List to hold all document contents
151
-
152
- for j, uploaded_file in enumerate(batch):
153
- try:
154
- # Use a temporary file to save the uploaded file
155
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
156
- temp_pdf.write(uploaded_file.getvalue())
157
- temp_pdf_path = temp_pdf.name
158
-
159
- # Load the PDF using PyPDFLoader
160
- loader = PyPDFLoader(temp_pdf_path)
161
- docs = loader.load()
162
- documents.extend(docs)
163
-
164
- finally:
165
- # Remove the temporary file after processing
166
- if os.path.exists(temp_pdf_path):
167
- os.remove(temp_pdf_path)
168
-
169
- # Text splitting for embeddings
170
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)
171
- splits = text_splitter.split_documents(documents)
172
-
173
- # Create FAISS vectorstore for retrieval
174
- vectorstore = FAISS.from_documents(splits, embeddings)
175
- retriever = vectorstore.as_retriever()
176
-
177
- # Define prompt and QA chain
178
- system_prompt = (
179
- f"You are a smart AI agent tasked with evaluating resumes against the job description: "
180
- f"Job Title: {job_title}, Location: {location}, Experience: {exp}. "
181
- f"Your evaluation should provide a score (0-100) for each resume based on skills, experience, and other factors. "
182
- f"Extract the following details from each uploaded PDF: Name, Contact Number, Email,Address and the calculated Score. "
183
- "Output must be a JSON array of dictionaries, where each dictionary has the keys: 'Name', 'Contact Number', 'Email', 'Address' and 'Score' "
184
-
185
-
186
- )
187
-
188
- qa_prompt = ChatPromptTemplate.from_messages(
189
- [
190
- ("system", system_prompt),
191
- ("human", "{context}\n{input}"),
192
- ]
193
- )
194
-
195
- # Create question-answering chain
196
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
197
- rag_chain = create_retrieval_chain(retriever, question_answer_chain)
198
-
199
- try:
200
- # Button for scoring resumes
201
- response = rag_chain.invoke({
202
- "input": "Evaluate these resumes and provide scores scores should be very accurate and strictly evaluated as it would be used by recruiter, as given by system prompt ,"
203
- " just provide the json data only not anything else and make sure to be consistent with the output and generate text only. Output must be a JSON array of dictionaries in text format, "
204
- "where each dictionary has the keys: 'Name', 'Contact Number', 'Email','Address and 'Score' .Just provide the json data nothing else."
205
- "Also the generated data should be equal to uploaded resumes not more nor less"
206
- })
207
-
208
-
209
-
210
- json_data = json.loads(response["answer"])
211
-
212
- # Append the JSON data to the all_json_data list
213
-
214
- all_json_data.extend(json_data)
215
-
216
- #st.write(json_data)
217
-
218
- except Exception as e:
219
- st.error(f"Error: {e}")
220
-
221
- # Once all batches are processed, you can use all_json_data as needed
222
- # For example, converting it into a DataFrame and displaying
223
- df = pd.DataFrame(all_json_data)
224
- st.dataframe(
225
- df.style
226
- # Highlight min values
227
- .set_table_styles([
228
- {'selector': 'thead th', 'props': [('background-color', '#4CAF50'), ('color', 'white')]},
229
- # Table header style
230
- {'selector': 'tbody td', 'props': [('border', '1px solid #ddd'), ('padding', '8px')]} # Table body style
231
- ])
232
- )
233
-
234
-
235
- # Call the batch processing function if files are uploaded
236
- if uploaded_files:
237
- process_pdfs_in_batches(uploaded_files)
238
-
239
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain.chains import create_history_aware_retriever, create_retrieval_chain
3
+ from langchain.chains.combine_documents import create_stuff_documents_chain
4
+
5
+ from langchain_core.prompts import ChatPromptTemplate
6
+ from langchain_groq import ChatGroq
7
+
8
+ from langchain_huggingface import HuggingFaceEmbeddings
9
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
10
+ from langchain_community.document_loaders import PyPDFLoader
11
+ from langchain.vectorstores import FAISS
12
+ import os
13
+ from dotenv import load_dotenv
14
+ import google.generativeai as genai
15
+ import pandas as pd
16
+ import json
17
+ from io import BytesIO
18
+ import tempfile
19
+ from st_aggrid import AgGrid
20
+ import base64
21
+
22
+
23
+ # Load environment variables
24
+ load_dotenv()
25
+
26
+
27
+
28
+ # CSS for background and alignment
29
+ # CSS for background with reduced transparency
30
+
31
+
32
+ # Set up embeddings
33
+ HF_TOKEN = os.getenv('HF_TOKEN')
34
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
35
+
36
+ # API keys
37
+ api_key = os.getenv('API_KEY')
38
+ GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
39
+ genai.configure(api_key=GEMINI_API_KEY)
40
+
41
+ # Set up generative model
42
+ model = genai.GenerativeModel('gemini-pro')
43
+
44
+ #st.sidebar.title("Select AI Model")
45
+
46
+ # model_name = st.sidebar.selectbox("Select AI Model", [
47
+ # "gemma-7b-it",
48
+ # "gemma2-9b-it",
49
+ # "llama-3.1-70b-versatile",
50
+ # "llama-3.1-8b-instant",
51
+ # "llama-3.2-1b-preview",
52
+ # "llama-3.2-3b-preview",
53
+ # "llama-3.2-90b-text-preview",
54
+ # "llama-3.2-90b-vision-preview",
55
+ # "llama-guard-3-8b",
56
+ # "llama3-70b-8192",
57
+ # "llama3-8b-8192",
58
+ # "llama3-groq-70b-8192-tool-use-preview",
59
+ # "llama3-groq-8b-8192-tool-use-preview",
60
+ # "llava-v1.5-7b-4096-preview",
61
+ # "mixtral-8x7b-32768"
62
+ # ])
63
+
64
+ st.title("πŸ•΅οΈ Recruitment AI πŸ€–")
65
+
66
+ def create_job_post(job_title, location, exp,salary_range,other_input):
67
+ prompt = (
68
+ f"Create a job opening post for platforms like Internshala, LinkedIn, and Naukri.com. "
69
+ f"The post should include the job title: {job_title}, location: {location}, and required experience: {exp},salart range:{salary_range} and other input:{other_input}. "
70
+ f"Make it attractive, include skills (if possible but the skills in boxes and highlight them) required, who can apply, benefits, and other necessary details. "
71
+ f"The post should be 100-200 words."
72
+ )
73
+
74
+ try:
75
+ # Replace 'model.generate_content' with the actual method to generate content
76
+ response = model.generate_content(prompt) # assuming 'model' is defined elsewhere
77
+ return response.text
78
+ except Exception as e:
79
+ return f"Error generating response: {e}"
80
+
81
+
82
+ # Streamlit app title
83
+
84
+
85
+ with st.form("job_post_form"):
86
+ st.write("πŸ“ Fill in the details to create a job post ✍🏼 :")
87
+ st.write(" ───────────────────────────────────────────────────────────")
88
+
89
+ left, right = st.columns(2)
90
+ with left:
91
+ # Job title, location, and experience input fields
92
+ job_title = st.text_input("Enter the job title you are looking for:")
93
+ location = st.text_input("Enter the location you are looking for:")
94
+ with right:
95
+ exp = st.text_input("Enter the experience you are looking for:")
96
+ salary_range = st.text_input("Enter the Salary range you are looking for:")
97
+
98
+ other_input = st.text_input("Enter any other details you want to add in the job post:")
99
+
100
+ st.write(" ───────────────────────────────────────────────────────────")
101
+
102
+ # Form submission button
103
+ submitted = st.form_submit_button("Create Job Post βœ…")
104
+
105
+ if submitted:
106
+ if job_title and location and exp:
107
+ job_post = create_job_post(job_title, location, exp, salary_range, other_input)
108
+ st.write("### Generated Job Post:")
109
+ st.write(job_post)
110
+ else:
111
+ st.warning("Please fill in all required fields to generate the job post.")
112
+
113
+ job_post = create_job_post(job_title, location, exp, salary_range,other_input)
114
+
115
+
116
+
117
+
118
+ # Resume scoring section
119
+
120
+ llm = ChatGroq(groq_api_key=api_key, model_name="gemma2-9b-it")
121
+ llm_2 = ChatGroq(groq_api_key=api_key, model_name="gemma-7b-it")
122
+
123
+
124
+
125
+ jd=st.file_uploader("πŸ“ Upload Job Description πŸ“œ", type="pdf")
126
+ def get_jd(jd):
127
+ try:
128
+ # Use a temporary file to save the uploaded file
129
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
130
+ temp_pdf.write(jd.getvalue())
131
+ temp_pdf_path = temp_pdf.name
132
+
133
+ # Load the PDF using PyPDFLoader
134
+ loader = PyPDFLoader(temp_pdf_path)
135
+ docs = loader.load()
136
+
137
+ finally:
138
+ # Remove the temporary file after processing
139
+ if os.path.exists(temp_pdf_path):
140
+ os.remove(temp_pdf_path)
141
+
142
+ # Text splitting for embeddings
143
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)
144
+ splits = text_splitter.split_documents(docs)
145
+
146
+ # Create FAISS vectorstore for retrieval
147
+ vectorstore = FAISS.from_documents(splits, embeddings)
148
+ retriever = vectorstore.as_retriever()
149
+
150
+ # Define prompt and QA chain
151
+ system_prompt = (
152
+ f"Extract the Job description from the uploaded file in proper format. Also keep the value of the Job Location in mind as it will be required Later to match with resumes "
153
+ )
154
+
155
+ qa_prompt = ChatPromptTemplate.from_messages(
156
+ [
157
+ ("system", system_prompt),
158
+ ("human", "{context}\n{input}"),
159
+ ]
160
+ )
161
+
162
+ # Create question-answering chain
163
+ question_answer_chain = create_stuff_documents_chain(llm_2,qa_prompt)
164
+ rag_chain = create_retrieval_chain(retriever, question_answer_chain)
165
+
166
+ try:
167
+ # Retrieve the job description using the chain
168
+ response = rag_chain.invoke({
169
+ "input": "Describe the job description in proper format"
170
+ })
171
+ job_description = response["answer"]
172
+
173
+ return job_description
174
+
175
+ except Exception as e:
176
+ raise RuntimeError(f"Error retrieving job description: {e}")
177
+
178
+ if jd:
179
+ job_description = get_jd(jd)
180
+
181
+
182
+
183
+ # File uploader for PDF resumes
184
+
185
+
186
+
187
+
188
+
189
+
190
+ def process_pdfs_in_batches(files):
191
+ batch_size = 4
192
+ num_batches = (len(files) // batch_size) + (1 if len(files) % batch_size != 0 else 0)
193
+ all_json_data = []
194
+
195
+ for i in range(num_batches):
196
+ batch = files[i * batch_size: (i + 1) * batch_size] # Select a batch of files
197
+ documents = [] # List to hold all document contents
198
+
199
+ for j, uploaded_file in enumerate(batch):
200
+ try:
201
+ # Use a temporary file to save the uploaded file
202
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
203
+ temp_pdf.write(uploaded_file.getvalue())
204
+ temp_pdf_path = temp_pdf.name
205
+
206
+ # Load the PDF using PyPDFLoader
207
+ loader = PyPDFLoader(temp_pdf_path)
208
+ docs = loader.load()
209
+ documents.extend(docs)
210
+
211
+ finally:
212
+ # Remove the temporary file after processing
213
+ if os.path.exists(temp_pdf_path):
214
+ os.remove(temp_pdf_path)
215
+
216
+ # Text splitting for embeddings
217
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=500)
218
+ splits = text_splitter.split_documents(documents)
219
+
220
+ # Create FAISS vectorstore for retrieval
221
+ vectorstore = FAISS.from_documents(splits, embeddings)
222
+ retriever = vectorstore.as_retriever()
223
+
224
+ # Define prompt and QA chain
225
+ system_prompt = (
226
+ f"You are a smart AI agent tasked with evaluating resumes against the job description: "
227
+ f"Job Title: {job_title}, Location: {location}, Experience: {exp}. "
228
+ f"Your evaluation should provide a score (0-100) for each resume based on skills, experience, and other factors. "
229
+ f"Extract the following details from each uploaded PDF: Name, Contact Number, Email,Address and the calculated Score. "
230
+ "Output must be a JSON array of dictionaries, where each dictionary has the keys: 'Name', 'Contact Number', 'Email', 'Address' and 'Score' "
231
+ "Generate JSON data for, but present it as plain text in the response. Do not use a code block or any structured formatting like boxes."
232
+ "Do not include extra line breaks or whitespace outside the JSON array. The JSON must start with [ and end with ]"
233
+ f"if the Address of the candidate is too far (like more than 100 kms) away from {location} or the job location mentioned in the {job_description}, then the score should be 0."
234
+ )
235
+
236
+ qa_prompt = ChatPromptTemplate.from_messages(
237
+ [
238
+ ("system", system_prompt),
239
+ ("human", "{context}\n{input}"),
240
+ ]
241
+ )
242
+
243
+ # Create question-answering chain
244
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
245
+ rag_chain = create_retrieval_chain(retriever, question_answer_chain)
246
+
247
+ try:
248
+ # Button for scoring resumes
249
+ response = rag_chain.invoke({
250
+ "input": (
251
+ "You are a smart AI agent tasked with evaluating resumes based on a job description. "
252
+ "Strictly follow the instructions below to generate the output:\n\n"
253
+ "1. Extract the following details from each resume: Name, Contact Number, Email, Address, and Score.\n"
254
+ "2. Output the data as a JSON array of dictionaries. Each dictionary must contain these keys: "
255
+ "'Name', 'Contact Number', 'Email', 'Address', and 'Score'.\n"
256
+ "3. The output must be plain text JSON without any extra formatting, syntax highlighting, or visual artifacts. "
257
+ "Do not include explanations, metadata, or anything other than the JSON array.\n"
258
+ "4. Ensure the JSON is well-formed and matches the number of resumes exactly.\n\n"
259
+ "Generate only the JSON array in text format, ensuring it adheres to this structure."
260
+ "Generate JSON data for, but present it as plain text in the response. Do not use a code block or any structured formatting like boxes."
261
+ f"if the Address of the candidate is too far (like more than 100 kms) away from {location} or the job location mentioned in the {job_description}, then the score should be 0.but dont include comparison in the output"
262
+ )
263
+ })
264
+
265
+
266
+ json_data = json.loads(response["answer"])
267
+
268
+ # Append the JSON data to the all_json_data list
269
+
270
+ all_json_data.extend(json_data)
271
+ sorted_data = sorted(all_json_data, key=lambda x: x["Score"], reverse=True)
272
+
273
+ #st.write(json_data)
274
+
275
+ except Exception as e:
276
+ st.error(f"Error: {e}")
277
+
278
+ # Once all batches are processed, you can use all_json_data as needed
279
+ # For example, converting it into a DataFrame and displaying
280
+ df = pd.DataFrame(sorted_data)
281
+
282
+ st.dataframe(
283
+ df.style
284
+ # Highlight min values
285
+ .set_table_styles([
286
+ {'selector': 'thead th', 'props': [('background-color', '#4CAF50'), ('color', 'white')]},
287
+ # Table header style
288
+ {'selector': 'tbody td', 'props': [('border', '1px solid #ddd'), ('padding', '8px')]} # Table body style
289
+ ])
290
+ )
291
+
292
+
293
+ st.write(" ───────────────────────────────────────────────────────────")
294
+ st.write("πŸ“‚ Upload the resumes to score them πŸ“‘:")
295
+
296
+ uploaded_files = st.file_uploader("Choose PDF files", type="pdf", accept_multiple_files=True)
297
+
298
+ st.write(" ───────────────────────────────────────────────────────────")
299
+ if st.button("Score Resumesβœ”οΈ"):
300
+ if uploaded_files:
301
+ process_pdfs_in_batches(uploaded_files)
302
+ else:
303
+ st.warning("Please upload files to score.")
304
+
305
+
306
+ # Call the batch processing function if files are uploaded
307
+
308
+
309
+