maahikachitagi commited on
Commit
c32ea75
·
verified ·
1 Parent(s): 16db526

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -110
app.py CHANGED
@@ -1,17 +1,15 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
- import re
4
- import random
5
  import whisper
6
  from pydub import AudioSegment
7
- # models
 
8
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
9
  whisper_model = whisper.load_model("base")
10
 
11
- # whisper audio-to-text function
12
  def transcribe_audio(file_path):
13
  try:
14
- print(f"📂 Processing audio: {file_path}")
15
  audio = AudioSegment.from_file(file_path)
16
  converted_path = "converted.wav"
17
  audio.export(converted_path, format="wav")
@@ -19,24 +17,25 @@ def transcribe_audio(file_path):
19
  return result["text"]
20
  except Exception as e:
21
  return f"❌ ERROR: {str(e)}"
22
- # setting up the users profile (step 1)
 
23
  def set_type(choice, user_profile):
24
  user_profile["interview_type"] = choice
25
  return "Great! What’s your background and what field/role are you aiming for?", user_profile
26
 
27
- # step 2
28
  def save_background(info, user_profile):
29
  user_profile["field"] = info
30
  return "Awesome! Type 'start' below to begin your interview.", user_profile
31
 
32
- # generate question using LLM
33
  def generate_question(user_profile):
34
  system_prompt = f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}. Generate one thoughtful, clear, and concise interview question."
35
  messages = [{"role": "system", "content": system_prompt}]
36
  response = client.chat_completion(messages, max_tokens=100, stream=False)
37
  return response.choices[0].message.content.strip()
38
 
39
- # generate feedback using LLM
40
  def generate_feedback_llm(user_profile):
41
  feedback = []
42
  for i, (question, answer) in enumerate(zip(user_profile.get("questions", []), user_profile.get("user_answers", []))):
@@ -48,13 +47,14 @@ def generate_feedback_llm(user_profile):
48
  feedback.append(f"Question {i+1}: {response.choices[0].message.content.strip()}")
49
  return "\n\n".join(feedback)
50
 
51
- # step 3: interview loop
52
  def respond(message, chat_history, user_profile):
53
  message_lower = message.strip().lower()
54
 
55
  if not user_profile.get("interview_type") or not user_profile.get("field"):
56
  bot_msg = "Please finish steps 1 and 2 before starting the interview."
57
- chat_history.append((message, bot_msg))
 
58
  return chat_history
59
 
60
  if message_lower == 'start':
@@ -66,19 +66,22 @@ def respond(message, chat_history, user_profile):
66
  intro = f"Welcome to your {user_profile['interview_type']} interview for a {user_profile['field']} position. I will ask you up to 10 questions. Type 'stop' anytime to end."
67
  first_q = generate_question(user_profile)
68
  user_profile['questions'].append(first_q)
69
- chat_history.append((message, intro))
70
- chat_history.append(("", f"First question: {first_q}"))
 
71
  return chat_history
72
 
73
  if message_lower == 'stop' and user_profile.get("interview_in_progress"):
74
  user_profile['interview_in_progress'] = False
75
  bot_msg = "Interview stopped. Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"
76
- chat_history.append((message, bot_msg))
 
77
  return chat_history
78
 
79
  if message_lower == 'feedback':
80
  feedback = generate_feedback_llm(user_profile)
81
- chat_history.append((message, feedback))
 
82
  return chat_history
83
 
84
  if user_profile.get("interview_in_progress"):
@@ -93,7 +96,8 @@ def respond(message, chat_history, user_profile):
93
  user_profile['interview_in_progress'] = False
94
  bot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"
95
 
96
- chat_history.append((message, bot_msg))
 
97
  return chat_history
98
 
99
  # fallback LLM response
@@ -103,132 +107,57 @@ def respond(message, chat_history, user_profile):
103
  ]
104
  response = client.chat_completion(messages, max_tokens=150, stream=False)
105
  bot_msg = response.choices[0].message.content.strip()
106
- chat_history.append((message, bot_msg))
 
