AIMLdeepanshu commited on
Commit
ced8c16
Β·
verified Β·
1 Parent(s): 5c0808b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -60
app.py CHANGED
@@ -1,9 +1,10 @@
1
- # βœ… FINAL MERGED & ENHANCED CODE: AI Interview Bot with Gemini, Jason/Erica, One-by-One Flow
2
 
3
  import os
4
  import gradio as gr
5
  import whisper
6
  import tempfile
 
7
  from dotenv import load_dotenv
8
  from TTS.api import TTS
9
  import google.generativeai as genai
@@ -18,50 +19,42 @@ model = genai.GenerativeModel("gemini-1.5-flash-latest")
18
  # βœ… LOAD MODELS
19
  # -----------------------------
20
  asr_model = whisper.load_model("base")
21
- tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC", progress_bar=False, gpu=False)
22
 
23
  # -----------------------------
24
  # βœ… GLOBAL STATE
25
  # -----------------------------
26
  candidate_name = ""
27
  field = ""
28
- selected_voice = "Erica"
29
  interview_questions = []
30
  current_question_index = 0
31
  feedback_summary = []
32
 
33
  # -----------------------------
34
- # βœ… STEP 1: Collect Candidate Info + Interviewer Selection
35
  # -----------------------------
36
- def save_user_info(name, user_field, voice):
37
- global candidate_name, field, selected_voice
38
  candidate_name = name
39
  field = user_field
40
- selected_voice = voice
41
- greeting = f"Hi {name}! Your interviewer will be {voice}. Preparing questions for a {field} internship."
42
  return greeting
43
 
44
  # -----------------------------
45
- # βœ… STEP 2: Generate Questions from Gemini
46
  # -----------------------------
47
  def generate_questions():
48
  global field, interview_questions, current_question_index, feedback_summary
49
- import re
50
  current_question_index = 0
51
  feedback_summary = []
52
 
53
  prompt = (
54
- f"You are a professional interview panel. Generate exactly 12 interview questions "
55
- f"(7 technical and 5 behavioral) for an internship interview in the field of {field}.\n"
56
- f"Return the output in the following strict format:\n"
57
- f"1. <question one>\n2. <question two>\n... up to 12. <question twelve>\n"
58
- f"No explanations or headings. Just the 12 numbered questions."
59
  )
60
  try:
61
  response = model.generate_content(prompt)
62
  raw_output = response.text.strip()
63
-
64
- # βœ… Extract lines that start with "1." to "12."
65
  lines = re.findall(r"^\d+\.\s+.*", raw_output, re.MULTILINE)
66
  interview_questions = [line.strip() for line in lines]
67
 
@@ -72,9 +65,8 @@ def generate_questions():
72
  except Exception as e:
73
  return f"Error: {str(e)}", ""
74
 
75
-
76
  # -----------------------------
77
- # βœ… STEP 3: Speak Current Question
78
  # -----------------------------
79
  def speak_current_question():
80
  if not interview_questions or current_question_index >= len(interview_questions):
@@ -82,18 +74,16 @@ def speak_current_question():
82
 
83
  question = interview_questions[current_question_index]
84
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
85
- tts_model.tts_to_file(text=question, file_path=temp_file.name)
86
  return question, temp_file.name
87
 
88
  # -----------------------------
89
- # βœ… STEP 4: Record Answer β†’ Transcribe β†’ Store (Analysis Later)
90
  # -----------------------------
91
  def record_answer(audio_file):
92
  global current_question_index
93
-
94
  if not interview_questions:
95
- return "❌ Please generate questions first.", ""
96
-
97
  if audio_file is None:
98
  return "❌ Please record your answer.", ""
99
 
@@ -101,22 +91,16 @@ def record_answer(audio_file):
101
  result = asr_model.transcribe(audio_file)
102
  transcript = result["text"]
103
  question = interview_questions[current_question_index]
104
-
105
- feedback_summary.append({
106
- "question": question,
107
- "answer": transcript,
108
- "feedback": None # Will be filled later
109
- })
110
 
111
  current_question_index += 1
112
- next_q = interview_questions[current_question_index] if current_question_index < len(interview_questions) else "βœ… End of questions. Please click SUBMIT for feedback."
113
-
114
  return f"βœ… Answer recorded for Q{current_question_index}.", next_q
115
  except Exception as e:
116
  return f"Error: {str(e)}", ""
117
 
118
  # -----------------------------
119
- # βœ… STEP 5: Submit & Analyze All Answers via Gemini
120
  # -----------------------------
121
  def analyze_all():
122
  if not feedback_summary:
@@ -127,11 +111,10 @@ def analyze_all():
127
  prompt = (
128
  f"Interview Question: {item['question']}\n"
129
  f"Candidate's Answer: {item['answer']}\n"
130
- "You are an experienced interview evaluator. Analyze the answer:\n"
131
- "- Overall Rating (Weak to Excellent)\n"
132
- "- Score out of 100\n"
133
- "- Suggestions\n\n"
134
- "Format:\nOverall Rating: <...>\nScore: <...>\nSuggestions: <...>"
135
  )
