Personalized_Learning_App / evaluation.py
Kiki0203's picture
Update evaluation.py
bdba85b verified
def evaluate_answers(quiz: dict, answers: dict) -> dict:
questions = quiz["questions"]
total = len(questions)
correct_count = 0
details = []
for i, q in enumerate(questions):
user_ans = str(answers.get(i, "")).strip().lower()
correct_ans = str(q.get("answer", "")).strip().lower()
q_type = q.get("type", "")
# Check empty answer first
if user_ans == "":
is_correct = False
# For descriptive questions
elif q_type in ("Short Answer", "Fill in the Blank"):
# Accept if either string contains the other
is_correct = (
correct_ans in user_ans or
user_ans in correct_ans
)
# For objective questions
else:
is_correct = user_ans == correct_ans
# Count correct answers
if is_correct:
correct_count += 1
# Store result details
details.append({
"correct": is_correct,
"correct_answer": q.get("answer", "N/A"),
"explanation": q.get("explanation", ""),
})
# Calculate percentage
score_pct = round((correct_count / total) * 100) if total > 0 else 0
# Feedback generation
if score_pct == 100:
feedback = "🌟 Perfect score! Outstanding work!"
elif score_pct >= 80:
feedback = "πŸŽ‰ Excellent! You have a strong grasp of the material."
elif score_pct >= 60:
feedback = "πŸ‘ Good effort! Review the questions you missed to reinforce your understanding."
elif score_pct >= 40:
feedback = "πŸ“– Keep practising. Revisit the study material for the topics you found tricky."
else:
feedback = "πŸ’ͺ Don't give up! Go back to the study notes and try again β€” you'll improve."
return {
"score_percent": score_pct,
"correct": correct_count,
"total": total,
"feedback": feedback,
"details": details,
}