107
  return chat_history
108
 
109
- # handle audio input
110
  def handle_audio(audio_file, chat_history, user_profile):
111
  transcribed = transcribe_audio(audio_file)
112
  if transcribed.startswith("❌"):
113
- chat_history.append(("Audio input", transcribed))
114
  return chat_history
115
  return respond(transcribed, chat_history, user_profile)
116
- # The new Intervu 2.0 UI with your design!
117
- with gr.Blocks(css="""
118
- body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }
119
- h1 { text-align: center; color: #2c3e50; }
120
- img { display: block; margin: auto; width: 100px; border-radius: 20px; }
121
- button {
122
- font-size: 16px;
123
- padding: 10px 20px;
124
- border-radius: 10px;
125
- border: 2px solid rgba(124, 248, 255, 0.4);
126
- background-color: rgba(124, 248, 255, 0.4);
127
- color: #fafdff;
128
- transition: all 0.2s ease;
129
- }
130
- button:hover {
131
- background-color: #49888f;
132
- border-color: #7cf8ff;
133
- transform: scale(1.05);
134
- }
135
-
136
- .gr-chatbot { background-color: white; border-radius: 15px; padding: 20px; }
137
- """) as demo:
138
-
139
-
140
-
141
-
142
- gr.Markdown("""
143
- <div style='width: 100%; text-align: center;'>
144
- <img src="https://cdn-uploads.huggingface.co/production/uploads/6841b10b397a67a7c7a39b89/MTR_dMHte-RCIbyujLW83.png" style="width: 100%; height: auto; object-fit: contain;">
145
- </div>
146
- """)
147
-
148
-
149
-
150
-
151
-
152
  user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})
153
  chat_history = gr.State([])
154
 
155
- #Header
156
- gr.Markdown("""<div style='
157
- font-family: 'Lato', sans-serif;
158
- text-align: center;
159
- padding: 30px;
160
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
161
- margin-bottom: 20px;
162
- '>
163
- <h1 style='font-size: 89.5px; color: #fafdff;'>Welcome to <b><span style='color: #7cf8ff;'>Intervu</span></b></h1>
164
- <p style='font-size: 22.1px; color: #fafdff; margin-top: 30px; text-align: center; margin-bottom: 30px;'>Before you begin, complete Step 1 to select your interview type and Step 2 to enter your background. Practice is available through text, speech, or webcam.</p>
165
- </div>
166
- """)
167
-
168
-
169
- # Step 1 - Choose Interview Type
170
- # gr.Markdown("### Step 1: Choose Interview Type")
171
- # with gr.Row():
172
- # btn1 = gr.Button("Technical")
173
- # btn2 = gr.Button("Competency-Based Interview")
174
- # btn3 = gr.Button("Case")
175
- # type_output = gr.Textbox(label="Bot response", interactive=False)
176
  with gr.Row():
177
-
178
- # LEFT SIDE: Transparent box with interview type buttons
179
- with gr.Column(scale=2):
180
- gr.Markdown("""
181
- <div style="
182
- background: rgba(255, 255, 255, 0.1);
183
- padding: 20px;
184
- border-radius: 15px;
185
- backdrop-filter: blur(5px);
186
- box-shadow: 0 4px 10px rgba(0,0,0,0.2);
187
- ">
188
- <h3>Step 1: Choose Interview Type</h3>
189
- <p>Select the type of interview you want to practice.</p>
190
- </div>
191
- """)
192
-
193
  btn1 = gr.Button("Technical")
194
  btn2 = gr.Button("Competency-Based Interview")
195
  btn3 = gr.Button("Case")
196
-
197
- # RIGHT SIDE: Bot response display (type_output)
198
- with gr.Column(scale=2):
199
- type_output = gr.Textbox(label="Bot Response", interactive=False)
200
-
201
-
202
 
203
  btn1.click(set_type, inputs=[gr.Textbox(value="Technical", visible=False), user_profile], outputs=[type_output, user_profile])
