Skip to content

Commit 46fe007

Browse files
committed
feat/grading
- Create grading logic
1 parent c740c7d commit 46fe007

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

api/services.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
def grade_submission(submission):
2+
"""
3+
Modular grading service to evaluate a submission.
4+
Currently implements a Mock Grading Service using keyword matching.
5+
"""
6+
# TODO: Implement AI integration to help grade a and provide feedback on SA (Short answer questions)
7+
total_questions = submission.exam.questions.count()
8+
correct_count = 0
9+
feedback_notes = []
10+
11+
# Get all student answers for this submission
12+
answers = submission.answers.all()
13+
14+
for ans in answers:
15+
question = ans.question
16+
# if question is Multiple Choice Question
17+
if question.question_type == 'MCQ':
18+
expected = question.correct_answers.get('answer')
19+
actual = ans.student_answer.get('choice')
20+
21+
if expected == actual:
22+
ans.is_correct = True
23+
correct_count += 1
24+
else:
25+
ans.is_correct = False
26+
feedback_notes.append(f"Q{question.order}: Expected {expected}, got {actual}.")
27+
28+
# if question is Short Answer (SA) - Keyword Matching
29+
elif question.question_type == 'SA':
30+
expected_keywords = question.correct_answers.get('keywords', [])
31+
student_text = ans.student_answer.get('text', '').lower()
32+
33+
# Checks for how many keywords match
34+
matches = [word for word in expected_keywords if word.lower() in student_text]
35+
if len(matches) >= len(expected_keywords) * 0.666: # 66% match threshold (1 matching keyword at least...)
36+
ans.is_correct = True
37+
correct_count += 1
38+
else:
39+
ans.is_correct = False
40+
feedback_notes.append(f"Q{question.order}: Missed key concepts.")
41+
42+
ans.save()
43+
44+
# Calculate final score
45+
if total_questions > 0:
46+
submission.total_score = (correct_count / total_questions) * 100
47+
48+
submission.status = 'graded' # Update status per requirement
49+
submission.feedback = " ".join(feedback_notes) if feedback_notes else "Excellent work!"
50+
submission.save()

0 commit comments

Comments
 (0)