136
  try:
137
  response = model.generate_content(prompt)
@@ -139,46 +122,43 @@ def analyze_all():
139
  item['feedback'] = feedback
140
  final_summary += f"Q{i}: {item['question']}\nAnswer: {item['answer']}\n{feedback}\n{'-'*50}\n"
141
  except Exception as e:
142
- final_summary += f"Q{i}: {item['question']}\nAnswer: {item['answer']}\nFeedback Error: {str(e)}\n{'-'*50}\n"
143
  return final_summary
144
 
145
  # -----------------------------
146
- # βœ… GRADIO UI (Visually Structured)
147
  # -----------------------------
148
- with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
149
  gr.Markdown("""
150
- # 🧠 AI Mock Interview Bot
151
- πŸ‘‹ Welcome! Select your field, interviewer, and get ready for your personalized mock interview experience powered by Gemini.
152
  """)
153
 
154
  with gr.Row():
155
- name = gr.Textbox(label="Your Name")
156
- field = gr.Textbox(label="Interview Field (e.g. Sales, Software, HR)")
157
- voice = gr.Radio(choices=["Jason", "Erica"], label="Select Interviewer Voice", value="Erica")
158
- start_btn = gr.Button("βœ… Start Interview")
159
- greet = gr.Textbox(label="Greeting", interactive=False)
160
-
161
- start_btn.click(save_user_info, inputs=[name, field, voice], outputs=greet)
162
 
163
  with gr.Row():
164
- gen_btn = gr.Button("🎯 Generate Questions")
165
  status = gr.Textbox(label="Status")
166
- current_q = gr.Textbox(label="Current Question", lines=2)
167
-
168
  gen_btn.click(generate_questions, outputs=[status, current_q])
169
 
170
- speak = gr.Button("πŸ”Š Hear Question")
171
- audio = gr.Audio(label="Audio Output")
172
  speak.click(fn=speak_current_question, outputs=[current_q, audio])
173
 
174
- record = gr.Audio(sources=["microphone"], type="filepath", label="πŸŽ™οΈ Record Your Answer")
175
- submit_ans = gr.Button("βœ”οΈ Submit Answer")
176
- rec_status = gr.Textbox(label="Recording Status")
177
  next_q = gr.Textbox(label="Next Question")
178
  submit_ans.click(fn=record_answer, inputs=record, outputs=[rec_status, current_q])
179
 
180
- submit_all = gr.Button("πŸ“Š Finish Interview & Analyze")
181
- analysis = gr.Textbox(label="🧾 Final Feedback", lines=20)
182
  submit_all.click(fn=analyze_all, outputs=analysis)
183
 
184
  # -----------------------------
 
1
+ # βœ… FINAL MERGED & ENHANCED CODE: AI Interview Bot (Jason Voice, One-by-One, Stylish UI)
2
 
3
  import os
4
  import gradio as gr
5
  import whisper
6
  import tempfile
7
+ import re
8
  from dotenv import load_dotenv
9
  from TTS.api import TTS
10
  import google.generativeai as genai
 
19
  # βœ… LOAD MODELS
20
  # -----------------------------
21
  asr_model = whisper.load_model("base")
22
+ jason_tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC", progress_bar=False, gpu=False)
23
 
24
  # -----------------------------
25
  # βœ… GLOBAL STATE
26
  # -----------------------------
27
  candidate_name = ""
28
  field = ""
 
29
  interview_questions = []
30
  current_question_index = 0
31
  feedback_summary = []
32
 
33
  # -----------------------------
34
+ # βœ… STEP 1: Collect Candidate Info
35
  # -----------------------------
36
+ def save_user_info(name, user_field):
37
+ global candidate_name, field
38
  candidate_name = name
39
  field = user_field
40
+ greeting = f"Welcome {name}! Jason will conduct your mock interview for the {field} internship."
 
41
  return greeting
42
 
43
  # -----------------------------
44
+ # βœ… STEP 2: Generate Questions with Strict Format
45
  # -----------------------------
46
  def generate_questions():
47
  global field, interview_questions, current_question_index, feedback_summary
 
48
  current_question_index = 0
49
  feedback_summary = []
50
 
51
  prompt = (
52
+ f"You are a professional interviewer. Generate exactly 12 internship questions (7 technical + 5 behavioral) for the field of {field}.\n"
53
+ f"Output only the questions, each starting with a number (e.g., 1. ..., 2. ..., ..., 12.). Do not include headings or explanations."
 
 
 
54
  )
55
  try:
56
  response = model.generate_content(prompt)
57
  raw_output = response.text.strip()
 
 
58
  lines = re.findall(r"^\d+\.\s+.*", raw_output, re.MULTILINE)