204
  btn2.click(set_type, inputs=[gr.Textbox(value="Competency-Based Interview", visible=False), user_profile], outputs=[type_output, user_profile])
205
  btn3.click(set_type, inputs=[gr.Textbox(value="Case", visible=False), user_profile], outputs=[type_output, user_profile])
206
 
207
- # Step 2 - Enter Background
208
- gr.Markdown("### Step 2: Enter Your Background")
209
  background = gr.Textbox(label="Your background and field/goal")
210
  background_btn = gr.Button("Submit")
211
  background_output = gr.Textbox(label="Bot response", interactive=False)
212
  background_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])
213
 
214
- # Step 3 - Chatbot Mode Selection
215
- # Step 3 - Chatbot Mode Selection
216
- # Step 3 - Chatbot Mode Selection
217
- gr.Markdown("### Step 3: Choose Chat Mode")
218
-
219
  with gr.Tabs():
220
  with gr.Tab("Text Mode"):
221
- chatbot_text = gr.Chatbot(label="Interview Chat (Text Mode)")
222
  msg = gr.Textbox(label="Type 'start' to begin")
223
  send_btn = gr.Button("Send")
224
  send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot_text], queue=False)
225
  send_btn.click(lambda: "", None, msg, queue=False)
226
-
227
  with gr.Tab("Audio Mode"):
228
- chatbot_audio = gr.Chatbot(label="Interview Chat (Audio Mode)")
229
- audio_input = gr.Audio(source="microphone", type="filepath", label="Record Your Answer")
230
  audio_btn = gr.Button("Send Audio")
231
  audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot_audio], queue=False)
232
 
233
-
234
  demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
3
  import whisper
4
  from pydub import AudioSegment
5
+
6
+ # Load models
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
  whisper_model = whisper.load_model("base")
9
 
10
+ # Whisper transcription function
11
  def transcribe_audio(file_path):
12
  try:
 
13
  audio = AudioSegment.from_file(file_path)
14
  converted_path = "converted.wav"
15
  audio.export(converted_path, format="wav")
 
17
  return result["text"]
18
  except Exception as e:
19
  return f"❌ ERROR: {str(e)}"
20
+
21
+ # Step 1: Set interview type
22
  def set_type(choice, user_profile):
23
  user_profile["interview_type"] = choice
24
  return "Great! What’s your background and what field/role are you aiming for?", user_profile
25
 
26
+ # Step 2: Save background
27
  def save_background(info, user_profile):
28
  user_profile["field"] = info
29
  return "Awesome! Type 'start' below to begin your interview.", user_profile
30
 
31
+ # Generate interview question
32
  def generate_question(user_profile):
33
  system_prompt = f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}. Generate one thoughtful, clear, and concise interview question."
34
  messages = [{"role": "system", "content": system_prompt}]
35
  response = client.chat_completion(messages, max_tokens=100, stream=False)
36
  return response.choices[0].message.content.strip()
37
 
38
+ # Generate feedback using LLM
39
  def generate_feedback_llm(user_profile):
40
  feedback = []
41
  for i, (question, answer) in enumerate(zip(user_profile.get("questions", []), user_profile.get("user_answers", []))):
 
47
  feedback.append(f"Question {i+1}: {response.choices[0].message.content.strip()}")
48
  return "\n\n".join(feedback)
49
 
50
+ # Chat logic
51
  def respond(message, chat_history, user_profile):
52
  message_lower = message.strip().lower()
53
 
54
  if not user_profile.get("interview_type") or not user_profile.get("field"):
55
  bot_msg = "Please finish steps 1 and 2 before starting the interview."
56
+ chat_history.append({"role": "user", "content": message})
57
+ chat_history.append({"role": "assistant", "content": bot_msg})
58
  return chat_history
59
 
60
  if message_lower == 'start':
 
66
  intro = f"Welcome to your {user_profile['interview_type']} interview for a {user_profile['field']} position. I will ask you up to 10 questions. Type 'stop' anytime to end."
67
  first_q = generate_question(user_profile)
68
  user_profile['questions'].append(first_q)
