Imarticuslearning commited on
Commit
c74f540
·
verified ·
1 Parent(s): d5e8a51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +747 -747
app.py CHANGED
@@ -1,747 +1,747 @@
1
-
2
- import os
3
- import re
4
- import time
5
- from dotenv import load_dotenv
6
- import streamlit as st
7
- from gtts import gTTS
8
- import PyPDF2
9
- import google.generativeai as genai
10
- import speech_recognition as sr
11
- from random import sample
12
- import random
13
- from html import escape
14
-
15
- # ✅ MUST be the first Streamlit command
16
- st.set_page_config(page_title="GrillMaster", layout="wide")
17
-
18
- # Load API key
19
- load_dotenv()
20
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
21
-
22
- # Initialize session state
23
- for key, default in {
24
- "generated_questions": [],
25
- "current_question_index": 0,
26
- "answers": [],
27
- "evaluation_feedback": "",
28
- "overall_score": 0,
29
- "percentage_score": 0,
30
- "is_recording": False,
31
- "question_played": False,
32
- "selected_domain": "",
33
- "response_captured": False,
34
- "timer_start": None,
35
- "show_summary": False,
36
- "recorded_text": "",
37
- "recording_complete": False,
38
- "recording_started": False,
39
- "audio_played": False,
40
- "question_start_time": 0.0,
41
- "record_phase": ""
42
- }.items():
43
- if key not in st.session_state:
44
- st.session_state[key] = default
45
-
46
- # Utility functions
47
- def extract_pdf_text(uploaded_file):
48
- pdf_reader = PyPDF2.PdfReader(uploaded_file)
49
- return "".join(page.extract_text() or "" for page in pdf_reader.pages).strip()
50
-
51
- def get_questions(prompt, input_text, num_questions=3, max_retries=10):
52
- model = genai.GenerativeModel('gemini-1.5-pro-latest')
53
-
54
- if "previous_questions" not in st.session_state:
55
- st.session_state["previous_questions"] = set()
56
-
57
- new_questions = []
58
- retries = 0
59
-
60
- while len(new_questions) < num_questions and retries < max_retries:
61
- # Add artificial noise/randomness to input
62
- noise = f" [session: {random.randint(1000,9999)} time: {time.time()}]"
63
- modified_input = input_text + noise
64
-
65
- response = model.generate_content([prompt, modified_input])
66
- questions = [q.strip("*•- ") for q in response.text.strip().split("") if q.strip() and "question" not in q.lower()]
67
-
68
- for q in questions:
69
- if q not in st.session_state["previous_questions"]:
70
- st.session_state["previous_questions"].add(q)
71
- new_questions.append(q)
72
- if len(new_questions) == num_questions:
73
- break
74
-
75
- retries += 1
76
-
77
- return new_questions
78
-
79
-
80
- # def evaluate_answers():
81
- # model = genai.GenerativeModel('gemini-1.5-pro-latest')
82
- # prompt = """
83
- # You are an expert interview evaluator. Assess responses based on:
84
- # - Conceptual Understanding
85
- # - Communication Skills
86
- # - Clarity & Depth of Explanation
87
- # - Use of Real-World Examples
88
- # - Logical Flow
89
-
90
- # Provide a score (out of 10) and an evaluation summary.
91
-
92
- # **Format:**
93
- # **Overall Score:** x/10
94
- # **Evaluation Summary:**
95
- # - Concept Understanding: .
96
- # - Communication: .
97
- # - Depth of Explanation: .
98
- # - Examples: .
99
- # - Logical Flow: .
100
- # """
101
- # candidate_responses = "\n\n".join(
102
- # [f"Q: {entry['question']}\nA: {entry['response']}" for entry in st.session_state["answers"]]
103
- # )
104
- # full_prompt = f"{prompt}\n\nCandidate Responses:\n{candidate_responses}"
105
- # response = model.generate_content(full_prompt)
106
- # st.session_state["evaluation_feedback"] = response.text.strip()
107
- # match = re.search(r"\*\*Overall Score:\*\* (\d+)/10", response.text)
108
- # st.session_state["overall_score"] = int(match.group(1)) if match else 0
109
- # st.session_state["percentage_score"] = st.session_state["overall_score"] * 10
110
-
111
- import asyncio
112
- import edge_tts
113
-
114
- import re
115
- import tempfile
116
- import asyncio
117
- import edge_tts
118
-
119
- async def generate_question_audio(question, voice="en-IE-EmilyNeural"):
120
- clean_question = re.sub(r'[^A-Za-z0-9.,?! ]+', '', question)
121
- tts = edge_tts.Communicate(text=clean_question, voice=voice)
122
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
123
- await tts.save(tmp_file.name)
124
- return tmp_file.name
125
-
126
-
127
- # === KEYWORD-BASED SCORING LOGIC ===
128
-
129
- KEYWORDS = {
130
- "Analytics": {
131
- "Python": ["loops", "list", "dictionary", "function", "pandas", "numpy"],
132
- "SQL": ["join", "group by", "select", "where", "index", "foreign key"],
133
- "Machine Learning": ["model", "features", "training", "accuracy", "regression"]
134
- },
135
- "Finance": {
136
- "Fund Accounting": ["NAV", "mutual fund", "reconciliation", "journal entry"],
137
- "AML/KYC": ["customer", "verification", "risk", "compliance", "money laundering"]
138
- },
139
- "Soft Skills": {
140
- "default": ["communication", "teamwork", "problem solving", "motivation", "adaptability"]
141
- }
142
- }
143
-
144
- def score_answer(answer_text, domain, skill):
145
- answer = answer_text.strip().lower()
146
- if answer in ["", "[no response]", "no response", "skipped"]:
147
- return 0.0
148
- if any(phrase in answer for phrase in ["don't know", "not sure", "unaware"]):
149
- return 0.0
150
-
151
- keywords = KEYWORDS.get(domain, {}).get(skill, KEYWORDS["Soft Skills"]["default"])
152
- match_count = sum(1 for kw in keywords if kw in answer)
153
- match_ratio = match_count / len(keywords) if keywords else 0
154
-
155
- if match_ratio == 0:
156
- return 1.5
157
- elif match_ratio <= 0.5:
158
- return 3.0
159
- else:
160
- return 5.0
161
-
162
- # Evaluate candidate answers - YOUR FUNCTION
163
-
164
-
165
-
166
- def evaluate_answers():
167
- model = genai.GenerativeModel('gemini-1.5-pro-latest')
168
- difficulty_level = st.session_state.get("difficulty_level_select", "Beginner")
169
- level_string = difficulty_level.lower()
170
-
171
- # --- Start: Check for all no-responses ---
172
- all_no_response = True
173
- if not st.session_state.get("answers"):
174
- all_no_response = True
175
- else:
176
- for entry in st.session_state["answers"]:
177
- response_text = str(entry.get('response', '')).strip().lower()
178
- no_response_placeholders = [
179
- "", "[no response provided]", "[no response - timed out]",
180
- "[no response]", "no response", "[could not understand audio]",
181
- "[no clear response recorded]"
182
- ]
183
- if response_text not in no_response_placeholders:
184
- all_no_response = False
185
- break
186
-
187
- if all_no_response:
188
- st.session_state["evaluation_feedback"] = (
189
- "**Overall Score:** 0/10\n"
190
- "**Evaluation Summary:**\n"
191
- "- Concept Understanding: N/A - No response provided.\n"
192
- "- Communication: N/A - No response provided.\n"
193
- "- Depth of Explanation: N/A - No response provided.\n"
194
- "- Examples: N/A - No response provided.\n"
195
- "- Logical Flow: N/A - No response provided.\n\n"
196
- "The candidate did not provide any meaningful answers."
197
- )
198
- st.session_state["overall_score"] = 0
199
- st.session_state["percentage_score"] = 0
200
- return
201
- # --- End: Check for all no-responses ---
202
-
203
- base_assessment_criteria = """
204
- Assess responses based on:
205
- - Conceptual Understanding (effort and relevance more than perfect accuracy)
206
- - Communication Clarity (can the core idea be understood?)
207
- - Depth of Explanation (relative to expected level)
208
- - Use of Examples (if any, and if appropriate for the level)
209
- - Logical Flow (is there a basic structure or train of thought?)
210
- """
211
-
212
- if level_string == "beginner":
213
- level_specific_instructions = """
214
- You are an extremely understanding and encouraging interview evaluator for a **BEGINNER/FRESHER**. Your primary goal is to build confidence.
215
- **Scoring Guidelines for Beginners:**
216
- - Be VERY lenient. Focus on ANY sign of understanding or effort.
217
- - A one-liner, if relevant, deserves a good score (e.g., 6-8/10). Partial correctness with effort: 7-9/10. Generally correct but brief: 8-10/10.(Just doubles the score)
218
- - Only score 0/10 if completely irrelevant or no attempt.
219
- - If all answers are empty/placeholders (like '[No response]'), overall score MUST be 0/10.
220
- Provide highly positive, motivating feedback.
221
- """
222
- elif level_string == "intermediate":
223
- level_specific_instructions = """
224
- You are a supportive evaluator for an **INTERMEDIATE** candidate. Expect reasonable conceptual grasp.
225
- **Scoring Guidelines for Intermediate:**
226
- - 7–10: Mostly correct, clear, good understanding.
227
- - 4–6: Partially correct, or needs clarity/depth.
228
- - 1–3: Largely incorrect or irrelevant.
229
- - Overall score 0/10 if all responses are empty.
230
- Provide balanced feedback.
231
- """
232
- else: # Advanced
233
- level_specific_instructions = """
234
- You are a discerning evaluator for an **ADVANCED** candidate. Expect accuracy and depth.
235
- **Scoring Guidelines for Advanced:**
236
- - 8–10: Accurate, comprehensive, deep understanding.
237
- - 5–7: Generally correct but lacks some depth/precision.
238
- - 1–4: Significant inaccuracies or superficial.
239
- - Overall score 0/10 if all responses are empty.
240
- Provide precise feedback.
241
- """
242
-
243
- evaluation_prompt_template = f"""
244
- {level_specific_instructions}
245
- {base_assessment_criteria}
246
-
247
- **YOUR RESPONSE MUST STRICTLY START WITH THE OVERALL SCORE ON THE VERY FIRST LINE.**
248
- Follow this exact format for your entire output:
249
-
250
- *Overall Score:* [score]/10
251
- *Evaluation Summary:*
252
- - Concept Understanding: [Your feedback here]
253
- - Communication: [Your feedback here]
254
- - Depth of Explanation: [Your feedback here]
255
- - Examples: [Your feedback here]
256
- - Logical Flow: [Your feedback here]
257
- [Any additional overall encouraging remarks can optionally follow here]
258
-
259
- The [score] must be a number (e.g., 7 or 7.5) between 0 and 10.
260
- """
261
-
262
- candidate_responses_formatted = "\n\n".join(
263
- [f"Q: {entry['question']}\nA: {str(entry.get('response', '[No response provided]'))}" for entry in st.session_state["answers"]]
264
- )
265
- full_prompt_for_evaluation = f"{evaluation_prompt_template}\n\nCandidate Responses:\n{candidate_responses_formatted}"
266
-
267
- try:
268
- response_content = model.generate_content(full_prompt_for_evaluation)
269
- st.session_state["evaluation_feedback"] = response_content.text.strip()
270
-
271
- extracted_text_for_scoring = response_content.text.strip()
272
- print("--- LLM Output for Score Extraction (evaluate_answers) ---")
273
- print(extracted_text_for_scoring)
274
- print("----------------------------------------------------------")
275
-
276
- overall_score_val = 0.0
277
-
278
- # Pattern 1: More flexible, looks for "Overall Score" then captures number/10
279
- score_pattern_flexible = r"(?i).*Overall Score[\s:]*(\d+(?:\.\d+)?)\s*/\s*10"
280
- score_match = re.search(score_pattern_flexible, extracted_text_for_scoring)
281
-
282
- if score_match:
283
- try:
284
- score_text = score_match.group(1)
285
- print(f"Flexible Pattern Matched! Score text: '{score_text}', Full context: '{score_match.group(0)}'")
286
- overall_score_val = float(score_text)
287
- if overall_score_val.is_integer():
288
- overall_score_val = int(overall_score_val)
289
- print(f"Parsed score value: {overall_score_val}")
290
- except ValueError:
291
- st.warning(f"Flexible pattern matched, but could not parse '{score_text}' as a number. Defaulting score to 0.")
292
- print(f"ValueError during parsing (flexible pattern). Score text: '{score_text}'")
293
- overall_score_val = 0.0
294
- else:
295
- # Fallback Pattern: Simplest possible X/10 if "Overall Score" line completely missing/mangled
296
- score_pattern_fallback = r"(\d+(?:\.\d+)?)\s*/\s*10"
297
- # Search for fallback only if primary pattern fails
298
- print(f"Flexible pattern ('{score_pattern_flexible}') did not match. Trying fallback.")
299
- score_match_fallback = re.search(score_pattern_fallback, extracted_text_for_scoring)
300
- if score_match_fallback:
301
- try:
302
- score_text = score_match_fallback.group(1)
303
- print(f"Fallback Pattern Matched! Score text: '{score_text}', Full context: '{score_match_fallback.group(0)}'")
304
- overall_score_val = float(score_text)
305
- if overall_score_val.is_integer():
306
- overall_score_val = int(overall_score_val)
307
- print(f"Parsed score value (from fallback): {overall_score_val}")
308
- st.warning("Used fallback regex to find score. LLM format for 'Overall Score' line was unexpected.")
309
- except ValueError:
310
- st.warning(f"Fallback pattern matched, but could not parse '{score_text}' as a number. Score set to 0.")
311
- print(f"ValueError during parsing (fallback pattern). Score text: '{score_text}'")
312
- overall_score_val = 0.0
313
- else:
314
- st.warning(f"Could not find any 'X/10' score pattern in the LLM response. Score defaulted to 0. LLM Output (first 300 chars):\n{extracted_text_for_scoring[:300]}...")
315
- print(f"All score patterns failed. LLM output did not contain a recognizable score.")
316
- overall_score_val = 0.0
317
-
318
- st.session_state["overall_score"] = overall_score_val
319
- st.session_state["percentage_score"] = float(overall_score_val) * 10
320
-
321
- except Exception as e:
322
- st.error(f"An error occurred during evaluation or score parsing: {e}")
323
- st.session_state["evaluation_feedback"] = (
324
- f"Could not evaluate answers due to an error: {e}. "
325
- f"LLM output might be missing or malformed."
326
- )
327
- st.session_state["overall_score"] = 0
328
- st.session_state["percentage_score"] = 0
329
-
330
- # --- Prompts for Question Generation ---
331
- BEGINNER_PROMPT = """
332
- You are a friendly mock interview trainer conducting a **Beginner-level** spoken interview in the domain of **{domain}**.
333
- Ask basic verbal interview questions based on the candidate's input: **{input_text}**.
334
-
335
- Guidelines:
336
- - Ask simple conceptual questions.
337
- - Avoid jargon and complex examples.
338
- - Use easy language.
339
- - No coding or technical syntax required.
340
- Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
341
- **New Requirement:**
342
- 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
343
-
344
- **Guidelines:**
345
- ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
346
- ✅ Ensure questions are direct, structured, and relevant to real-world applications.
347
- ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
348
- ❌ Avoid vague or open-ended statements—each question should be concise and specific.
349
- """
350
-
351
- INTERMEDIATE_PROMPT = """
352
- You are a professional mock interviewer conducting an **Intermediate-level** spoken interview in the domain of **{domain}**.
353
- Ask moderately challenging verbal interview questions based on the candidate's input: **{input_text}**.
354
-
355
- Guidelines:
356
- - Use a mix of conceptual and real-world scenario questions.
357
- - Include light critical thinking.
358
- - Still no need for code, formulas, or complex diagrams.
359
- Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
360
- **New Requirement:**
361
- 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
362
-
363
- **Guidelines:**
364
- ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
365
- ✅ Ensure questions are direct, structured, and relevant to real-world applications.
366
- ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
367
- ❌ Avoid vague or open-ended statements—each question should be concise and specific.
368
- """
369
-
370
- ADVANCED_PROMPT = """
371
- You are a strict mock interviewer conducting an **Advanced-level** spoken interview in the domain of **{domain}**.
372
- Ask deep, analytical, real-world scenario-based questions from the candidate's input: **{input_text}**.
373
-
374
- Guidelines:
375
- - Expect detailed, logical, well-structured answers.
376
- - Include challenging “why” and “how” based questions.
377
- - No need for code, but assume candidate has high expertise.
378
- Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
379
- **New Requirement:**
380
- 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
381
-
382
- **Guidelines:**
383
- ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
384
- ✅ Ensure questions are direct, structured, and relevant to real-world applications.
385
- ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
386
- ❌ Avoid vague or open-ended statements—each question should be concise and specific.
387
- """
388
-
389
-
390
- # UI styles
391
- st.markdown("""
392
- <style>
393
- /* Base style for all stButton elements */
394
- .stButton > button {
395
- background-color: #007BFF !important;
396
- color: white !important;
397
- border-radius: 10px !important;
398
- font-weight: bold !important;
399
- width: 100% !important;
400
- padding: 0.4rem 0.75rem !important;
401
- font-size: 0.95rem !important;
402
- line-height: 1.5 !important;
403
- border: 1px solid transparent !important;
404
- transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out !important;
405
- margin-bottom: 8px !important;
406
- box-sizing: border-box;
407
- }
408
- .stButton > button:hover {
409
- background-color: #0056b3 !important;
410
- color: white !important;
411
- border-color: #0056b3 !important;
412
- }
413
- .stButton > button:focus,
414
- .stButton > button:active {
415
- background-color: #0056b3 !important;
416
- border-color: #004085 !important;
417
- box-shadow: 0 0 0 0.2rem rgba(0,123,255,.5) !important;
418
- outline: none !important;
419
- }
420
-
421
- .timer-text {
422
- font-size: 1.3rem;
423
- font-weight: 600;
424
- color: #00bcd4;
425
- animation: pulse 1s infinite;
426
- }
427
- @keyframes pulse {
428
- 0% {opacity: 1;}
429
- 50% {opacity: 0.4;}
430
- 100% {opacity: 1;}
431
- }
432
-
433
- .summary-card {
434
- background-color: #f9f9f9;
435
- padding: 20px;
436
- border-radius: 12px;
437
- border: 1px solid #ddd;
438
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
439
- }
440
- /* More specific selector for the pre text color */
441
- div.summary-card > pre {
442
- white-space: pre-wrap !important;
443
- word-wrap: break-word !important;
444
- font-family: inherit !important;
445
- font-size: 0.95rem !important;
446
- color: #000000 !important; /* TRYING PURE BLACK with !important */
447
- background-color: #ffffff !important; /* Ensure background is white */
448
- padding: 15px !important;
449
- border-radius: 8px !important;
450
- border: 1px solid #e0e0e0 !important;
451
- max-height: 400px !important;
452
- overflow-y: auto !important;
453
- }
454
- </style>
455
- """, unsafe_allow_html=True)
456
-
457
- # Header
458
- st.markdown("""
459
- <div style='text-align: center; margin-top: -30px; padding-top: 10px;'>
460
- <h1 style='font-size: 2.8rem; font-weight: 800; color: #003366;'>🎯 Welcome to <span style='color: #007BFF;'>GrillMaster</span></h1>
461
- <p style='font-size: 1.1rem; color: #555;'>Your AI-powered mock interview assistant</p>
462
- </div>
463
- <hr style='border: 1px solid #e0e0e0; margin: 20px auto;'>
464
- """, unsafe_allow_html=True)
465
-
466
- if not st.session_state["generated_questions"]:
467
- st.markdown("""
468
- <div style='text-align: center; margin-top: -10px; margin-bottom: 30px;'>
469
- <h3 style='font-weight: 700; color: #333;'>🚀 Let's get started!</h3>
470
- <p style='font-size: 1rem; color: #666;'>Select your interview domain and input type to begin your practice session.</p>
471
- </div>
472
- <hr style='border: 1px solid #e0e0e0; margin-top: 0px;'>
473
- """, unsafe_allow_html=True)
474
-
475
- # Example soft skills questions for HR/Soft Skills domain
476
- if st.session_state["selected_domain"] == "Soft Skills":
477
- hr_questions = [
478
- "Tell me about yourself.",
479
- "Why should we hire you?",
480
- "What are your strengths and weaknesses?",
481
- "What is the difference between hard work and smart work?",
482
- "Why do you want to work at our company?",
483
- "How do you feel about working nights and weekends?",
484
- "Can you work under pressure?",
485
- "What are your goals?",
486
- "Are you willing to relocate or travel?",
487
- "What motivates you to do good job?",
488
- "What would you want to accomplish within your first 30 days of employment?",
489
- "What do you prefer working alone or in collaborative environment?",
490
- "Give me an example of your creativity.",
491
- "How long would you expect to work for us if hired?",
492
- "Are not you overqualified for this position?",
493
- "Describe your ideal company, location and job.",
494
- "Explain how would you be an asset to this organization?",
495
- "What are your interests?",
496
- "Would you lie for the company?",
497
- "Who has inspired you in your life and why?",
498
- "What was the toughest decision you ever had to make?",
499
- "Have you considered starting your own business?",
500
- "How do you define success and how do you measure up to your own definition?",
501
- "Tell me something about our company.",
502
- "How much salary do you expect?",
503
- "Where do you see yourself five years from now?",
504
- "Do you have any questions for me?",
505
- "Are you a manager or a leader?",
506
- "Imagine that you are not lucky enough to get this job, how will you take it?"
507
- ]
508
-
509
- # === Sidebar: Domain and Input Configuration ===
510
- st.sidebar.subheader("Select Interview Domain:")
511
- for domain in ["Analytics", "Finance", "Soft Skills"]:
512
- if st.sidebar.button(domain):
513
- st.session_state["selected_domain"] = domain
514
- st.session_state["generated_questions"] = []
515
- st.session_state["current_question_index"] = 0
516
- st.session_state["answers"] = []
517
- st.session_state["evaluation_feedback"] = ""
518
- st.session_state["recorded_text"] = ""
519
- st.session_state["response_captured"] = False
520
- st.session_state["timer_start"] = None
521
- st.session_state["show_summary"] = False
522
- st.session_state["question_played"] = False
523
- st.session_state["recording_complete"] = False
524
- st.rerun()
525
-
526
- if not st.session_state["selected_domain"]:
527
- st.sidebar.info("Please select a domain to continue.")
528
- st.stop()
529
-
530
- st.sidebar.markdown(f"**Selected Domain:** {st.session_state['selected_domain']}")
531
- num_qs = st.sidebar.slider("Number of Questions:", 1, 10, 3)
532
-
533
- if st.session_state["selected_domain"] == "Soft Skills":
534
- if st.sidebar.button("Generate Questions"):
535
- st.session_state["generated_questions"] = sample(hr_questions, num_qs)
536
- st.session_state["current_question_index"] = 0
537
- st.rerun()
538
- else:
539
- section_choice = st.sidebar.radio("Choose Input Type:", ("Resume", "Job Description", "Skills"))
540
- difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
541
- input_text = ""
542
-
543
- if section_choice == "Resume":
544
- uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
545
- if uploaded_file:
546
- input_text = extract_pdf_text(uploaded_file)
547
-
548
- elif section_choice == "Job Description":
549
- input_text = st.sidebar.text_area("Paste Job Description:")
550
-
551
- elif section_choice == "Skills":
552
- # Define available skills for each domain
553
- skills = {
554
- "Analytics": ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"],
555
- "Finance": ["Fund Accounting", "AML/KYC", "Derivatives"]
556
- }
557
- skill_list = skills.get(st.session_state["selected_domain"], [])
558
- if skill_list:
559
- selected_skill = st.sidebar.selectbox("Select a Skill:", skill_list, key="skill_select")
560
- input_text = selected_skill
561
- st.sidebar.markdown(f"✅ Selected Skill: **{selected_skill}**") # Debug display
562
-
563
- if st.sidebar.button("Generate Questions"):
564
- if not input_text.strip():
565
- st.warning("⚠️ Please provide input based on the selected method.")
566
- st.stop()
567
-
568
- prompt = f"Ask {num_qs} direct and core-level {difficulty} interview questions related to {input_text}. Do not include intros or numbering."
569
- model = genai.GenerativeModel('gemini-1.5-pro-latest')
570
- response = model.generate_content([prompt, input_text])
571
- lines = response.text.strip().split("\n")
572
- questions = [q.strip("* ") for q in lines if q.strip()]
573
- st.session_state["generated_questions"] = questions[:num_qs]
574
- st.session_state["current_question_index"] = 0
575
- st.session_state["answers"] = []
576
- st.session_state["evaluation_feedback"] = ""
577
- st.session_state["recorded_text"] = ""
578
- st.session_state["response_captured"] = False
579
- st.session_state["timer_start"] = None
580
- st.session_state["show_summary"] = False
581
- st.session_state["question_played"] = False
582
- st.session_state["recording_complete"] = False
583
- st.rerun()
584
-
585
- # === Main QA Interface ===
586
- if st.session_state["generated_questions"]:
587
- idx = st.session_state["current_question_index"]
588
- if idx < len(st.session_state["generated_questions"]):
589
- question = st.session_state["generated_questions"][idx].lstrip("1234567890. ").strip()
590
-
591
- # Phase 0: Play audio first and wait 5s before countdown
592
- if not st.session_state.get("question_played"):
593
- st.session_state["question_audio_file"] = asyncio.run(generate_question_audio(question))
594
- st.session_state.update({
595
- "question_played": True,
596
- "question_start_time": time.time(),
597
- "record_phase": "audio_playing",
598
- "recorded_text": ""
599
- })
600
-
601
- st.markdown(f"**Q{idx + 1}:** {question}")
602
- st.audio(st.session_state["question_audio_file"], format="audio/mp3")
603
-
604
- now = time.time()
605
- elapsed = now - st.session_state.get("question_start_time", 0)
606
-
607
- if st.session_state["record_phase"] == "audio_playing":
608
- if elapsed < 5:
609
- st.markdown(f"<h4 class='timer-text'>🔊 Playing question audio... Please listen</h4>", unsafe_allow_html=True)
610
- time.sleep(1)
611
- st.rerun()
612
- else:
613
- st.session_state["record_phase"] = "waiting_to_start"
614
- st.session_state["question_start_time"] = time.time()
615
- st.rerun()
616
-
617
- elif st.session_state["record_phase"] == "waiting_to_start":
618
- remaining = 10 - int(elapsed)
619
- if remaining > 0:
620
- st.markdown(f"<h4 class='timer-text'>⏳ {remaining} seconds to click 'Start Recording'...</h4>", unsafe_allow_html=True)
621
- if st.button("🎙️ Start Recording"):
622
- st.session_state.update({
623
- "record_phase": "recording",
624
- "timer_start": time.time(),
625
- "recording_started": False
626
- })
627
- st.rerun()
628
- time.sleep(1)
629
- st.rerun()
630
- else:
631
- st.markdown("<div style='padding:10px; background:#fff8e1; border-left:5px solid orange;color: #212529;'>⚠️ <strong>No action detected.</strong> Automatically skipping to next question...</div>", unsafe_allow_html=True)
632
- st.session_state["answers"].append({"question": question, "response": "[No response]"})
633
- st.session_state.update({
634
- "record_phase": "idle",
635
- "question_played": False,
636
- "question_start_time": 0.0,
637
- "current_question_index": idx + 1
638
- })
639
- if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
640
- evaluate_answers()
641
- st.session_state["show_summary"] = True
642
- st.rerun()
643
-
644
- elif st.session_state["record_phase"] == "recording":
645
- remaining = 15 - int(now - st.session_state.get("timer_start", 0))
646
- if remaining > 0:
647
- st.markdown(f"<h4 class='timer-text'>🎙️ {remaining} seconds to answer...</h4>", unsafe_allow_html=True)
648
- recognizer = sr.Recognizer()
649
- with sr.Microphone() as source:
650
- recognizer.adjust_for_ambient_noise(source)
651
- try:
652
- audio = recognizer.listen(source, timeout=1, phrase_time_limit=1)
653
- try:
654
- result = recognizer.recognize_google(audio)
655
- st.session_state.update({
656
- "recorded_text": result,
657
- "record_phase": "listening"
658
- })
659
- except sr.UnknownValueError:
660
- pass
661
- except sr.WaitTimeoutError:
662
- pass
663
- time.sleep(1)
664
- st.rerun()
665
- else:
666
- st.markdown("<div style='padding:10px; background:#fff3e0; border-left:5px solid orange;'>⚠️ <strong>No response detected.</strong> Moving to next question...</div>", unsafe_allow_html=True)
667
- st.session_state["answers"].append({"question": question, "response": "[No response]"})
668
- st.session_state.update({
669
- "record_phase": "idle",
670
- "recording_started": False,
671
- "question_played": False,
672
- "question_start_time": 0.0,
673
- "current_question_index": idx + 1
674
- })
675
- if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
676
- evaluate_answers()
677
- st.session_state["show_summary"] = True
678
- st.rerun()
679
-
680
- elif st.session_state["record_phase"] == "listening":
681
- st.success("🎧 Listening... You may stop when ready.")
682
- if st.button("⏹️ Stop Recording"):
683
- st.session_state["answers"].append({"question": question, "response": st.session_state["recorded_text"]})
684
- st.session_state.update({
685
- "record_phase": "idle",
686
- "recorded_text": "",
687
- "recording_started": False,
688
- "question_played": False,
689
- "question_start_time": 0.0,
690
- "current_question_index": idx + 1
691
- })
692
- if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
693
- evaluate_answers()
694
- st.session_state["show_summary"] = True
695
- st.rerun()
696
-
697
-
698
- # === Summary Display ===
699
- if st.session_state.get("show_summary", False):
700
- # st.balloons()
701
- st.subheader("📊 Complete Mock Interview Summary")
702
-
703
- feedback_content = st.session_state.get('evaluation_feedback', "Evaluation not yet available.")
704
- if not isinstance(feedback_content, str):
705
- feedback_content = str(feedback_content)
706
-
707
- # Escape HTML special characters from the feedback for security
708
- escaped_feedback_for_html = escape(feedback_content)
709
- # Replace newlines with <br> for HTML display within markdown
710
- formatted_feedback_for_markdown = escaped_feedback_for_html.replace("\n", "<br>")
711
-
712
- st.markdown(f"""
713
- <div class='summary-card'>
714
- <h4 style="color: #212529;">✅ <strong>Overall Score (Model Evaluation):</strong></h4>{st.session_state.get('percentage_score', 0):.0f}% ({st.session_state.get('overall_score',0)}/10)</h4>
715
- <div style='margin:10px 0; position:relative;'>
716
- <div style="color: #212529; background-color: #00c851; border-radius:10px; overflow:hidden; height:30px; position:relative;">
717
- <div style="
718
- width:{st.session_state.get('percentage_score', 0)}%;
719
- background:#00c851;
720
- height:100%;
721
- border-radius:10px 0 0 10px;
722
- transition: width 0.4s ease-in-out;
723
- "></div>
724
- <div style="
725
- position:absolute;
726
- top:0;
727
- left:0;
728
- width:100%;
729
- height:100%;
730
- display:flex;
731
- align-items:center;
732
- justify-content:center;
733
- font-weight:bold;
734
- color: black !important;
735
- font-size: 0.9rem;
736
- user-select:none;
737
- ">
738
- {st.session_state.get('percentage_score', 0):.0f}%
739
- </div>
740
- </div>
741
- </div>
742
- <h4 style="color: #212529;">Detailed Evaluation:</h4>
743
- <div style="color: #212529; background-color: #ffffff; padding: 10px; border-radius: 5px; border: 1px solid #eee; margin-top: 5px; white-space: pre-wrap; word-wrap: break-word; max-height: 400px; overflow-y: auto;">
744
- {formatted_feedback_for_markdown}
745
- </div>
746
- </div>
747
- """, unsafe_allow_html=True)
 
