usmanyousaf commited on
Commit
a04bc03
Β·
verified Β·
1 Parent(s): a58e5b1

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +668 -0
app.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
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
+ # -------------------- Configuration --------------------
10
+ st.set_page_config(
11
+ page_title="AI Interview Coach",
12
+ page_icon="πŸ’Ό",
13
+ layout="centered",
14
+ initial_sidebar_state="collapsed"
15
+ )
16
+
17
+ # Custom CSS with Dark Theme
18
+
19
+
20
+ st.markdown("""
21
+ <style>
22
+ .main {background-color: #121212; color: #ffffff;}
23
+ .stButton>button {background-color: #4A90E2; color: white; border-radius: 8px; padding: 0.5rem 1rem;}
24
+ .question-card {background: #1A1A1A; border-radius: 15px; padding: 2rem; margin: 1.5rem 0; border: 1px solid #333333; animation: fadeIn 0.5s ease-in;}
25
+ .welcome-card {background: #1A1A1A; border-radius: 15px; padding: 2rem; margin: 1.5rem 0; border: 1px solid #4A90E2; animation: glow 2s infinite alternate;}
26
+ .final-report {background: #1A1A1A; border-radius: 15px; padding: 2rem; margin: 1rem 0; border: 1px solid #333333;}
27
+ .feedback-card {background: #2D2D2D; border-left: 4px solid #4A90E2; border-radius: 8px; padding: 1.5rem; margin: 1rem 0;}
28
+ .resource-card {background: #2D2D2D; border-radius: 10px; padding: 1rem; margin: 1rem 0; animation: slideIn 0.5s ease-out;}
29
+ .correct-answer {color: #4CD964; border-left: 4px solid #4CD964; padding-left: 1rem; margin: 1rem 0;}
30
+ .wrong-answer {color: #FF3B30; border-left: 4px solid #FF3B30; padding-left: 1rem; margin: 1rem 0;}
31
+ .topic-chip {display: inline-block; background: #333333; padding: 5px 10px; margin: 5px; border-radius: 15px; font-size: 0.8rem;}
32
+ .stTextInput>div>div>input {background-color: #2D2D2D !important; color: #FFFFFF !important; border-radius: 8px;}
33
+ .stTextArea>div>div>textarea {background-color: #2D2D2D !important; color: #FFFFFF !important; border-radius: 8px;}
34
+
35
+ /* New Enhanced Styles */
36
+ .report-question {
37
+ background: linear-gradient(145deg, #1E1E1E 0%, #2D2D2D 100%);
38
+ border-radius: 15px;
39
+ padding: 1.5rem;
40
+ margin: 1.5rem 0;
41
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
42
+ transition: transform 0.3s ease;
43
+ border-left: 4px solid #4A90E2;
44
+ }
45
+ .report-question:hover {
46
+ transform: translateY(-3px);
47
+ }
48
+ .question-header {
49
+ color: #4A90E2;
50
+ font-size: 1.2rem;
51
+ margin-bottom: 1rem;
52
+ padding-bottom: 0.5rem;
53
+ border-bottom: 1px solid #333333;
54
+ display: flex;
55
+ align-items: center;
56
+ gap: 10px;
57
+ }
58
+ .user-answer {
59
+ background: #333333;
60
+ padding: 1rem;
61
+ border-radius: 8px;
62
+ margin: 1rem 0;
63
+ position: relative;
64
+ }
65
+ .user-answer::before {
66
+ content: "πŸ—£οΈ Your Answer";
67
+ font-size: 0.8rem;
68
+ color: #888888;
69
+ position: absolute;
70
+ top: -10px;
71
+ left: 15px;
72
+ background: #2D2D2D;
73
+ padding: 2px 8px;
74
+ border-radius: 4px;
75
+ }
76
+ .analysis-section {
77
+ padding: 1rem;
78
+ border-radius: 8px;
79
+ margin: 1rem 0;
80
+ }
81
+ .strength-badge {
82
+ background: rgba(76, 217, 100, 0.15);
83
+ color: #4CD964;
84
+ padding: 8px 15px;
85
+ border-radius: 20px;
86
+ display: inline-flex;
87
+ align-items: center;
88
+ gap: 8px;
89
+ margin: 5px;
90
+ }
91
+ .improvement-badge {
92
+ background: rgba(255, 59, 48, 0.15);
93
+ color: #FF3B30;
94
+ padding: 8px 15px;
95
+ border-radius: 20px;
96
+ display: inline-flex;
97
+ align-items: center;
98
+ gap: 8px;
99
+ margin: 5px;
100
+ }
101
+ .topic-pill {
102
+ background: rgba(74, 144, 226, 0.15);
103
+ color: #4A90E2;
104
+ padding: 8px 20px;
105
+ border-radius: 20px;
106
+ margin: 5px;
107
+ display: inline-block;
108
+ transition: all 0.3s ease;
109
+ }
110
+ .topic-pill:hover {
111
+ transform: scale(1.05);
112
+ background: rgba(74, 144, 226, 0.25);
113
+ }
114
+ @keyframes fadeIn {
115
+ from {opacity: 0; transform: translateY(20px);}
116
+ to {opacity: 1; transform: translateY(0);}
117
+ }
118
+ @keyframes slideIn {
119
+ from {transform: translateX(-20px); opacity: 0;}
120
+ to {transform: translateX(0); opacity: 1;}
121
+ }
122
+ @keyframes glow {
123
+ 0% {box-shadow: 0 0 5px rgba(74, 144, 226, 0.5);}
124
+ 100% {box-shadow: 0 0 20px rgba(74, 144, 226, 0.8);}
125
+ }
126
+ </style>
127
+ """, unsafe_allow_html=True)
128
+
129
+
130
+
131
+ # -------------------- Core Functions --------------------
132
+ @st.cache_resource
133
+ def setup_embeddings():
134
+ return HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
135
+
136
+ @st.cache_resource
137
+ def setup_chromadb():
138
+ client = chromadb.PersistentClient(path="./chroma_db")
139
+ return client.get_or_create_collection(name="resumes")
140
+
141
+ def extract_text_from_resume(file):
142
+ if file.type == "application/pdf":
143
+ doc = fitz.open(stream=file.read(), filetype="pdf")
144
+ return "\n".join([page.get_text("text") for page in doc])
145
+ elif file.type == "text/plain":
146
+ return file.read().decode("utf-8")
147
+ return ""
148
+
149
+ def extract_candidate_name(resume_text):
150
+ # Simple regex to extract names (look for first capitalized words)
151
+ name_match = re.search(r"([A-Z][a-z]+\s+[A-Z][a-z]+)", resume_text[:500])
152
+ if name_match:
153
+ return name_match.group(1)
154
+ return "Candidate"
155
+
156
+ def store_resume(text, user_id):
157
+ chunks = [text[i:i+512] for i in range(0, len(text), 512)]
158
+ for i, chunk in enumerate(chunks):
159
+ embedding = embedding_model.embed_query(chunk)
160
+ collection.add(
161
+ ids=[f"{user_id}-{i}"],
162
+ embeddings=[embedding],
163
+ metadatas=[{"text": chunk}]
164
+ )
165
+ return extract_candidate_name(text)
166
+
167
+ def retrieve_resume(user_id, query):
168
+ query_embedding = embedding_model.embed_query(query)
169
+ results = collection.query(query_embeddings=[query_embedding], n_results=3)
170
+ return "\n".join([doc["text"] for doc in results["metadatas"][0]])
171
+
172
+ def generate_groq_response(prompt, agent_type, temperature=0.7):
173
+ # Different system prompts based on agent type
174
+ system_prompts = {
175
+ "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.""",
176
+
177
+ "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.""",
178
+
179
+ "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.""",
180
+
181
+ "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."""
182
+ }
183
+
184
+ client = Groq(api_key="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")
185
+ response = client.chat.completions.create(
186
+ model="llama-3.3-70b-versatile",
187
+ messages=[
188
+ {"role": "system", "content": system_prompts.get(agent_type, "You are an AI interview coach.")},
189
+ {"role": "user", "content": prompt}
190
+ ],
191
+ temperature=temperature,
192
+ max_tokens=800
193
+ )
194
+ return response.choices[0].message.content
195
+
196
+ # -------------------- Agent Functions --------------------
197
+ def zero_agent_greeting(resume_data, candidate_name):
198
+ prompt = f"""
199
+ Resume Data: {resume_data}
200
+ Candidate Name: {candidate_name}
201
+
202
+ Generate a brief, warm greeting for {candidate_name}. The greeting should:
203
+ 1. Begin with "Hello [Candidate Name]"
204
+ 2. Very briefly mention something from their resume (one skill or experience)
205
+ 3. Ask ONE simple question about their most recent job or experience
206
+ 4. Keep it extremely concise (2-3 short sentences maximum)
207
+
208
+ The greeting must be brief as it will be converted to voice later.
209
+ """
210
+ return generate_groq_response(prompt, "zero_agent", temperature=0.7)
211
+
212
+ def technical_agent_question(resume_data, interview_history, question_count):
213
+ difficulty = "introductory" if question_count < 2 else "intermediate" if question_count < 4 else "advanced"
214
+
215
+ prompt = f"""
216
+ Resume Data: {resume_data}
217
+ Interview History: {interview_history}
218
+ Question Number: {question_count + 1}
219
+ Difficulty: {difficulty}
220
+
221
+ Generate a relevant technical interview question based on the candidate's resume. The question should:
222
+ 1. Be specific to skills or experiences mentioned in their resume
223
+ 2. Feel like it's coming from someone who has read their background
224
+ 3. Be appropriately challenging based on their experience level
225
+ 4. Be directly relevant to their field
226
+ 5. Be clearly phrased as a question (no preambles or explanations)
227
+ """
228
+ return generate_groq_response(prompt, "technical_agent", temperature=0.7)
229
+
230
+ def clarification_agent_response(question, candidate_response, resume_data):
231
+ # Check if the response indicates confusion or asks for clarification
232
+ needs_clarification = any(phrase in candidate_response.lower() for phrase in
233
+ ["i don't understand", "can you explain", "not sure", "what do you mean",
234
+ "confused", "unclear", "can you clarify", "don't know what", "?"])
235
+
236
+ if needs_clarification:
237
+ prompt = f"""
238
+ Original Question: {question}
239
+ Candidate Response: {candidate_response}
240
+ Resume Data: {resume_data}
241
+
242
+ The candidate needs clarification. Your task is to:
243
+ 1. Acknowledge their confusion
244
+ 2. Explain the question in simpler terms
245
+ 3. Provide a concrete example to illustrate what you're asking
246
+ 4. Rephrase the question in a more approachable way
247
+
248
+ IMPORTANT: Respond in a direct, conversational manner WITHOUT any explanation of your reasoning.
249
+ """
250
+ return generate_groq_response(prompt, "clarification_agent", temperature=0.6)
251
+ else:
252
+ # Check if the answer is incomplete and needs a follow-up
253
+ prompt = f"""
254
+ Original Question: {question}
255
+ Candidate Response: {candidate_response}
256
+ Resume Data: {resume_data}
257
+
258
+ Evaluate if this response is complete or needs a follow-up.
259
+ If the response is thorough and complete, respond with "COMPLETE".
260
+ If the response is partial or could benefit from elaboration, provide a specific follow-up question.
261
+ If the response is off-topic, provide a more specific version of the original question.
262
+
263
+ IMPORTANT: If providing a follow-up question, give ONLY the question itself without any explanation of why you're asking it.
264
+ """
265
+ follow_up = generate_groq_response(prompt, "clarification_agent", temperature=0.6)
266
+
267
+ if "COMPLETE" in follow_up:
268
+ return None
269
+ else:
270
+ # Filter out any reasoning or explanation before the question
271
+ # This regex attempts to find the actual question
272
+ question_match = re.search(r"(?:To help|I would|Let me|Could you|What|How|Why|Can you|Tell me|Describe|Explain).*\?", follow_up)
273
+ if question_match:
274
+ return question_match.group(0)
275
+ return follow_up
276
+
277
+ def strip_markdown(text):
278
+ """Remove markdown formatting from text"""
279
+ # Remove bold/italic markers
280
+ text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
281
+ text = re.sub(r'\*(.*?)\*', r'\1', text)
282
+ # Remove backticks
283
+ text = re.sub(r'`(.*?)`', r'\1', text)
284
+ # Remove links
285
+ text = re.sub(r'\[(.*?)\]\((.*?)\)', r'\1', text)
286
+ # Remove headers
287
+ text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
288
+ # Remove blockquotes
289
+ text = re.sub(r'^>\s+', '', text, flags=re.MULTILINE)
290
+ # Remove horizontal rules
291
+ text = re.sub(r'^\s*[-*_]{3,}\s*$', '', text, flags=re.MULTILINE)
292
+ # Remove list markers
293
+ text = re.sub(r'^\s*[-*+]\s+', 'β€’ ', text, flags=re.MULTILINE)
294
+ text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE)
295
+
296
+ return text
297
+
298
+ def report_agent_feedback(interview_data, resume_data):
299
+ questions_answers = "\n\n".join([
300
+ f"Q{i+1}: {qa['question']}\nAnswer: {qa['answer']}"
301
+ for i, qa in enumerate(interview_data)
302
+ ])
303
+
304
+ prompt = f"""
305
+ Resume Data: {resume_data}
306
+
307
+ Interview Transcript:
308
+ {questions_answers}
309
+
310
+ Generate a detailed, visually appealing interview report that:
311
+ 1. Analyzes each answer without scoring or grading
312
+ 2. Identifies correct information (prefix with "CORRECT: ")
313
+ 3. Identifies areas for improvement (prefix with "IMPROVE: ")
314
+ 4. Recommends 3-5 specific technical topics (not platforms) the candidate should focus on
315
+
316
+ Format guidelines:
317
+ - Use emojis to make sections more engaging (βœ… for correct points, πŸ’‘ for improvement areas)
318
+ - ABSOLUTELY NO MARKDOWN SYNTAX - use plain text only without asterisks, backticks, hashes, etc.
319
+ - Use simple formatting that works well in HTML
320
+ - For each question, provide concise bullet-point style feedback
321
+ - Keep language encouraging and constructive
322
+
323
+ Format the report with these sections:
324
+ - QUESTION ANALYSIS (for each question)
325
+ - KEY STRENGTHS
326
+ - FOCUS AREAS
327
+ - RECOMMENDED TOPICS
328
+
329
+ Do not include any numerical scores or grades.
330
+ """
331
+ feedback = generate_groq_response(prompt, "report_agent", temperature=0.7)
332
+ return strip_markdown(feedback) # Apply the markdown stripper
333
+
334
+ def strict_agent_monitor(candidate_response):
335
+ prompt = f"""
336
+ Candidate Response: "{candidate_response}"
337
+
338
+ Check for these behaviors strictly but fairly:
339
+ 1. Repeated gibberish or nonsensical keyboard smashing.
340
+ 2. Harsh, rude, or aggressive language.
341
+ 3. Profanity or clearly offensive content.
342
+
343
+ If clearly inappropriate (repeated profanity/aggression/gibberish), respond:
344
+ "INAPPROPRIATE: [reason]"
345
+
346
+ If minor awkwardness, occasional mistakes, or nervousness, respond simply:
347
+ "ACCEPTABLE"
348
+
349
+ Be forgiving, human-like, and flexibleβ€”only flag clear and serious issues.
350
+
351
+ Be human-like: allow up to two minor instances before marking responses as inappropriate.
352
+ Only flag as inappropriate after clear repeated offenses (3 or more times) or severe disrespect/profanity.
353
+ """
354
+ return generate_groq_response(prompt, "technical_agent", temperature=0.1)
355
+
356
+ # -------------------- Initialize Components --------------------
357
+ embedding_model = setup_embeddings()
358
+ collection = setup_chromadb()
359
+
360
+ # -------------------- Session State --------------------
361
+ if "user_id" not in st.session_state:
362
+ st.session_state.user_id = str(uuid.uuid4())
363
+ if "interview_active" not in st.session_state:
364
+ st.session_state.interview_active = False
365
+ if "current_step" not in st.session_state:
366
+ st.session_state.current_step = 0
367
+ if "interview_phase" not in st.session_state:
368
+ st.session_state.interview_phase = "greeting" # greeting, technical, wrap_up
369
+ if "questions" not in st.session_state:
370
+ st.session_state.questions = []
371
+ if "responses" not in st.session_state:
372
+ st.session_state.responses = []
373
+ if "candidate_name" not in st.session_state:
374
+ st.session_state.candidate_name = "Candidate"
375
+ if "needs_clarification" not in st.session_state:
376
+ st.session_state.needs_clarification = False
377
+ if "clarification_response" not in st.session_state:
378
+ st.session_state.clarification_response = None
379
+
380
+ # -------------------- UI Components --------------------
381
+ def show_message(message, is_question=True):
382
+ style_class = "question-card" if is_question else "feedback-card"
383
+ st.markdown(f"""
384
+ <div class="{style_class}">
385
+ <p style="color: #FFFFFF;">{message}</p>
386
+ </div>
387
+ """, unsafe_allow_html=True)
388
+
389
+ def show_welcome(greeting):
390
+ st.markdown(f"""
391
+ <div class="welcome-card">
392
+ <h3 style="color: #4A90E2; margin-bottom: 1rem;">πŸ‘‹ Welcome to Your Interview Session</h3>
393
+ <p style="color: #FFFFFF;">{greeting}</p>
394
+ </div>
395
+ """, unsafe_allow_html=True)
396
+
397
+ # -------------------- Main Application Flow --------------------
398
+ st.title("πŸ’Ό AI-Powered Interview Coach")
399
+ st.markdown("Upload your resume for a personalized mock interview session")
400
+
401
+ # Resume Upload Section
402
+ with st.expander("πŸ“„ Upload Your Resume", expanded=True):
403
+ uploaded_file = st.file_uploader("Choose PDF or TXT file", type=["pdf", "txt"])
404
+ if uploaded_file and not st.session_state.interview_active:
405
+ with st.spinner("Processing your resume..."):
406
+ resume_text = extract_text_from_resume(uploaded_file)
407
+ st.session_state.candidate_name = store_resume(resume_text, st.session_state.user_id)
408
+ st.success("Resume analysis completed!")
409
+
410
+ # Interview Control
411
+ if not st.session_state.interview_active and uploaded_file:
412
+ if st.button("πŸš€ Start Interview Session"):
413
+ st.session_state.interview_active = True
414
+ st.session_state.current_step = 0
415
+ st.session_state.interview_phase = "greeting"
416
+ st.session_state.questions = []
417
+ st.session_state.responses = []
418
+ st.rerun()
419
+
420
+ # Interview Session
421
+ if st.session_state.interview_active:
422
+ # Greeting Phase
423
+ if st.session_state.interview_phase == "greeting" and not st.session_state.questions:
424
+ with st.spinner("Preparing your interview..."):
425
+ resume_data = retrieve_resume(st.session_state.user_id, "background experience")
426
+ greeting = zero_agent_greeting(resume_data, st.session_state.candidate_name)
427
+ st.session_state.questions.append(greeting)
428
+ show_welcome(greeting)
429
+
430
+ # Show current message/question
431
+ if st.session_state.needs_clarification and st.session_state.clarification_response:
432
+ show_message(st.session_state.clarification_response, is_question=True)
433
+ elif st.session_state.questions and st.session_state.current_step < len(st.session_state.questions):
434
+ current_question = st.session_state.questions[st.session_state.current_step]
435
+ if st.session_state.current_step > 0 or st.session_state.interview_phase != "greeting":
436
+ show_message(current_question, is_question=True)
437
+
438
+ # Answer input
439
+ answer = st.text_area(
440
+ "Your Response:",
441
+ key=f"answer_{st.session_state.current_step}_{st.session_state.needs_clarification}",
442
+ height=150,
443
+ placeholder="Type your response here..."
444
+ )
445
+
446
+ if st.button("Submit Response"):
447
+ if answer.strip():
448
+ with st.spinner("Processing your response..."):
449
+ appropriateness_check = strict_agent_monitor(answer)
450
+ if "INAPPROPRIATE:" in appropriateness_check:
451
+ reason = appropriateness_check.split("INAPPROPRIATE:")[1].strip()
452
+
453
+ # End the interview with a popup
454
+ st.session_state.interview_active = False
455
+ st.error(f"⚠️ Interview Terminated")
456
+
457
+ st.markdown(f"""
458
+ <div style="background:#FF3B30; padding:1.5rem; border-radius:10px; color:white; text-align:center;">
459
+ <h3 style="margin:0 0 1rem 0;">Interview Terminated</h3>
460
+ <p style="margin:0;">{reason}</p>
461
+ <p style="margin:1rem 0 0 0; font-size:0.9rem;">Professional communication is essential in interview settings.
462
+ Please restart the interview and maintain appropriate professional discourse.</p>
463
+ </div>
464
+ """, unsafe_allow_html=True)
465
+
466
+ # No further processing needed
467
+ st.rerun()
468
+
469
+ current_question = st.session_state.questions[st.session_state.current_step]
470
+
471
+ # Handle clarification request if needed
472
+ if st.session_state.needs_clarification:
473
+ st.session_state.needs_clarification = False
474
+ st.session_state.responses[-1]['clarification'] = st.session_state.clarification_response
475
+ st.session_state.responses[-1]['clarification_response'] = answer
476
+ st.session_state.clarification_response = None
477
+
478
+ # Move to next question
479
+ if st.session_state.interview_phase == "greeting":
480
+ st.session_state.interview_phase = "technical"
481
+ resume_data = retrieve_resume(st.session_state.user_id, "technical skills")
482
+ new_question = technical_agent_question(resume_data, "", 0)
483
+ st.session_state.questions.append(new_question)
484
+ st.session_state.current_step += 1
485
+ elif len(st.session_state.responses) >= 6: # Limit to 5 technical questions + greeting
486
+ st.session_state.interview_active = False
487
+ else:
488
+ interview_history = "\n".join([
489
+ f"Q: {item['question']}\nA: {item['answer']}"
490
+ for item in st.session_state.responses
491
+ ])
492
+ resume_data = retrieve_resume(st.session_state.user_id, "technical skills")
493
+ new_question = technical_agent_question(
494
+ resume_data,
495
+ interview_history,
496
+ len(st.session_state.responses) - 1
497
+ )
498
+ st.session_state.questions.append(new_question)
499
+ st.session_state.current_step += 1
500
+ else:
501
+ # Store the response
502
+ st.session_state.responses.append({
503
+ 'question': current_question,
504
+ 'answer': answer
505
+ })
506
+
507
+ # Check if clarification is needed
508
+ resume_data = retrieve_resume(st.session_state.user_id, current_question)
509
+ clarification = clarification_agent_response(
510
+ current_question,
511
+ answer,
512
+ resume_data
513
+ )
514
+
515
+ if clarification:
516
+ st.session_state.needs_clarification = True
517
+ st.session_state.clarification_response = clarification
518
+ else:
519
+ # No clarification needed, proceed to next question
520
+ if st.session_state.interview_phase == "greeting":
521
+ st.session_state.interview_phase = "technical"
522
+ resume_data = retrieve_resume(st.session_state.user_id, "technical skills")
523
+ new_question = technical_agent_question(resume_data, "", 0)
524
+ st.session_state.questions.append(new_question)
525
+ st.session_state.current_step += 1
526
+ elif len(st.session_state.responses) >= 6: # Limit to 5 technical questions + greeting
527
+ st.session_state.interview_active = False
528
+ else:
529
+ interview_history = "\n".join([
530
+ f"Q: {item['question']}\nA: {item['answer']}"
531
+ for item in st.session_state.responses
532
+ ])
533
+ resume_data = retrieve_resume(st.session_state.user_id, "technical skills")
534
+ new_question = technical_agent_question(
535
+ resume_data,
536
+ interview_history,
537
+ len(st.session_state.responses) - 1
538
+ )
539
+ st.session_state.questions.append(new_question)
540
+ st.session_state.current_step += 1
541
+
542
+ st.rerun()
543
+
544
+ # Final Report
545
+ if not st.session_state.interview_active and st.session_state.responses:
546
+ st.balloons()
547
+ st.markdown("---")
548
+ st.subheader("πŸ“Š Interview Feedback Report")
549
+
550
+ with st.spinner("Generating comprehensive feedback..."):
551
+ resume_data = retrieve_resume(st.session_state.user_id, "complete profile")
552
+ feedback = report_agent_feedback(st.session_state.responses, resume_data)
553
+
554
+ # Process the feedback to extract correct/improve sections
555
+ processed_feedback = []
556
+ for qa_index, qa in enumerate(st.session_state.responses):
557
+ question_section = f"Q{qa_index+1}: {qa['question']}"
558
+ answer_section = f"Answer: {qa['answer']}"
559
+
560
+ # Find analysis for this question
561
+ correct_parts = re.findall(r"CORRECT:(.*?)(?=IMPROVE:|$)", feedback, re.DOTALL)
562
+ improve_parts = re.findall(r"IMPROVE:(.*?)(?=CORRECT:|$)", feedback, re.DOTALL)
563
+
564
+ correct_html = ""
565
+ if qa_index < len(correct_parts) and correct_parts[qa_index].strip():
566
+ correct_text = strip_markdown(correct_parts[qa_index].strip())
567
+ correct_html = f"""
568
+ <div class="correct-answer">
569
+ <h4 style="color: #4CD964; margin:0;">βœ… Strong Points</h4>
570
+ <p style="color: #CCCCCC; margin-top:0.5rem;">{correct_text}</p>
571
+ </div>
572
+ """
573
+
574
+ improve_html = ""
575
+ if qa_index < len(improve_parts) and improve_parts[qa_index].strip():
576
+ improve_html = f"""
577
+ <div class="wrong-answer">
578
+ <h4 style="color: #FF3B30; margin:0;">πŸ’‘ Areas to Develop</h4>
579
+ <p style="color: #CCCCCC; margin-top:0.5rem;">{improve_parts[qa_index].strip()}</p>
580
+ </div>
581
+ """
582
+
583
+ processed_feedback.append({
584
+ "question": question_section,
585
+ "answer": answer_section,
586
+ "correct_html": correct_html,
587
+ "improve_html": improve_html
588
+ })
589
+
590
+ # Extract recommended topics
591
+ topic_match = re.search(r"RECOMMENDED TOPICS:(.*?)(?=$)", feedback, re.DOTALL)
592
+ topics = []
593
+ if topic_match:
594
+ topics_text = topic_match.group(1).strip()
595
+ topics = [topic.strip() for topic in re.split(r'\d+\.\s+', topics_text) if topic.strip()]
596
+ topics = [topic for topic in topics if len(topic) > 3] # Filter out short/empty topics
597
+
598
+ with st.container():
599
+ st.markdown("""
600
+ <div class='final-report'>
601
+ <h3 style='color: #4A90E2; margin-bottom: 1.5rem;'>Interview Summary Report</h3>
602
+ """, unsafe_allow_html=True)
603
+
604
+ # Interview Overview
605
+ st.markdown("""
606
+ <div style="background:#2D2D2D; padding:1.5rem; border-radius:10px; margin:2rem 0;">
607
+ <h4 style="margin:0; color:#FFFFFF;">Interview Overview</h4>
608
+ <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>
609
+ </div>
610
+ """, unsafe_allow_html=True)
611
+
612
+ # Detailed Responses
613
+ st.markdown("<h4 style='color: #FFFFFF; margin-bottom:1rem;'>Question-by-Question Analysis</h4>", unsafe_allow_html=True)
614
+ for idx, response in enumerate(processed_feedback):
615
+ with st.expander(f"Question {idx+1}", expanded=False):
616
+ st.markdown(f"""
617
+ <div style='margin-bottom: 1.5rem;'>
618
+ <p style='font-weight: 500; color: #FFFFFF; font-size: 1.1rem;'>❝{response['question']}❞</p>
619
+
620
+ <div style='background: #333333; padding:1rem; border-radius:8px; margin:1rem 0;'>
621
+ <p style='color: #888888; margin:0;'>Your Answer:</p>
622
+ <p style='color: #FFFFFF; margin:0.5rem 0;'>{response['answer']}</p>
623
+ </div>
624
+
625
+ {response['correct_html']}
626
+ {response['improve_html']}
627
+ </div>
628
+ """, unsafe_allow_html=True)
629
+
630
+ # Improvement Recommendations
631
+ st.markdown("<h4 style='color: #FFFFFF; margin:2rem 0 1rem 0;'>πŸ“š Focus Areas for Improvement</h4>", unsafe_allow_html=True)
632
+
633
+ if topics:
634
+ st.markdown("""
635
+ <div style="background:#2D2D2D; padding:1.5rem; border-radius:10px; margin:1rem 0;">
636
+ <h4 style="margin:0; color:#FFFFFF;">Recommended Topics to Study</h4>
637
+ <p style="margin:1rem 0; color:#CCCCCC;">Based on your interview responses, we recommend focusing on these key areas:</p>
638
+ <div style="margin-top:1rem;">
639
+ """, unsafe_allow_html=True)
640
+
641
+ for topic in topics:
642
+ st.markdown(f"""
643
+ <div class="topic-chip">{topic}</div>
644
+ """, unsafe_allow_html=True)
645
+
646
+ st.markdown("""
647
+ </div>
648
+ </div>
649
+ """, unsafe_allow_html=True)
650
+
651
+ st.markdown("</div>", unsafe_allow_html=True)
652
+
653
+ # Restart button
654
+ if st.button("Start New Interview"):
655
+ st.session_state.interview_active = False
656
+ st.session_state.current_step = 0
657
+ st.session_state.interview_phase = "greeting"
658
+ st.session_state.questions = []
659
+ st.session_state.responses = []
660
+ st.session_state.needs_clarification = False
661
+ st.session_state.clarification_response = None
662
+ st.rerun()
663
+
664
+ st.markdown("---")
665
+ st.markdown("<div style='text-align: center; color: #888888; margin: 2rem 0;'>Structured practice interviews to enhance your technical communication skills</div>", unsafe_allow_html=True)
666
+
667
+
668
+