From dc1b4baa75e9875c08b6b72cf5874d9454755e70 Mon Sep 17 00:00:00 2001 From: mormal1016 Date: Mon, 16 Nov 2026 01:05:56 +0800 Subject: [PATCH] feat(graph): add on-demand topic explanations and course examples --- components/knowledge_graph.py | 5 +++ components/topic_explanation.py | 65 +++++++++++++++++++++++++++++ pages/4_Knowledge_Graph.py | 2 +- services/i18n.py | 14 +++++++ tests/test_topic_explanation.py | 72 +++++++++++++++++++++++++++++++++ 5 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 components/topic_explanation.py create mode 100644 tests/test_topic_explanation.py diff --git a/components/knowledge_graph.py b/components/knowledge_graph.py index 455ed49..381388d 100644 --- a/components/knowledge_graph.py +++ b/components/knowledge_graph.py @@ -215,6 +215,7 @@ def get_selected_topic_details( def render_topic_details( details: dict | None, topic_stats: TopicStats | None = None, + course: StudyPackage | None = None, ) -> None: if details is None: st.info(tr("Click a knowledge point to see its details.")) @@ -227,6 +228,10 @@ def render_topic_details( st.subheader(tr("Summary")) st.write(details["summary"]) + if course is not None: + from components.topic_explanation import render_topic_explanation + render_topic_explanation(course, details["id"]) + source_pages = details["source_pages"] if source_pages: st.caption(tr(f"Source pages: {', '.join(map(str, source_pages))}")) diff --git a/components/topic_explanation.py b/components/topic_explanation.py new file mode 100644 index 0000000..fedf211 --- /dev/null +++ b/components/topic_explanation.py @@ -0,0 +1,65 @@ +"""On-demand topic teaching, with existing course examples available offline.""" +import hashlib + +import streamlit as st + +from models.schemas import StudyPackage +from services.ai_service import ask_tutor +from services.i18n import LANGUAGE_KEY, tr + + +def render_topic_explanation(course: StudyPackage, topic_id: str) -> None: + topic = next((item for item in course.topics if item.id == topic_id), None) + if topic is None: + return + chinese = bool(st.session_state.get(LANGUAGE_KEY, False)) + # Include content, not just IDs: regenerated courses must not reuse old answers. + fingerprint = hashlib.sha256( + (course.model_dump_json() + topic_id + str(chinese)).encode() + ).hexdigest() + with st.expander(tr("Detailed explanation & examples")): + st.caption(tr("Go beyond the summary: understand the idea, then work through an example.")) + if st.button(tr("Explain step by step"), key=f"graph_explain_{fingerprint}"): + language = "Simplified Chinese" if chinese else "English" + prompt = ( + f"Explain this selected topic in {language} for a student who found the summary too abstract. " + "Use short numbered sections: 1. Intuition in everyday language; " + "2. Key conditions or steps and why each matters; " + "3. One simple worked example with each reasoning step; " + "4. A common mistake and how to avoid it; 5. One self-check question. " + "Label any illustrative example as an example, not a quotation from the course. " + "Use only the supported concepts; explicitly acknowledge missing context. " + "Do not merely repeat the summary." + ) + with st.spinner(tr("Preparing the explanation…")): + result = ask_tutor(course.model_dump(mode="json"), prompt, topic_id) + if result.get("ok") and result.get("answer", "").strip(): + st.session_state["graph_topic_explanation"] = { + "fingerprint": fingerprint, "answer": result["answer"] + } + else: + st.warning(tr("The explanation is unavailable. You can still read the course example below, or try again.")) + saved = st.session_state.get("graph_topic_explanation", {}) + if saved.get("fingerprint") == fingerprint: + st.caption(tr("AI explanation · check it against your course material.")) + st.write(saved["answer"]) + + examples = [question for question in course.questions if question.topic_id == topic_id] + st.markdown(tr("**Example from this course**")) + st.caption(tr("Original course wording is preserved. Reading examples does not count as a graded attempt.")) + if not examples: + st.caption(tr("There is no example for this topic in the current course yet.")) + return + example = st.selectbox( + tr("Choose an example"), examples, + format_func=lambda item: item.question, + key=f"graph_example_{fingerprint}", + ) + st.write(example.question) + for index, option in enumerate(example.options): + st.write(f"{chr(65 + index)}. {option}") + if st.checkbox(tr("Show answer and explanation"), key=f"graph_solution_{fingerprint}_{example.id}"): + st.markdown(tr("**Answer**")) + st.write(f"{chr(65 + example.correct_index)}. {example.options[example.correct_index]}") + st.markdown(tr("**Why this answer**")) + st.write(example.explanation) diff --git a/pages/4_Knowledge_Graph.py b/pages/4_Knowledge_Graph.py index 2ab9b00..e7d9647 100644 --- a/pages/4_Knowledge_Graph.py +++ b/pages/4_Knowledge_Graph.py @@ -328,7 +328,7 @@ ), None, ) - render_topic_details(details, topic_stats) + render_topic_details(details, topic_stats, course) if details is not None: links = related_topics(course, selected_node_id) st.divider() diff --git a/services/i18n.py b/services/i18n.py index cf3c026..f6a2933 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -20,6 +20,20 @@ def remember_language() -> None: _TRANSLATIONS = { + 'Detailed explanation & examples': '详细讲解与例题', + 'Go beyond the summary: understand the idea, then work through an example.': '不止看概述:先理解思路,再通过例题掌握用法。', + 'Explain step by step': '分步骤讲解', + 'Preparing the explanation…': '正在准备讲解…', + 'The explanation is unavailable. You can still read the course example below, or try again.': '暂时无法生成讲解。你仍可查看下方课程例题,或重新尝试。', + 'AI explanation · check it against your course material.': 'AI 辅助讲解 · 请结合课程资料核对。', + '**Example from this course**': '**本课程例题**', + 'Original course wording is preserved. Reading examples does not count as a graded attempt.': '例题保留课程原文。查看例题不会计入答题成绩。', + 'There is no example for this topic in the current course yet.': '当前课程暂时没有这个知识点的例题。', + 'Choose an example': '选择例题', + 'Show answer and explanation': '显示答案与解析', + '**Answer**': '**答案**', + '**Why this answer**': '**解题解析**', + "Home": "首页", "Review & tools": "复习与工具", "Account": "账户", "Start with one question, or open a course you already study.": "先试做一道题,或打开已经在学的课程。", "Try one practice question after signing in, then follow the next step from your result.": "登录后试做一道题,再根据结果继续学习。", diff --git a/tests/test_topic_explanation.py b/tests/test_topic_explanation.py new file mode 100644 index 0000000..af13ac4 --- /dev/null +++ b/tests/test_topic_explanation.py @@ -0,0 +1,72 @@ +from unittest.mock import Mock + +from streamlit.testing.v1 import AppTest + +from components import topic_explanation + + +def app_script(): + import streamlit as st + from models.schemas import StudyPackage + from components.topic_explanation import render_topic_explanation + from services.i18n import LANGUAGE_KEY + st.toggle('Chinese', key=LANGUAGE_KEY) + selected = st.selectbox('Topic', ['t1', 't2']) + course = StudyPackage.model_validate({ + 'course_id': 'course', 'course_name': 'Test', + 'topics': [dict(id='t1', name='Addition', summary='Combine numbers.'), + dict(id='t2', name='Other', summary='Other topic.')], + 'relationships': [], + 'questions': [dict(id='q1', topic_id='t1', question='1 + 1?', + options=['2', '3', '4', '5'], correct_index=0, + explanation='One plus one makes two.')], + }) + render_topic_explanation(course, selected) + + +def test_examples_are_offline_and_answers_require_action(monkeypatch): + tutor = Mock() + monkeypatch.setattr(topic_explanation, 'ask_tutor', tutor) + app = AppTest.from_function(app_script).run() + assert not app.exception + assert not tutor.called + assert not any('One plus one' in item.value for item in app.markdown) + app.checkbox[0].check().run() + assert any('One plus one' in item.value for item in app.markdown) + assert not tutor.called + + +def test_explicit_generation_language_and_topic_isolation(monkeypatch): + tutor = Mock(return_value={'ok': True, 'answer': 'Worked explanation'}) + monkeypatch.setattr(topic_explanation, 'ask_tutor', tutor) + app = AppTest.from_function(app_script).run() + app.button[0].click().run() + assert tutor.call_count == 1 + assert tutor.call_args.args[2] == 't1' + assert any(item.value == 'Worked explanation' for item in app.markdown) + app.run() + assert tutor.call_count == 1 + app.toggle[0].set_value(True).run() + assert not any(item.value == 'Worked explanation' for item in app.markdown) + assert tutor.call_count == 1 + app.selectbox[0].select('t2').run() + assert not any(item.value == 'Worked explanation' for item in app.markdown) + assert any("暂时没有" in item.value for item in app.caption) + app.toggle[0].set_value(True).run() + assert app.expander[0].label == '详细讲解与例题' + app.button[0].click().run() + assert 'Simplified Chinese' in tutor.call_args.args[1] + assert tutor.call_args.args[2] == 't2' + assert not app.exception + + +def test_failure_keeps_examples_and_allows_retry(monkeypatch): + tutor = Mock(side_effect=[{'ok': False}, {'ok': True, 'answer': 'Recovered'}]) + monkeypatch.setattr(topic_explanation, 'ask_tutor', tutor) + app = AppTest.from_function(app_script).run() + app.button[0].click().run() + assert len(app.warning) == 1 + assert app.checkbox[0].label == 'Show answer and explanation' + app.button[0].click().run() + assert any(item.value == 'Recovered' for item in app.markdown) + assert not app.exception