Manas281 commited on
Commit
098a7cf
·
verified ·
1 Parent(s): 6343a6c

Create app.py

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