rohitashva commited on
Commit
709add7
·
verified ·
1 Parent(s): 8af5fee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -18
app.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import streamlit as st
2
  import os
3
  import logging
@@ -8,7 +11,10 @@ from langchain_community.vectorstores import FAISS
8
  from langchain_community.embeddings import HuggingFaceEmbeddings
9
  from langchain.prompts import PromptTemplate
10
  from langchain.llms import HuggingFaceHub
11
- import os
 
 
 
12
  dotenv.load_dotenv()
13
 
14
  # Load configuration from YAML
@@ -17,7 +23,6 @@ def load_config():
17
  return yaml.safe_load(f)
18
 
19
  config = load_config()
20
- hf_token = os.getenv("Gem") # Store API token in .env
21
  logging.basicConfig(level=logging.INFO)
22
 
23
  # Load embedding model
@@ -31,31 +36,66 @@ def extract_text_from_pdf(file):
31
  text += page.extract_text() or ""
32
  return text.strip()
33
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # Get interview questions and assess responses
35
- def get_interview_response(jd_text, resume_text, candidate_response=None):
36
- prompt_template = """
37
- You are an AI interviewer assessing a candidate for a job role.
38
-
 
 
 
 
 
 
 
 
 
 
39
  JOB DESCRIPTION:
40
  {jd_text}
41
 
42
  CANDIDATE PROFILE:
43
  {resume_text}
44
 
45
- 1. Start by asking an **introductory question**: "Tell me about yourself."
46
- 2. Then, based on the job description, ask a **technical question**.
47
- 3. If the candidate has already responded, evaluate their answer and provide constructive feedback.
48
 
49
- Maintain a professional yet friendly tone.
50
  """
51
 