1
+
2
+ import os
3
+ import re
4
+ import time
5
+ from dotenv import load_dotenv
6
+ import streamlit as st
7
+ from gtts import gTTS
8
+ import PyPDF2
9
+ import google.generativeai as genai
10
+ import speech_recognition as sr
11
+ from random import sample
12
+ import random
13
+ from html import escape
14
+
15
+ # ✅ MUST be the first Streamlit command
16
+ st.set_page_config(page_title="GrillMaster", layout="wide")
17
+
18
+ # Load API key
19
+ #load_dotenv()
20
+ genai.configure(api_key="GOOGLE_API_KEY")
21
+
22
+ # Initialize session state
23
+ for key, default in {
24
+ "generated_questions": [],
25
+ "current_question_index": 0,
26
+ "answers": [],
27
+ "evaluation_feedback": "",
28
+ "overall_score": 0,
29
+ "percentage_score": 0,
30
+ "is_recording": False,
31
+ "question_played": False,
32
+ "selected_domain": "",
33
+ "response_captured": False,
34
+ "timer_start": None,
35
+ "show_summary": False,
36
+ "recorded_text": "",
37
+ "recording_complete": False,
38
+ "recording_started": False,
39
+ "audio_played": False,
40
+ "question_start_time": 0.0,
41
+ "record_phase": ""
42
+ }.items():
43
+ if key not in st.session_state:
44
+ st.session_state[key] = default
45
+
46
+ # Utility functions
47
+ def extract_pdf_text(uploaded_file):
48
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
49
+ return "".join(page.extract_text() or "" for page in pdf_reader.pages).strip()
50
+
51
+ def get_questions(prompt, input_text, num_questions=3, max_retries=10):
52
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
53
+
54
+ if "previous_questions" not in st.session_state:
55
+ st.session_state["previous_questions"] = set()
56
+
57
+ new_questions = []
58
+ retries = 0
59
+
60
+ while len(new_questions) < num_questions and retries < max_retries:
61
+ # Add artificial noise/randomness to input
62
+ noise = f" [session: {random.randint(1000,9999)} time: {time.time()}]"
63
+ modified_input = input_text + noise
64
+
65
+ response = model.generate_content([prompt, modified_input])
66
+ questions = [q.strip("*•- ") for q in response.text.strip().split("") if q.strip() and "question" not in q.lower()]
67
+
68
+ for q in questions:
69
+ if q not in st.session_state["previous_questions"]:
70
+ st.session_state["previous_questions"].add(q)
71
+ new_questions.append(q)
72
+ if len(new_questions) == num_questions:
73
+ break
74
+
75
+ retries += 1
76
+
77
+ return new_questions
78
+
79
+
80
+ # def evaluate_answers():
81
+ # model = genai.GenerativeModel('gemini-1.5-pro-latest')
82
+ # prompt = """
83
+ # You are an expert interview evaluator. Assess responses based on:
84
+ # - Conceptual Understanding
85
+ # - Communication Skills
86
+ # - Clarity & Depth of Explanation
87
+ # - Use of Real-World Examples
88
+ # - Logical Flow
89
+
90
+ # Provide a score (out of 10) and an evaluation summary.
91
+
92
+ # **Format:**
93
+ # **Overall Score:** x/10
94
+ # **Evaluation Summary:**
95
+ # - Concept Understanding: .
96
+ # - Communication: .
97
+ # - Depth of Explanation: .
98
+ # - Examples: .
99
+ # - Logical Flow: .
100
+ # """
101
+ # candidate_responses = "\n\n".join(
102
+ # [f"Q: {entry['question']}\nA: {entry['response']}" for entry in st.session_state["answers"]]
103
+ # )
104
+ # full_prompt = f"{prompt}\n\nCandidate Responses:\n{candidate_responses}"
105
+ # response = model.generate_content(full_prompt)
106
+ # st.session_state["evaluation_feedback"] = response.text.strip()
107
+ # match = re.search(r"\*\*Overall Score:\*\* (\d+)/10", response.text)
108
+ # st.session_state["overall_score"] = int(match.group(1)) if match else 0
109
+ # st.session_state["percentage_score"] = st.session_state["overall_score"] * 10
110
+
111
+ import asyncio
112
+ import edge_tts
113
+
114
+ import re
115
+ import tempfile
116
+ import asyncio
117
+ import edge_tts
118
+
119
+ async def generate_question_audio(question, voice="en-IE-EmilyNeural"):
120
+ clean_question = re.sub(r'[^A-Za-z0-9.,?! ]+', '', question)
121
+ tts = edge_tts.Communicate(text=clean_question, voice=voice)
122
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
123
+ await tts.save(tmp_file.name)
124
+ return tmp_file.name
125
+
126
+
127
+ # === KEYWORD-BASED SCORING LOGIC ===
128
+
129
+ KEYWORDS = {
130
+ "Analytics": {
131
+ "Python": ["loops", "list", "dictionary", "function", "pandas", "numpy"],
132
+ "SQL": ["join", "group by", "select", "where", "index", "foreign key"],
133
+ "Machine Learning": ["model", "features", "training", "accuracy", "regression"]
134
+ },
135
+ "Finance": {
136
+ "Fund Accounting": ["NAV", "mutual fund", "reconciliation", "journal entry"],
137
+ "AML/KYC": ["customer", "verification", "risk", "compliance", "money laundering"]
138
+ },
139
+ "Soft Skills": {
140
+ "default": ["communication", "teamwork", "problem solving", "motivation", "adaptability"]
141
+ }
142
+ }
143
+
144
+ def score_answer(answer_text, domain, skill):
145
+ answer = answer_text.strip().lower()
146
+ if answer in ["", "[no response]", "no response", "skipped"]:
147
+ return 0.0
148
+ if any(phrase in answer for phrase in ["don't know", "not sure", "unaware"]):
149
+ return 0.0
150
+
151
+ keywords = KEYWORDS.get(domain, {}).get(skill, KEYWORDS["Soft Skills"]["default"])
152
+ match_count = sum(1 for kw in keywords if kw in answer)
153
+ match_ratio = match_count / len(keywords) if keywords else 0
154
+
155
+ if match_ratio == 0:
156
+ return 1.5
157
+ elif match_ratio <= 0.5:
158
+ return 3.0
159
+ else:
160
+ return 5.0
161
+
162
+ # Evaluate candidate answers - YOUR FUNCTION
163
+
164
+
165
+
166
+ def evaluate_answers():
167
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
168
+ difficulty_level = st.session_state.get("difficulty_level_select", "Beginner")
169
+ level_string = difficulty_level.lower()
170
+
171
+ # --- Start: Check for all no-responses ---
172
+ all_no_response = True
173
+ if not st.session_state.get("answers"):
174
+ all_no_response = True
175
+ else:
176
+ for entry in st.session_state["answers"]:
177
+ response_text = str(entry.get('response', '')).strip().lower()
178
+ no_response_placeholders = [
179
+ "", "[no response provided]", "[no response - timed out]",
180
+ "[no response]", "no response", "[could not understand audio]",
181
+ "[no clear response recorded]"
182
+ ]
183
+ if response_text not in no_response_placeholders:
184
+ all_no_response = False
185
+ break
186
+
187
+ if all_no_response:
188
+ st.session_state["evaluation_feedback"] = (
189
+ "**Overall Score:** 0/10\n"
190
+ "**Evaluation Summary:**\n"
191
+ "- Concept Understanding: N/A - No response provided.\n"
192
+ "- Communication: N/A - No response provided.\n"
193
+ "- Depth of Explanation: N/A - No response provided.\n"
194
+ "- Examples: N/A - No response provided.\n"
195
+ "- Logical Flow: N/A - No response provided.\n\n"
196
+ "The candidate did not provide any meaningful answers."
197
+ )
198
+ st.session_state["overall_score"] = 0
199
+ st.session_state["percentage_score"] = 0
200
+ return
201
+ # --- End: Check for all no-responses ---
202
+
203
+ base_assessment_criteria = """
204
+ Assess responses based on:
205
+ - Conceptual Understanding (effort and relevance more than perfect accuracy)
206
+ - Communication Clarity (can the core idea be understood?)
207
+ - Depth of Explanation (relative to expected level)
208
+ - Use of Examples (if any, and if appropriate for the level)
209
+ - Logical Flow (is there a basic structure or train of thought?)
210
+ """
211
+
212
+ if level_string == "beginner":
213
+ level_specific_instructions = """
214
+ You are an extremely understanding and encouraging interview evaluator for a **BEGINNER/FRESHER**. Your primary goal is to build confidence.
215
+ **Scoring Guidelines for Beginners:**
216
+ - Be VERY lenient. Focus on ANY sign of understanding or effort.
217
+ - A one-liner, if relevant, deserves a good score (e.g., 6-8/10). Partial correctness with effort: 7-9/10. Generally correct but brief: 8-10/10.(Just doubles the score)
218
+ - Only score 0/10 if completely irrelevant or no attempt.
219
+ - If all answers are empty/placeholders (like '[No response]'), overall score MUST be 0/10.
220
+ Provide highly positive, motivating feedback.
221
+ """
222
+ elif level_string == "intermediate":
223
+ level_specific_instructions = """
224
+ You are a supportive evaluator for an **INTERMEDIATE** candidate. Expect reasonable conceptual grasp.
225
+ **Scoring Guidelines for Intermediate:**
226
+ - 7–10: Mostly correct, clear, good understanding.
227
+ - 4–6: Partially correct, or needs clarity/depth.
228
+ - 1–3: Largely incorrect or irrelevant.
229
+ - Overall score 0/10 if all responses are empty.
230
+ Provide balanced feedback.
231
+ """
232
+ else: # Advanced
233
+ level_specific_instructions = """
234
+ You are a discerning evaluator for an **ADVANCED** candidate. Expect accuracy and depth.
235
+ **Scoring Guidelines for Advanced:**
236
+ - 8–10: Accurate, comprehensive, deep understanding.
237
+ - 5–7: Generally correct but lacks some depth/precision.
238
+ - 1–4: Significant inaccuracies or superficial.
239
+ - Overall score 0/10 if all responses are empty.
240
+ Provide precise feedback.
241
+ """
242
+
243
+ evaluation_prompt_template = f"""
244
+ {level_specific_instructions}
245
+ {base_assessment_criteria}
246
+
247
+ **YOUR RESPONSE MUST STRICTLY START WITH THE OVERALL SCORE ON THE VERY FIRST LINE.**
248
+ Follow this exact format for your entire output:
249
+
250
+ *Overall Score:* [score]/10
251
+ *Evaluation Summary:*
252
+ - Concept Understanding: [Your feedback here]
253
+ - Communication: [Your feedback here]
254
+ - Depth of Explanation: [Your feedback here]
255
+ - Examples: [Your feedback here]
256
+ - Logical Flow: [Your feedback here]
257
+ [Any additional overall encouraging remarks can optionally follow here]
258
+
259
+ The [score] must be a number (e.g., 7 or 7.5) between 0 and 10.
260
+ """
261
+
262
+ candidate_responses_formatted = "\n\n".join(
263
+ [f"Q: {entry['question']}\nA: {str(entry.get('response', '[No response provided]'))}" for entry in st.session_state["answers"]]
264
+ )
265
+ full_prompt_for_evaluation = f"{evaluation_prompt_template}\n\nCandidate Responses:\n{candidate_responses_formatted}"
266
+
267
+ try:
268
+ response_content = model.generate_content(full_prompt_for_evaluation)
269
+ st.session_state["evaluation_feedback"] = response_content.text.strip()
270
+
271
+ extracted_text_for_scoring = response_content.text.strip()
272
+ print("--- LLM Output for Score Extraction (evaluate_answers) ---")
273
+ print(extracted_text_for_scoring)
274
+ print("----------------------------------------------------------")
275
+
276
+ overall_score_val = 0.0
277
+
278
+ # Pattern 1: More flexible, looks for "Overall Score" then captures number/10
279
+ score_pattern_flexible = r"(?i).*Overall Score[\s:]*(\d+(?:\.\d+)?)\s*/\s*10"
280
+ score_match = re.search(score_pattern_flexible, extracted_text_for_scoring)
281
+
282
+ if score_match:
283
+ try:
284
+ score_text = score_match.group(1)
285
+ print(f"Flexible Pattern Matched! Score text: '{score_text}', Full context: '{score_match.group(0)}'")
286
+ overall_score_val = float(score_text)
287
+ if overall_score_val.is_integer():
288
+ overall_score_val = int(overall_score_val)
289
+ print(f"Parsed score value: {overall_score_val}")
290
+ except ValueError:
291
+ st.warning(f"Flexible pattern matched, but could not parse '{score_text}' as a number. Defaulting score to 0.")
292
+ print(f"ValueError during parsing (flexible pattern). Score text: '{score_text}'")
293
+ overall_score_val = 0.0
294
+ else:
295
+ # Fallback Pattern: Simplest possible X/10 if "Overall Score" line completely missing/mangled
296
+ score_pattern_fallback = r"(\d+(?:\.\d+)?)\s*/\s*10"
297
+ # Search for fallback only if primary pattern fails
298
+ print(f"Flexible pattern ('{score_pattern_flexible}') did not match. Trying fallback.")
299
+ score_match_fallback = re.search(score_pattern_fallback, extracted_text_for_scoring)
300
+ if score_match_fallback:
301
+ try:
302
+ score_text = score_match_fallback.group(1)
303
+ print(f"Fallback Pattern Matched! Score text: '{score_text}', Full context: '{score_match_fallback.group(0)}'")
304
+ overall_score_val = float(score_text)
305
+ if overall_score_val.is_integer():
306
+ overall_score_val = int(overall_score_val)
307
+ print(f"Parsed score value (from fallback): {overall_score_val}")
308
+ st.warning("Used fallback regex to find score. LLM format for 'Overall Score' line was unexpected.")
309
+ except ValueError:
310
+ st.warning(f"Fallback pattern matched, but could not parse '{score_text}' as a number. Score set to 0.")
311
+ print(f"ValueError during parsing (fallback pattern). Score text: '{score_text}'")
312
+ overall_score_val = 0.0
313
+ else:
314
+ st.warning(f"Could not find any 'X/10' score pattern in the LLM response. Score defaulted to 0. LLM Output (first 300 chars):\n{extracted_text_for_scoring[:300]}...")
315
+ print(f"All score patterns failed. LLM output did not contain a recognizable score.")
316
+ overall_score_val = 0.0
317
+
318
+ st.session_state["overall_score"] = overall_score_val
319
+ st.session_state["percentage_score"] = float(overall_score_val) * 10
320
+
321
+ except Exception as e:
322
+ st.error(f"An error occurred during evaluation or score parsing: {e}")
323
+ st.session_state["evaluation_feedback"] = (
324
+ f"Could not evaluate answers due to an error: {e}. "
325
+ f"LLM output might be missing or malformed."
326
+ )
327
+ st.session_state["overall_score"] = 0
328
+ st.session_state["percentage_score"] = 0
329
+
330
+ # --- Prompts for Question Generation ---
331
+ BEGINNER_PROMPT = """
332
+ You are a friendly mock interview trainer conducting a **Beginner-level** spoken interview in the domain of **{domain}**.
333
+ Ask basic verbal interview questions based on the candidate's input: **{input_text}**.
334
+
335
+ Guidelines:
336
+ - Ask simple conceptual questions.
337
+ - Avoid jargon and complex examples.
338
+ - Use easy language.
339
+ - No coding or technical syntax required.
340
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
341
+ **New Requirement:**
342
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
343
+
344
+ **Guidelines:**
345
+ ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
346
+ ✅ Ensure questions are direct, structured, and relevant to real-world applications.
347
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
348
+ ❌ Avoid vague or open-ended statements—each question should be concise and specific.
349
+ """
350
+
351
+ INTERMEDIATE_PROMPT = """
352
+ You are a professional mock interviewer conducting an **Intermediate-level** spoken interview in the domain of **{domain}**.
353
+ Ask moderately challenging verbal interview questions based on the candidate's input: **{input_text}**.
354
+
355
+ Guidelines:
356
+ - Use a mix of conceptual and real-world scenario questions.
357
+ - Include light critical thinking.
358
+ - Still no need for code, formulas, or complex diagrams.
359
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
360
+ **New Requirement:**
361
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
362
+
363
+ **Guidelines:**
364
+ ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
365
+ ✅ Ensure questions are direct, structured, and relevant to real-world applications.
366
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
367
+ ❌ Avoid vague or open-ended statements—each question should be concise and specific.
368
+ """
369
+
370
+ ADVANCED_PROMPT = """
371
+ You are a strict mock interviewer conducting an **Advanced-level** spoken interview in the domain of **{domain}**.
372
+ Ask deep, analytical, real-world scenario-based questions from the candidate's input: **{input_text}**.
373
+
374
+ Guidelines:
375
+ - Expect detailed, logical, well-structured answers.
376
+ - Include challenging “why” and “how” based questions.
377
+ - No need for code, but assume candidate has high expertise.
378
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
379
+ **New Requirement:**
380
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
381
+
382
+ **Guidelines:**
383
+ ✅ Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
384
+ ✅ Ensure questions are direct, structured, and relevant to real-world applications.
385
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
386
+ ❌ Avoid vague or open-ended statements—each question should be concise and specific.
387
+ """
388
+
389
+
390
+ # UI styles
391
+ st.markdown("""
392
+ <style>
393
+ /* Base style for all stButton elements */
394
+ .stButton > button {
395
+ background-color: #007BFF !important;
396
+ color: white !important;
397
+ border-radius: 10px !important;
398
+ font-weight: bold !important;
399
+ width: 100% !important;
400
+ padding: 0.4rem 0.75rem !important;
401
+ font-size: 0.95rem !important;
402
+ line-height: 1.5 !important;
403
+ border: 1px solid transparent !important;
404
+ transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out !important;
405
+ margin-bottom: 8px !important;
406
+ box-sizing: border-box;
407
+ }
408
+ .stButton > button:hover {
409
+ background-color: #0056b3 !important;
410
+ color: white !important;
411
+ border-color: #0056b3 !important;
412
+ }
413
+ .stButton > button:focus,
414
+ .stButton > button:active {
415
+ background-color: #0056b3 !important;
416
+ border-color: #004085 !important;
417
+ box-shadow: 0 0 0 0.2rem rgba(0,123,255,.5) !important;
418
+ outline: none !important;
419
+ }
420
+
421
+ .timer-text {
422
+ font-size: 1.3rem;
423
+ font-weight: 600;
424
+ color: #00bcd4;
425
+ animation: pulse 1s infinite;
426
+ }
427
+ @keyframes pulse {
428
+ 0% {opacity: 1;}
429
+ 50% {opacity: 0.4;}
430
+ 100% {opacity: 1;}
431
+ }
432
+
433
+ .summary-card {
434
+ background-color: #f9f9f9;
435
+ padding: 20px;
436
+ border-radius: 12px;
437
+ border: 1px solid #ddd;
438
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
439
+ }
440
+ /* More specific selector for the pre text color */
441
+ div.summary-card > pre {
442
+ white-space: pre-wrap !important;
443
+ word-wrap: break-word !important;
444
+ font-family: inherit !important;
445
+ font-size: 0.95rem !important;
446
+ color: #000000 !important; /* TRYING PURE BLACK with !important */
447
+ background-color: #ffffff !important; /* Ensure background is white */
448
+ padding: 15px !important;
449
+ border-radius: 8px !important;
450
+ border: 1px solid #e0e0e0 !important;
451
+ max-height: 400px !important;
452
+ overflow-y: auto !important;
453
+ }
454
+ </style>
455
+ """, unsafe_allow_html=True)
456
+
457
+ # Header
458
+ st.markdown("""
459
+ <div style='text-align: center; margin-top: -30px; padding-top: 10px;'>
460
+ <h1 style='font-size: 2.8rem; font-weight: 800; color: #003366;'>🎯 Welcome to <span style='color: #007BFF;'>GrillMaster</span></h1>
461
+ <p style='font-size: 1.1rem; color: #555;'>Your AI-powered mock interview assistant</p>
462
+ </div>
463
+ <hr style='border: 1px solid #e0e0e0; margin: 20px auto;'>
464
+ """, unsafe_allow_html=True)
465
+
466
+ if not st.session_state["generated_questions"]:
467
+ st.markdown("""
468
+ <div style='text-align: center; margin-top: -10px; margin-bottom: 30px;'>
469
+ <h3 style='font-weight: 700; color: #333;'>🚀 Let's get started!</h3>
470
+ <p style='font-size: 1rem; color: #666;'>Select your interview domain and input type to begin your practice session.</p>
471
+ </div>
472
+ <hr style='border: 1px solid #e0e0e0; margin-top: 0px;'>
473
+ """, unsafe_allow_html=True)
474
+
475
+ # Example soft skills questions for HR/Soft Skills domain
476
+ if st.session_state["selected_domain"] == "Soft Skills":
477
+ hr_questions = [
478
+ "Tell me about yourself.",
479
+ "Why should we hire you?",
480
+ "What are your strengths and weaknesses?",
481
+ "What is the difference between hard work and smart work?",
482
+ "Why do you want to work at our company?",
483
+ "How do you feel about working nights and weekends?",
484
+ "Can you work under pressure?",
485
+ "What are your goals?",
486
+ "Are you willing to relocate or travel?",
487
+ "What motivates you to do good job?",
488
+ "What would you want to accomplish within your first 30 days of employment?",
489
+ "What do you prefer working alone or in collaborative environment?",
490
+ "Give me an example of your creativity.",
491
+ "How long would you expect to work for us if hired?",
492
+ "Are not you overqualified for this position?",
493
+ "Describe your ideal company, location and job.",
494
+ "Explain how would you be an asset to this organization?",
495
+ "What are your interests?",
496
+ "Would you lie for the company?",
497
+ "Who has inspired you in your life and why?",
498
+ "What was the toughest decision you ever had to make?",
499
+ "Have you considered starting your own business?",
500
+ "How do you define success and how do you measure up to your own definition?",
501
+ "Tell me something about our company.",
502
+ "How much salary do you expect?",
503
+ "Where do you see yourself five years from now?",
504
+ "Do you have any questions for me?",
505
+ "Are you a manager or a leader?",
506
+ "Imagine that you are not lucky enough to get this job, how will you take it?"
507
+ ]
508
+
509
+ # === Sidebar: Domain and Input Configuration ===
510
+ st.sidebar.subheader("Select Interview Domain:")
511
+ for domain in ["Analytics", "Finance", "Soft Skills"]:
512
+ if st.sidebar.button(domain):
513
+ st.session_state["selected_domain"] = domain
514
+ st.session_state["generated_questions"] = []
515
+ st.session_state["current_question_index"] = 0
516
+ st.session_state["answers"] = []
517
+ st.session_state["evaluation_feedback"] = ""
518
+ st.session_state["recorded_text"] = ""
519
+ st.session_state["response_captured"] = False
520
+ st.session_state["timer_start"] = None
521
+ st.session_state["show_summary"] = False
522
+ st.session_state["question_played"] = False
523
+ st.session_state["recording_complete"] = False
524
+ st.rerun()
525
+
526
+ if not st.session_state["selected_domain"]:
527
+ st.sidebar.info("Please select a domain to continue.")
528
+ st.stop()
529
+
530
+ st.sidebar.markdown(f"**Selected Domain:** {st.session_state['selected_domain']}")
531
+ num_qs = st.sidebar.slider("Number of Questions:", 1, 10, 3)
532
+
533
+ if st.session_state["selected_domain"] == "Soft Skills":
534
+ if st.sidebar.button("Generate Questions"):
535
+ st.session_state["generated_questions"] = sample(hr_questions, num_qs)
536
+ st.session_state["current_question_index"] = 0
537
+ st.rerun()
538
+ else:
539
+ section_choice = st.sidebar.radio("Choose Input Type:", ("Resume", "Job Description", "Skills"))
540
+ difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
541
+ input_text = ""
542
+
543
+ if section_choice == "Resume":
544
+ uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
545
+ if uploaded_file:
546
+ input_text = extract_pdf_text(uploaded_file)
547
+
548
+ elif section_choice == "Job Description":
549
+ input_text = st.sidebar.text_area("Paste Job Description:")
550
+
551
+ elif section_choice == "Skills":
552
+ # Define available skills for each domain
553
+ skills = {
554
+ "Analytics": ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"],
555
+ "Finance": ["Fund Accounting", "AML/KYC", "Derivatives"]
556
+ }
557
+ skill_list = skills.get(st.session_state["selected_domain"], [])
558
+ if skill_list:
559
+ selected_skill = st.sidebar.selectbox("Select a Skill:", skill_list, key="skill_select")
560
+ input_text = selected_skill
561
+ st.sidebar.markdown(f"✅ Selected Skill: **{selected_skill}**") # Debug display
562
+
563
+ if st.sidebar.button("Generate Questions"):
564
+ if not input_text.strip():
565
+ st.warning("⚠️ Please provide input based on the selected method.")
566
+ st.stop()
567
+
568
+ prompt = f"Ask {num_qs} direct and core-level {difficulty} interview questions related to {input_text}. Do not include intros or numbering."
569
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
570
+ response = model.generate_content([prompt, input_text])
571
+ lines = response.text.strip().split("\n")
572
+ questions = [q.strip("* ") for q in lines if q.strip()]
573
+ st.session_state["generated_questions"] = questions[:num_qs]
574
+ st.session_state["current_question_index"] = 0
575
+ st.session_state["answers"] = []
576
+ st.session_state["evaluation_feedback"] = ""
577
+ st.session_state["recorded_text"] = ""
578
+ st.session_state["response_captured"] = False
579
+ st.session_state["timer_start"] = None
580
+ st.session_state["show_summary"] = False
581
+ st.session_state["question_played"] = False
582
+ st.session_state["recording_complete"] = False
583
+ st.rerun()
584
+
585
+ # === Main QA Interface ===
586
+ if st.session_state["generated_questions"]:
587
+ idx = st.session_state["current_question_index"]
588
+ if idx < len(st.session_state["generated_questions"]):
589
+ question = st.session_state["generated_questions"][idx].lstrip("1234567890. ").strip()
590
+
591
+ # Phase 0: Play audio first and wait 5s before countdown
592
+ if not st.session_state.get("question_played"):
593
+ st.session_state["question_audio_file"] = asyncio.run(generate_question_audio(question))
594
+ st.session_state.update({
595
+ "question_played": True,
596
+ "question_start_time": time.time(),
597
+ "record_phase": "audio_playing",
598
+ "recorded_text": ""
599
+ })
600
+
601
+ st.markdown(f"**Q{idx + 1}:** {question}")
602
+ st.audio(st.session_state["question_audio_file"], format="audio/mp3")
603
+
604
+ now = time.time()
605
+ elapsed = now - st.session_state.get("question_start_time", 0)
606
+
607
+ if st.session_state["record_phase"] == "audio_playing":
608
+ if elapsed < 5:
609
+ st.markdown(f"<h4 class='timer-text'>🔊 Playing question audio... Please listen</h4>", unsafe_allow_html=True)
610
+ time.sleep(1)
611
+ st.rerun()
612
+ else:
613
+ st.session_state["record_phase"] = "waiting_to_start"
614
+ st.session_state["question_start_time"] = time.time()
615
+ st.rerun()
616
+
617
+ elif st.session_state["record_phase"] == "waiting_to_start":
618
+ remaining = 10 - int(elapsed)
619
+ if remaining > 0:
620
+ st.markdown(f"<h4 class='timer-text'>⏳ {remaining} seconds to click 'Start Recording'...</h4>", unsafe_allow_html=True)
621
+ if st.button("🎙️ Start Recording"):
622
+ st.session_state.update({
623
+ "record_phase": "recording",
624
+ "timer_start": time.time(),
625
+ "recording_started": False
626
+ })
627
+ st.rerun()
628
+ time.sleep(1)
629
+ st.rerun()
630
+ else:
631
+ st.markdown("<div style='padding:10px; background:#fff8e1; border-left:5px solid orange;color: #212529;'>⚠️ <strong>No action detected.</strong> Automatically skipping to next question...</div>", unsafe_allow_html=True)
632
+ st.session_state["answers"].append({"question": question, "response": "[No response]"})
633
+ st.session_state.update({
634
+ "record_phase": "idle",
635
+ "question_played": False,
636
+ "question_start_time": 0.0,
637
+ "current_question_index": idx + 1
638
+ })
639
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
640
+ evaluate_answers()
641
+ st.session_state["show_summary"] = True
642
+ st.rerun()
643
+
644
+ elif st.session_state["record_phase"] == "recording":
645
+ remaining = 15 - int(now - st.session_state.get("timer_start", 0))
646
+ if remaining > 0:
647
+ st.markdown(f"<h4 class='timer-text'>🎙️ {remaining} seconds to answer...</h4>", unsafe_allow_html=True)
648
+ recognizer = sr.Recognizer()
649
+ with sr.Microphone() as source:
650
+ recognizer.adjust_for_ambient_noise(source)
651
+ try:
652
+ audio = recognizer.listen(source, timeout=1, phrase_time_limit=1)
653
+ try:
654
+ result = recognizer.recognize_google(audio)
655
+ st.session_state.update({
656
+ "recorded_text": result,
657
+ "record_phase": "listening"
658
+ })
659
+ except sr.UnknownValueError:
660
+ pass
661
+ except sr.WaitTimeoutError:
662
+ pass
663
+ time.sleep(1)
664
+ st.rerun()
665
+ else:
666
+ st.markdown("<div style='padding:10px; background:#fff3e0; border-left:5px solid orange;'>⚠️ <strong>No response detected.</strong> Moving to next question...</div>", unsafe_allow_html=True)
667
+ st.session_state["answers"].append({"question": question, "response": "[No response]"})
668
+ st.session_state.update({
669
+ "record_phase": "idle",
670
+ "recording_started": False,
671
+ "question_played": False,
672
+ "question_start_time": 0.0,
673
+ "current_question_index": idx + 1
674
+ })
675
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
676
+ evaluate_answers()
677
+ st.session_state["show_summary"] = True
678
+ st.rerun()
679
+
680
+ elif st.session_state["record_phase"] == "listening":
681
+ st.success("🎧 Listening... You may stop when ready.")
682
+ if st.button("⏹️ Stop Recording"):
683
+ st.session_state["answers"].append({"question": question, "response": st.session_state["recorded_text"]})
684
+ st.session_state.update({
685
+ "record_phase": "idle",
686
+ "recorded_text": "",
687
+ "recording_started": False,
688
+ "question_played": False,
689
+ "question_start_time": 0.0,
690
+ "current_question_index": idx + 1
691
+ })
692
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
693
+ evaluate_answers()
694
+ st.session_state["show_summary"] = True
695
+ st.rerun()
696
+
697
+
698
+ # === Summary Display ===
699
+ if st.session_state.get("show_summary", False):
700
+ # st.balloons()
701
+ st.subheader("📊 Complete Mock Interview Summary")
702
+
703
+ feedback_content = st.session_state.get('evaluation_feedback', "Evaluation not yet available.")
704
+ if not isinstance(feedback_content, str):
705
+ feedback_content = str(feedback_content)
706
+
707
+ # Escape HTML special characters from the feedback for security
708
+ escaped_feedback_for_html = escape(feedback_content)
709
+ # Replace newlines with <br> for HTML display within markdown
710
+ formatted_feedback_for_markdown = escaped_feedback_for_html.replace("\n", "<br>")
711
+
712
+ st.markdown(f"""
713
+ <div class='summary-card'>
714
+ <h4 style="color: #212529;">✅ <strong>Overall Score (Model Evaluation):</strong></h4>{st.session_state.get('percentage_score', 0):.0f}% ({st.session_state.get('overall_score',0)}/10)</h4>
715
+ <div style='margin:10px 0; position:relative;'>
716
+ <div style="color: #212529; background-color: #00c851; border-radius:10px; overflow:hidden; height:30px; position:relative;">
717
+ <div style="
718
+ width:{st.session_state.get('percentage_score', 0)}%;
719
+ background:#00c851;
720
+ height:100%;
721
+ border-radius:10px 0 0 10px;
722
+ transition: width 0.4s ease-in-out;
723
+ "></div>
724
+ <div style="
725
+ position:absolute;
726
+ top:0;
727
+ left:0;
728
+ width:100%;
729
+ height:100%;
730
+ display:flex;
731
+ align-items:center;
732
+ justify-content:center;
733
+ font-weight:bold;
734
+ color: black !important;
735
+ font-size: 0.9rem;
736
+ user-select:none;
737
+ ">
738
+ {st.session_state.get('percentage_score', 0):.0f}%
739
+ </div>
740
+ </div>
741
+ </div>
742
+ <h4 style="color: #212529;">Detailed Evaluation:</h4>
743
+ <div style="color: #212529; background-color: #ffffff; padding: 10px; border-radius: 5px; border: 1px solid #eee; margin-top: 5px; white-space: pre-wrap; word-wrap: break-word; max-height: 400px; overflow-y: auto;">
744
+ {formatted_feedback_for_markdown}
745
+ </div>
746
+ </div>
747
+ """, unsafe_allow_html=True)