lanna_lalala;- commited on
Commit ·
618422f
1
Parent(s): bb9dd1f
miniquiz try
Browse filesFiles changed (3)
- phase/Student_view/lesson.py+175-163
- phase/Student_view/mini_quiz.pyAdded+234
- phase/Student_view/practice_quiz.pyDeleted-1
12345678910111213145 unmodified lines20212223242526272829181 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930078 unmodified lines37938038138238338438538638738822 unmodified lines41141241341441541641741841942042126 unmodified lines4484494504514524534544554564574584594604614624634644654664674684694704714724734747 unmodified lines48248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153220 unmodified lines5535545555565575585595605615626 unmodified lines56957057157257357457557657757857958066 unmodified lines6476486496506516527 unmodified lines660661662663664665666667668669670671672# phase/Student_view/lesson.pyimport streamlit as stfrom typing import List, Dict, Any, Optional, Tupleimport reimport datetimeimport osfrom utils import db as dbapifrom utils import api as backend_api # unified backend clientUSE_LOCAL_DB = os.getenv("DISABLE_DB", "1") != "1"FALLBACK_TAG = "<!--fallback-->"# ---------------------------------------------5 unmodified lines"topic_idx": 0, # 0-based within module"mode": "catalog", # catalog | lesson | quiz | results"topics_cache": {}, # {(level, module_id): [(title, text), ...]}"quiz_data": None, # original quiz payload (list[dict])"quiz_answers": {}, # q_index -> "A"|"B"|"C"|"D""quiz_result": None, # backend result dict"chatbot_feedback": None, # str}def _ensure_state():181 unmodified linessents = re.split(r"(?<=[.!?])\s+", text.strip())return [s for s in sents if len(s) > 20][:min(max_items, 3)]def _start_quiz(level: str, module_id: int) -> Optional[List[Dict[str, Any]]]:"""Ask backend to generate a 5-question mini quiz for this module."""module_conf = next(m for m in MODULES_META[level] if m["id"] == module_id)try:quiz = backend_api.generate_quiz(lesson_id=module_id,level_slug=level,lesson_title=module_conf["title"],)if isinstance(quiz, list) and quiz:return quizreturn Noneexcept Exception as e:st.error(f"Could not generate quiz: {e}")return Nonedef _submit_quiz(level: str, module_id: int, original_quiz: List[Dict[str, Any]], answers_map: Dict[int, str]) -> Optional[Dict[str, Any]]:"""Submit answers and get score + tutor feedback."""user_answers = []for i, q in enumerate(original_quiz):user_answers.append({"question": q.get("question", f"Q{i+1}"),"answer": answers_map.get(i, ""), # "A".."D"})# student_id is required by utils/api.submit_quizstudent_id = int(((st.session_state.get("user") or {}).get("user_id") or 0))try:result = backend_api.submit_quiz(student_id=student_id,lesson_id=module_id,level_slug=level,user_answers=user_answers,original_quiz=original_quiz,)return resultexcept Exception as e:st.error(f"Could not submit quiz: {e}")return Nonedef _send_quiz_summary_to_chatbot(result: Dict[str, Any]):"""Send a concise, actionable summary of the quiz outcome to the chatbot,then navigate to the Chatbot page with the conversation pre-seeded."""level = st.session_state.levelmodule_id = st.session_state.module_idmod = next(m for m in MODULES_META[level] if m["id"] == module_id)score = result.get("score", {})correct = int(score.get("correct", 0))total = int(score.get("total", 0))feedback = (result.get("feedback") or st.session_state.get("chatbot_feedback") or "").strip()user_prompt = (f"I just finished the quiz for '{mod['title']}' (module {module_id}) "f"and scored {correct}/{total}. Please give me 2–3 targeted tips and 1 tiny action "f"to improve before the next lesson. If there were wrong answers, explain them simply.\n\n"f"Context from grader:\n{feedback}")try:# Call FastAPI /chat via utils.api.chat_aibot_reply = (backend_api.chat_ai(query=user_prompt,lesson_id=module_id,level_slug=level,history=[]) or "").strip()except Exception:bot_reply = f"(Chatbot unavailable) Based on your result: {feedback or 'Nice work!'}"# Seed Chatbot pagemsgs = st.session_state.get("messages") or [{"id": "1","text": "Hi! I'm your AI Financial Tutor. What would you like to learn today?","sender": "assistant","timestamp": datetime.datetime.now(),}]msgs.append({"text": user_prompt, "sender": "user", "timestamp": datetime.datetime.now()})msgs.append({"text": bot_reply, "sender": "assistant", "timestamp": datetime.datetime.now()})st.session_state.messages = msgsst.session_state.current_page = "Chatbot"def _fallback_text(title: str, module_id: int, topic_ordinal: int) -> str:"""78 unmodified linesst.session_state.topics_cache[cache_key] = outreturn outdef _letter_for(i: int) -> str:return chr(ord("A") + i)def _render_lesson():level = st.session_state.levelmodule_id = st.session_state.module_idif module_id is None:22 unmodified lines# Special Quiz placeholderif t_title.strip().lower() == "quiz":with st.spinner("Generating quiz…"):quiz = _start_quiz(level, module_id)if quiz:st.session_state.quiz_data = quizst.session_state.quiz_answers = {}st.session_state.mode = "quiz"st.rerun()else:st.error("Quiz could not be generated. Please try again or skip.")26 unmodified linesst.rerun()with col3:is_last = st.session_state.topic_idx >= len(topics) - 1if is_last:if not st.session_state.get("_auto_quiz_started", False):st.session_state["_auto_quiz_started"] = Truewith st.spinner("Generating quiz…"):quiz = _start_quiz(level, module_id)if quiz:st.session_state.quiz_data = quizst.session_state.quiz_answers = {}st.session_state.mode = "quiz"st.rerun()else:st.error("Quiz could not be generated. Please try again.")else:if st.button("Take Lesson Quiz →"):with st.spinner("Generating quiz…"):quiz = _start_quiz(level, module_id)if quiz:st.session_state.quiz_data = quizst.session_state.quiz_answers = {}st.session_state.mode = "quiz"st.rerun()else:st.error("Quiz could not be generated. Please try again.")7 unmodified lineslabel = f"{i+1}. {tt}"st.button(label, key=f"jump_{i}", on_click=lambda j=i: st.session_state.update({"topic_idx": j}) or st.rerun())def _render_quiz():quiz: List[Dict[str, Any]] = st.session_state.quiz_data or []if not quiz:st.session_state.mode = "lesson"st.rerun()st.markdown("### Lesson Quiz")# Render each question (single page)for q_idx, q in enumerate(quiz):st.markdown(f"**Q{q_idx+1}. {q.get('question','').strip()}**")opts = q.get("options") or []def _on_select():sel = st.session_state[f"ans_{q_idx}"] # "A. option text"letter = sel.split(".", 1)[0] if isinstance(sel, str) else ""st.session_state.quiz_answers[q_idx] = letterlabels = [f"{_letter_for(i)}. {opt}" for i, opt in enumerate(opts)]saved_letter = st.session_state.quiz_answers.get(q_idx)pre_idx = next((i for i, l in enumerate(labels) if saved_letter and l.startswith(f"{saved_letter}.")), None)st.radio("",labels,index=pre_idx,key=f"ans_{q_idx}",on_change=_on_select,)st.divider()all_answered = len(st.session_state.quiz_answers) == len(quiz)if st.button("Submit Quiz", disabled=not all_answered):with st.spinner("Grading…"):result = _submit_quiz(st.session_state.level,st.session_state.module_id,quiz,st.session_state.quiz_answers,)if result:st.session_state.quiz_result = resultst.session_state.chatbot_feedback = result.get("feedback")_send_quiz_summary_to_chatbot(result)st.rerun()def _render_results():result = st.session_state.quiz_result or {}20 unmodified lineslevel = st.session_state.levelmodule_id = st.session_state.module_idplanned = next((m.get("topics", []) for m in MODULES_META[level] if m["id"] == module_id), [])try:quiz_index = [t.strip().lower() for t in planned].index("quiz")except ValueError:quiz_index = Nonec1, c2, c3 = st.columns([1, 1, 1])with c1:6 unmodified linesst.session_state.current_page = "Chatbot"st.session_state.chatbot_prefill = fbst.rerun()with c3:if quiz_index is not None and quiz_index + 1 < len(planned):if st.button("Continue Lesson →"):st.session_state.mode = "lesson"st.session_state.topic_idx = quiz_index + 1st.rerun()# ---------------------------------------------# Public entry point(s)66 unmodified linesdef render():_ensure_state()route = st.session_state.get("lesson_route")if route and route.get("source") == "teacher":_render_assigned_lesson(int(route.get("lesson_id", 0)), route.get("assignment_id"))7 unmodified lineselif mode == "lesson":_render_lesson()elif mode == "quiz":_render_quiz()elif mode == "results":_render_results()else:st.session_state.mode = "catalog"_render_catalog()# For pages that import and call `show_page()`show_page = render123456789101112131415161718192021225 unmodified lines28293031323334353637181 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730878 unmodified lines38738838939039139239339439539639739822 unmodified lines42142242342442542642742826 unmodified lines4554564574584594604614624634644654664674684694704714724734747 unmodified lines48248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253320 unmodified lines5545555565575585595605615625635645655666 unmodified lines57357457557657757857958058158258358466 unmodified lines6516526536546556566577 unmodified lines665666667668669670671672673674675676677678679680681682683684import streamlit as stfrom typing import List, Dict, Any, Optional, Tupleimport reimport datetimeimport osfrom utils import db as dbapifrom utils import api as backend_api # unified backend client# NEW: import the decoupled mini-quiz module (supports both package and flat runs)try:from .mini_quiz import ensure_quiz_state, start_quiz, render_quiz, render_results as quiz_resultsexcept Exception:from mini_quiz import ensure_quiz_state, start_quiz, render_quiz, render_results as quiz_resultsUSE_LOCAL_DB = os.getenv("DISABLE_DB", "1") != "1"FALLBACK_TAG = "<!--fallback-->"# ---------------------------------------------5 unmodified lines"topic_idx": 0, # 0-based within module"mode": "catalog", # catalog | lesson | quiz | results"topics_cache": {}, # {(level, module_id): [(title, text), ...]}# "quiz_data": None, # original quiz payload (list[dict])# "quiz_answers": {}, # q_index -> "A"|"B"|"C"|"D"# "quiz_result": None, # backend result dict# "chatbot_feedback": None, # str}def _ensure_state():181 unmodified linessents = re.split(r"(?<=[.!?])\s+", text.strip())return [s for s in sents if len(s) > 20][:min(max_items, 3)]# def _start_quiz(level: str, module_id: int) -> Optional[List[Dict[str, Any]]]:# """Ask backend to generate a 5-question mini quiz for this module."""# module_conf = next(m for m in MODULES_META[level] if m["id"] == module_id)# try:# quiz = backend_api.generate_quiz(# lesson_id=module_id,# level_slug=level,# lesson_title=module_conf["title"],# )# if isinstance(quiz, list) and quiz:# return quiz# return None# except Exception as e:# st.error(f"Could not generate quiz: {e}")# return None# def _submit_quiz(level: str, module_id: int, original_quiz: List[Dict[str, Any]], answers_map: Dict[int, str]) -> Optional[Dict[str, Any]]:# """Submit answers and get score + tutor feedback."""# user_answers = []# for i, q in enumerate(original_quiz):# user_answers.append({# "question": q.get("question", f"Q{i+1}"),# "answer": answers_map.get(i, ""), # "A".."D"# })# # student_id is required by utils/api.submit_quiz# student_id = int(((st.session_state.get("user") or {}).get("user_id") or 0))# try:# result = backend_api.submit_quiz(# student_id=student_id,# lesson_id=module_id,# level_slug=level,# user_answers=user_answers,# original_quiz=original_quiz,# )# return result# except Exception as e:# st.error(f"Could not submit quiz: {e}")# return None# def _send_quiz_summary_to_chatbot(result: Dict[str, Any]):# """# Send a concise, actionable summary of the quiz outcome to the chatbot,# then navigate to the Chatbot page with the conversation pre-seeded.# """# level = st.session_state.level# module_id = st.session_state.module_id# mod = next(m for m in MODULES_META[level] if m["id"] == module_id)# score = result.get("score", {})# correct = int(score.get("correct", 0))# total = int(score.get("total", 0))# feedback = (result.get("feedback") or st.session_state.get("chatbot_feedback") or "").strip()# user_prompt = (# f"I just finished the quiz for '{mod['title']}' (module {module_id}) "# f"and scored {correct}/{total}. Please give me 2–3 targeted tips and 1 tiny action "# f"to improve before the next lesson. If there were wrong answers, explain them simply.\n\n"# f"Context from grader:\n{feedback}"# )# try:# # Call FastAPI /chat via utils.api.chat_ai# bot_reply = (backend_api.chat_ai(# query=user_prompt,# lesson_id=module_id,# level_slug=level,# history=[]# ) or "").strip()# except Exception:# bot_reply = f"(Chatbot unavailable) Based on your result: {feedback or 'Nice work!'}"# # Seed Chatbot page# msgs = st.session_state.get("messages") or [{# "id": "1",# "text": "Hi! I'm your AI Financial Tutor. What would you like to learn today?",# "sender": "assistant",# "timestamp": datetime.datetime.now(),# }]# msgs.append({"text": user_prompt, "sender": "user", "timestamp": datetime.datetime.now()})# msgs.append({"text": bot_reply, "sender": "assistant", "timestamp": datetime.datetime.now()})# st.session_state.messages = msgs# st.session_state.current_page = "Chatbot"def _fallback_text(title: str, module_id: int, topic_ordinal: int) -> str:"""78 unmodified linesst.session_state.topics_cache[cache_key] = outreturn out# def _letter_for(i: int) -> str:# return chr(ord("A") + i)def _render_lesson():ensure_quiz_state() # make sure quiz keys existlevel = st.session_state.levelmodule_id = st.session_state.module_idif module_id is None:22 unmodified lines# Special Quiz placeholderif t_title.strip().lower() == "quiz":with st.spinner("Generating quiz…"):ok = start_quiz(level, module_id, mod["title"])if ok:st.rerun()else:st.error("Quiz could not be generated. Please try again or skip.")26 unmodified linesst.rerun()with col3:is_last = st.session_state.topic_idx >= len(topics) - 1if is_last:if not st.session_state.get("_auto_quiz_started", False):st.session_state["_auto_quiz_started"] = Truewith st.spinner("Generating quiz…"):ok = start_quiz(level, module_id, mod["title"])if ok:st.rerun()else:st.error("Quiz could not be generated. Please try again.")else:if st.button("Take Lesson Quiz →"):with st.spinner("Generating quiz…"):ok = start_quiz(level, module_id, mod["title"])if ok:st.rerun()else:st.error("Quiz could not be generated. Please try again.")7 unmodified lineslabel = f"{i+1}. {tt}"st.button(label, key=f"jump_{i}", on_click=lambda j=i: st.session_state.update({"topic_idx": j}) or st.rerun())# def _render_quiz():# quiz: List[Dict[str, Any]] = st.session_state.quiz_data or []# if not quiz:# st.session_state.mode = "lesson"# st.rerun()# st.markdown("### Lesson Quiz")# # Render each question (single page)# for q_idx, q in enumerate(quiz):# st.markdown(f"**Q{q_idx+1}. {q.get('question','').strip()}**")# opts = q.get("options") or []# def _on_select():# sel = st.session_state[f"ans_{q_idx}"] # "A. option text"# letter = sel.split(".", 1)[0] if isinstance(sel, str) else ""# st.session_state.quiz_answers[q_idx] = letter# labels = [f"{_letter_for(i)}. {opt}" for i, opt in enumerate(opts)]# saved_letter = st.session_state.quiz_answers.get(q_idx)# pre_idx = next((i for i, l in enumerate(labels) if saved_letter and l.startswith(f"{saved_letter}.")), None)# st.radio(# "",# labels,# index=pre_idx,# key=f"ans_{q_idx}",# on_change=_on_select,# )# st.divider()# all_answered = len(st.session_state.quiz_answers) == len(quiz)# if st.button("Submit Quiz", disabled=not all_answered):# with st.spinner("Grading…"):# result = _submit_quiz(# st.session_state.level,# st.session_state.module_id,# quiz,# st.session_state.quiz_answers,# )# if result:# st.session_state.quiz_result = result# st.session_state.chatbot_feedback = result.get("feedback")# _send_quiz_summary_to_chatbot(result)# st.rerun()def _render_results():result = st.session_state.quiz_result or {}20 unmodified lineslevel = st.session_state.levelmodule_id = st.session_state.module_idplanned = next((m.get("topics", []) for m in MODULES_META[level] if m["id"] == module_id), [])# Let mini_quiz handle the full results UI (review, feedback, nav)quiz_results(planned_topics=planned)# try:# quiz_index = [t.strip().lower() for t in planned].index("quiz")# except ValueError:# quiz_index = Nonec1, c2, c3 = st.columns([1, 1, 1])with c1:6 unmodified linesst.session_state.current_page = "Chatbot"st.session_state.chatbot_prefill = fbst.rerun()# with c3:# if quiz_index is not None and quiz_index + 1 < len(planned):# if st.button("Continue Lesson →"):# st.session_state.mode = "lesson"# st.session_state.topic_idx = quiz_index + 1# st.rerun()# ---------------------------------------------# Public entry point(s)66 unmodified linesdef render():_ensure_state()ensure_quiz_state() # ensure quiz keys whenever the page rendersroute = st.session_state.get("lesson_route")if route and route.get("source") == "teacher":_render_assigned_lesson(int(route.get("lesson_id", 0)), route.get("assignment_id"))7 unmodified lineselif mode == "lesson":_render_lesson()elif mode == "quiz":# Hand off to mini-quiz UI. Pass title for chatbot summary when grading.# We can retrieve the module title here for convenience.try:mod = next(m for m in MODULES_META[st.session_state.level] if m["id"] == st.session_state.module_id)render_quiz(lesson_title=mod["title"])except Exception:render_quiz(lesson_title=None)elif mode == "results":_render_results()else:st.session_state.mode = "catalog"_render_catalog()# For pages that import and call `show_page()`show_page = render
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234# phase/Student_view/mini_quiz.pyimport datetimefrom typing import List, Dict, Any, Optionalimport streamlit as st
# Reuse the unified backend clientfrom utils import api as backend_api
# ---------------------------------------------# Public quiz-state helpers# ---------------------------------------------QUIZ_SS_DEFAULTS = { "quiz_data": None, # original quiz payload (list[dict]) "quiz_answers": {}, # q_index -> "A"|"B"|"C"|"D" "quiz_result": None, # backend result dict "chatbot_feedback": None, # str "_auto_quiz_started": False, # helper to avoid double-start}
def ensure_quiz_state(): """Ensure quiz-related keys exist in st.session_state.""" for k, v in QUIZ_SS_DEFAULTS.items(): if k not in st.session_state: st.session_state[k] = v
# ---------------------------------------------# Backend calls (isolated here)# ---------------------------------------------
def start_quiz(level: str, module_id: int, lesson_title: str) -> bool: """Generate and stage a quiz for the given module. Returns True on success.""" ensure_quiz_state() try: quiz = backend_api.generate_quiz( lesson_id=module_id, level_slug=level, lesson_title=lesson_title, ) except Exception as e: st.error(f"Could not generate quiz: {e}") return False
if isinstance(quiz, list) and quiz: st.session_state.quiz_data = quiz st.session_state.quiz_answers = {} st.session_state.mode = "quiz" return True
st.error("Quiz could not be generated. Please try again.") return False
def submit_quiz(level: str, module_id: int, original_quiz: List[Dict[str, Any]], answers_map: Dict[int, str]) -> Optional[Dict[str, Any]]: """Submit answers and return the grading result dict.""" user_answers = [] for i, q in enumerate(original_quiz): user_answers.append({ "question": q.get("question", f"Q{i+1}"), "answer": answers_map.get(i, ""), # "A".."D" })
# student_id is required by utils.api.submit_quiz student_id = int(((st.session_state.get("user") or {}).get("user_id") or 0))
try: result = backend_api.submit_quiz( student_id=student_id, lesson_id=module_id, level_slug=level, user_answers=user_answers, original_quiz=original_quiz, ) return result except Exception as e: st.error(f"Could not submit quiz: {e}") return None
def send_quiz_summary_to_chatbot(level: str, module_id: int, lesson_title: str, result: Dict[str, Any]): """Send a concise summary to the chatbot and navigate there.""" score = result.get("score", {}) correct = int(score.get("correct", 0)) total = int(score.get("total", 0)) feedback = (result.get("feedback") or st.session_state.get("chatbot_feedback") or "").strip()
user_prompt = ( f"I just finished the quiz for '{lesson_title}' (module {module_id}) " f"and scored {correct}/{total}. Please give me 2–3 targeted tips and 1 tiny action " f"to improve before the next lesson. If there were wrong answers, explain them simply.\n\n" f"Context from grader:\n{feedback}" )
try: bot_reply = (backend_api.chat_ai( query=user_prompt, lesson_id=module_id, level_slug=level, history=[], ) or "").strip() except Exception: bot_reply = f"(Chatbot unavailable) Based on your result: {feedback or 'Nice work!'}"
# Seed Chatbot page msgs = st.session_state.get("messages") or [{ "id": "1", "text": "Hi! I'm your AI Financial Tutor. What would you like to learn today?", "sender": "assistant", "timestamp": datetime.datetime.now(), }] msgs.append({"text": user_prompt, "sender": "user", "timestamp": datetime.datetime.now()}) msgs.append({"text": bot_reply, "sender": "assistant", "timestamp": datetime.datetime.now()})
st.session_state.messages = msgs st.session_state.current_page = "Chatbot"
# ---------------------------------------------# UI helpers# ---------------------------------------------
def _letter_for(i: int) -> str: return chr(ord("A") + i)
def render_quiz(lesson_title: Optional[str] = None): """Render the quiz UI (single page). Expects st.session_state.level/module_id to be set.""" ensure_quiz_state()
quiz: List[Dict[str, Any]] = st.session_state.quiz_data or [] if not quiz: # No staged quiz — bounce back to lesson st.session_state.mode = "lesson" st.rerun()
st.markdown("### Lesson Quiz")
# Render each question for q_idx, q in enumerate(quiz): st.markdown(f"**Q{q_idx+1}. {q.get('question','').strip()}**") opts = q.get("options") or []
def _on_select(): sel = st.session_state[f"ans_{q_idx}"] # e.g. "A. option text" letter = sel.split(".", 1)[0] if isinstance(sel, str) else "" st.session_state.quiz_answers[q_idx] = letter
labels = [f"{_letter_for(i)}. {opt}" for i, opt in enumerate(opts)] saved_letter = st.session_state.quiz_answers.get(q_idx) pre_idx = next((i for i, l in enumerate(labels) if saved_letter and l.startswith(f"{saved_letter}.")), None)
st.radio( "", labels, index=pre_idx, key=f"ans_{q_idx}", on_change=_on_select, ) st.divider()
all_answered = len(st.session_state.quiz_answers) == len(quiz) if st.button("Submit Quiz", disabled=not all_answered): with st.spinner("Grading…"): result = submit_quiz( st.session_state.level, st.session_state.module_id, quiz, st.session_state.quiz_answers, ) if result: st.session_state.quiz_result = result st.session_state.chatbot_feedback = result.get("feedback") # Keep current behavior: jump to Chatbot after grading send_quiz_summary_to_chatbot( st.session_state.level, st.session_state.module_id, lesson_title or "This Lesson", result, ) st.rerun()
def render_results(planned_topics: Optional[List[str]] = None): """Optional results screen (not used by default flow which jumps to Chatbot).""" ensure_quiz_state()
result = st.session_state.quiz_result or {} score = result.get("score", {}) correct = score.get("correct", 0) total = score.get("total", 0)
st.success(f"Quiz Complete! You scored {correct} / {total}.")
wrong = result.get("wrong", []) if wrong: with st.expander("Review your answers"): for w in wrong: st.markdown(f"**{w.get('question','')}**") st.write(f"Your answer: {w.get('your_answer','')}") st.write(f"Correct answer: {w.get('correct_answer','')}") st.divider()
fb = st.session_state.chatbot_feedback if fb: st.markdown("#### Tutor Explanation") st.write(fb)
# Navigation controls planned_topics = planned_topics or [] try: quiz_index = [t.strip().lower() for t in planned_topics].index("quiz") except ValueError: quiz_index = None
c1, c2, c3 = st.columns([1, 1, 1]) with c1: if st.button("Back to Modules"): st.session_state.mode = "catalog" st.session_state.module_id = None st.rerun() with c2: if st.button("Ask the Chatbot →"): st.session_state.current_page = "Chatbot" st.session_state.chatbot_prefill = fb st.rerun() with c3: if quiz_index is not None and quiz_index + 1 < len(planned_topics): if st.button("Continue Lesson →"): st.session_state.mode = "lesson" st.session_state.topic_idx = quiz_index + 1 st.rerun()
1#added a practice_quiz.py (for the general practice quiz code could go here and the lesson_quiz code stuff in quiz.py)phase/Student_view/lesson.py+175-163
phase/Student_view/mini_quiz.pyAdded+234
phase/Student_view/practice_quiz.pyDeleted-1