maahikachitagi commited on
Commit
637a592
·
verified ·
1 Parent(s): 1aa5fd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -77
app.py CHANGED
@@ -2,47 +2,53 @@ import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import re
4
  import random
5
-
6
- # Load questions (your original backend)
7
- def load_questions(file_path):
8
- with open(file_path, 'r') as f:
9
- data = f.read()
10
- question_blocks = re.split(r'Question:\s*', data)[1:]
11
- questions = []
12
- for block in question_blocks:
13
- parts = block.split('Possible Answers:')
14
- question_text = parts[0].strip()
15
- answers_text = parts[1].strip()
16
- possible_answers = [ans.strip() for ans in re.split(r'\d+\.\s+', answers_text) if ans.strip()]
17
- questions.append({'question': question_text, 'answers': possible_answers})
18
- return questions
19
-
20
- all_questions = load_questions('knowledge.txt')
21
-
22
- # Question categorization (same as your existing code)
23
- questions_by_type = {
24
- 'Technical': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in [
25
- 'function', 'linked list', 'url', 'rest', 'graphql', 'garbage', 'cap theorem', 'sql', 'hash table',
26
- 'stack', 'queue', 'recursion', 'reverse', 'bfs', 'dfs', 'time complexity', 'binary search tree',
27
- 'web application', 'chat system', 'load balancing', 'caching', 'normalization', 'acid', 'indexing',
28
- 'sql injection', 'https', 'xss', 'hash', 'vulnerabilities'])],
29
- 'Competency-Based Interview': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in [
30
- "debugging", "learning", "deadlines", "teamwork", "leadership", "mistake", "conflict", "decision"])],
31
- 'Case': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in [
32
- "testing", "financial", "automation", "analysis", "regression", "business", "stakeholder"])]
33
- }
34
-
35
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
36
-
37
- # Backend logic (all functions same as before — no changes)
 
 
 
 
 
 
 
 
 
 
 
 
38
  def set_type(choice, user_profile):
39
  user_profile["interview_type"] = choice
40
  return "Great! What’s your background and what field/role are you aiming for?", user_profile
41
 
 
42
  def save_background(info, user_profile):
43
  user_profile["field"] = info
44
  return "Awesome! Type 'start' below to begin your interview.", user_profile
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def respond(message, chat_history, user_profile):
47
  message_lower = message.strip().lower()
48
 
@@ -52,74 +58,61 @@ def respond(message, chat_history, user_profile):
52
  return chat_history
53
 
54
  if message_lower == 'start':
55
- interview_type = user_profile['interview_type']
56
- selected_questions = questions_by_type.get(interview_type, [])
57
- random.shuffle(selected_questions)
58
- selected_questions = selected_questions[:10]
59
-
60
- user_profile['questions'] = selected_questions
61
- user_profile['current_q'] = 0
62
  user_profile['user_answers'] = []
 
63
  user_profile['interview_in_progress'] = True
64
 
65
- intro = f"Welcome to your {interview_type} interview for a {user_profile['field']} position. I will ask you up to 10 questions. Type 'stop' anytime to end."
66
- first_q = f"First question: {selected_questions[0]['question']}"
 
67
  chat_history.append((message, intro))
68
- chat_history.append(("", first_q))
69
  return chat_history
70
 
71
  if message_lower == 'stop' and user_profile.get("interview_in_progress"):
72
  user_profile['interview_in_progress'] = False
73
- bot_msg = "Interview stopped. Type 'feedback' if you'd like me to analyze your answers."
74
  chat_history.append((message, bot_msg))
75
  return chat_history
76
 
 
 
 
 
 
77
  if user_profile.get("interview_in_progress"):
78
- q_index = user_profile['current_q']
79
  user_profile['user_answers'].append(message)
80
- q_index += 1
81
- user_profile['current_q'] = q_index
82
 
83
- if q_index < len(user_profile['questions']):
84
- bot_msg = f"Next question: {user_profile['questions'][q_index]['question']}"
 
 
85
  else:
86
  user_profile['interview_in_progress'] = False
87
- bot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers."
88
- chat_history.append((message, bot_msg))
89
- return chat_history
90
 
91
- if message_lower == 'feedback':
92
- feedback = generate_feedback(user_profile)
93
- chat_history.append((message, feedback))
94
  return chat_history
95
 
96
- # Normal chatbot conversation
97
- messages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."}]
98
- for q, a in chat_history:
99
- messages.append({"role": "user", "content": q})
100
- messages.append({"role": "assistant", "content": a})
101
- messages.append({"role": "user", "content": message})
102
-
103
  response = client.chat_completion(messages, max_tokens=150, stream=False)
104
- bot_msg = response.choices[0].message.content
105
  chat_history.append((message, bot_msg))
106
  return chat_history
107
 
108
- def generate_feedback(user_profile):
109
- feedback = []
110
- questions = user_profile.get('questions', [])
111
- answers = user_profile.get('user_answers', [])
112
- for i, user_ans in enumerate(answers):
113
- correct_answers = questions[i]['answers']
114
- match = any(ans.lower() in user_ans.lower() for ans in correct_answers)
115
- if match:
116
- fb = f"Question {i+1}: ✅ Good job!"
117
- else:
118
- fb = f"Question {i+1}: ❌ Missed key points: {correct_answers[0]}"
119
- feedback.append(fb)
120
- return "\n".join(feedback)
121
-
122
-
123
  # The new Intervu 2.0 UI with your design!
124
  with gr.Blocks(css="""
125
  body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }
 
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")
18
+ result = whisper_model.transcribe(converted_path, fp16=False)
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", []))):
43
+ messages = [
44
+ {"role": "system", "content": f"You are a professional interviewer providing feedback for a candidate's response in a {user_profile['interview_type']} interview for a {user_profile['field']} role."},
45
+ {"role": "user", "content": f"Question: {question}\nAnswer: {answer}\nPlease give specific, constructive feedback."}
46
+ ]
47
+ response = client.chat_completion(messages, max_tokens=150, stream=False)
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
 
 
58
  return chat_history
59
 
60
  if message_lower == 'start':
61
+ user_profile['questions'] = []
 
 
 
 
 
 
62
  user_profile['user_answers'] = []
63
+ user_profile['current_q'] = 0
64
  user_profile['interview_in_progress'] = True
65
 
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"):
 
85
  user_profile['user_answers'].append(message)
86
+ user_profile['current_q'] += 1
 
87
 
88
+ if user_profile['current_q'] < 10:
89
+ next_q = generate_question(user_profile)
90
+ user_profile['questions'].append(next_q)
91
+ bot_msg = f"Next question: {next_q}"
92
  else:
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
100
+ messages = [
101
+ {"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."},
102
+ {"role": "user", "content": message}
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; }