KittyMona commited on
Commit
b4c218d
Β·
verified Β·
1 Parent(s): d69dd0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -20
app.py CHANGED
@@ -1,5 +1,4 @@
1
- # Updated full code with safe feedback handling
2
-
3
  import gradio as gr
4
  from huggingface_hub import InferenceClient
5
  import re
@@ -7,7 +6,7 @@ import random
7
  import whisper
8
  from pydub import AudioSegment
9
 
10
- # Load and parse the knowledge file
11
  def load_questions(file_path):
12
  with open(file_path, 'r') as f:
13
  data = f.read()
@@ -24,6 +23,7 @@ def load_questions(file_path):
24
 
25
  all_questions = load_questions('knowledge.txt')
26
 
 
27
  questions_by_type = {
28
  'Technical': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in [
29
  'function', 'linked list', 'url', 'rest', 'graphql', 'garbage', 'cap theorem', 'sql', 'hash table',
@@ -36,28 +36,33 @@ questions_by_type = {
36
  "testing", "financial", "automation", "analysis", "regression", "business", "stakeholder"])]
37
  }
38
 
 
39
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
40
  whisper_model = whisper.load_model("base")
41
 
 
42
  def transcribe_audio(file_path):
43
  try:
44
- print(f"\U0001F4C2 Processing audio: {file_path}")
45
  audio = AudioSegment.from_file(file_path)
46
  converted_path = "converted.wav"
47
  audio.export(converted_path, format="wav")
48
  result = whisper_model.transcribe(converted_path, fp16=False)
49
  return result["text"]
50
  except Exception as e:
51
- return f"\u274C ERROR: {str(e)}"
52
 
 
53
  def set_type(choice, user_profile):
54
  user_profile["interview_type"] = choice
55
  return "Great! What’s your background and what field/role are you aiming for?", user_profile
56
 
 
57
  def save_background(info, user_profile):
58
  user_profile["field"] = info
59
  return "Awesome! Type 'start' below to begin your interview.", user_profile
60
 
 
61
  def respond(message, chat_history, user_profile):
62
  message_lower = message.strip().lower()
63
 
@@ -66,6 +71,7 @@ def respond(message, chat_history, user_profile):
66
  chat_history.append((message, bot_msg))
67
  return chat_history
68
 
 
69
  if message_lower == 'start':
70
  interview_type = user_profile['interview_type']
71
  selected_questions = questions_by_type.get(interview_type, [])
@@ -109,6 +115,7 @@ def respond(message, chat_history, user_profile):
109
  chat_history.append((message, feedback))
110
  return chat_history
111
 
 
112
  messages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."}]
113
  for q, a in chat_history:
114
  messages.append({"role": "user", "content": q})
@@ -124,29 +131,17 @@ def generate_feedback(user_profile):
124
  feedback = []
125
  questions = user_profile.get('questions', [])
126
  answers = user_profile.get('user_answers', [])
127
-
128
- if not questions or not answers:
129
- return "⚠️ Feedback unavailable: Make sure you've completed the interview first."
130
-
131
  for i, user_ans in enumerate(answers):
132
- if i >= len(questions):
133
- feedback.append(f"⚠️ No matching question for answer {i+1}.")
134
- continue
135
-
136
- correct_answers = questions[i].get('answers', [])
137
- if not correct_answers:
138
- feedback.append(f"❌ No expected answers listed for question {i+1}.")
139
- continue
140
-
141
  match = any(ans.lower() in user_ans.lower() for ans in correct_answers)
142
  if match:
143
  fb = f"Question {i+1}: βœ… Good job!"
144
  else:
145
  fb = f"Question {i+1}: ❌ Missed some key points: {correct_answers[0]}"
146
  feedback.append(fb)
147
-
148
  return "\n".join(feedback)
149
 
 
150
  def handle_audio(audio_file, chat_history, user_profile):
151
  transcribed = transcribe_audio(audio_file)
152
  if transcribed.startswith("❌"):
@@ -154,6 +149,7 @@ def handle_audio(audio_file, chat_history, user_profile):
154
  return chat_history
155
  return respond(transcribed, chat_history, user_profile)
156
 
 
157
  with gr.Blocks() as demo:
