Anupam007 commited on
Commit
2e07387
·
verified ·
1 Parent(s): 974ef3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -132
app.py CHANGED
@@ -7,19 +7,20 @@ from PyPDF2 import PdfReader
7
  import gtts
8
  import tempfile
9
  import warnings
10
- import threading # For asynchronous feedback
11
  import time
12
- import speech_recognition as sr # Speech to Text
13
- import cv2 # OpenCV
14
- import numpy as np # NumPy
 
 
15
 
16
-
17
- # Suppress gTTS warnings
18
  warnings.filterwarnings("ignore", category=UserWarning, module="gtts")
19
 
20
-
21
- # Initialize NLP model (You might want to use a smaller model for faster processing)
22
  nlp = pipeline("text-generation", model="distilgpt2", tokenizer="distilgpt2", device=0 if torch.cuda.is_available() else -1)
 
23
 
24
  # Speech recognizer setup
25
  r = sr.Recognizer()
@@ -27,7 +28,7 @@ r = sr.Recognizer()
27
  # Extract text from PDF resume
28
  def extract_text_from_pdf(pdf_file):
29
  try:
30
- reader = PdfReader(pdf_file.name) # Access file using pdf_file.name
31
  text = ""
32
  for page in reader.pages:
33
  text += page.extract_text() or ""
@@ -35,170 +36,190 @@ def extract_text_from_pdf(pdf_file):
35
  except Exception as e:
36
  return f"Error reading PDF: {str(e)}"
37
 
38
- # Analyze resume and generate questions (Same as before)
39
- def analyze_resume(resume_text):
40
- if not resume_text:
41
- return ["No resume content found. Please tell me about yourself."]
42
-
43
- skills = re.findall(r"Skills:\s*(.*?)(?:\n|$)", resume_text, re.DOTALL | re.IGNORECASE)
44
- experience = re.findall(r"Experience:\s*(.*?)(?:\n[A-Z]|\Z)", resume_text, re.DOTALL | re.IGNORECASE)
45
- education = re.findall(r"Education:\s*(.*?)(?:\n|$)", resume_text, re.DOTALL | re.IGNORECASE)
 
46
 
47
  questions = []
48
-
49
- if skills:
50
- first_skill = skills[0].split(',')[0].strip() # Get first skill
51
- questions.append(f"Tell me about a time you used {first_skill} in a project.")
52
-
53
- if experience:
54
- try: # Add try-except block
55
- experience_text = experience[0].strip()
56
- company_name = re.search(r"at\s+([\w\s]+?)\s*\(", experience_text) # improved regex
57
- if company_name:
58
- company_name = company_name.group(1).strip()
59
- else:
60
- company_name = "the company" # provide a default value if match is none.
61
- questions.append(f"Can you describe a key contribution you made at {company_name}?")
62
- except IndexError:
63
- print("IndexError encountered while processing experience data.") # print statement
64
- pass # Handle the exception gracefully
65
-
66
- if education:
67
- first_education = education[0].split('(')[0].strip() # Get first education
68
- questions.append(f"How did your education at {first_education} prepare you for this role?")
69
-
70
- return questions if questions else ["Tell me about yourself."]
71
-
72
-
73
- # Provide feedback (Modified for real-time)
 
 
 
74
  def provide_feedback(response):
75
  if not response:
76
  return "Please provide an answer."
77
- response_length = len(response.split()) # count the words instead of chars
78
- if response_length < 20:
79
- return "Your answer is short. Please elaborate."
80
- elif "I don’t know" in response.lower():
81
- return "Try sharing a related experience instead."
82
- else:
83
- return "Great answer! Well detailed."
84
-
 
 
 
 
 
 
 
 
 
 
 
 
85
 
 
86
  def create_interview_video(questions, responses, output_path="interview_simulation.mp4"):
87
- """Creates a simple video with questions and responses using OpenCV."""
88
  try:
89
- frame_rate = 1 # Frames per second
90
- resolution = (1280, 720) # Video resolution
91
- fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for MP4
92
- out = cv2.VideoWriter(output_path, fourcc, int(frame_rate), resolution)
93
 
94
  for i, (question, response) in enumerate(zip(questions, responses)):
