Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -157,6 +157,19 @@ syllabus_topics = {
|
|
| 157 |
"Advanced Statistics",
|
| 158 |
"Probability Theory"
|
| 159 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
}
|
| 161 |
}
|
| 162 |
|
|
@@ -368,6 +381,11 @@ class StudentSession:
|
|
| 368 |
self.total_points = 0
|
| 369 |
self.session_history = []
|
| 370 |
self.achievements = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
def log_attempt(self, grade, topic, result):
|
| 373 |
"""Log a learning attempt"""
|
|
@@ -542,6 +560,63 @@ def export_as_csv():
|
|
| 542 |
|
| 543 |
return filepath
|
| 544 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
# ---------- 10. Gradio UI with Enhanced Design ----------
|
| 546 |
css_styles = """
|
| 547 |
:root {
|
|
@@ -916,6 +991,112 @@ Format:
|
|
| 916 |
inputs=practice_output,
|
| 917 |
outputs=download_status
|
| 918 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 919 |
|
| 920 |
# ===== TAB 3: AI TUTOR CHAT =====
|
| 921 |
with gr.Tab("💬 Ask AI Tutor"):
|
|
|
|
| 157 |
"Advanced Statistics",
|
| 158 |
"Probability Theory"
|
| 159 |
]
|
| 160 |
+
,
|
| 161 |
+
"Primary 7": [
|
| 162 |
+
"Number Theory & Indices",
|
| 163 |
+
"Algebraic Manipulation (Quadratics, Simultaneous Equations)",
|
| 164 |
+
"Geometry - Circles & Constructions",
|
| 165 |
+
"Trigonometry - Basic Identities & Applications",
|
| 166 |
+
"Mensuration (Area, Perimeter, Volume)",
|
| 167 |
+
"Statistics & Probability (Data Handling)",
|
| 168 |
+
"Functions & Graphs",
|
| 169 |
+
"Coordinate Geometry",
|
| 170 |
+
"Ratio, Proportion & Rates",
|
| 171 |
+
"Examination-style Problem Solving (UNEB practice)"
|
| 172 |
+
]
|
| 173 |
}
|
| 174 |
}
|
| 175 |
|
|
|
|
| 381 |
self.total_points = 0
|
| 382 |
self.session_history = []
|
| 383 |
self.achievements = []
|
| 384 |
+
# Exam state for UNEB practice
|
| 385 |
+
self.current_exam = None # dict with questions and solutions
|
| 386 |
+
self.exam_start_time = None
|
| 387 |
+
self.exam_answers = {}
|
| 388 |
+
self.exam_scores = {}
|
| 389 |
|
| 390 |
def log_attempt(self, grade, topic, result):
|
| 391 |
"""Log a learning attempt"""
|
|
|
|
| 560 |
|
| 561 |
return filepath
|
| 562 |
|
| 563 |
+
# ---------- 11. UNEB Exam Generation & Marking ----------
|
| 564 |
+
def generate_uneb_exam(grade_level, topic, num_questions=5):
|
| 565 |
+
"""Generate a UNEB-style exam with numbered questions and solutions as JSON"""
|
| 566 |
+
if not topic:
|
| 567 |
+
return None
|
| 568 |
+
prompt = f"""Generate a JSON array of {num_questions} UNEB-style exam questions for {grade_level} on the topic '{topic}'.
|
| 569 |
+
Each item should be an object with keys: 'question' and 'solution'.
|
| 570 |
+
Make questions suitable for Primary 7 UNEB practice, clear and exam-like. Return only valid JSON.
|
| 571 |
+
"""
|
| 572 |
+
response, _ = ask_ai(prompt, temperature=0.5)
|
| 573 |
+
# Try parse JSON from response
|
| 574 |
+
try:
|
| 575 |
+
data = json.loads(response)
|
| 576 |
+
# validate structure
|
| 577 |
+
if isinstance(data, list) and all('question' in q and 'solution' in q for q in data):
|
| 578 |
+
return data
|
| 579 |
+
except Exception:
|
| 580 |
+
# fallback: try to extract numbered items
|
| 581 |
+
parts = []
|
| 582 |
+
lines = response.splitlines()
|
| 583 |
+
current = None
|
| 584 |
+
for ln in lines:
|
| 585 |
+
if ln.strip().startswith(('1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.', '10.')):
|
| 586 |
+
if current:
|
| 587 |
+
parts.append(current)
|
| 588 |
+
current = ln.strip()
|
| 589 |
+
elif current is not None:
|
| 590 |
+
current += '\n' + ln
|
| 591 |
+
if current:
|
| 592 |
+
parts.append(current)
|
| 593 |
+
result = []
|
| 594 |
+
for p in parts[:num_questions]:
|
| 595 |
+
result.append({'question': p, 'solution': 'Solution not parsed - refer to AI'} )
|
| 596 |
+
return result
|
| 597 |
+
return None
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def grade_answer(question_text, expected_solution, student_answer_text):
|
| 601 |
+
"""Use AI to grade a single answer and return score and feedback."""
|
| 602 |
+
prompt = f"""You are an experienced UNEB examiner. Grade the student's answer.
|
| 603 |
+
Question: {question_text}
|
| 604 |
+
Expected solution: {expected_solution}
|
| 605 |
+
Student answer: {student_answer_text}
|
| 606 |
+
|
| 607 |
+
Return a short JSON object: {{"score": <number>, "max_score": <number>, "feedback": "..."}}
|
| 608 |
+
Be strict and clear, score out of the full marks (use 1 for simple, or 5 if multi-step)."""
|
| 609 |
+
response, _ = ask_ai(prompt, temperature=0.3)
|
| 610 |
+
try:
|
| 611 |
+
j = json.loads(response)
|
| 612 |
+
return j.get('score', 0), j.get('max_score', 1), j.get('feedback', response)
|
| 613 |
+
except Exception:
|
| 614 |
+
# fallback simple heuristic
|
| 615 |
+
feedback = response
|
| 616 |
+
# if keywords like 'correct' appear, full score
|
| 617 |
+
score = 1 if 'correct' in response.lower() or 'well' in response.lower() else 0
|
| 618 |
+
return score, 1, feedback
|
| 619 |
+
|
| 620 |
# ---------- 10. Gradio UI with Enhanced Design ----------
|
| 621 |
css_styles = """
|
| 622 |
:root {
|
|
|
|
| 991 |
inputs=practice_output,
|
| 992 |
outputs=download_status
|
| 993 |
)
|
| 994 |
+
|
| 995 |
+
# ===== TAB X: UNEB EXAM PRACTICE =====
|
| 996 |
+
with gr.Tab("🧾 UNEB Exam Practice"):
|
| 997 |
+
gr.Markdown("""
|
| 998 |
+
### 🧾 UNEB-style Exam Practice (Primary 7)
|
| 999 |
+
Generate timed UNEB-style exams, answer using the canvas or text, and get examiner-style grading and feedback.
|
| 1000 |
+
""")
|
| 1001 |
+
with gr.Row():
|
| 1002 |
+
exam_num = gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Number of Questions")
|
| 1003 |
+
exam_time = gr.Slider(minimum=5, maximum=120, value=30, step=5, label="Time (minutes)")
|
| 1004 |
+
with gr.Row():
|
| 1005 |
+
start_exam_btn = gr.Button("▶️ Start Exam", variant="primary")
|
| 1006 |
+
finish_exam_btn = gr.Button("🏁 Finish Exam")
|
| 1007 |
+
download_exam_btn = gr.Button("📥 Download Exam & Feedback")
|
| 1008 |
+
exam_question = gr.Textbox(label="Current Exam Question", lines=8)
|
| 1009 |
+
exam_idx = gr.State(value=0)
|
| 1010 |
+
with gr.Row():
|
| 1011 |
+
exam_sketch = gr.Sketchpad(label="Write your answer (draw/working)", type="pil", height=350)
|
| 1012 |
+
exam_upload = gr.Image(label="Or upload an image of your answer (optional)", type="pil", height=200)
|
| 1013 |
+
exam_text_answer = gr.Textbox(label="Or type your answer here", lines=8)
|
| 1014 |
+
with gr.Row():
|
| 1015 |
+
prev_btn = gr.Button("◀️ Prev")
|
| 1016 |
+
submit_answer_btn = gr.Button("✅ Submit Answer")
|
| 1017 |
+
next_btn = gr.Button("▶️ Next")
|
| 1018 |
+
exam_status = gr.Textbox(label="Exam Status", value="Not started", interactive=False)
|
| 1019 |
+
|
| 1020 |
+
def start_uneb_exam(grade, topic, num_q, minutes):
|
| 1021 |
+
if grade != 'Primary 7':
|
| 1022 |
+
return "⚠️ UNEB Exam Practice is tailored for Primary 7 students. Please set Grade to 'Primary 7'."
|
| 1023 |
+
data = generate_uneb_exam(grade, topic, int(num_q))
|
| 1024 |
+
if not data:
|
| 1025 |
+
return "❌ Failed to generate exam. Try again."
|
| 1026 |
+
# store exam
|
| 1027 |
+
session.current_exam = data
|
| 1028 |
+
session.exam_start_time = datetime.now()
|
| 1029 |
+
session.exam_answers = {}
|
| 1030 |
+
session.exam_scores = {}
|
| 1031 |
+
# return first question
|
| 1032 |
+
q0 = data[0]['question']
|
| 1033 |
+
session.log_attempt(grade, topic, 'exam_started')
|
| 1034 |
+
return q0, 0
|
| 1035 |
+
|
| 1036 |
+
def submit_uneb_answer(sketch, upload, text, index):
|
| 1037 |
+
if session.current_exam is None:
|
| 1038 |
+
return "⚠️ No active exam. Start an exam first."
|
| 1039 |
+
# choose student answer
|
| 1040 |
+
if sketch is not None:
|
| 1041 |
+
# save image to bytes and mark as placeholder text
|
| 1042 |
+
buffered = BytesIO()
|
| 1043 |
+
sketch.save(buffered, format="PNG")
|
| 1044 |
+
student_text = f"[Image answer saved - size {len(buffered.getvalue())} bytes]"
|
| 1045 |
+
elif upload is not None:
|
| 1046 |
+
buffered = BytesIO()
|
| 1047 |
+
upload.save(buffered, format="PNG")
|
| 1048 |
+
student_text = f"[Uploaded image answer - size {len(buffered.getvalue())} bytes]"
|
| 1049 |
+
else:
|
| 1050 |
+
student_text = text or ""
|
| 1051 |
+
# store answer
|
| 1052 |
+
session.exam_answers[int(index)] = student_text
|
| 1053 |
+
return "✅ Answer recorded"
|
| 1054 |
+
|
| 1055 |
+
def show_question(idx_state):
|
| 1056 |
+
if session.current_exam is None:
|
| 1057 |
+
return "No active exam",
|
| 1058 |
+
idx = int(idx_state)
|
| 1059 |
+
if idx < 0:
|
| 1060 |
+
idx = 0
|
| 1061 |
+
if idx >= len(session.current_exam):
|
| 1062 |
+
idx = len(session.current_exam) - 1
|
| 1063 |
+
return session.current_exam[idx]['question'], idx
|
| 1064 |
+
|
| 1065 |
+
def finish_uneb_exam_and_grade():
|
| 1066 |
+
if not session.current_exam:
|
| 1067 |
+
return "⚠️ No active exam to finish."
|
| 1068 |
+
results = []
|
| 1069 |
+
total_score = 0
|
| 1070 |
+
total_max = 0
|
| 1071 |
+
for i, item in enumerate(session.current_exam):
|
| 1072 |
+
q = item.get('question')
|
| 1073 |
+
sol = item.get('solution', '')
|
| 1074 |
+
ans = session.exam_answers.get(i, '')
|
| 1075 |
+
score, max_score, feedback = grade_answer(q, sol, ans)
|
| 1076 |
+
session.exam_scores[i] = {'score': score, 'max': max_score, 'feedback': feedback}
|
| 1077 |
+
total_score += score
|
| 1078 |
+
total_max += max_score
|
| 1079 |
+
results.append(f"Q{i+1}: score {score}/{max_score}\nFeedback: {feedback}\n")
|
| 1080 |
+
# update session stats
|
| 1081 |
+
session.problems_attempted += len(session.current_exam)
|
| 1082 |
+
session.session_history.append({'timestamp': datetime.now().isoformat(), 'grade': 'Primary 7', 'topic': 'UNEB Exam', 'result': f'{total_score}/{total_max}'})
|
| 1083 |
+
# build report
|
| 1084 |
+
report = "\n\n".join(results)
|
| 1085 |
+
report_text = f"UNEB Exam Results for {session.student_name}\nTotal: {total_score}/{total_max}\n\n" + report
|
| 1086 |
+
# save feedback file
|
| 1087 |
+
fp = download_feedback(report_text)
|
| 1088 |
+
# clear current exam
|
| 1089 |
+
session.current_exam = None
|
| 1090 |
+
session.exam_answers = {}
|
| 1091 |
+
session.exam_scores = {}
|
| 1092 |
+
return f"✅ Exam graded. Total: {total_score}/{total_max}. Feedback saved: {fp}"
|
| 1093 |
+
|
| 1094 |
+
start_exam_btn.click(fn=start_uneb_exam, inputs=[grade_level, topic_select, exam_num, exam_time], outputs=[exam_question, exam_idx])
|
| 1095 |
+
submit_answer_btn.click(fn=submit_uneb_answer, inputs=[exam_sketch, exam_upload, exam_text_answer, exam_idx], outputs=exam_status)
|
| 1096 |
+
prev_btn.click(fn=lambda idx: show_question(int(idx)-1), inputs=[exam_idx], outputs=[exam_question, exam_idx])
|
| 1097 |
+
next_btn.click(fn=lambda idx: show_question(int(idx)+1), inputs=[exam_idx], outputs=[exam_question, exam_idx])
|
| 1098 |
+
finish_exam_btn.click(fn=finish_uneb_exam_and_grade, inputs=[], outputs=exam_status)
|
| 1099 |
+
download_exam_btn.click(fn=lambda: export_session_summary(), inputs=[], outputs=exam_status)
|
| 1100 |
|
| 1101 |
# ===== TAB 3: AI TUTOR CHAT =====
|
| 1102 |
with gr.Tab("💬 Ask AI Tutor"):
|