52
- prompt = PromptTemplate(
53
- input_variables=["jd_text", "resume_text"],
54
- template=prompt_template
55
- ).format(jd_text=jd_text, resume_text=resume_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  if candidate_response:
58
- prompt += f"\n\nCANDIDATE RESPONSE: {candidate_response}\n\nAssess the response and provide feedback."
 
 
 
59
 
60
  llm = HuggingFaceHub(
61
  repo_id=config["model_name"],
@@ -63,7 +103,17 @@ def get_interview_response(jd_text, resume_text, candidate_response=None):
63
  huggingfacehub_api_token=hf_token
64
  )
65
 
66
- return llm(prompt).strip()
 
 
 
 
 
 
 
 
 
 
67
 
68
  # Streamlit UI
69
  st.set_page_config(page_title="AI Interviewer", layout="centered")
@@ -78,18 +128,43 @@ if jd_file and resume_file:
78
  jd_text = extract_text_from_pdf(jd_file)
79
  resume_text = extract_text_from_pdf(resume_file)
80
 
 
 
 
 
81
  if "interview_history" not in st.session_state:
82
  st.session_state["interview_history"] = []
 
83
  first_question = get_interview_response(jd_text, resume_text)
84
  st.session_state["interview_history"].append(("AI", first_question))
85
 
 
 
86
  for role, msg in st.session_state["interview_history"]:
87
  st.chat_message(role).write(msg)
88
 
89
  query = st.chat_input("Your Response:")
90
-
91
  if query:
92
  response = get_interview_response(jd_text, resume_text, query)
93
  st.session_state["interview_history"].append(("You", query))
94
  st.session_state["interview_history"].append(("AI", response))
95
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ hf_token = os.getenv("Gem") # Store API token in .env
4
  import streamlit as st
5
  import os
6
  import logging
 
11
  from langchain_community.embeddings import HuggingFaceEmbeddings
12
  from langchain.prompts import PromptTemplate
13
  from langchain.llms import HuggingFaceHub
14
+ import random
15
+ from sklearn.feature_extraction.text import TfidfVectorizer
16
+ from sklearn.metrics.pairwise import cosine_similarity
17
+
18
  dotenv.load_dotenv()
19
 
20
  # Load configuration from YAML
 
23
  return yaml.safe_load(f)
24
 
25
  config = load_config()
 
26
  logging.basicConfig(level=logging.INFO)
27
 
28
  # Load embedding model
 
36
  text += page.extract_text() or ""
37
  return text.strip()
38
 
39
+ # Function to calculate matching score between job description and resume
40
+ def calculate_matching_score(jd_text, resume_text):
41
+ vectorizer = TfidfVectorizer().fit_transform([jd_text, resume_text])
42
+ score = cosine_similarity(vectorizer[0], vectorizer[1])[0][0] * 100
43
+ return round(score, 2)
44
+
45
+ # Function to generate final score based on user responses
46
+ def calculate_final_score(responses):
47
+ total_questions = len(responses)
48
+ correct_responses = sum(1 for response in responses if "good" in response.lower() or "correct" in response.lower())
49
+ return round((correct_responses / total_questions) * 100, 2) if total_questions > 0 else 0
50
+
51
  # Get interview questions and assess responses
52
+ def get_interview_response(jd_text, resume_text, candidate_response=None, round_stage="intro", question_count=0):
53
+ technical_names = ["Alex", "Jordan", "Casey", "Morgan"]
54
+ hr_names = ["Taylor", "Jamie", "Riley", "Sam"]
55
+
56
+ if round_stage in ["technical", "coding"]:
57
+ interviewer_name = random.choice(technical_names)
58
+ role = "Technical Lead"
59
+ else:
60
+ interviewer_name = random.choice(hr_names)
61
+ role = "HR Manager"
62
+
63
+ prompt_template = f"""
64
+ My name is {interviewer_name}, and I am your {role} for this round.
65
+
66
  JOB DESCRIPTION:
67
  {jd_text}
68
 
69
  CANDIDATE PROFILE:
70
  {resume_text}
71
 
72
+ This is question {question_count+1} of 5.
 
 
73
 
 
74
  """
75
 
76
+ if question_count >= 5:
77
+ return f"{interviewer_name}: This round is complete. Moving to the next stage."
78
+
79
+ if round_stage == "intro":
80
+ prompt_template += f"{interviewer_name}: Let's start with an introduction. Tell me about yourself."
81
+
82
+ elif round_stage == "technical":
83
+ prompt_template += f"{interviewer_name}: Based on your resume and the job description, here is a technical question for you."
84
+
85
+ elif round_stage == "coding":
86
+ prompt_template += f"{interviewer_name}: Let's move to a coding problem relevant to your role."
87
+
88
+ elif round_stage == "hr":
89
+ prompt_template += f"{interviewer_name}: Now let's discuss some HR aspects, starting with your motivation for this role."
90
+
91
+ elif round_stage == "final_feedback":
92
+ prompt_template += "Summarize the candidate’s performance in both rounds in a structured format."
93
 
94
  if candidate_response:
95
+ if candidate_response.lower() == "hint":
96
+ prompt_template += f"{interviewer_name}: Here is a helpful hint."
97
+ else:
98
+ prompt_template += f"The candidate answered: {candidate_response}. Assess the response and move to the next question."
99
 
100
  llm = HuggingFaceHub(
101
  repo_id=config["model_name"],
 
103
  huggingfacehub_api_token=hf_token
104
  )
105
 
106
+ response = llm(prompt_template).strip()
107
+
108
+ # Store the full assessment in a text file for admin review
109
+ with open("candidate_assessment.txt", "a") as f:
110
+ f.write(f"Round: {round_stage}, Question {question_count+1}\n")
111
+ f.write(f"Interviewer: {interviewer_name} ({role})\n")
112
+ f.write(f"Question: {prompt_template}\n")
113
+ f.write(f"Candidate Response: {candidate_response}\n")
114
+ f.write(f"Feedback: {response}\n\n")
115
+
116
+ return response if round_stage != "final_feedback" else f"{interviewer_name}: The interview is now complete."
117
 
118
  # Streamlit UI
119
  st.set_page_config(page_title="AI Interviewer", layout="centered")
 
128
  jd_text = extract_text_from_pdf(jd_file)
129
  resume_text = extract_text_from_pdf(resume_file)
130
 
131
+ # Calculate matching score
132
+ matching_score = calculate_matching_score(jd_text, resume_text)
133
+
134
+ # Store interview history & matching score
135
  if "interview_history" not in st.session_state:
136
  st.session_state["interview_history"] = []
137
+ st.session_state["responses"] = []
138
  first_question = get_interview_response(jd_text, resume_text)
139
  st.session_state["interview_history"].append(("AI", first_question))
140
 
141
+ st.write(f"**Matching Score:** {matching_score}%")
142
+
143
  for role, msg in st.session_state["interview_history"]:
144
  st.chat_message(role).write(msg)
145
 
146
  query = st.chat_input("Your Response:")
147
+
148
  if query:
149
  response = get_interview_response(jd_text, resume_text, query)
150
  st.session_state["interview_history"].append(("You", query))
151
  st.session_state["interview_history"].append(("AI", response))
152
+ st.session_state["responses"].append(response) # Store responses for final score
153
+ st.rerun()
154
+
155
+ # Generate final score and store the results for download
156
+ if "responses" in st.session_state and len(st.session_state["responses"]) >= 5:
157
+ final_score = calculate_final_score(st.session_state["responses"])
158
+
159
+ # Store all results in a text file
160
+ file_path = "candidate_assessment.txt"
161
+ with open(file_path, "w") as f:
162
+ f.write(f"Matching Score: {matching_score}%\n")
163
+ f.write(f"Final Score: {final_score}%\n\n")
164
+ f.write("Interview Assessment:\n")
165
+ for role, msg in st.session_state["interview_history"]:
166
+ f.write(f"{role}: {msg}\n")
167
+
168
+ # Provide file download option
169
+ with open(file_path, "rb") as f:
170
+ st.download_button("Download Assessment", f, file_name="candidate_assessment.txt")