95
- # --- Question Frames ---
96
- question_text = f"Question {i+1}: {question}"
97
- for j in range(int(5 * frame_rate)): # 5 seconds per question
98
- frame = np.zeros((resolution[1], resolution[0], 3), dtype=np.uint8)
99
- cv2.putText(frame, question_text, (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) # White text
100
  out.write(frame)
101
 
102
- # --- Response Frames ---
103
  if response:
104
- response_text = f"Response: {response}"
105
- for j in range(int(5 * frame_rate)): # 5 seconds per response
106
- frame = np.zeros((resolution[1], resolution[0], 3), dtype=np.uint8)
107
- cv2.putText(frame, response_text, (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2) # Yellow text
108
  out.write(frame)
109
 
110
- out.release() # Release the video writer
111
- cv2.destroyAllWindows()
112
- print(f"Video saved to {output_path}")
113
  return output_path
114
  except Exception as e:
115
  return f"Video creation failed: {str(e)}"
116
 
117
- def transcribe_audio(audio_file):
118
- """Transcribes audio to text using SpeechRecognition."""
119
  try:
120
- with sr.AudioFile(audio_file) as source:
 
 
 
 
 
 
 
121
  audio = r.record(source)
122
- return r.recognize_google(audio) # Use Google Web Speech API
123
  except Exception as e:
124
- print(f"Transcribe audio error: {e}")
125
- return f"Error transcribing audio: {str(e)}" # Important - MUST return something.
126
 
127
- # Main interview function (Modified for audio input)
128
- def run_interview(pdf_file, audio_file, user_response, question_index, questions_state, responses_state):
129
  try:
130
- if pdf_file is None:
131
- return "Please upload a PDF resume.", "No feedback yet.", None, [], [], 0
132
-
133
- # Extract resume text
134
- resume_text = extract_text_from_pdf(pdf_file)
135
  if not questions_state:
136
- questions_state = analyze_resume(resume_text)
137
-
138
- # Manage responses
139
- if not responses_state:
140
  responses_state = [""] * len(questions_state)
141
-
142
- # Process audio if provided
143
- if audio_file:
144
- transcription = transcribe_audio(audio_file)
145
- user_response = transcription # Use the transcribed text
 
 
 
 
 
 
 
146
  else:
147
- transcription = "" # Ensure transcription is defined even if no audio
148
- # Save the transcribed response
 
149
  if user_response and 0 <= question_index < len(questions_state):
150
  responses_state[question_index] = user_response
151
 
152
  # Check if interview is complete
153
  if question_index >= len(questions_state):
154
  video_path = create_interview_video(questions_state, responses_state)
155
- return "Interview complete!", "Thank you!", video_path, questions_state, responses_state, question_index # Add None for video
156
 
157
  # Current question and feedback
158
  current_question = questions_state[question_index]
159
- feedback = provide_feedback(user_response) if user_response else "Please answer."
160
 
161
- return current_question, feedback, None, questions_state, responses_state, question_index + 1# Add None for video
 
 
 
162
 
163
  except Exception as e:
164
- print(f"Run interview error: {e}")
165
- return f"Error: {str(e)}", "Something went wrong.", None, [], [], 0
166
 
167
  # Gradio interface
168
  with gr.Blocks(title="Nancy AI - Advanced Interview Simulator") as demo:
169
- try: # Add a try-except block around the entire Gradio interface
170
- gr.Markdown("# Nancy AI - Advanced Interview Simulator")
171
- gr.Markdown("Upload your PDF resume and participate in a voice-based interview!")
172
-
173
- question_state = gr.State(value=0)
174
- questions_state = gr.State(value=[])
175
- responses_state = gr.State(value=[])
176
-
177
- with gr.Row():
178
- pdf_input = gr.File(label="Upload PDF Resume", file_types=[".pdf"])
179
-
180
- with gr.Row():
181
- audio_input = gr.Audio(sources=["microphone"], label="Record Your Response") # Audio input
182
- response_input = gr.Textbox(label="Your Response (Optional)", placeholder="Type your answer here...")
183
-
184
-
185
- with gr.Row():
186
- question_output = gr.Textbox(label="Current Question", interactive=False)
187
- feedback_output = gr.Textbox(label="Feedback", interactive=False)
188
-
189
- video_output = gr.Video(label="Interview Simulation (MP4)", visible=False) # initially hidden
190
-
191
-
192
- submit_btn = gr.Button("Submit Response & Next Question")
193
-
194
- submit_btn.click(
195
- fn=run_interview,
196
- inputs=[pdf_input, audio_input, response_input, question_state, questions_state, responses_state],
197
- outputs=[question_output, feedback_output, video_output, questions_state, responses_state, question_state]
198
- )
199
- except Exception as e:
200
- print(f"Error in Gradio interface: {e}") # Print the error
201
- finally:
202
- pass # Add a finally block (optional, but good practice)
203
 
204
  demo.launch()
 
7
  import gtts
8
  import tempfile
9
  import warnings
10
+ import threading
11
  import time
12
+ import speech_recognition as sr
13
+ import cv2
14
+ import numpy as np
15
+ import ast
16
+ from moviepy.editor import VideoFileClip
17
 
18
+ # Suppress warnings
 
19
  warnings.filterwarnings("ignore", category=UserWarning, module="gtts")
20
 
21
+ # Initialize NLP models
 
22
  nlp = pipeline("text-generation", model="distilgpt2", tokenizer="distilgpt2", device=0 if torch.cuda.is_available() else -1)
23
+ sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
24
 
25
  # Speech recognizer setup
26
  r = sr.Recognizer()
 
28
  # Extract text from PDF resume
29
  def extract_text_from_pdf(pdf_file):
30
  try:
31
+ reader = PdfReader(pdf_file.name)
32
  text = ""
33
  for page in reader.pages:
34
  text += page.extract_text() or ""
 
36
  except Exception as e:
37
  return f"Error reading PDF: {str(e)}"
38
 
39
+ # Analyze resume and generate questions
40
+ def analyze_resume(resume_text, custom_questions=None, difficulty=1):
41
+ generic_questions = [
42
+ "What’s your greatest strength?",
43
+ "Describe a challenge you overcame.",
44
+ "Why do you want this role?"
45
+ ]
46
+ if not resume_text and not custom_questions:
47
+ return generic_questions[:difficulty]
48
 
49
  questions = []
50
+ if resume_text:
51
+ skills = re.findall(r"Skills:\s*(.*?)(?:\n|$)", resume_text, re.DOTALL | re.IGNORECASE)
52
+ experience = re.findall(r"Experience:\s*(.*?)(?:\n[A-Z]|\Z)", resume_text, re.DOTALL | re.IGNORECASE)
53
+ education = re.findall(r"Education:\s*(.*?)(?:\n|$)", resume_text, re.DOTALL | re.IGNORECASE)
54
+
55
+ if skills:
56
+ first_skill = skills[0].split(',')[0].strip()
57
+ questions.append(f"Tell me about a time you used {first_skill} in a project.")
58
+ if experience:
59
+ try:
60
+ company_name = re.search(r"at\s+([\w\s]+?)\s*\(", experience[0]) or "the company"
61
+ if isinstance(company_name, str):
62
+ company_name = company_name
63
+ else:
64
+ company_name = company_name.group(1).strip()
65
+ questions.append(f"Can you describe a key contribution you made at {company_name}?")
66
+ except Exception:
67
+ pass
68
+ if education:
69
+ first_education = education[0].split('(')[0].strip()
70
+ questions.append(f"How did your education at {first_education} prepare you for this role?")
71
+
72
+ if custom_questions:
73
+ with open(custom_questions.name, "r") as f:
74
+ questions.extend(f.read().splitlines())
75
+
76
+ return (questions + generic_questions)[:max(1, difficulty)]
77
+
78
+ # Enhanced feedback with sentiment analysis
79
  def provide_feedback(response):
80
  if not response:
81
  return "Please provide an answer."
82
+ word_count = len(response.split())
83
+ sentiment = sentiment_analyzer(response)[0]
84
+ feedback = []
85
+ if word_count < 20:
86
+ feedback.append("Your answer is short. Please elaborate.")
87
+ if "I don’t know" in response.lower():
88
+ feedback.append("Try sharing a related experience instead.")
89
+ if sentiment["label"] == "NEGATIVE":
90
+ feedback.append("Try to sound more positive and confident!")
91
+ return " ".join(feedback) or "Great answer! Well detailed and positive."
92
+
93
+ # Analyze code input
94
+ def analyze_code(code):
95
+ if not code:
96
+ return "No code provided."
97
+ try:
98
+ ast.parse(code)
99
+ return "Code syntax is valid! Consider adding comments for clarity."
100
+ except SyntaxError as e:
101
+ return f"Code error: {str(e)}"
102
 
103
+ # Create interview video
104
  def create_interview_video(questions, responses, output_path="interview_simulation.mp4"):
 
105
  try:
106
+ frame_rate = 1
107
+ resolution = (1280, 720)
108
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
109
+ out = cv2.VideoWriter(output_path, fourcc, frame_rate, resolution)
110
 
111
  for i, (question, response) in enumerate(zip(questions, responses)):
112
+ frame = np.zeros((resolution[1], resolution[0], 3), dtype=np.uint8)
113
+ cv2.putText(frame, f"Question {i+1}: {question}", (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
114
+ for _ in range(5 * frame_rate):
 
 
115
  out.write(frame)
116
 
 
117
  if response:
118
+ frame = np.zeros((resolution[1], resolution[0], 3), dtype=np.uint8)
119
+ cv2.putText(frame, f"Response: {response}", (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2)
120
+ for _ in range(5 * frame_rate):
 
121
  out.write(frame)
122
 
123
+ out.release()
 
 
124
  return output_path
125
  except Exception as e:
126
  return f"Video creation failed: {str(e)}"
127
 
128
+ # Transcribe audio from video or audio file
129
+ def transcribe_audio(file_path):
130
  try:
131
+ if file_path.endswith(".mp4"): # Handle video input
132
+ video = VideoFileClip(file_path)
133
+ audio_path = tempfile.NamedTemporaryFile(suffix=".wav").name
134
+ video.audio.write_audiofile(audio_path)
135
+ else:
136
+ audio_path = file_path
137
+
138
+ with sr.AudioFile(audio_path) as source:
139
  audio = r.record(source)
140
+ return r.recognize_google(audio)
141
  except Exception as e:
142
+ return f"Error transcribing: {str(e)}"
 
143
 
144
+ # Main interview function
145
+ def run_interview(pdf_file, video_file, code_input, mc_input, user_response, question_index, questions_state, responses_state, timer_state, custom_questions, difficulty):
146
  try:
147
+ # Initialize questions if not set
 
 
 
 
148
  if not questions_state:
149
+ resume_text = extract_text_from_pdf(pdf_file) if pdf_file else ""
150
+ questions_state = analyze_resume(resume_text, custom_questions, difficulty)
 
 
151
  responses_state = [""] * len(questions_state)
152
+ timer_state = 60 # Reset timer
153
+
154
+ # Process video/audio input
155
+ if video_file:
156
+ user_response = transcribe_audio(video_file)
157
+
158
+ # Handle multiple-choice or code input if provided
159
+ if mc_input:
160
+ user_response = f"Selected: {mc_input}"
161
+ elif code_input:
162
+ user_response = code_input
163
+ code_feedback = analyze_code(code_input)
164
  else:
165
+ code_feedback = ""
166
+
167
+ # Save response
168
  if user_response and 0 <= question_index < len(questions_state):
169
  responses_state[question_index] = user_response
170
 
171
  # Check if interview is complete
172
  if question_index >= len(questions_state):
173
  video_path = create_interview_video(questions_state, responses_state)
174
+ return "Interview complete!", "Thank you!", video_path, questions_state, responses_state, question_index, 0, None
175
 
176
  # Current question and feedback
177
  current_question = questions_state[question_index]
178
+ feedback = provide_feedback(user_response) + (f" {code_feedback}" if code_feedback else "")
179
 
180
+ # Update timer (simplified for demo)
181
+ timer_state = max(0, timer_state - 10) # Decrement by 10 seconds per submission
182
+
183
+ return current_question, feedback, None, questions_state, responses_state, question_index + 1, timer_state, str(timer_state)
184
 
185
  except Exception as e:
186
+ return f"Error: {str(e)}", "Something went wrong.", None, [], [], 0, 60, "60"
 
187
 
188
  # Gradio interface
189
  with gr.Blocks(title="Nancy AI - Advanced Interview Simulator") as demo:
190
+ gr.Markdown("# Nancy AI - Advanced Interview Simulator")
191
+ gr.Markdown("Upload your resume and a video response (Note: Webcam recording not supported in Colab; upload pre-recorded videos instead).")
192
+
193
+ question_state = gr.State(value=0)
194
+ questions_state = gr.State(value=[])
195
+ responses_state = gr.State(value=[])
196
+ timer_state = gr.State(value=60)
197
+
198
+ with gr.Row():
199
+ pdf_input = gr.File(label="Upload PDF Resume", file_types=[".pdf"])
200
+ custom_questions = gr.File(label="Upload Custom Questions (TXT)", file_types=[".txt"])
201
+ difficulty = gr.Slider(1, 5, step=1, label="Difficulty Level", value=1)
202
+
203
+ with gr.Row():
204
+ # Updated: No 'source' parameter; use interactive=True for recording in non-Colab environments
205
+ video_input = gr.Video(label="Upload or Record Video Response", interactive=True)
206
+ code_input = gr.Code(language="python", label="Write Your Code (if applicable)")
207
+ mc_input = gr.Radio(["Option A", "Option B", "Option C"], label="Multiple Choice (if applicable)")
208
+ text_input = gr.Textbox(label="Your Response (Optional)", placeholder="Type your answer here...")
209
+
210
+ with gr.Row():
211
+ question_output = gr.Textbox(label="Current Question", interactive=False)
212
+ feedback_output = gr.Textbox(label="Feedback", interactive=False)
213
+ timer_display = gr.Textbox(label="Time Left (seconds)", interactive=False, value="60")
214
+
215
+ video_output = gr.Video(label="Interview Simulation", visible=False)
216
+
217
+ submit_btn = gr.Button("Submit Response & Next Question")
218
+
219
+ submit_btn.click(
220
+ fn=run_interview,
221
+ inputs=[pdf_input, video_input, code_input, mc_input, text_input, question_state, questions_state, responses_state, timer_state, custom_questions, difficulty],
222
+ outputs=[question_output, feedback_output, video_output, questions_state, responses_state, question_state, timer_state, timer_display]
223
+ )
224
 
225
  demo.launch()