Mahmoud-Dev's picture
Fix: Handle missing 'level' field with .get() method and improve error handling
820f8ca verified
import gradio as gr
import random
from datasets import load_dataset
questions_data = None
def load_questions():
global questions_data
if questions_data is None:
try:
ds = load_dataset('Aiman1234/Interview-questions')
questions_data = ds['train']
return True
except Exception as e:
print(f"Error loading dataset: {e}")
return False
return True
class InterviewBot:
def __init__(self):
self.current_question = None
self.score = 0
self.total_questions = 0
self.answers_given = []
def get_next_question(self, difficulty='Easy'):
if not load_questions():
return "Failed to load questions. Please try again.", "N/A", "N/A"
try:
filtered = list(questions_data)
random_q = random.choice(filtered)
self.current_question = random_q
self.total_questions += 1
lang = random_q.get('language', 'Unknown')
level = random_q.get('level', 'Not specified')
question = random_q.get('Questions', 'No question')
return (
f"{question}",
str(lang),
str(level)
)
except Exception as e:
return f"Error getting question: {str(e)}", "Error", "Error"
def evaluate_answer(self, user_answer):
if not self.current_question:
return "Please get a question first!"
try:
answer_length = len(user_answer.split())
correct_answer = self.current_question.get('Answers', '')
correct_answer_length = len(correct_answer.split())
similarity = min(answer_length, correct_answer_length) / max(answer_length, correct_answer_length) if max(answer_length, correct_answer_length) > 0 else 0
if similarity > 0.5:
feedback = f"Good effort! Your answer covers key points.\nExpected answer length: ~{correct_answer_length} words\nYour answer: {answer_length} words"
self.score += 1
else:
feedback = f"Consider expanding your answer.\nExpected length: ~{correct_answer_length} words\nYour answer: {answer_length} words"
self.answers_given.append({
'question': self.current_question.get('Questions', ''),
'your_answer': user_answer,
'similarity': similarity
})
return feedback
except Exception as e:
return f"Error evaluating answer: {str(e)}"
def get_performance_analysis(self):
if self.total_questions == 0:
return "No questions answered yet!"
try:
accuracy = (self.score / self.total_questions) * 100
analysis = f"""
PERFORMANCE ANALYSIS
{'='*50}
Total Questions Attempted: {self.total_questions}
Correct Answers: {self.score}
Accuracy Rate: {accuracy:.1f}%
STRENGTHS:
- Successfully completed {self.total_questions} interview questions
- Current accuracy rate: {accuracy:.1f}%
AREAS FOR IMPROVEMENT:
- Focus on providing detailed answers
- Practice technical concepts
- Improve clarity in explanations
RECOMMENDATIONS:
1. Review expected answers for questions
2. Practice similar questions
3. Work on comprehensive responses
4. Explain concepts clearly
"""
return analysis
except Exception as e:
return f"Error generating analysis: {str(e)}"
bot = InterviewBot()
def start_interview(difficulty):
try:
question, language, level = bot.get_next_question(difficulty)
return f"{question}\n\n(Language: {language} | Level: {level})"
except Exception as e:
return f"Error: {str(e)}"
def submit_answer(answer_text):
if not answer_text.strip():
return "Please provide an answer!"
return bot.evaluate_answer(answer_text)
def show_analysis():
return bot.get_performance_analysis()
with gr.Blocks(title="AI Interview Bot CS") as demo:
gr.Markdown("# AI Job Interview Bot - Computer Science")
gr.Markdown("Practice 496+ technical interview questions with AI feedback")
with gr.Row():
with gr.Column():
gr.Markdown("### Settings")
difficulty = gr.Radio(
choices=['Easy', 'Medium', 'Hard'],
value='Easy',
label="Difficulty"
)
start_btn = gr.Button("Get Next Question", variant="primary")
with gr.Column():
gr.Markdown("### Question")
question_display = gr.Textbox(
label="Question",
interactive=False,
lines=5
)
with gr.Row():
with gr.Column():
gr.Markdown("### Your Answer")
answer_input = gr.Textbox(
lines=6,
placeholder="Your answer..."
)
submit_btn = gr.Button("Submit Answer", variant="primary")
with gr.Column():
gr.Markdown("### Feedback")
feedback_display = gr.Textbox(
interactive=False,
lines=6
)
analysis_btn = gr.Button("Performance Analysis", variant="secondary")
analysis_display = gr.Textbox(
interactive=False,
lines=12
)
start_btn.click(
fn=start_interview,
inputs=[difficulty],
outputs=[question_display]
)
submit_btn.click(
fn=submit_answer,
inputs=[answer_input],
outputs=[feedback_display]
)
analysis_btn.click(
fn=show_analysis,
outputs=[analysis_display]
)
if __name__ == "__main__":
demo.launch()