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 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import fitz # PyMuPDF
3
+ from langchain_community.embeddings import HuggingFaceEmbeddings
4
+ import chromadb
5
+ import uuid
6
+ from groq import Groq
7
+ import re
8
+ import json
9
+ import os
10
+
11
+ # -------------------- Core Functions --------------------
12
+ def setup_embeddings():
13
+ return HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
14
+
15
+ def setup_chromadb():
16
+ client = chromadb.PersistentClient(path="./chroma_db")
17
+ return client.get_or_create_collection(name="resumes")
18
+
19
+ def extract_text_from_resume(file):
20
+ if file.name.endswith('.pdf'):
21
+ doc = fitz.open(stream=file.read(), filetype="pdf")
22
+ return "\n".join([page.get_text("text") for page in doc])
23
+ elif file.name.endswith('.txt'):
24
+ return file.read().decode("utf-8")
25
+ return ""
26
+
27
+ def extract_candidate_name(resume_text):
28
+ name_match = re.search(r"([A-Z][a-z]+\s+[A-Z][a-z]+)", resume_text[:500])
29
+ if name_match:
30
+ return name_match.group(1)
31
+ return "Candidate"
32
+
33
+ def store_resume(text, user_id):
34
+ chunks = [text[i:i+512] for i in range(0, len(text), 512)]
35
+ for i, chunk in enumerate(chunks):
36
+ embedding = embedding_model.embed_query(chunk)
37
+ collection.add(
38
+ ids=[f"{user_id}-{i}"],
39
+ embeddings=[embedding],
40
+ metadatas=[{"text": chunk}]
41
+ )
42
+ return extract_candidate_name(text)
43
+
44
+ def retrieve_resume(user_id, query):
45
+ query_embedding = embedding_model.embed_query(query)
46
+ results = collection.query(query_embeddings=[query_embedding], n_results=3)
47
+ return "\n".join([doc["text"] for doc in results["metadatas"][0]])
48
+
49
+ def generate_groq_response(prompt, agent_type, temperature=0.7):
50
+ system_prompts = {
51
+ "zero_agent": """You are the initial interviewer. Your role is to warmly greet the candidate by name and ask general background questions to make them comfortable before transitioning to technical topics. Be conversational, friendly, and engaging. Focus on understanding their motivation, work history, and personality.""",
52
+ "technical_agent": """You are an expert technical interviewer. Analyze the candidate's resume thoroughly and ask highly relevant technical questions that demonstrate your understanding of their background. Your questions should be challenging but fair, focusing on their claimed skills and past projects. Phrase questions clearly and directly.""",
53
+ "clarification_agent": """You are a supportive interviewer who helps clarify questions when candidates need assistance. When a candidate seems confused or directly asks for clarification, explain the question in simpler terms with examples. If they give a partial answer, ask follow-up questions to help them elaborate. Your goal is to maintain conversation flow and help candidates showcase their knowledge.""",
54
+ "report_agent": """You are an interview assessment specialist. Create a detailed, constructive report of the interview without scoring or grading the candidate. Identify correct answers with green text and areas for improvement with red text. Focus on suggesting specific technical topics the candidate should study further rather than platforms or resources. Be encouraging and specific in your feedback."""
55
+ }
56
+
57
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
58
+ response = client.chat.completions.create(
59
+ model="llama-3.3-70b-versatile",
60
+ messages=[
61
+ {"role": "system", "content": system_prompts.get(agent_type, "You are an AI interview coach.")},
62
+ {"role": "user", "content": prompt}
63
+ ],
64
+ temperature=temperature,
65
+ max_tokens=800
66
+ )
67
+ return response.choices[0].message.content
68
+
69
+ def strip_markdown(text):
70
+ text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
71
+ text = re.sub(r'\*(.*?)\*', r'\1', text)
72
+ text = re.sub(r'`(.*?)`', r'\1', text)
73
+ text = re.sub(r'\[(.*?)\]\((.*?)\)', r'\1', text)
74
+ text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
75
+ text = re.sub(r'^>\s+', '', text, flags=re.MULTILINE)
76
+ text = re.sub(r'^\s*[-*_]{3,}\s*$', '', text, flags=re.MULTILINE)
77
+ text = re.sub(r'^\s*[-*+]\s+', 'β€’ ', text, flags=re.MULTILINE)
78
+ text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE)
79
+ return text
80
+
81
+ def strict_agent_monitor(candidate_response):
82
+ prompt = f"""
83
+ Candidate Response: "{candidate_response}"
84
+ Check for these behaviors strictly but fairly:
85
+ 1. Repeated gibberish or nonsensical keyboard smashing.
86
+ 2. Harsh, rude, or aggressive language.
87
+ 3. Profanity or clearly offensive content.
88
+ If clearly inappropriate (repeated profanity/aggression/gibberish), respond:
89
+ "INAPPROPRIATE: [reason]"
90
+ If minor awkwardness, occasional mistakes, or nervousness, respond simply:
91
+ "ACCEPTABLE"
92
+ Be forgiving, human-like, and flexibleβ€”only flag clear and serious issues.
93
+ Be human-like: allow up to two minor instances before marking responses as inappropriate.
94
+ Only flag as inappropriate after clear repeated offenses (3 or more times) or severe disrespect/profanity.
95
+ """
96
+ return generate_groq_response(prompt, "technical_agent", temperature=0.1)
97
+
98
+ # -------------------- Initialize Components --------------------
99
+ embedding_model = setup_embeddings()
100
+ collection = setup_chromadb()
101
+
102
+ # -------------------- Gradio Interface --------------------
103
+ class InterviewCoach:
104
+ def __init__(self):
105
+ self.user_id = str(uuid.uuid4())
106
+ self.interview_active = False
107
+ self.current_step = 0
108
+ self.interview_phase = "greeting"
109
+ self.questions = []
110
+ self.responses = []
111
+ self.candidate_name = "Candidate"
112
+ self.needs_clarification = False
113
+ self.clarification_response = None
114
+ self.uploaded_file = None
115
+
116
+ def process_resume(self, file):
117
+ self.uploaded_file = file
118
+ with open(file.name, "rb") as f:
119
+ resume_text = extract_text_from_resume(f)
120
+ self.candidate_name = store_resume(resume_text, self.user_id)
121
+ return f"Resume processed for {self.candidate_name}"
122
+
123
+ def start_interview(self):
124
+ if not self.uploaded_file:
125
+ return "Please upload a resume first", None
126
+
127
+ self.interview_active = True
128
+ self.current_step = 0
129
+ self.interview_phase = "greeting"
130
+ self.questions = []
131
+ self.responses = []
132
+
133
+ resume_data = retrieve_resume(self.user_id, "background experience")
134
+ greeting = zero_agent_greeting(resume_data, self.candidate_name)
135
+ self.questions.append(greeting)
136
+
137
+ return f"Interview started with {self.candidate_name}", greeting
138
+
139
+ def zero_agent_greeting(self, resume_data, candidate_name):
140
+ prompt = f"""
141
+ Resume Data: {resume_data}
142
+ Candidate Name: {candidate_name}
143
+
144
+ Generate a brief, warm greeting for {candidate_name}. The greeting should:
145
+ 1. Begin with "Hello [Candidate Name]"
146
+ 2. Very briefly mention something from their resume (one skill or experience)
147
+ 3. Ask ONE simple question about their most recent job or experience
148
+ 4. Keep it extremely concise (2-3 short sentences maximum)
149
+ """
150
+ return generate_groq_response(prompt, "zero_agent", temperature=0.7)
151
+
152
+ def technical_agent_question(self, resume_data, interview_history, question_count):
153
+ difficulty = "introductory" if question_count < 2 else "intermediate" if question_count < 4 else "advanced"
154
+
155
+ prompt = f"""
156
+ Resume Data: {resume_data}
157
+ Interview History: {interview_history}
158
+ Question Number: {question_count + 1}
159
+ Difficulty: {difficulty}
160
+
161
+ Generate a relevant technical interview question based on the candidate's resume.
162
+ """
163
+ return generate_groq_response(prompt, "technical_agent", temperature=0.7)
164
+
165
+ def clarification_agent_response(self, question, candidate_response, resume_data):
166
+ needs_clarification = any(phrase in candidate_response.lower() for phrase in
167
+ ["i don't understand", "can you explain", "not sure", "what do you mean",
168
+ "confused", "unclear", "can you clarify", "don't know what", "?"])
169
+
170
+ if needs_clarification:
171
+ prompt = f"""
172
+ Original Question: {question}
173
+ Candidate Response: {candidate_response}
174
+ Resume Data: {resume_data}
175
+
176
+ The candidate needs clarification. Your task is to:
177
+ 1. Acknowledge their confusion
178
+ 2. Explain the question in simpler terms
179
+ 3. Provide a concrete example to illustrate what you're asking
180
+ 4. Rephrase the question in a more approachable way
181
+
182
+ IMPORTANT: Respond in a direct, conversational manner WITHOUT any explanation of your reasoning.
183
+ """
184
+ return generate_groq_response(prompt, "clarification_agent", temperature=0.6)
185
+ else:
186
+ prompt = f"""
187
+ Original Question: {question}
188
+ Candidate Response: {candidate_response}
189
+ Resume Data: {resume_data}
190
+
191
+ Evaluate if this response is complete or needs a follow-up.
192
+ If the response is thorough and complete, respond with "COMPLETE".
193
+ If the response is partial or could benefit from elaboration, provide a specific follow-up question.
194
+ If the response is off-topic, provide a more specific version of the original question.
195
+
196
+ IMPORTANT: If providing a follow-up question, give ONLY the question itself without any explanation of why you're asking it.
197
+ """
198
+ follow_up = generate_groq_response(prompt, "clarification_agent", temperature=0.6)
199
+
200
+ if "COMPLETE" in follow_up:
201
+ return None
202
+ else:
203
+ question_match = re.search(r"(?:To help|I would|Let me|Could you|What|How|Why|Can you|Tell me|Describe|Explain).*\?", follow_up)
204
+ if question_match:
205
+ return question_match.group(0)
206
+ return follow_up
207
+
208
+ def report_agent_feedback(self, interview_data, resume_data):
209
+ questions_answers = "\n\n".join([
210
+ f"Q{i+1}: {qa['question']}\nAnswer: {qa['answer']}"
211
+ for i, qa in enumerate(interview_data)
212
+ ])
213
+
214
+ prompt = f"""
215
+ Resume Data: {resume_data}
216
+
217
+ Interview Transcript:
218
+ {questions_answers}
219
+
220
+ Generate a detailed, visually appealing interview report that:
221
+ 1. Analyzes each answer without scoring or grading
222
+ 2. Identifies correct information (prefix with "CORRECT: ")
223
+ 3. Identifies areas for improvement (prefix with "IMPROVE: ")
224
+ 4. Recommends 3-5 specific technical topics (not platforms) the candidate should focus on
225
+
226
+ Format guidelines:
227
+ - Use emojis to make sections more engaging (βœ… for correct points, πŸ’‘ for improvement areas)
228
+ - ABSOLUTELY NO MARKDOWN SYNTAX - use plain text only without asterisks, backticks, hashes, etc.
229
+ - Use simple formatting that works well in HTML
230
+ - For each question, provide concise bullet-point style feedback
231
+ - Keep language encouraging and constructive
232
+
233
+ Format the report with these sections:
234
+ - QUESTION ANALYSIS (for each question)
235
+ - KEY STRENGTHS
236
+ - FOCUS AREAS
237
+ - RECOMMENDED TOPICS
238
+
239
+ Do not include any numerical scores or grades.
240
+ """
241
+ feedback = generate_groq_response(prompt, "report_agent", temperature=0.7)
242
+ return strip_markdown(feedback)
243
+
244
+ def submit_response(self, answer):
245
+ if not self.interview_active:
246
+ return "Interview not active. Please start the interview first.", None, None
247
+
248
+ if not answer.strip():
249
+ return "Please enter a response.", None, None
250
+
251
+ appropriateness_check = strict_agent_monitor(answer)
252
+ if "INAPPROPRIATE:" in appropriateness_check:
253
+ reason = appropriateness_check.split("INAPPROPRIATE:")[1].strip()
254
+ self.interview_active = False
255
+ return f"⚠️ Interview Terminated: {reason}", None, None
256
+
257
+ current_question = self.questions[self.current_step]
258
+
259
+ if self.needs_clarification:
260
+ self.needs_clarification = False
261
+ self.responses[-1]['clarification'] = self.clarification_response
262
+ self.responses[-1]['clarification_response'] = answer
263
+ self.clarification_response = None
264
+
265
+ if self.interview_phase == "greeting":
266
+ self.interview_phase = "technical"
267
+ resume_data = retrieve_resume(self.user_id, "technical skills")
268
+ new_question = self.technical_agent_question(resume_data, "", 0)
269
+ self.questions.append(new_question)
270
+ self.current_step += 1
271
+ return None, new_question, None
272
+ elif len(self.responses) >= 6:
273
+ self.interview_active = False
274
+ return self.generate_final_report(), None, None
275
+ else:
276
+ interview_history = "\n".join([
277
+ f"Q: {item['question']}\nA: {item['answer']}"
278
+ for item in self.responses
279
+ ])
280
+ resume_data = retrieve_resume(self.user_id, "technical skills")
281
+ new_question = self.technical_agent_question(
282
+ resume_data,
283
+ interview_history,
284
+ len(self.responses) - 1
285
+ )
286
+ self.questions.append(new_question)
287
+ self.current_step += 1
288
+ return None, new_question, None
289
+ else:
290
+ self.responses.append({
291
+ 'question': current_question,
292
+ 'answer': answer
293
+ })
294
+
295
+ resume_data = retrieve_resume(self.user_id, current_question)
296
+ clarification = self.clarification_agent_response(
297
+ current_question,
298
+ answer,
299
+ resume_data
300
+ )
301
+
302
+ if clarification:
303
+ self.needs_clarification = True
304
+ self.clarification_response = clarification
305
+ return None, clarification, None
306
+ else:
307
+ if self.interview_phase == "greeting":
308
+ self.interview_phase = "technical"
309
+ resume_data = retrieve_resume(self.user_id, "technical skills")
310
+ new_question = self.technical_agent_question(resume_data, "", 0)
311
+ self.questions.append(new_question)
312
+ self.current_step += 1
313
+ return None, new_question, None
314
+ elif len(self.responses) >= 6:
315
+ self.interview_active = False
316
+ return self.generate_final_report(), None, None
317
+ else:
318
+ interview_history = "\n".join([
319
+ f"Q: {item['question']}\nA: {item['answer']}"
320
+ for item in self.responses
321
+ ])
322
+ resume_data = retrieve_resume(self.user_id, "technical skills")
323
+ new_question = self.technical_agent_question(
324
+ resume_data,
325
+ interview_history,
326
+ len(self.responses) - 1
327
+ )
328
+ self.questions.append(new_question)
329
+ self.current_step += 1
330
+ return None, new_question, None
331
+
332
+ def generate_final_report(self):
333
+ resume_data = retrieve_resume(self.user_id, "complete profile")
334
+ feedback = self.report_agent_feedback(self.responses, resume_data)
335
+
336
+ processed_feedback = []
337
+ for qa_index, qa in enumerate(self.responses):
338
+ question_section = f"Q{qa_index+1}: {qa['question']}"
339
+ answer_section = f"Answer: {qa['answer']}"
340
+
341
+ correct_parts = re.findall(r"CORRECT:(.*?)(?=IMPROVE:|$)", feedback, re.DOTALL)
342
+ improve_parts = re.findall(r"IMPROVE:(.*?)(?=CORRECT:|$)", feedback, re.DOTALL)
343
+
344
+ correct_html = ""
345
+ if qa_index < len(correct_parts) and correct_parts[qa_index].strip():
346
+ correct_text = strip_markdown(correct_parts[qa_index].strip())
347
+ correct_html = f"""
348
+ <div style="color: #4CD964; border-left: 4px solid #4CD964; padding-left: 1rem; margin: 1rem 0;">
349
+ <h4 style="color: #4CD964; margin:0;">βœ… Strong Points</h4>
350
+ <p style="color: #CCCCCC; margin-top:0.5rem;">{correct_text}</p>
351
+ </div>
352
+ """
353
+
354
+ improve_html = ""
355
+ if qa_index < len(improve_parts) and improve_parts[qa_index].strip():
356
+ improve_html = f"""
357
+ <div style="color: #FF3B30; border-left: 4px solid #FF3B30; padding-left: 1rem; margin: 1rem 0;">
358
+ <h4 style="color: #FF3B30; margin:0;">πŸ’‘ Areas to Develop</h4>
359
+ <p style="color: #CCCCCC; margin-top:0.5rem;">{improve_parts[qa_index].strip()}</p>
360
+ </div>
361
+ """
362
+
363
+ processed_feedback.append({
364
+ "question": question_section,
365
+ "answer": answer_section,
366
+ "correct_html": correct_html,
367
+ "improve_html": improve_html
368
+ })
369
+
370
+ topic_match = re.search(r"RECOMMENDED TOPICS:(.*?)(?=$)", feedback, re.DOTALL)
371
+ topics = []
372
+ if topic_match:
373
+ topics_text = topic_match.group(1).strip()
374
+ topics = [topic.strip() for topic in re.split(r'\d+\.\s+', topics_text) if topic.strip()]
375
+ topics = [topic for topic in topics if len(topic) > 3]
376
+
377
+ report_html = """
378
+ <div style="background:#1A1A1A; border-radius:15px; padding:2rem; margin:1rem 0; border:1px solid #333333;">
379
+ <h3 style='color: #4A90E2; margin-bottom: 1.5rem;'>Interview Summary Report</h3>
380
+ <div style="background:#2D2D2D; padding:1.5rem; border-radius:10px; margin:2rem 0;">
381
+ <h4 style="margin:0; color:#FFFFFF;">Interview Overview</h4>
382
+ <p style="margin:1rem 0 0 0; color:#CCCCCC;">Below is a detailed breakdown of your interview responses with constructive feedback to help you improve your technical skills.</p>
383
+ </div>
384
+ <h4 style='color: #FFFFFF; margin-bottom:1rem;'>Question-by-Question Analysis</h4>
385
+ """
386
+
387
+ for idx, response in enumerate(processed_feedback):
388
+ report_html += f"""
389
+ <details style='margin-bottom: 1.5rem; background:#2D2D2D; padding:1rem; border-radius:8px;'>
390
+ <summary style='color: #FFFFFF; cursor: pointer;'>Question {idx+1}</summary>
391
+ <div style='margin-top: 1rem;'>
392
+ <p style='font-weight: 500; color: #FFFFFF; font-size: 1.1rem;'>❝{response['question']}❞</p>
393
+
394
+ <div style='background: #333333; padding:1rem; border-radius:8px; margin:1rem 0;'>
395
+ <p style='color: #888888; margin:0;'>Your Answer:</p>
396
+ <p style='color: #FFFFFF; margin:0.5rem 0;'>{response['answer']}</p>
397
+ </div>
398
+
399
+ {response['correct_html']}
400
+ {response['improve_html']}
401
+ </div>
402
+ </details>
403
+ """
404
+
405
+ if topics:
406
+ report_html += """
407
+ <h4 style='color: #FFFFFF; margin:2rem 0 1rem 0;'>πŸ“š Focus Areas for Improvement</h4>
408
+ <div style="background:#2D2D2D; padding:1.5rem; border-radius:10px; margin:1rem 0;">
409
+ <h4 style="margin:0; color:#FFFFFF;">Recommended Topics to Study</h4>
410
+ <p style="margin:1rem 0; color:#CCCCCC;">Based on your interview responses, we recommend focusing on these key areas:</p>
411
+ <div style="margin-top:1rem;">
412
+ """
413
+
414
+ for topic in topics:
415
+ report_html += f"""
416
+ <span style="display: inline-block; background: #333333; padding: 5px 10px; margin: 5px; border-radius: 15px; font-size: 0.8rem;">{topic}</span>
417
+ """
418
+
419
+ report_html += """
420
+ </div>
421
+ </div>
422
+ """
423
+
424
+ report_html += "</div>"
425
+ return report_html
426
+
427
+ # Create the interface
428
+ coach = InterviewCoach()
429
+
430
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
431
+ gr.Markdown("# πŸ’Ό AI-Powered Interview Coach")
432
+ gr.Markdown("Upload your resume for a personalized mock interview session")
433
+
434
+ with gr.Row():
435
+ with gr.Column():
436
+ file_input = gr.File(label="Upload Resume (PDF or TXT)", file_types=[".pdf", ".txt"])
437
+ upload_btn = gr.Button("Upload Resume")
438
+ upload_status = gr.Textbox(label="Upload Status", interactive=False)
439
+
440
+ start_btn = gr.Button("πŸš€ Start Interview Session")
441
+ interview_status = gr.Textbox(label="Interview Status", interactive=False)
442
+
443
+ question_display = gr.Textbox(label="Current Question", interactive=False)
444
+ answer_input = gr.Textbox(label="Your Response", lines=5)
445
+ submit_btn = gr.Button("Submit Response")
446
+
447
+ clarification_display = gr.Textbox(label="Clarification", visible=False, interactive=False)
448
+
449
+ report_display = gr.HTML(label="Interview Report")
450
+
451
+ def toggle_clarification(needs_clarification):
452
+ return gr.Textbox(visible=needs_clarification)
453
+
454
+ # Event handlers
455
+ upload_btn.click(
456
+ fn=coach.process_resume,
457
+ inputs=file_input,
458
+ outputs=upload_status
459
+ )
460
+
461
+ start_btn.click(
462
+ fn=coach.start_interview,
463
+ outputs=[interview_status, question_display]
464
+ )
465
+
466
+ submit_btn.click(
467
+ fn=coach.submit_response,
468
+ inputs=answer_input,
469
+ outputs=[interview_status, question_display, report_display]
470
+ )
471
+
472
+ if __name__ == "__main__":
473
+ demo.launch()