69
+ chat_history.append({"role": "user", "content": message})
70
+ chat_history.append({"role": "assistant", "content": intro})
71
+ chat_history.append({"role": "assistant", "content": f"First question: {first_q}"})
72
  return chat_history
73
 
74
  if message_lower == 'stop' and user_profile.get("interview_in_progress"):
75
  user_profile['interview_in_progress'] = False
76
  bot_msg = "Interview stopped. Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"
77
+ chat_history.append({"role": "user", "content": message})
78
+ chat_history.append({"role": "assistant", "content": bot_msg})
79
  return chat_history
80
 
81
  if message_lower == 'feedback':
82
  feedback = generate_feedback_llm(user_profile)
83
+ chat_history.append({"role": "user", "content": message})
84
+ chat_history.append({"role": "assistant", "content": feedback})
85
  return chat_history
86
 
87
  if user_profile.get("interview_in_progress"):
 
96
  user_profile['interview_in_progress'] = False
97
  bot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"
98
 
99
+ chat_history.append({"role": "user", "content": message})
100
+ chat_history.append({"role": "assistant", "content": bot_msg})
101
  return chat_history
102
 
103
  # fallback LLM response
 
107
  ]
108
  response = client.chat_completion(messages, max_tokens=150, stream=False)
109
  bot_msg = response.choices[0].message.content.strip()
110
+ chat_history.append({"role": "user", "content": message})
111
+ chat_history.append({"role": "assistant", "content": bot_msg})
112
  return chat_history
113
 
114
+ # Handle audio input
115
  def handle_audio(audio_file, chat_history, user_profile):
116
  transcribed = transcribe_audio(audio_file)
117
  if transcribed.startswith("❌"):
118
+ chat_history.append({"role": "assistant", "content": transcribed})
119
  return chat_history
120
  return respond(transcribed, chat_history, user_profile)
121
+
122
+ # Gradio UI
123
+ with gr.Blocks(css="""body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }""") as demo:
124
+ gr.Markdown("# 🎤 Welcome to Intervu")
125
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})
127
  chat_history = gr.State([])
128
 
129
+ # Step 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  with gr.Row():
131
+ with gr.Column():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  btn1 = gr.Button("Technical")
133
  btn2 = gr.Button("Competency-Based Interview")
134
  btn3 = gr.Button("Case")
135
+ type_output = gr.Textbox(label="Bot Response", interactive=False)
 
 
 
 
 
136
 
137
  btn1.click(set_type, inputs=[gr.Textbox(value="Technical", visible=False), user_profile], outputs=[type_output, user_profile])
138
  btn2.click(set_type, inputs=[gr.Textbox(value="Competency-Based Interview", visible=False), user_profile], outputs=[type_output, user_profile])
139
  btn3.click(set_type, inputs=[gr.Textbox(value="Case", visible=False), user_profile], outputs=[type_output, user_profile])
140
 
141
+ # Step 2
 
142
  background = gr.Textbox(label="Your background and field/goal")
143
  background_btn = gr.Button("Submit")
144
  background_output = gr.Textbox(label="Bot response", interactive=False)
145
  background_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])
146
 
147
+ # Step 3 - Tabs
148
+ gr.Markdown("### Choose Chat Mode")
 
 
 
149
  with gr.Tabs():
150
  with gr.Tab("Text Mode"):
151
+ chatbot_text = gr.Chatbot(label="Interview Chat (Text Mode)", type="messages")
152
  msg = gr.Textbox(label="Type 'start' to begin")
153
  send_btn = gr.Button("Send")
154
  send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot_text], queue=False)
155
  send_btn.click(lambda: "", None, msg, queue=False)
156
+
157
  with gr.Tab("Audio Mode"):
158
+ chatbot_audio = gr.Chatbot(label="Interview Chat (Audio Mode)", type="messages")
159
+ audio_input = gr.Audio(type="filepath", label="Record Your Answer")
160
  audio_btn = gr.Button("Send Audio")
161
  audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot_audio], queue=False)
162
 
 
163
  demo.launch()