158
  user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})
159
  chat_history = gr.State([])
@@ -191,8 +187,10 @@ with gr.Blocks() as demo:
191
  send_btn = gr.Button("Send Text")
192
  audio_btn = gr.Button("Send Audio")
193
 
 
194
  send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot], queue=False)
195
  send_btn.click(lambda: "", None, msg, queue=False)
196
  audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot], queue=False)
197
 
198
- demo.launch()
 
 
1
+ # imports
 
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
  import re
 
6
  import whisper
7
  from pydub import AudioSegment
8
 
9
+ # uploading and cleaning the knowledge txt file
10
  def load_questions(file_path):
11
  with open(file_path, 'r') as f:
12
  data = f.read()
 
23
 
24
  all_questions = load_questions('knowledge.txt')
25
 
26
+ # creating the questions based on each interview
27
  questions_by_type = {
28
  'Technical': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in [
29
  'function', 'linked list', 'url', 'rest', 'graphql', 'garbage', 'cap theorem', 'sql', 'hash table',
 
36
  "testing", "financial", "automation", "analysis", "regression", "business", "stakeholder"])]
37
  }
38
 
39
+ # models
40
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
41
  whisper_model = whisper.load_model("base")
42
 
43
+ # whisper audio-to-text function
44
  def transcribe_audio(file_path):
45
  try:
46
+ print(f"πŸ“‚ Processing audio: {file_path}")
47
  audio = AudioSegment.from_file(file_path)
48
  converted_path = "converted.wav"
49
  audio.export(converted_path, format="wav")
50
  result = whisper_model.transcribe(converted_path, fp16=False)
51
  return result["text"]
52
  except Exception as e:
53
+ return f"❌ ERROR: {str(e)}"
54
 
55
+ # setting up the users profile (step 1)
56
  def set_type(choice, user_profile):
57
  user_profile["interview_type"] = choice
58
  return "Great! What’s your background and what field/role are you aiming for?", user_profile
59
 
60
+ # step 2
61
  def save_background(info, user_profile):
62
  user_profile["field"] = info
63
  return "Awesome! Type 'start' below to begin your interview.", user_profile
64
 
65
+ # step 3
66
  def respond(message, chat_history, user_profile):
67
  message_lower = message.strip().lower()
68
 
 
71
  chat_history.append((message, bot_msg))
72
  return chat_history
73
 
74
+ # interview process
75
  if message_lower == 'start':
76
  interview_type = user_profile['interview_type']
77
  selected_questions = questions_by_type.get(interview_type, [])
 
115
  chat_history.append((message, feedback))
116
  return chat_history
117
 
118
+ # starting the chatbot
119
  messages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."}]
120
  for q, a in chat_history:
121
  messages.append({"role": "user", "content": q})
 
131
  feedback = []
132
  questions = user_profile.get('questions', [])
133
  answers = user_profile.get('user_answers', [])
 
 
 
 
134
  for i, user_ans in enumerate(answers):
135
+ correct_answers = questions[i]['answers']
 
 
 
 
 
 
 
 
136
  match = any(ans.lower() in user_ans.lower() for ans in correct_answers)
137
  if match:
138
  fb = f"Question {i+1}: βœ… Good job!"
139
  else:
140
  fb = f"Question {i+1}: ❌ Missed some key points: {correct_answers[0]}"
141
  feedback.append(fb)
 
142
  return "\n".join(feedback)
143
 
144
+ # handle audio input
145
  def handle_audio(audio_file, chat_history, user_profile):
146
  transcribed = transcribe_audio(audio_file)
147
  if transcribed.startswith("❌"):
 
149
  return chat_history
150
  return respond(transcribed, chat_history, user_profile)
151
 
152
+ # creating the visual elements
153
  with gr.Blocks() as demo:
154
  user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})
155
  chat_history = gr.State([])
 
187
  send_btn = gr.Button("Send Text")
188
  audio_btn = gr.Button("Send Audio")
189
 
190
+
191
  send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot], queue=False)
192
  send_btn.click(lambda: "", None, msg, queue=False)
193
  audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot], queue=False)
194
 
195
+
196
+ demo.launch()