59
  interview_questions = [line.strip() for line in lines]
60
 
 
65
  except Exception as e:
66
  return f"Error: {str(e)}", ""
67
 
 
68
  # -----------------------------
69
+ # βœ… STEP 3: Jason Speaks Current Question
70
  # -----------------------------
71
  def speak_current_question():
72
  if not interview_questions or current_question_index >= len(interview_questions):
 
74
 
75
  question = interview_questions[current_question_index]
76
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
77
+ jason_tts.tts_to_file(text=question, file_path=temp_file.name)
78
  return question, temp_file.name
79
 
80
  # -----------------------------
81
+ # βœ… STEP 4: Record Answer & Store for Analysis
82
  # -----------------------------
83
  def record_answer(audio_file):
84
  global current_question_index
 
85
  if not interview_questions:
86
+ return "❌ Generate questions first.", ""
 
87
  if audio_file is None:
88
  return "❌ Please record your answer.", ""
89
 
 
91
  result = asr_model.transcribe(audio_file)
92
  transcript = result["text"]
93
  question = interview_questions[current_question_index]
94
+ feedback_summary.append({"question": question, "answer": transcript, "feedback": None})
 
 
 
 
 
95
 
96
  current_question_index += 1
97
+ next_q = interview_questions[current_question_index] if current_question_index < len(interview_questions) else "βœ… Interview complete. Click SUBMIT for feedback."
 
98
  return f"βœ… Answer recorded for Q{current_question_index}.", next_q
99
  except Exception as e:
100
  return f"Error: {str(e)}", ""
101
 
102
  # -----------------------------
103
+ # βœ… STEP 5: Analyze All Answers via Gemini
104
  # -----------------------------
105
  def analyze_all():
106
  if not feedback_summary:
 
111
  prompt = (
112
  f"Interview Question: {item['question']}\n"
113
  f"Candidate's Answer: {item['answer']}\n"
114
+ "Evaluate the answer:\n"
115
+ "- Overall Rating: Weak/Average/Good/Excellent\n"
116
+ "- Score: out of 100\n"
117
+ "- Suggestions:"
 
118
  )
119
  try:
120
  response = model.generate_content(prompt)
 
122
  item['feedback'] = feedback
123
  final_summary += f"Q{i}: {item['question']}\nAnswer: {item['answer']}\n{feedback}\n{'-'*50}\n"
124
  except Exception as e:
125
+ final_summary += f"Q{i}: {item['question']}\nAnswer: {item['answer']}\nError: {str(e)}\n{'-'*50}\n"
126
  return final_summary
127
 
128
  # -----------------------------
129
+ # βœ… GRADIO UI (Modern Look)
130
  # -----------------------------
131
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet")) as demo:
132
  gr.Markdown("""
133
+ <div style='text-align: center; font-size: 28px; font-weight: bold;'>πŸŽ™οΈ AI Mock Interview Bot</div>
134
+ <div style='text-align: center; font-size: 16px;'>Choose your field and get started. Jason will guide you through your interview.</div>
135
  """)
136
 
137
  with gr.Row():
138
+ name = gr.Textbox(label="πŸ‘€ Your Name")
139
+ field = gr.Textbox(label="🎯 Interview Field (e.g. Software, Marketing, HR)")
140
+ start_btn = gr.Button("πŸš€ Begin Interview")
141
+ greet = gr.Textbox(label="Welcome Message", interactive=False)
142
+ start_btn.click(save_user_info, inputs=[name, field], outputs=greet)
 
 
143
 
144
  with gr.Row():
145
+ gen_btn = gr.Button("πŸ“„ Generate Questions")
146
  status = gr.Textbox(label="Status")
147
+ current_q = gr.Textbox(label="πŸ“Œ Current Question", lines=2)
 
148
  gen_btn.click(generate_questions, outputs=[status, current_q])
149
 
150
+ speak = gr.Button("πŸ”Š Hear Question", elem_classes="speak-btn")
151
+ audio = gr.Audio(label="πŸ”ˆ Jason's Voice")
152
  speak.click(fn=speak_current_question, outputs=[current_q, audio])
153
 
154
+ record = gr.Audio(sources=["microphone"], type="filepath", label="🎀 Record Your Answer")
155
+ submit_ans = gr.Button("βœ… Submit This Answer")
156
+ rec_status = gr.Textbox(label="Answer Status")
157
  next_q = gr.Textbox(label="Next Question")
158
  submit_ans.click(fn=record_answer, inputs=record, outputs=[rec_status, current_q])
159
 
160
+ submit_all = gr.Button("πŸ“Š Submit All & Get Feedback")
161
+ analysis = gr.Textbox(label="πŸ“‹ Final Feedback Summary", lines=20)
162
  submit_all.click(fn=analyze_all, outputs=analysis)
163
 
164
  # -----------------------------