Imarticuslearning commited on
Commit
91606cf
ยท
verified ยท
1 Parent(s): ecd6cf4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1203 -0
app.py ADDED
@@ -0,0 +1,1203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-2.0-flash-lite')
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-2.0-flash-lite')
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-2.0-flash-lite')
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", "Finance", "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-2.0-flash-lite')
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", "Company Specific") if st.session_state["selected_domain"] == "Finance" else ("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
+ input_text = ""
756
+
757
+ if st.session_state["selected_domain"] == "Finance":
758
+ finance_levels = ["Level-1", "Level-2", "Level-3"]
759
+ selected_level = st.sidebar.selectbox("Select a Finance Level:", finance_levels, key="finance_level_select")
760
+
761
+ difficulty = st.session_state.get("difficulty", "Beginner")
762
+
763
+ if selected_level == "Level-1":
764
+ excel_filename = "CIBOP Mock Questions.xlsx"
765
+ module_prefix = "MODULE 1"
766
+ elif selected_level == "Level-2":
767
+ excel_filename = "CIBOP Level2.xlsx"
768
+ module_prefix = "MODULE 2"
769
+ else:
770
+ st.sidebar.warning(f"๐Ÿšง {selected_level} content is still under development. Please select Level-1 to continue.")
771
+ st.stop()
772
+
773
+ # Map difficulty level to column in Excel
774
+ column_map = {
775
+ "Beginner": f"{module_prefix}-EASY",
776
+ "Intermediate": f"{module_prefix}-MEDIUM",
777
+ "Advanced": f"{module_prefix}-DIFFICULT"
778
+ }
779
+
780
+ selected_column = column_map[difficulty]
781
+
782
+ # Load Excel and questions
783
+ excel_path = os.path.join("data", excel_filename)
784
+ try:
785
+ df = pd.read_excel(excel_path, engine="openpyxl")
786
+ questions_from_excel = df[selected_column].dropna().astype(str).tolist()
787
+ input_text = selected_column # Optional, for tracking
788
+ except Exception as e:
789
+ st.sidebar.error(f"โŒ Error reading Excel file: {e}")
790
+ st.stop()
791
+
792
+ st.sidebar.success(f"โœ… Loaded {difficulty}-level questions from {selected_level}")
793
+
794
+ else:
795
+ # For Analytics or any other domain
796
+ skills = {
797
+ "Analytics": ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"]
798
+ }
799
+ skill_list = skills.get(st.session_state["selected_domain"], [])
800
+ if skill_list:
801
+ selected_skill = st.sidebar.selectbox("Select a Skill:", skill_list, key="skill_select")
802
+ input_text = selected_skill
803
+ st.sidebar.markdown(f"โœ… Selected Skill: **{selected_skill}**")
804
+
805
+
806
+ elif section_choice == "Company Specific" and st.session_state["selected_domain"] == "Finance":
807
+ excel_path = os.path.join("data", "Company Specific.xlsx")
808
+ try:
809
+ # Load Excel and get sheet names (company names)
810
+ xls = pd.ExcelFile(excel_path, engine="openpyxl")
811
+ company_names = xls.sheet_names
812
+ except Exception as e:
813
+ st.sidebar.error(f"โŒ Error loading company-specific Excel: {e}")
814
+ st.stop()
815
+
816
+ selected_company = st.sidebar.selectbox("Select Company:", company_names)
817
+
818
+ try:
819
+ # Load the selected company's sheet
820
+ df = pd.read_excel(excel_path, sheet_name=selected_company, engine="openpyxl")
821
+
822
+ if "Job Role" not in df.columns:
823
+ st.sidebar.error(f"โŒ 'JobRole' column not found in sheet '{selected_company}'.")
824
+ st.stop()
825
+
826
+ job_roles = sorted(df["Job Role"].dropna().unique())
827
+ selected_job_role = st.sidebar.selectbox("Select Job Role:", job_roles)
828
+
829
+ filtered_df = df[df["Job Role"] == selected_job_role]
830
+
831
+ if "Question" in filtered_df.columns:
832
+ questions_from_excel = filtered_df["Questions"].dropna().astype(str).tolist()
833
+ else:
834
+ question_cols = [col for col in filtered_df.columns if col != "Job Role"]
835
+ if not question_cols:
836
+ st.sidebar.error(f"โŒ No question column found in '{selected_company}' sheet.")
837
+ st.stop()
838
+ questions_from_excel = filtered_df[question_cols[0]].dropna().astype(str).tolist()
839
+
840
+ input_text = f"{selected_company} - {selected_job_role}"
841
+ st.sidebar.success(f"โœ… Loaded {len(questions_from_excel)} questions for {selected_company} / {selected_job_role}")
842
+
843
+ except Exception as e:
844
+ st.sidebar.error(f"โŒ Error reading sheet '{selected_company}': {e}")
845
+ st.stop()
846
+
847
+ else:
848
+ # For Analytics or any other domain
849
+ skills = {
850
+ "Analytics": ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"]
851
+ }
852
+ skill_list = skills.get(st.session_state["selected_domain"], [])
853
+ if skill_list:
854
+ selected_skill = st.sidebar.selectbox("Select a Skill:", skill_list, key="skill_select")
855
+ input_text = selected_skill
856
+ st.sidebar.markdown(f"โœ… Selected Skill: **{selected_skill}**")
857
+
858
+
859
+ if st.sidebar.button("Generate Questions"):
860
+ if not input_text.strip():
861
+ st.warning("โš ๏ธ Please provide input based on the selected method.")
862
+ st.stop()
863
+
864
+ if st.session_state["selected_domain"] == "Finance" and section_choice in ["Skills","Company Specific"]:
865
+ st.session_state["generated_questions"] = sample(questions_from_excel, min(num_qs, len(questions_from_excel)))
866
+ else:
867
+ prompt = f"Ask {num_qs} direct and core-level {difficulty} interview questions related to {input_text}. Do not include intros or numbering."
868
+ model = genai.GenerativeModel('gemini-2.0-flash-lite')
869
+ response = model.generate_content([prompt, input_text])
870
+ lines = response.text.strip().split("\n")
871
+ questions = [q.strip("* ") for q in lines if q.strip()]
872
+ st.session_state["generated_questions"] = questions[:num_qs]
873
+
874
+ st.session_state["current_question_index"] = 0
875
+ st.session_state["answers"] = []
876
+ st.session_state["evaluation_feedback"] = ""
877
+ st.session_state["recorded_text"] = ""
878
+ st.session_state["response_captured"] = False
879
+ st.session_state["timer_start"] = None
880
+ st.session_state["show_summary"] = False
881
+ st.session_state["question_played"] = False
882
+ st.session_state["recording_complete"] = False
883
+ st.rerun()
884
+
885
+ def get_ice_servers():
886
+ """Use Twilio's TURN server because Streamlit Community Cloud has changed
887
+ its infrastructure and WebRTC connection cannot be established without TURN server now. # noqa: E501
888
+ We considered Open Relay Project (https://www.metered.ca/tools/openrelay/) too,
889
+ but it is not stable and hardly works as some people reported like https://github.com/aiortc/aiortc/issues/832#issuecomment-1482420656 # noqa: E501
890
+ See https://github.com/whitphx/streamlit-webrtc/issues/1213
891
+ """
892
+
893
+ # Ref: https://www.twilio.com/docs/stun-turn/api
894
+ try:
895
+ account_sid = os.environ["TWILIO_ACCOUNT_SID"]
896
+ auth_token = os.environ["TWILIO_AUTH_TOKEN"]
897
+ except KeyError:
898
+ logger.warning(
899
+ "Twilio credentials are not set. Fallback to a free STUN server from Google." # noqa: E501
900
+ )
901
+ return [{"urls": ["stun:stun.l.google.com:19302"]}]
902
+
903
+ client = Client(account_sid, auth_token)
904
+
905
+ token = client.tokens.create()
906
+
907
+ return token.ice_servers
908
+
909
+
910
+
911
+ # === Main QA Interface ===
912
+
913
+ if st.session_state.get("generated_questions"):
914
+ idx = st.session_state.get("current_question_index", 0)
915
+ if idx < len(st.session_state["generated_questions"]):
916
+ question = st.session_state["generated_questions"][idx].lstrip("1234567890. ").strip()
917
+
918
+ # Phase 0: Generate & play question audio
919
+ if not st.session_state.get("question_played"):
920
+ st.session_state["question_audio_file"] = asyncio.run(generate_question_audio(question))
921
+ st.session_state.update({
922
+ "question_played": True,
923
+ "question_start_time": time.time(),
924
+ "record_phase": "audio_playing",
925
+ "recorded_text": "",
926
+ "response_file": None
927
+ })
928
+ st.markdown(f"**Q{idx + 1}:** {question}")
929
+ st.audio(st.session_state["question_audio_file"], format="audio/mp3")
930
+
931
+ now = time.time()
932
+ elapsed = now - st.session_state.get("question_start_time", 0)
933
+
934
+ # Phase 1: Audio Playing
935
+ if st.session_state["record_phase"] == "audio_playing":
936
+ if elapsed < 5:
937
+ st.markdown("<h4 class='timer-text'>๐Ÿ”Š Playing question audio... Please listen</h4>", unsafe_allow_html=True)
938
+ time.sleep(1)
939
+ st.rerun()
940
+ else:
941
+ st.session_state["record_phase"] = "waiting_to_start"
942
+ st.session_state["question_start_time"] = time.time()
943
+ st.rerun()
944
+
945
+ # Phase 2: Waiting to Start Recording
946
+ elif st.session_state["record_phase"] == "waiting_to_start":
947
+ remaining = 20 - int(elapsed)
948
+ if remaining > 0:
949
+ st.markdown(f"<h4 class='timer-text'>โณ {remaining} seconds to click 'Start Recording'...</h4>", unsafe_allow_html=True)
950
+ if st.button("๐ŸŽ™๏ธ Start Recording"):
951
+ st.session_state.update({
952
+ "record_phase": "recording",
953
+ "timer_start": time.time(),
954
+ "recording_started": True,
955
+ "response_file": None
956
+ })
957
+ st.rerun()
958
+ time.sleep(1)
959
+ st.rerun()
960
+ else:
961
+ 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)
962
+ st.session_state["answers"].append({"question": question, "response": "[No response]"})
963
+ st.session_state.update({
964
+ "record_phase": "idle",
965
+ "question_played": False,
966
+ "question_start_time": 0.0,
967
+ "current_question_index": idx + 1
968
+ })
969
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
970
+ evaluate_answers()
971
+ st.session_state["show_summary"] = True
972
+ st.rerun()
973
+
974
+ # Phase 3: Recording
975
+ elif st.session_state["record_phase"] == "recording":
976
+ st.markdown(f"<h4 class='timer-text'>๐ŸŽ™๏ธ Recording... Click below to stop when done</h4>", unsafe_allow_html=True)
977
+ audio_value = st.audio_input("๐ŸŽค Tap to record your answer โ€” then stop when done", key=f"audio_{idx}")
978
+
979
+ if audio_value and st.button("โน๏ธ Stop Recording"):
980
+ wav_path = f"response_{idx}.wav"
981
+ with open(wav_path, "wb") as f:
982
+ f.write(audio_value.getbuffer())
983
+
984
+ recognizer = sr.Recognizer()
985
+ try:
986
+ with sr.AudioFile(wav_path) as source:
987
+ audio = recognizer.record(source)
988
+ transcript = recognizer.recognize_google(audio)
989
+ except sr.UnknownValueError:
990
+ transcript = "[Could not understand audio]"
991
+ except sr.RequestError:
992
+ transcript = "[Google API error]"
993
+ except Exception as e:
994
+ transcript = f"[Transcription failed: {e}]"
995
+
996
+ st.session_state.update({
997
+ "response_file": wav_path,
998
+ "record_phase": "listening",
999
+ "recorded_text": transcript
1000
+ })
1001
+ st.session_state["answers"].append({
1002
+ "question": question,
1003
+ "response_file": wav_path,
1004
+ "response": transcript
1005
+ })
1006
+ st.success("โœ… Audio recorded. You may now confirm your answer.")
1007
+ st.rerun()
1008
+
1009
+ # Phase 4: Listening / Confirming
1010
+ elif st.session_state["record_phase"] == "listening":
1011
+ st.success("๐ŸŽง Review your recorded response below:")
1012
+ #st.audio(st.session_state["response_file"], format="audio/wav")
1013
+ st.markdown(f"**Your Response (text):** {st.session_state['recorded_text']}")
1014
+
1015
+ if st.button("โœ… Confirm & Next"):
1016
+ st.session_state.update({
1017
+ "record_phase": "idle",
1018
+ "recording_started": False,
1019
+ "question_played": False,
1020
+ "question_start_time": 0.0,
1021
+ "current_question_index": idx + 1,
1022
+ "response_file": None
1023
+ })
1024
+ if st.session_state["current_question_index"] == len(st.session_state["generated_questions"]):
1025
+ evaluate_answers()
1026
+ st.session_state["show_summary"] = True
1027
+ st.rerun()
1028
+
1029
+
1030
+ # === Summary Display ===
1031
+ if st.session_state.get("show_summary", False):
1032
+ st.subheader("๐Ÿ“Š Complete Mock Interview Summary")
1033
+
1034
+ # Fetch values from session state, providing defaults
1035
+ feedback_content_for_display = st.session_state.get('evaluation_feedback', "Evaluation details not available.")
1036
+ if not isinstance(feedback_content_for_display, str):
1037
+ feedback_content_for_display = str(feedback_content_for_display)
1038
+
1039
+ # Max score basis is the number of questions that were *generated* for the session
1040
+ num_qs_in_session = len(st.session_state.get("generated_questions", []))
1041
+ if num_qs_in_session == 0 and st.session_state.get("answers"): # Fallback if no generated_questions but answers exist
1042
+ num_qs_in_session = len(st.session_state.answers)
1043
+
1044
+ if st.session_state["selected_domain"] == "Soft Skills":
1045
+ num_qs_in_session = len(st.session_state.get("answers", []))
1046
+ max_score_possible_for_session = num_qs_in_session * 5.0
1047
+
1048
+ else:
1049
+ if st.session_state["selected_domain"] == "Soft Skills":
1050
+ num_hr_params = len(st.session_state.get("hr_parameter_scores_dict", {}))
1051
+ max_score_possible_for_session = num_hr_params * 5.0
1052
+ else:
1053
+ max_score_possible_for_session = num_qs_in_session * 5.0
1054
+
1055
+ #max_score_possible_for_session = num_qs_in_session * 5.0
1056
+ current_percentage_score = st.session_state.get('percentage_score', 0.0)
1057
+ current_overall_score = st.session_state.get('overall_score', 0.0)
1058
+
1059
+ if st.session_state["selected_domain"] == "Soft Skills":
1060
+ hr_table_data = []
1061
+ for param, config in HR_PARAMETERS_CONFIG.items():
1062
+ score = st.session_state.get("hr_parameter_scores_dict", {}).get(param, 0.0)
1063
+ weight_percent = config["weight_original"]
1064
+ contribution = (score / 5.0) * config["weight_normalized"]
1065
+ hr_table_data.append({
1066
+ "Parameter": param,
1067
+ "Weight (Original %)": f"{weight_percent}%",
1068
+ "Score (1โ€“5)": round(score, 1),
1069
+ "Contribution to Final %": f"{contribution:.1f}%"
1070
+ })
1071
+
1072
+ hr_table_data.append({
1073
+ "Parameter": "Total",
1074
+ "Weight (Original %)": "100%",
1075
+ "Score (1โ€“5)": "",
1076
+ "Contribution to Final %": f"{current_percentage_score:.1f}%"
1077
+ })
1078
+
1079
+ hr_df = pd.DataFrame(hr_table_data)
1080
+ st.markdown("### ๐Ÿงพ Soft Skills Evaluation Breakdown")
1081
+ st.dataframe(hr_df, use_container_width=True)
1082
+
1083
+ # Display the calculated score and percentage bar first in a card
1084
+ st.markdown(f"""
1085
+ <div class='summary-card' style="margin-bottom: 20px;">
1086
+ <h4 style="color: #212529;">โœ… <strong>Overall Score:</strong> {current_overall_score:.1f} / {max_score_possible_for_session:.1f}
1087
+ ({current_percentage_score:.1f}%)
1088
+ </h4>
1089
+ <div style='margin:10px 0; position:relative;'>
1090
+ <div style="background:#eee; border-radius:10px; overflow:hidden; height:30px; position:relative;">
1091
+ <div style="
1092
+ width:{current_percentage_score}%;
1093
+ background:#00c851; /* Green for progress */
1094
+ height:100%;
1095
+ border-radius:10px 0 0 10px; /* Keep left radius for progress */
1096
+ transition: width 0.4s ease-in-out;
1097
+ "></div>
1098
+ <div style="
1099
+ position:absolute;
1100
+ top:0;
1101
+ left:0;
1102
+ width:100%;
1103
+ height:100%;
1104
+ display:flex;
1105
+ align-items:center;
1106
+ justify-content:center;
1107
+ font-weight:bold;
1108
+ color: black !important; /* Ensure text is visible on green/grey */
1109
+ font-size: 0.9rem;
1110
+ user-select:none; /* Prevent text selection */
1111
+ ">
1112
+ {current_percentage_score:.1f}%
1113
+ </div>
1114
+ </div>
1115
+ </div>
1116
+ </div>
1117
+ """, unsafe_allow_html=True)
1118
+
1119
+ # Display the detailed evaluation feedback text in a separate section
1120
+ st.markdown("---")
1121
+ st.markdown("<h4 style='color: #212529;'>Detailed Evaluation & Feedback from AI:</h4>", unsafe_allow_html=True)
1122
+
1123
+ # Use a styled div for the feedback text block to ensure good readability
1124
+ # Replace newlines with <br> for proper HTML multiline display
1125
+ html_formatted_feedback = feedback_content_for_display.replace('\n', '<br>')
1126
+ st.markdown(f"""
1127
+ <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;">
1128
+ {html_formatted_feedback}
1129
+ </div>
1130
+ """, unsafe_allow_html=True)
1131
+
1132
+ st.markdown("---") # Separator
1133
+
1134
+ # Buttons for suggestions, download, practice
1135
+ cols_summary_buttons = st.columns([1, 1, 1]) # 3 columns for the buttons
1136
+
1137
+ with cols_summary_buttons[0]:
1138
+ if st.button("๐Ÿ’ก Get Improvement Suggestions", key="get_suggestions_btn_final", use_container_width=True):
1139
+ # Regenerate suggestions if not present or explicitly requested again
1140
+ generate_improvement_suggestions() # This function should handle st.info/st.success
1141
+ st.rerun() # Rerun to show the expander or updated suggestions
1142
+
1143
+ # Helper function to prepare summary text for download
1144
+ def prepare_summary_for_download():
1145
+ download_text = f"# GrillMaster Mock Interview Summary\n\n"
1146
+ download_text += f"**Selected Domain:** {st.session_state.get('selected_domain', 'N/A')}\n"
1147
+ dl_difficulty = st.session_state.get('difficulty_level_select', 'N/A')
1148
+ download_text += f"**Difficulty Level:** {dl_difficulty}\n"
1149
+
1150
+ num_q_for_max_score = len(st.session_state.get("generated_questions", st.session_state.get("answers",[])))
1151
+ max_s_for_dl = num_q_for_max_score * 5.0
1152
+
1153
+ 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"
1154
+
1155
+ download_text += "## Questions & Candidate's Answers:\n"
1156
+ num_answers_actually_given = len(st.session_state.get("answers", []))
1157
+ for i in range(num_q_for_max_score):
1158
+ question_text_dl = st.session_state.generated_questions[i] if i < len(st.session_state.generated_questions) else "Question text not found"
1159
+ answer_text_dl = "[No answer recorded]"
1160
+ if i < num_answers_actually_given:
1161
+ answer_text_dl = str(st.session_state.answers[i].get('response', '[No response provided]'))
1162
+
1163
+ download_text += f"**Question {i+1}:** {question_text_dl}\n"
1164
+ download_text += f"**Your Answer {i+1}:** {answer_text_dl}\n\n"
1165
+
1166
+ download_text += "\n## AI Evaluation Details (Includes Parsed Scores and Qualitative Feedback):\n"
1167
+ # st.session_state.evaluation_feedback is now already pre-formatted
1168
+ download_text += st.session_state.get('evaluation_feedback', "No AI evaluation available.")
1169
+ download_text += "\n\n"
1170
+
1171
+ if st.session_state.get("improvement_suggestions_generated", False) and st.session_state.get("improvement_suggestions"):
1172
+ download_text += "\n## Detailed Improvement Suggestions from AI:\n"
1173
+ download_text += st.session_state.get('improvement_suggestions', "No improvement suggestions were generated.")
1174
+
1175
+ return download_text.encode('utf-8')
1176
+
1177
+ with cols_summary_buttons[1]:
1178
+ summary_bytes_dl_final = prepare_summary_for_download()
1179
+ st.download_button(
1180
+ label="๐Ÿ’พ Download Full Summary",
1181
+ data=summary_bytes_dl_final,
1182
+ file_name=f"GrillMaster_Summary_{st.session_state.get('selected_domain','General')}_{time.strftime('%Y%m%d_%H%M')}.md",
1183
+ mime="text/markdown",
1184
+ key="download_summary_final_btn",
1185
+ use_container_width=True
1186
+ )
1187
+
1188
+
1189
+
1190
+ # Expander for detailed suggestions, shown if generated
1191
+ if st.session_state.get("improvement_suggestions_generated", False) and st.session_state.get("improvement_suggestions"):
1192
+ with st.expander("๐Ÿ” View Detailed Improvement Suggestions", expanded=True): # Default to expanded once generated
1193
+ st.markdown(st.session_state.improvement_suggestions, unsafe_allow_html=True) # LLM might use markdown
1194
+
1195
+ # Conditional button for low scores
1196
+ if current_percentage_score < 50.0:
1197
+ 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.")
1198
+ if st.button("๐Ÿ” Practice Again & Reset All Settings", key="practice_full_reset_final_btn", use_container_width=True):
1199
+ # Clear all session state keys and re-initialize to defaults
1200
+ keys_to_fully_clear = list(st.session_state.keys())
1201
+ for key_to_del_full in keys_to_fully_clear:
1202
+ del st.session_state[key_to_del_full]
1203
+