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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
import torch
|
| 4 |
+
import re
|
| 5 |
+
import os
|
| 6 |
+
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()
|
| 26 |
+
|
| 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 ""
|
| 34 |
+
return text if text else "No text found in the PDF."
|
| 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()
|