Imarticuslearning commited on
Commit
84bc320
Β·
verified Β·
1 Parent(s): 9e0bbc6

Upload Placementprep_app.py

Browse files
Files changed (1) hide show
  1. Placementprep_app.py +1106 -0
Placementprep_app.py ADDED
@@ -0,0 +1,1106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import time
4
+ from dotenv import load_dotenv
5
+ import streamlit as st
6
+ import PyPDF2
7
+ import google.generativeai as genai
8
+ import speech_recognition as sr
9
+ from random import sample
10
+ import random
11
+ from html import escape
12
+ import asyncio
13
+ import edge_tts
14
+ import pandas as pd
15
+ import tempfile
16
+ import traceback
17
+ from streamlit_webrtc import webrtc_streamer, WebRtcMode
18
+ from twilio.rest import Client
19
+ import logging
20
+ import whisper
21
+ import speech_recognition as sr
22
+ #model = whisper.load_model("base")
23
+
24
+
25
+ # βœ… MUST be the first Streamlit command
26
+ st.set_page_config(page_title="GrillMaster", layout="wide")
27
+
28
+ # Load API key
29
+ load_dotenv()
30
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
31
+
32
+ # Initialize session state
33
+ for key, default in {
34
+ "generated_questions": [],
35
+ "current_question_index": 0,
36
+ "answers": [],
37
+ "evaluation_feedback": "",
38
+ "overall_score": 0,
39
+ "percentage_score": 0,
40
+ "is_recording": False,
41
+ "question_played": False,
42
+ "selected_domain": "",
43
+ "response_captured": False,
44
+ "timer_start": None,
45
+ "show_summary": False,
46
+ "recorded_text": "",
47
+ "recording_complete": False,
48
+ "recording_started": False,
49
+ "audio_played": False,
50
+ "question_start_time": 0.0,
51
+ "record_phase": ""
52
+ }.items():
53
+ if key not in st.session_state:
54
+ st.session_state[key] = default
55
+
56
+ # Utility functions
57
+ def extract_pdf_text(uploaded_file):
58
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
59
+ return "".join(page.extract_text() or "" for page in pdf_reader.pages).strip()
60
+
61
+ def get_questions(prompt, input_text, num_questions=3, max_retries=10):
62
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
63
+
64
+ if "previous_questions" not in st.session_state:
65
+ st.session_state["previous_questions"] = set()
66
+
67
+ new_questions = []
68
+ retries = 0
69
+
70
+ while len(new_questions) < num_questions and retries < max_retries:
71
+ # Add artificial noise/randomness to input
72
+ noise = f" [session: {random.randint(1000,9999)} time: {time.time()}]"
73
+ modified_input = input_text + noise
74
+
75
+ response = model.generate_content([prompt, modified_input])
76
+ questions = [q.strip("*β€’- ") for q in response.text.strip().split("") if q.strip() and "question" not in q.lower()]
77
+
78
+ for q in questions:
79
+ if q not in st.session_state["previous_questions"]:
80
+ st.session_state["previous_questions"].add(q)
81
+ new_questions.append(q)
82
+ if len(new_questions) == num_questions:
83
+ break
84
+
85
+ retries += 1
86
+
87
+ return new_questions
88
+
89
+ async def generate_question_audio(question, voice="en-IE-EmilyNeural"):
90
+ clean_question = re.sub(r'[^A-Za-z0-9.,?! ]+', '', question)
91
+ tts = edge_tts.Communicate(text=clean_question, voice=voice)
92
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
93
+ await tts.save(tmp_file.name)
94
+ return tmp_file.name
95
+
96
+ ########################################///////////////////////////////////////////////////#########################################
97
+
98
+ # HR_PARAMETERS_CONFIG - Updated based on your latest Excel sheet (input_file_0.png)
99
+ # These are the parameters that can be judged from audio/text responses.
100
+ HR_PARAMETERS_CONFIG = {
101
+ "Voice Modulation": { # Non-Verbal Cues
102
+ "weight_original": 5,
103
+ "rubric": "1-5 (5=Good pace/tone, conversational; 3=Sounds Scripted/Slight Monotony; 1=Flat tone/Robotic)"
104
+ },
105
+ "Confidence": { # Personality
106
+ "weight_original": 7,
107
+ "rubric": "1-5 (5=Bold & Confident throughout; 3=Confused/Nervous in parts; 1=Extremely nervous/Timid)"
108
+ },
109
+ "Attitude": { # Personality
110
+ "weight_original": 3,
111
+ "rubric": "1-5 (5=Assertive, Positive, Open; 3=Neutral/Mildly defensive; 1=Aggressive/Pessimistic/Dismissive)"
112
+ },
113
+ "Flow & Fluency": { # Articulation
114
+ "weight_original": 20,
115
+ "rubric": "1-5 (5=Excellent Fluency, Spontaneous; 3=Initially struggles, then manages/Takes some time; 1=Many fillers/Pauses/Dead silence)"
116
+ },
117
+ "Structured thoughts & Clarity": { # Articulation
118
+ "weight_original": 10,
119
+ "rubric": "1-5 (5=Organized, Crisp, Coherent thoughts, e.g. STAR method; 3=Ideas are okay but clarity/structure could be better; 1=Incoherent/Rambling/Struggles to put thoughts into words)"
120
+ },
121
+ "Sentence Formation": { # Language Skills
122
+ "weight_original": 20,
123
+ "rubric": "1-5 (5=Good Clarity, Variety in sentence structure, Good Vocab; 3=Decent communication, might find some words difficult; 1=Talks in fragments/one-liners, Hard to understand)"
124
+ },
125
+ "Basics of Grammar + SVA": { # Language Skills (SVA = Subject-Verb Agreement)
126
+ "weight_original": 10,
127
+ "rubric": "1-5 (5=Good Command over Language, Minimal errors; 3=Average communicator, some errors but understandable; 1=Makes a lot of Grammatical Errors impacting clarity)"
128
+ },
129
+ "Persuasiveness": { # Rapport Building
130
+ "weight_original": 3,
131
+ "rubric": "1-5 (5=Impactful, Convincing Answers, Connects with interviewer; 3=Average or Common Answers; 1=Lacks Presence of Mind/No connection)"
132
+ },
133
+ "Quality of Answers": { # Rapport Building
134
+ "weight_original": 7,
135
+ "rubric": "1-5 (5=Handles questions well, Relevant & Thoughtful Answers, Asks good questions; 3=Very Generic Answers; 1=Vague/Lacks Depth/Shallow/Irrelevant)"
136
+ }
137
+ }
138
+
139
+ # Calculate total original weight for normalization
140
+ TOTAL_ORIGINAL_WEIGHT_HR = sum(param_data["weight_original"] for param_data in HR_PARAMETERS_CONFIG.values()) # Should be 85
141
+
142
+ # Add normalized weights to the config for calculating score out of 100
143
+ for param in HR_PARAMETERS_CONFIG:
144
+ HR_PARAMETERS_CONFIG[param]["weight_normalized"] = (HR_PARAMETERS_CONFIG[param]["weight_original"] / TOTAL_ORIGINAL_WEIGHT_HR) * 100
145
+
146
+
147
+ ########################################///////////////////////////////////////////////////#########################################
148
+ # SUmmary of improvement(function)
149
+
150
+ def generate_improvement_suggestions():
151
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
152
+ difficulty_level = st.session_state.get("difficulty_level_select", "Beginner")
153
+ level_string = difficulty_level.lower()
154
+
155
+ if not st.session_state.get("answers"):
156
+ st.session_state.improvement_suggestions = "No answers were recorded to generate improvement suggestions."
157
+ return
158
+
159
+ # Prepare the context for the LLM
160
+ qa_context = []
161
+ for i, entry in enumerate(st.session_state["answers"]):
162
+ qa_context.append(
163
+ f"Question {i+1}: {entry['question']}\n"
164
+ f"Candidate's Answer {i+1}: {str(entry.get('response', '[No response provided]'))}"
165
+ )
166
+ full_qa_context = "\n\n".join(qa_context)
167
+
168
+ initial_evaluation_feedback = st.session_state.get("evaluation_feedback", "Initial evaluation not available.")
169
+
170
+ # Remove any previous "Total Calculated Score..." line from the initial feedback
171
+ # to avoid confusing the LLM when it sees it as part of the context.
172
+ initial_evaluation_lines = initial_evaluation_feedback.splitlines()
173
+ cleaned_initial_evaluation = "\n".join(
174
+ line for line in initial_evaluation_lines if not line.strip().startswith("**Total Calculated Score:**")
175
+ )
176
+
177
+
178
+ improvement_prompt_template = """
179
+ You are an expert interview coach. You have the following information about a candidate's mock interview:
180
+ - Candidate's Level: {level_string}
181
+ - Questions Asked and Candidate's Answers:
182
+ {full_qa_context}
183
+ - Initial Evaluation Feedback Provided to Candidate:
184
+ ---
185
+ {cleaned_initial_evaluation}
186
+ ---
187
+
188
+ Based on all this information, your task is to provide DETAILED and CONSTRUCTIVE suggestions for each question to help the candidate improve. Be supportive and encouraging.
189
+
190
+ For EACH question, please provide:
191
+ 1. **How to Improve This Answer:** Specific, actionable advice on what the candidate could have added, clarified, or approached differently to make their answer better for their {level_string} level. Focus on 1-2 key improvement points.
192
+ 2. **Hints for an Ideal Answer:** Briefly mention 2-3 key concepts, terms, or elements that a strong answer (appropriate for their {level_string} level) would typically include. DO NOT provide a full model answer, just hints and pointers.
193
+
194
+ Keep the tone positive and focused on learning.
195
+
196
+ Structure your response clearly for each question. Example for one question:
197
+
198
+ ---
199
+ **Regarding Question X: "[Original Question Text Here]"**
200
+
201
+ *How to Improve This Answer:*
202
+ [Your specific suggestion 1 for improvement...]
203
+ [Your specific suggestion 2 for improvement...]
204
+
205
+ *Hints for an Ideal Answer (Key Points to Consider):*
206
+ - Hint 1 or Key concept 1
207
+ - Hint 2 or Key concept 2
208
+ - Hint 3 or Key element 3 (optional)
209
+ ---
210
+ (Repeat this structure for all questions)
211
+ """
212
+
213
+ formatted_improvement_prompt = improvement_prompt_template.format(
214
+ level_string=level_string,
215
+ full_qa_context=full_qa_context,
216
+ cleaned_initial_evaluation=cleaned_initial_evaluation
217
+ )
218
+
219
+ try:
220
+ st.info("πŸ€– Generating detailed improvement suggestions... Please wait.")
221
+ response = model.generate_content(formatted_improvement_prompt)
222
+ st.session_state.improvement_suggestions = response.text.strip()
223
+ st.session_state.improvement_suggestions_generated = True
224
+ st.success("Detailed suggestions generated!")
225
+ except Exception as e:
226
+ st.error(f"Error generating improvement suggestions: {e}")
227
+ st.session_state.improvement_suggestions = f"Could not generate suggestions due to an error: {e}"
228
+ st.session_state.improvement_suggestions_generated = False
229
+
230
+ ########################################///////////////////////////////////////////////////#########################################
231
+
232
+ # Evaluate candidate answers - YOUR FUNCTION
233
+
234
+
235
+
236
+ def evaluate_answers():
237
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
238
+ # difficulty_level_select is the key for the difficulty selectbox in your sidebar
239
+ difficulty_level = st.session_state.get("difficulty_level_select", "Beginner")
240
+ level_string = difficulty_level.lower()
241
+ num_answered_questions = len(st.session_state.get("answers", []))
242
+
243
+ # Reset improvement suggestions flag when re-evaluating
244
+ st.session_state.improvement_suggestions_generated = False
245
+ st.session_state.improvement_suggestions = ""
246
+
247
+ meaningful_answers_exist = False
248
+ if st.session_state.get("answers"):
249
+ for entry in st.session_state["answers"]:
250
+ response_text = str(entry.get('response', '')).strip().lower()
251
+ no_response_placeholders = [
252
+ "", "[no response provided]", "[no response - timed out]",
253
+ "[no response]", "no response", "[could not understand audio]",
254
+ "[no clear response recorded]", "[no action - timed out before recording]",
255
+ "[no speech detected in recording time]", "[no speech recorded - time up]",
256
+ "[recording stopped manually, possibly empty]",
257
+ "[no action - did not start recording]",
258
+ "[no speech detected in recording phase]"
259
+ ]
260
+ if response_text not in no_response_placeholders:
261
+ meaningful_answers_exist = True
262
+ break
263
+
264
+ if not meaningful_answers_exist:
265
+ no_answer_feedback_qualitative = "No meaningful answers were provided for evaluation.\n\n"
266
+ if st.session_state.selected_domain == "Soft Skills":
267
+ hr_params_na = "\n".join([f"- {param}: 0/5" for param in HR_PARAMETERS_CONFIG.keys()])
268
+ no_answer_feedback = (
269
+ "No meaningful answers were provided for evaluation.\n\n"
270
+ f"**Parameter Scores (1-5):**\n{hr_params_na}\n\n"
271
+ "**Overall Qualitative Feedback:**\nCandidate did not provide responses to evaluate soft skills."
272
+ )
273
+ st.session_state["hr_parameter_scores_dict"] = {param: 0.0 for param in HR_PARAMETERS_CONFIG.keys()} # Store zeroed scores
274
+ else: # Non-HR domains
275
+ no_answer_feedback = (
276
+ "No meaningful answers were provided.\n"
277
+ "**Total Calculated Score:** 0.0 / 0.0 (0.0%)\n\n" # Placeholder for non-HR if no answers
278
+ "**Overall Evaluation Summary:** N/A"
279
+ )
280
+ st.session_state["evaluation_feedback"] = no_answer_feedback
281
+ st.session_state["overall_score"] = 0.0
282
+ st.session_state["percentage_score"] = 0.0
283
+ return
284
+
285
+ # --- BRANCHING FOR HR (SOFT SKILLS) VS OTHER DOMAINS ---
286
+ if st.session_state.selected_domain == "Soft Skills":
287
+ hr_prompt_parameter_list = ""
288
+ for param, config in HR_PARAMETERS_CONFIG.items():
289
+ hr_prompt_parameter_list += f"- **{param}:** {config['rubric']}\n"
290
+
291
+ hr_prompt_template = f"""
292
+ You are an experienced HR interview evaluator assessing a candidate's soft skills based on their answers to interview questions.
293
+ The candidate's performance across ALL answers should inform your scores for the following parameters.
294
+
295
+ **Parameters to Score (Assign a score from 1 to 5 for each):**
296
+ {hr_prompt_parameter_list}
297
+
298
+ After providing a score (1-5) for each of the above parameters, also write an **Overall Qualitative Feedback** section.
299
+ This section should summarize the candidate's general soft skill strengths and areas for improvement, based on their communication, engagement, and professionalism throughout the interview.
300
+
301
+ **REQUIRED OUTPUT FORMAT (Strictly Adhere):**
302
+
303
+ **Parameter Scores (1-5):**
304
+ Voice Modulation: [score]
305
+ Confidence: [score]
306
+ Attitude: [score]
307
+ Flow & Fluency: [score]
308
+ Structured thoughts & Clarity: [score]
309
+ Sentence Formation: [score]
310
+ Basics of Grammar + SVA: [score]
311
+ Persuasiveness: [score]
312
+ Quality of Answers: [score]
313
+
314
+ **Overall Qualitative Feedback:**
315
+ [Your holistic qualitative feedback here. Be encouraging and constructive.]
316
+ """
317
+ candidate_responses_formatted_hr = "\n\n".join(
318
+ [f"Question {i+1}: {entry['question']}\nCandidate's Answer {i+1}: {str(entry.get('response', '[No response provided]'))}"
319
+ for i, entry in enumerate(st.session_state["answers"])]
320
+ )
321
+ #full_prompt_for_hr_evaluation = f"{hr_prompt_template}\n\nCandidate's Interview Answers:\n{candidate_responses_formatted_hr}"
322
+ full_prompt_for_hr_evaluation = f"{hr_prompt_template}\n\nCandidate's Interview Answers (Consider all of these for holistic parameter scoring):\n{candidate_responses_formatted_hr}"
323
+
324
+ try:
325
+ response_content = model.generate_content(full_prompt_for_hr_evaluation)
326
+ full_llm_response_text = response_content.text.strip()
327
+ print("--- FULL LLM SOFT SKILLS RESPONSE ---")
328
+ print(full_llm_response_text)
329
+ print("------ END RESPONSE ------")
330
+ print("--- AI Full Response for Soft Skills ---\n", full_llm_response_text, "\n------------------------")
331
+
332
+ hr_parameter_scores_parsed_dict = {} # To store parsed scores for each HR param
333
+ total_weighted_score_percentage = 0.0
334
+
335
+ for param_name_config, config_data in HR_PARAMETERS_CONFIG.items():
336
+ # Using a more specific regex, anchored to the start of a line (after optional list marker)
337
+ # re.escape ensures special characters in param_name_config are treated literally.
338
+ param_score_pattern = re.compile(
339
+ r"^\s*(?:[\*\-]\s*)?" + re.escape(param_name_config.split('(')[0].strip()) + r"\s*[:\-–—]?\s*(\d+(?:\.\d+)?)\b",
340
+ re.IGNORECASE | re.MULTILINE
341
+ ) # \b for word boundary after score
342
+
343
+ match = param_score_pattern.search(full_llm_response_text)
344
+ param_score = 1.0 # Default to 1 (lowest actual score) if not found or unparseable
345
+ if match:
346
+ try:
347
+ score_text = match.group(1)
348
+ param_score = float(score_text)
349
+ param_score = max(1.0, min(5.0, param_score)) # Clamp score strictly 1-5 for HR
350
+ print(f"HR Param '{param_name_config}' - Matched text: '{score_text}', Parsed: {param_score}")
351
+ except ValueError:
352
+ print(f"HR Param '{param_name_config}' - ValueError parsing score from '{score_text}' in match '{match.group(0)}'. Defaulting to 1.0.")
353
+ param_score = 1.0
354
+ else:
355
+ print(f"HR Param '{param_name_config}' - Score pattern not found. Defaulting to 1.0 for this param.")
356
+
357
+ hr_parameter_scores_parsed_dict[param_name_config] = param_score
358
+ total_weighted_score_percentage += (param_score / 5.0) * config_data["weight_normalized"] # Use normalized weight
359
+
360
+ st.session_state["hr_parameter_scores_dict"] = hr_parameter_scores_parsed_dict # Store for table display
361
+
362
+ num_qs_in_session = len(st.session_state.get("answers", []))
363
+ max_possible_score = num_qs_in_session * 5.0 # Each Q worth 5
364
+ actual_score = (total_weighted_score_percentage / 100.0) * max_possible_score
365
+
366
+ st.session_state["overall_score"] = round(actual_score, 1)
367
+ st.session_state["percentage_score"] = round((actual_score / max_possible_score) * 100, 1)
368
+
369
+
370
+ # Construct the feedback to be displayed: Parsed scores + Qualitative from LLM
371
+ # The full_llm_response_text might still be useful if qualitative parsing is tricky
372
+ parsed_scores_display_text = "**Parsed Parameter Scores (1-5 based on AI Evaluation):**\n"
373
+ for p_name, p_score in hr_parameter_scores_parsed_dict.items():
374
+ parsed_scores_display_text += f"- {p_name}: {p_score:.1f}/5\n"
375
+
376
+ qualitative_feedback_hr_extract = "Overall qualitative feedback section not clearly identified in AI response."
377
+ qualitative_match_hr = re.search(r"\*\*Overall Qualitative Feedback:\*\*(.*)", full_llm_response_text, re.DOTALL | re.IGNORECASE)
378
+ if qualitative_match_hr:
379
+ qualitative_feedback_hr_extract = qualitative_match_hr.group(1).strip()
380
+
381
+ st.session_state["evaluation_feedback"] = f"{parsed_scores_display_text}\n\n**Overall Qualitative Feedback from AI:**\n{qualitative_feedback_hr_extract}"
382
+
383
+ except Exception as e_hr_eval:
384
+ st.error(f"Error during HR/Soft Skills evaluation processing: {e_hr_eval}")
385
+ print(f"HR EVALUATION PROCESSING TRACEBACK:\n{traceback.format_exc()}")
386
+ st.session_state["evaluation_feedback"] = f"Could not process HR skills evaluation: {e_hr_eval}"
387
+ st.session_state["overall_score"] = 0.0
388
+ st.session_state["percentage_score"] = 0.0
389
+
390
+ else: # --- NON-HR (Analytics, Finance) Evaluation Logic ---
391
+ base_assessment_criteria_qualitative_non_hr = """
392
+ For the OVERALL qualitative summary, assess responses based on:
393
+ - Conceptual Understanding (effort and relevance more than perfect accuracy for the level)
394
+ - Communication Clarity (can the core idea be understood?)
395
+ - Depth of Explanation (relative to expected level)
396
+ - Use of Examples (if any, and if appropriate for the level)
397
+ - Logical Flow (is there a basic structure or train of thought?)
398
+ """
399
+ per_question_scoring_guidelines_non_hr = f"""
400
+ For EACH question and its answer, provide a score from 0 to 5 points.
401
+ The candidate is at a {level_string} level.
402
+ Consider the following when assigning the per-question score:
403
+ - Effort: Did the candidate attempt a meaningful answer, even if partially incorrect?
404
+ - Relevance: Is the response at least partially related to the question topic?
405
+ - Clarity of thought for the candidate's level.
406
+ - Basic logical structure.
407
+ - Use of examples, if any were given and appropriate.
408
+ """
409
+ if level_string == "beginner":
410
+ level_specific_instructions_non_hr = """
411
+ You are an **extremely understanding, encouraging, and supportive** interview evaluator for a **BEGINNER/FRESHER**. Your primary goal is to **build confidence**.
412
+ **Scoring Guidelines for Beginners (0-5 points per question):**
413
+ - **5 points:** Accurate, clear, and well-structured answer. Shows clear effort and basic understanding.
414
+ - **4 points:** Mostly correct with minor gaps or unclear phrasing.Good attempt, relevant, shows some understanding or key terms (e.g., one/two relevant words).
415
+ - **3 points:** Partially correct with evident effort, but lacks clarity or completeness.
416
+ - **1-2 points:** Minimal effort, mostly irrelevant, but an attempt beyond silence.
417
+ - **0 points:** Candidate explicitly says "I don’t know", "I'm not sure", or provides placeholder/non-answers. No relevant effort or understanding shown.Incorrect or unrelated.
418
+ Provide VERY positive feedback.
419
+ """
420
+ elif level_string == "intermediate":
421
+ level_specific_instructions_non_hr = """Supportive evaluator for **INTERMEDIATE**. Scoring (0-5): 5=Correct/Clear; 3-4=Mostly correct; 1-2=Partial/Gaps; 0=Incorrect."""
422
+ else: # Advanced
423
+ level_specific_instructions_non_hr = """Discerning evaluator for **ADVANCED**. Scoring (0-5): 5=Accurate/Comprehensive; 3-4=Correct lacks nuance; 1-2=Inaccurate; 0=Fundamentally incorrect."""
424
+
425
+ evaluation_prompt_template_non_hr = f"""
426
+ {level_specific_instructions_non_hr}
427
+ {per_question_scoring_guidelines_non_hr}
428
+ {base_assessment_criteria_qualitative_non_hr}
429
+ **YOUR RESPONSE MUST STRICTLY FOLLOW THIS FORMAT. PROVIDE SCORES FOR EACH QUESTION.**
430
+ Output format:
431
+
432
+ **Per-Question Scores:**
433
+ Question 1 Score: [Score for Q1 out of 5]
434
+ ... (repeat for all {num_answered_questions} questions provided)
435
+
436
+ **Overall Evaluation Summary:**
437
+ - Concept Understanding: [Overall qualitative feedback here]
438
+ - Communication: [Overall qualitative feedback here]
439
+ - Depth of Explanation: [Overall qualitative feedback here]
440
+ - Examples: [Overall qualitative feedback here]
441
+ - Logical Flow: [Overall qualitative feedback here]
442
+ [Any additional overall encouraging remarks can optionally follow here]
443
+ """
444
+ candidate_responses_formatted_non_hr = "\n\n".join(
445
+ [f"Question {i+1}: {entry['question']}\nAnswer {i+1}: {str(entry.get('response', '[No response provided]'))}" for i, entry in enumerate(st.session_state["answers"])]
446
+ )
447
+ full_prompt_for_non_hr_evaluation = f"{evaluation_prompt_template_non_hr}\n\nCandidate Responses:\n{candidate_responses_formatted_non_hr}"
448
+
449
+ try:
450
+ response_content_non_hr = model.generate_content(full_prompt_for_non_hr_evaluation)
451
+ full_llm_response_text_non_hr = response_content_non_hr.text.strip()
452
+ raw_llm_feedback_non_hr = full_llm_response_text_non_hr
453
+
454
+ print("--- LLM Output for Non-HR Score Extraction ---"); print(full_llm_response_text_non_hr); print("---")
455
+
456
+ total_score_non_hr = 0.0; parsed_scores_count_non_hr = 0; per_question_scores_list_non_hr = []
457
+ score_line_pattern_non_hr = re.compile(r"Question\s*(\d+)\s*Score:\s*(\d+(?:\.\d+)?)(?:\s*/\s*5)?", re.IGNORECASE)
458
+ text_to_search_non_hr = full_llm_response_text_non_hr
459
+ scores_block_match_non_hr = re.search(r"(?i)\*\*Per-Question Scores:\*\*(.*?)(?=\*\*Overall Evaluation Summary:\*\*|\Z)", text_to_search_non_hr, re.DOTALL)
460
+
461
+ if scores_block_match_non_hr:
462
+ text_to_search_non_hr = scores_block_match_non_hr.group(1).strip()
463
+ print(f"Non-HR: Found 'Per-Question Scores' block:\n{text_to_search_non_hr}")
464
+ else:
465
+ print("Non-HR: No dedicated 'Per-Question Scores' block found; searching entire response.")
466
+
467
+
468
+ for match_non_hr in score_line_pattern_non_hr.finditer(text_to_search_non_hr):
469
+ q_num_text_non_hr, score_val_text_non_hr = match_non_hr.group(1), match_non_hr.group(2)
470
+ try:
471
+ score_non_hr = float(score_val_text_non_hr)
472
+ score_non_hr = max(0.0, min(5.0, score_non_hr))
473
+ total_score_non_hr += score_non_hr
474
+ parsed_scores_count_non_hr += 1
475
+ per_question_scores_list_non_hr.append(f"Question {q_num_text_non_hr}: {score_non_hr:.1f}/5")
476
+ print(f"Non-HR Matched Q{q_num_text_non_hr} Score: {score_non_hr}")
477
+ except ValueError:
478
+ print(f"Non-HR Warning: Could not parse score '{score_val_text_non_hr}' from: '{match_non_hr.group(0)}'")
479
+
480
+ if parsed_scores_count_non_hr != num_answered_questions and meaningful_answers_exist:
481
+ st.warning(f"Non-HR Score Count Mismatch: Parsed {parsed_scores_count_non_hr} scores, expected {num_answered_questions}.")
482
+ print(f"Non-HR Score Count Mismatch: Expected {num_answered_questions}, got {parsed_scores_count_non_hr}")
483
+
484
+ if parsed_scores_count_non_hr == 0 and meaningful_answers_exist:
485
+ st.warning("CRITICAL (Non-HR): No per-question scores parsed from LLM response. Total score set to 0.")
486
+ print("CRITICAL (Non-HR): No per-question scores parsed.")
487
+ total_score_non_hr = 0.0
488
+
489
+ max_score_non_hr = num_answered_questions * 5.0
490
+ st.session_state["overall_score"] = total_score_non_hr
491
+ st.session_state["percentage_score"] = (total_score_non_hr / max_score_non_hr) * 100.0 if max_score_non_hr > 0 else 0.0
492
+
493
+ final_feedback_non_hr = f"**Total Calculated Score:** {st.session_state['overall_score']:.1f} / {max_score_non_hr:.1f} ({st.session_state['percentage_score']:.1f}%)\n\n"
494
+ if per_question_scores_list_non_hr:
495
+ final_feedback_non_hr += "**Parsed Per-Question Scores:**\n" + "\n".join(per_question_scores_list_non_hr) + "\n\n"
496
+
497
+ qual_summary_match_non_hr = re.search(r"\*\*Overall Evaluation Summary:\*\*(.*)", raw_llm_feedback_non_hr, re.DOTALL | re.IGNORECASE)
498
+ if qual_summary_match_non_hr:
499
+ final_feedback_non_hr += "**Overall Qualitative Summary (from AI):**\n" + qual_summary_match_non_hr.group(1).strip()
500
+ else:
501
+ final_feedback_non_hr += "\n---\n**Full AI Response (for context if summary parsing failed):**\n" + raw_llm_feedback_non_hr
502
+ st.session_state["evaluation_feedback"] = final_feedback_non_hr.strip()
503
+
504
+ except Exception as e_non_hr_eval:
505
+ st.error(f"Error during Non-HR evaluation processing: {e_non_hr_eval}")
506
+ print(f"NON-HR EVALUATION PROCESSING TRACEBACK:\n{traceback.format_exc()}")
507
+ st.session_state["evaluation_feedback"] = f"Could not process Non-HR evaluation: {e_non_hr_eval}"
508
+ st.session_state["overall_score"] = 0.0
509
+ st.session_state["percentage_score"] = 0.0
510
+ ########################################///////////////////////////////////////////////////#########################################
511
+ # --- Prompts for Question Generation ---
512
+ BEGINNER_PROMPT = """
513
+ You are a friendly mock interview trainer conducting a **Beginner-level** spoken interview in the domain of **{domain}**.
514
+ Ask basic verbal interview questions based on the candidate's input: **{input_text}**.
515
+
516
+ Guidelines:
517
+ - Ask simple conceptual questions.
518
+ - Avoid jargon and complex examples.
519
+ - Use easy language.
520
+ - No coding or technical syntax required.
521
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
522
+ **New Requirement:**
523
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
524
+
525
+ **Guidelines:**
526
+ βœ… Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
527
+ βœ… Ensure questions are direct, structured, and relevant to real-world applications.
528
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
529
+ ❌ Avoid vague or open-ended statementsβ€”each question should be concise and specific.
530
+ """
531
+
532
+ INTERMEDIATE_PROMPT = """
533
+ You are a professional mock interviewer conducting an **Intermediate-level** spoken interview in the domain of **{domain}**.
534
+ Ask moderately challenging verbal interview questions based on the candidate's input: **{input_text}**.
535
+
536
+ Guidelines:
537
+ - Use a mix of conceptual and real-world scenario questions.
538
+ - Include light critical thinking.
539
+ - Still no need for code, formulas, or complex diagrams.
540
+ - No coding or technical syntax required.
541
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
542
+ **New Requirement:**
543
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
544
+
545
+ **Guidelines:**
546
+ βœ… Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
547
+ βœ… Ensure questions are direct, structured, and relevant to real-world applications.
548
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
549
+ ❌ Avoid vague or open-ended statementsβ€”each question should be concise and specific.
550
+ """
551
+
552
+ ADVANCED_PROMPT = """
553
+ You are a strict mock interviewer conducting an **Advanced-level** spoken interview in the domain of **{domain}**.
554
+ Ask deep, analytical, real-world scenario-based questions from the candidate's input: **{input_text}**.
555
+
556
+ Guidelines:
557
+ - Expect detailed, logical, well-structured answers.
558
+ - Include challenging β€œwhy” and β€œhow” based questions.
559
+ - No need for code, but assume candidate has high expertise.
560
+ - No coding or technical syntax required.
561
+ Ensure the questions are clear, to the point, and suitable for a {difficulty_level}-level interview in {selected_domain}.
562
+ **New Requirement:**
563
+ 🚫 **Do NOT repeat any questions from previous generations again and again.** Ensure all generated questions are unique and different from past sessions.
564
+
565
+ **Guidelines:**
566
+ βœ… Questions should focus on key concepts, best practices, and problem-solving within {selected_domain}.
567
+ βœ… Ensure questions are direct, structured, and relevant to real-world applications.
568
+ ❌ Do NOT include greetings like 'Let's begin' or 'Welcome to the interview'.
569
+ ❌ Avoid vague or open-ended statementsβ€”each question should be concise and specific.
570
+ """
571
+
572
+ ########################################///////////////////////////////////////////////////#########################################
573
+ # UI styles
574
+ st.markdown("""
575
+ <style>
576
+ /* Base style for all stButton elements */
577
+ .stButton > button {
578
+ background-color: #007BFF !important;
579
+ color: white !important;
580
+ border-radius: 10px !important;
581
+ font-weight: bold !important;
582
+ width: 100% !important;
583
+ padding: 0.4rem 0.75rem !important;
584
+ font-size: 0.95rem !important;
585
+ line-height: 1.5 !important;
586
+ border: 1px solid transparent !important;
587
+ transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out !important;
588
+ margin-bottom: 8px !important;
589
+ box-sizing: border-box;
590
+ }
591
+ .stButton > button:hover {
592
+ background-color: #0056b3 !important;
593
+ color: white !important;
594
+ border-color: #0056b3 !important;
595
+ }
596
+ .stButton > button:focus,
597
+ .stButton > button:active {
598
+ background-color: #0056b3 !important;
599
+ border-color: #004085 !important;
600
+ box-shadow: 0 0 0 0.2rem rgba(0,123,255,.5) !important;
601
+ outline: none !important;
602
+ }
603
+
604
+ .timer-text {
605
+ font-size: 1.3rem;
606
+ font-weight: 600;
607
+ color: #00bcd4;
608
+ animation: pulse 1s infinite;
609
+ }
610
+ @keyframes pulse {
611
+ 0% {opacity: 1;}
612
+ 50% {opacity: 0.4;}
613
+ 100% {opacity: 1;}
614
+ }
615
+
616
+ .summary-card {
617
+ background-color: #f9f9f9;
618
+ padding: 20px;
619
+ border-radius: 12px;
620
+ border: 1px solid #ddd;
621
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
622
+ }
623
+ /* More specific selector for the pre text color */
624
+ div.summary-card > pre {
625
+ white-space: pre-wrap !important;
626
+ word-wrap: break-word !important;
627
+ font-family: inherit !important;
628
+ font-size: 0.95rem !important;
629
+ color: #000000 !important; /* TRYING PURE BLACK with !important */
630
+ background-color: #ffffff !important; /* Ensure background is white */
631
+ padding: 15px !important;
632
+ border-radius: 8px !important;
633
+ border: 1px solid #e0e0e0 !important;
634
+ max-height: 400px !important;
635
+ overflow-y: auto !important;
636
+ }
637
+ </style>
638
+ """, unsafe_allow_html=True)
639
+
640
+ # Header
641
+ st.markdown("""
642
+ <div style='text-align: center; margin-top: -30px; padding-top: 10px;'>
643
+ <h1 style='font-size: 2.8rem; font-weight: 800; color: #003366;'>🎯 Welcome to <span style='color: #007BFF;'>GrillMaster</span></h1>
644
+ <p style='font-size: 1.1rem; color: #555;'>Your AI-powered mock interview assistant</p>
645
+ </div>
646
+ <hr style='border: 1px solid #e0e0e0; margin: 20px auto;'>
647
+ """, unsafe_allow_html=True)
648
+
649
+ if not st.session_state["generated_questions"]:
650
+ st.markdown("""
651
+ <div style='text-align: center; margin-top: -10px; margin-bottom: 30px;'>
652
+ <h3 style='font-weight: 700; color: #333;'>πŸš€ Let's get started!</h3>
653
+ <p style='font-size: 1rem; color: #666;'>Select your interview domain and input type to begin your practice session.</p>
654
+ </div>
655
+ <hr style='border: 1px solid #e0e0e0; margin-top: 0px;'>
656
+ """, unsafe_allow_html=True)
657
+
658
+ # Example soft skills questions for HR/Soft Skills domain
659
+ if st.session_state["selected_domain"] == "Soft Skills":
660
+ hr_questions = [
661
+ "Tell me about yourself.",
662
+ "Why should we hire you?",
663
+ "What are your strengths and weaknesses?",
664
+ "What is the difference between hard work and smart work?",
665
+ "Why do you want to work at our company?",
666
+ "How do you feel about working nights and weekends?",
667
+ "Can you work under pressure?",
668
+ "What are your goals?",
669
+ "Are you willing to relocate or travel?",
670
+ "What motivates you to do good job?",
671
+ "What would you want to accomplish within your first 30 days of employment?",
672
+ "What do you prefer working alone or in collaborative environment?",
673
+ "Give me an example of your creativity.",
674
+ "How long would you expect to work for us if hired?",
675
+ "Are not you overqualified for this position?",
676
+ "Describe your ideal company, location and job.",
677
+ "Explain how would you be an asset to this organization?",
678
+ "What are your interests?",
679
+ "Would you lie for the company?",
680
+ "Who has inspired you in your life and why?",
681
+ "What was the toughest decision you ever had to make?",
682
+ "Have you considered starting your own business?",
683
+ "How do you define success and how do you measure up to your own definition?",
684
+ "Tell me something about our company.",
685
+ "How much salary do you expect?",
686
+ "Where do you see yourself five years from now?",
687
+ "Do you have any questions for me?",
688
+ "Are you a manager or a leader?",
689
+ "Imagine that you are not lucky enough to get this job, how will you take it?"
690
+ ]
691
+
692
+ # === Sidebar: Domain and Input Configuration ===
693
+ st.sidebar.subheader("Select Interview Domain:")
694
+ for domain in ["Analytics", "Soft Skills"]:
695
+ if st.sidebar.button(domain):
696
+ st.session_state.clear() # πŸ” Reset entire session state
697
+ st.session_state["selected_domain"] = domain
698
+ st.rerun()
699
+
700
+ if not st.session_state["selected_domain"]:
701
+ st.sidebar.info("Please select a domain to continue.")
702
+ st.stop()
703
+
704
+ st.sidebar.markdown(f"**Selected Domain:** {st.session_state['selected_domain']}")
705
+ num_qs = st.sidebar.slider("Number of Questions:", 1, 10, 3)
706
+
707
+ if st.session_state["selected_domain"] == "Soft Skills":
708
+ soft_skill_mode = st.sidebar.radio(
709
+ "Choose Soft Skills Mode:",
710
+ ("Resume-Based", "HR Round")
711
+ )
712
+ if soft_skill_mode == "Resume-Based":
713
+ uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
714
+ if uploaded_file:
715
+ input_text = extract_pdf_text(uploaded_file)
716
+ else:
717
+ input_text = "General HR Round"
718
+
719
+ if st.sidebar.button("Generate Questions"):
720
+ if soft_skill_mode == "HR Round":
721
+ st.session_state["generated_questions"] = sample(hr_questions, num_qs)
722
+ else:
723
+ if not input_text.strip():
724
+ st.warning("⚠️ Please upload a resume.")
725
+ st.stop()
726
+ prompt = f"Ask {num_qs} HR-style interview questions based on this resume: {input_text}"
727
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
728
+ response = model.generate_content([prompt])
729
+ questions = [q.strip("* ") for q in response.text.strip().split("\n") if q.strip()]
730
+ st.session_state["generated_questions"] = questions[:num_qs]
731
+
732
+ st.session_state["current_question_index"] = 0
733
+ st.rerun()
734
+
735
+ else:
736
+ section_choice = st.sidebar.radio(
737
+ "Choose Input Type:",
738
+ ("Resume", "Job Description", "Skills")
739
+ )
740
+ #difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
741
+ input_text = ""
742
+
743
+ if section_choice == "Resume":
744
+ difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
745
+ uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
746
+ if uploaded_file:
747
+ input_text = extract_pdf_text(uploaded_file)
748
+
749
+ elif section_choice == "Job Description":
750
+ difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
751
+ input_text = st.sidebar.text_area("Paste Job Description:")
752
+
753
+ elif section_choice == "Skills":
754
+ difficulty = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
755
+ skills = {
756
+ "Analytics": ["Excel","Python", "SQL", "Machine Learning", "Statistics", "Power BI","Tableau"]
757
+ }
758
+ skill_list = skills.get(st.session_state["selected_domain"], [])
759
+ if skill_list:
760
+ selected_skill = st.sidebar.selectbox("Select a Skill:", skill_list, key="skill_select")
761
+ input_text = selected_skill
762
+ st.sidebar.markdown(f"βœ… Selected Skill: **{selected_skill}**")
763
+
764
+
765
+ if st.sidebar.button("Generate Questions"):
766
+ if not input_text.strip():
767
+ st.warning("⚠️ Please provide input based on the selected method.")
768
+ st.stop()
769
+
770
+ prompt = f"Ask {num_qs} direct and core-level {difficulty} interview questions related to {input_text}. Do not include intros or numbering."
771
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
772
+ response = model.generate_content([prompt, input_text])
773
+ lines = response.text.strip().split("\n")
774
+ questions = [q.strip("* ") for q in lines if q.strip()]
775
+ st.session_state["generated_questions"] = questions[:num_qs]
776
+
777
+ st.session_state["current_question_index"] = 0
778
+ st.session_state["answers"] = []
779
+ st.session_state["evaluation_feedback"] = ""
780
+ st.session_state["recorded_text"] = ""
781
+ st.session_state["response_captured"] = False
782
+ st.session_state["timer_start"] = None
783
+ st.session_state["show_summary"] = False
784
+ st.session_state["question_played"] = False
785
+ st.session_state["recording_complete"] = False
786
+ st.rerun()
787
+
788
+ def get_ice_servers():
789
+ """Use Twilio's TURN server because Streamlit Community Cloud has changed
790
+ its infrastructure and WebRTC connection cannot be established without TURN server now. # noqa: E501
791
+ We considered Open Relay Project (https://www.metered.ca/tools/openrelay/) too,
792
+ but it is not stable and hardly works as some people reported like https://github.com/aiortc/aiortc/issues/832#issuecomment-1482420656 # noqa: E501
793
+ See https://github.com/whitphx/streamlit-webrtc/issues/1213
794
+ """
795
+
796
+ # Ref: https://www.twilio.com/docs/stun-turn/api
797
+ try:
798
+ account_sid = os.environ["TWILIO_ACCOUNT_SID"]
799
+ auth_token = os.environ["TWILIO_AUTH_TOKEN"]
800
+ except KeyError:
801
+ logger.warning(
802
+ "Twilio credentials are not set. Fallback to a free STUN server from Google." # noqa: E501
803
+ )
804
+ return [{"urls": ["stun:stun.l.google.com:19302"]}]
805
+
806
+ client = Client(account_sid, auth_token)
807
+
808
+ token = client.tokens.create()
809
+
810
+ return token.ice_servers
811
+
812
+
813
+
814
+ # === Main QA Interface ===
815
+
816
+ if st.session_state.get("generated_questions"):
817
+ idx = st.session_state.get("current_question_index", 0)
818
+ if idx < len(st.session_state["generated_questions"]):
819
+ question = st.session_state["generated_questions"][idx].lstrip("1234567890. ").strip()
820
+
821
+ # Phase 0: Generate & play question audio
822
+ if not st.session_state.get("question_played"):
823
+ st.session_state["question_audio_file"] = asyncio.run(generate_question_audio(question))
824
+ st.session_state.update({
825
+ "question_played": True,
826
+ "question_start_time": time.time(),
827
+ "record_phase": "audio_playing",
828
+ "recorded_text": "",
829
+ "response_file": None
830
+ })
831
+ st.markdown(f"**Q{idx + 1}:** {question}")
832
+ st.audio(st.session_state["question_audio_file"], format="audio/mp3")
833
+
834
+ now = time.time()
835
+ elapsed = now - st.session_state.get("question_start_time", 0)
836
+
837
+ # Phase 1: Audio Playing
838
+ if st.session_state["record_phase"] == "audio_playing":
839
+ if elapsed < 5:
840
+ st.markdown("<h4 class='timer-text'>πŸ”Š Playing question audio... Please listen</h4>", unsafe_allow_html=True)
841
+ time.sleep(1)
842
+ st.rerun()
843
+ else:
844
+ st.session_state["record_phase"] = "waiting_to_start"
845
+ st.session_state["question_start_time"] = time.time()
846
+ st.rerun()
847
+
848
+ # Phase 2: Waiting to Start Recording
849
+ elif st.session_state["record_phase"] == "waiting_to_start":
850
+ remaining = 10 - int(elapsed)
851
+ if remaining > 0:
852
+ st.markdown(f"<h4 class='timer-text'>⏳ {remaining} seconds to click 'Start Recording'...</h4>", unsafe_allow_html=True)
853
+ if st.button("πŸŽ™οΈ Start Recording"):
854
+ st.session_state.update({
855
+ "record_phase": "recording",
856
+ "timer_start": time.time(),
857
+ "recording_started": True,
858
+ "response_file": None
859
+ })
860
+ st.rerun()
861
+ time.sleep(1)
862
+ st.rerun()
863
+ else:
864
+ 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)
865
+ st.session_state["answers"].append({"question": question, "response": "[No response]"})
866
+ st.session_state.update({
867
+ "record_phase": "idle",
868
+ "question_played": False,
869
+ "question_start_time": 0.0,
870
+ "current_question_index": idx + 1
871
+ })
872
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
873
+ evaluate_answers()
874
+ st.session_state["show_summary"] = True
875
+ st.rerun()
876
+
877
+ # Phase 3: Recording
878
+ elif st.session_state["record_phase"] == "recording":
879
+ st.markdown(f"<h4 class='timer-text'>πŸŽ™οΈ Recording... Click below to stop when done</h4>", unsafe_allow_html=True)
880
+ audio_value = st.audio_input("🎀 Tap to record your answer β€” then stop when done", key=f"audio_{idx}")
881
+
882
+ if audio_value and st.button("⏹️ Stop Recording"):
883
+ wav_path = f"response_{idx}.wav"
884
+ with open(wav_path, "wb") as f:
885
+ f.write(audio_value.getbuffer())
886
+
887
+ recognizer = sr.Recognizer()
888
+ try:
889
+ with sr.AudioFile(wav_path) as source:
890
+ audio = recognizer.record(source)
891
+ transcript = recognizer.recognize_google(audio)
892
+ except sr.UnknownValueError:
893
+ transcript = "[Could not understand audio]"
894
+ except sr.RequestError:
895
+ transcript = "[Google API error]"
896
+ except Exception as e:
897
+ transcript = f"[Transcription failed: {e}]"
898
+
899
+ st.session_state.update({
900
+ "response_file": wav_path,
901
+ "record_phase": "listening",
902
+ "recorded_text": transcript
903
+ })
904
+ st.session_state["answers"].append({
905
+ "question": question,
906
+ "response_file": wav_path,
907
+ "response": transcript
908
+ })
909
+ st.success("βœ… Audio recorded. You may now confirm your answer.")
910
+ st.rerun()
911
+
912
+ # Phase 4: Listening / Confirming
913
+ elif st.session_state["record_phase"] == "listening":
914
+ st.success("🎧 Review your recorded response below:")
915
+ #st.audio(st.session_state["response_file"], format="audio/wav")
916
+ st.markdown(f"**Your Response (text):** {st.session_state['recorded_text']}")
917
+
918
+ if st.button("βœ… Confirm & Next"):
919
+ st.session_state.update({
920
+ "record_phase": "idle",
921
+ "recording_started": False,
922
+ "question_played": False,
923
+ "question_start_time": 0.0,
924
+ "current_question_index": idx + 1,
925
+ "response_file": None
926
+ })
927
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
928
+ evaluate_answers()
929
+ st.session_state["show_summary"] = True
930
+ st.rerun()
931
+
932
+
933
+ # === Summary Display ===
934
+ if st.session_state.get("show_summary", False):
935
+ st.subheader("πŸ“Š Complete Mock Interview Summary")
936
+
937
+ # Fetch values from session state, providing defaults
938
+ feedback_content_for_display = st.session_state.get('evaluation_feedback', "Evaluation details not available.")
939
+ if not isinstance(feedback_content_for_display, str):
940
+ feedback_content_for_display = str(feedback_content_for_display)
941
+
942
+ # Max score basis is the number of questions that were *generated* for the session
943
+ num_qs_in_session = len(st.session_state.get("generated_questions", []))
944
+ if num_qs_in_session == 0 and st.session_state.get("answers"): # Fallback if no generated_questions but answers exist
945
+ num_qs_in_session = len(st.session_state.answers)
946
+
947
+ if st.session_state["selected_domain"] == "Soft Skills":
948
+ num_qs_in_session = len(st.session_state.get("answers", []))
949
+ max_score_possible_for_session = num_qs_in_session * 5.0
950
+
951
+ else:
952
+ if st.session_state["selected_domain"] == "Soft Skills":
953
+ num_hr_params = len(st.session_state.get("hr_parameter_scores_dict", {}))
954
+ max_score_possible_for_session = num_hr_params * 5.0
955
+ else:
956
+ max_score_possible_for_session = num_qs_in_session * 5.0
957
+
958
+ #max_score_possible_for_session = num_qs_in_session * 5.0
959
+ current_percentage_score = st.session_state.get('percentage_score', 0.0)
960
+ current_overall_score = st.session_state.get('overall_score', 0.0)
961
+
962
+ if st.session_state["selected_domain"] == "Soft Skills":
963
+ hr_table_data = []
964
+ for param, config in HR_PARAMETERS_CONFIG.items():
965
+ score = st.session_state.get("hr_parameter_scores_dict", {}).get(param, 0.0)
966
+ weight_percent = config["weight_original"]
967
+ contribution = (score / 5.0) * config["weight_normalized"]
968
+ hr_table_data.append({
969
+ "Parameter": param,
970
+ "Weight (Original %)": f"{weight_percent}%",
971
+ "Score (1–5)": round(score, 1),
972
+ "Contribution to Final %": f"{contribution:.1f}%"
973
+ })
974
+
975
+ hr_table_data.append({
976
+ "Parameter": "Total",
977
+ "Weight (Original %)": "100%",
978
+ "Score (1–5)": "",
979
+ "Contribution to Final %": f"{current_percentage_score:.1f}%"
980
+ })
981
+
982
+ hr_df = pd.DataFrame(hr_table_data)
983
+ st.markdown("### 🧾 Soft Skills Evaluation Breakdown")
984
+ st.dataframe(hr_df, use_container_width=True)
985
+
986
+ # Display the calculated score and percentage bar first in a card
987
+ st.markdown(f"""
988
+ <div class='summary-card' style="margin-bottom: 20px;">
989
+ <h4 style="color: #212529;">βœ… <strong>Overall Score:</strong> {current_overall_score:.1f} / {max_score_possible_for_session:.1f}
990
+ ({current_percentage_score:.1f}%)
991
+ </h4>
992
+ <div style='margin:10px 0; position:relative;'>
993
+ <div style="background:#eee; border-radius:10px; overflow:hidden; height:30px; position:relative;">
994
+ <div style="
995
+ width:{current_percentage_score}%;
996
+ background:#00c851; /* Green for progress */
997
+ height:100%;
998
+ border-radius:10px 0 0 10px; /* Keep left radius for progress */
999
+ transition: width 0.4s ease-in-out;
1000
+ "></div>
1001
+ <div style="
1002
+ position:absolute;
1003
+ top:0;
1004
+ left:0;
1005
+ width:100%;
1006
+ height:100%;
1007
+ display:flex;
1008
+ align-items:center;
1009
+ justify-content:center;
1010
+ font-weight:bold;
1011
+ color: black !important; /* Ensure text is visible on green/grey */
1012
+ font-size: 0.9rem;
1013
+ user-select:none; /* Prevent text selection */
1014
+ ">
1015
+ {current_percentage_score:.1f}%
1016
+ </div>
1017
+ </div>
1018
+ </div>
1019
+ </div>
1020
+ """, unsafe_allow_html=True)
1021
+
1022
+ # Display the detailed evaluation feedback text in a separate section
1023
+ st.markdown("---")
1024
+ st.markdown("<h4 style='color: #212529;'>Detailed Evaluation & Feedback from AI:</h4>", unsafe_allow_html=True)
1025
+
1026
+ # Use a styled div for the feedback text block to ensure good readability
1027
+ # Replace newlines with <br> for proper HTML multiline display
1028
+ html_formatted_feedback = feedback_content_for_display.replace('\n', '<br>')
1029
+ st.markdown(f"""
1030
+ <div style="background-color: #ffffff; color: #212529; padding: 15px; border-radius: 8px; border: 1px solid #e0e0e0; margin-top:10px; max-height: 500px; overflow-y: auto; white-space: normal; word-wrap: break-word;">
1031
+ {html_formatted_feedback}
1032
+ </div>
1033
+ """, unsafe_allow_html=True)
1034
+
1035
+ st.markdown("---") # Separator
1036
+
1037
+ # Buttons for suggestions, download, practice
1038
+ cols_summary_buttons = st.columns([1, 1, 1]) # 3 columns for the buttons
1039
+
1040
+ with cols_summary_buttons[0]:
1041
+ if st.button("πŸ’‘ Get Improvement Suggestions", key="get_suggestions_btn_final", use_container_width=True):
1042
+ # Regenerate suggestions if not present or explicitly requested again
1043
+ generate_improvement_suggestions() # This function should handle st.info/st.success
1044
+ st.rerun() # Rerun to show the expander or updated suggestions
1045
+
1046
+ # Helper function to prepare summary text for download
1047
+ def prepare_summary_for_download():
1048
+ download_text = f"# GrillMaster Mock Interview Summary\n\n"
1049
+ download_text += f"**Selected Domain:** {st.session_state.get('selected_domain', 'N/A')}\n"
1050
+ dl_difficulty = st.session_state.get('difficulty_level_select', 'N/A')
1051
+ download_text += f"**Difficulty Level:** {dl_difficulty}\n"
1052
+
1053
+ num_q_for_max_score = len(st.session_state.get("generated_questions", st.session_state.get("answers",[])))
1054
+ max_s_for_dl = num_q_for_max_score * 5.0
1055
+
1056
+ download_text += f"**Calculated Overall Score:** {st.session_state.get('overall_score', 0.0):.1f} / {max_s_for_dl:.1f} ({st.session_state.get('percentage_score', 0.0):.1f}%)\n\n"
1057
+
1058
+ download_text += "## Questions & Candidate's Answers:\n"
1059
+ num_answers_actually_given = len(st.session_state.get("answers", []))
1060
+ for i in range(num_q_for_max_score):
1061
+ question_text_dl = st.session_state.generated_questions[i] if i < len(st.session_state.generated_questions) else "Question text not found"
1062
+ answer_text_dl = "[No answer recorded]"
1063
+ if i < num_answers_actually_given:
1064
+ answer_text_dl = str(st.session_state.answers[i].get('response', '[No response provided]'))
1065
+
1066
+ download_text += f"**Question {i+1}:** {question_text_dl}\n"
1067
+ download_text += f"**Your Answer {i+1}:** {answer_text_dl}\n\n"
1068
+
1069
+ download_text += "\n## AI Evaluation Details (Includes Parsed Scores and Qualitative Feedback):\n"
1070
+ # st.session_state.evaluation_feedback is now already pre-formatted
1071
+ download_text += st.session_state.get('evaluation_feedback', "No AI evaluation available.")
1072
+ download_text += "\n\n"
1073
+
1074
+ if st.session_state.get("improvement_suggestions_generated", False) and st.session_state.get("improvement_suggestions"):
1075
+ download_text += "\n## Detailed Improvement Suggestions from AI:\n"
1076
+ download_text += st.session_state.get('improvement_suggestions', "No improvement suggestions were generated.")
1077
+
1078
+ return download_text.encode('utf-8')
1079
+
1080
+ with cols_summary_buttons[1]:
1081
+ summary_bytes_dl_final = prepare_summary_for_download()
1082
+ st.download_button(
1083
+ label="πŸ’Ύ Download Full Summary",
1084
+ data=summary_bytes_dl_final,
1085
+ file_name=f"GrillMaster_Summary_{st.session_state.get('selected_domain','General')}_{time.strftime('%Y%m%d_%H%M')}.md",
1086
+ mime="text/markdown",
1087
+ key="download_summary_final_btn",
1088
+ use_container_width=True
1089
+ )
1090
+
1091
+
1092
+
1093
+ # Expander for detailed suggestions, shown if generated
1094
+ if st.session_state.get("improvement_suggestions_generated", False) and st.session_state.get("improvement_suggestions"):
1095
+ with st.expander("πŸ” View Detailed Improvement Suggestions", expanded=True): # Default to expanded once generated
1096
+ st.markdown(st.session_state.improvement_suggestions, unsafe_allow_html=True) # LLM might use markdown
1097
+
1098
+ # Conditional button for low scores
1099
+ if current_percentage_score < 50.0:
1100
+ st.warning(f"Your score is {current_percentage_score:.1f}%. Keep practicing! You can also reset all settings to try a new domain or difficulty.")
1101
+ if st.button("πŸ” Practice Again & Reset All Settings", key="practice_full_reset_final_btn", use_container_width=True):
1102
+ # Clear all session state keys and re-initialize to defaults
1103
+ keys_to_fully_clear = list(st.session_state.keys())
1104
+ for key_to_del_full in keys_to_fully_clear:
1105
+ del st.session_state[key_to_del_full]
1106
+