From 5d3fffa55377a24c8823d2174c8e8283938aa31c Mon Sep 17 00:00:00 2001 From: Charles Chen Date: Sat, 14 Nov 2026 22:52:08 -0500 Subject: [PATCH 01/21] perf(radar): refresh other students' flags once a minute Each radar refresh opens two new database connections (the course counts and the user's own flags). Measured from a laptop against the hosted database that is roughly 0.4 s. With a 15-second cache the cost came back on the Knowledge Map and Study Plan every few interactions. Keep the shared session cache for 60 seconds instead. The user's own flag or unflag still appears at once, because it clears the cache through forget_course_radar. The two cache tests now follow the constant. --- components/knowledge_graph.py | 5 ++++- tests/test_knowledge_graph.py | 4 ++-- tests/test_study_hub_radar.py | 5 +++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/components/knowledge_graph.py b/components/knowledge_graph.py index 17160ee..4c46d46 100644 --- a/components/knowledge_graph.py +++ b/components/knowledge_graph.py @@ -248,7 +248,10 @@ def render_topic_details( st.badge(tr(_MASTERY_LABELS[status]), color=_MASTERY_BADGE_COLORS[status]) -RADAR_CACHE_SECONDS = 15 +# Every refresh opens new database connections, so other students' flags are +# re-read at most once a minute. The user's own flag or unflag still shows at +# once, because it clears the cache through forget_course_radar. +RADAR_CACHE_SECONDS = 60 def radar_cache_key(course_id: str) -> str: diff --git a/tests/test_knowledge_graph.py b/tests/test_knowledge_graph.py index 978e2bf..6894536 100644 --- a/tests/test_knowledge_graph.py +++ b/tests/test_knowledge_graph.py @@ -1198,7 +1198,7 @@ def test_no_flag_button_without_signed_in_user(monkeypatch): assert radar.calls["get_user_flags"] == [] -def test_radar_is_reused_for_fifteen_seconds(monkeypatch): +def test_radar_is_reused_until_the_cache_expires(monkeypatch): radar = RadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") @@ -1210,7 +1210,7 @@ def test_radar_is_reused_for_fifteen_seconds(monkeypatch): assert len(radar.calls["get_user_flags"]) == 1 snapshot = dict(app.session_state[CACHE_KEY]) - snapshot["fetched_at"] -= 16 + snapshot["fetched_at"] -= knowledge_graph.RADAR_CACHE_SECONDS + 1 app.session_state[CACHE_KEY] = snapshot app.run() diff --git a/tests/test_study_hub_radar.py b/tests/test_study_hub_radar.py index a92e921..84d5d17 100644 --- a/tests/test_study_hub_radar.py +++ b/tests/test_study_hub_radar.py @@ -11,6 +11,7 @@ from streamlit.testing.v1 import AppTest from streamlit.testing.v1.element_tree import Block +from components.knowledge_graph import RADAR_CACHE_SECONDS from models.schemas import StudyPackage from services import learning_radar from tests.auth_helpers import TEST_USER, signed_in_app @@ -404,7 +405,7 @@ def test_registered_app_navigates_from_study_plan_to_selected_practice(monkeypat assert app.selectbox(key="practice_topic_calculus-i-demo").value == "calc_derivatives" -def test_two_reruns_within_fifteen_seconds_fetch_the_radar_once(monkeypatch): +def test_two_reruns_within_the_cache_window_fetch_the_radar_once(monkeypatch): radar = RadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _study_page(_calculus_course(), signed_in=True) @@ -417,7 +418,7 @@ def test_two_reruns_within_fifteen_seconds_fetch_the_radar_once(monkeypatch): assert app.session_state[CACHE_KEY]["user_id"] == TEST_USER.user_id snapshot = dict(app.session_state[CACHE_KEY]) - snapshot["fetched_at"] -= 16 + snapshot["fetched_at"] -= RADAR_CACHE_SECONDS + 1 app.session_state[CACHE_KEY] = snapshot app.run() From b70dd39f12159588d89a47205fbab0a336672a64 Mon Sep 17 00:00:00 2001 From: Jiale Li Date: Sat, 14 Nov 2026 22:57:27 -0500 Subject: [PATCH 02/21] Fix mobile Pilot overlap, review navigation and demo contrast --- app.py | 17 ++++++++++++++--- assets/academic_ui.css | 18 ++++++++++++++++++ assets/tutor_assistant.js | 16 ++++++++++++---- tests/test_learning_flow_ux.py | 9 +++++++++ 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/app.py b/app.py index 268915c..0873320 100644 --- a/app.py +++ b/app.py @@ -109,9 +109,20 @@ st.page_link(pages[0], label=tr("Home"), icon=":material/home:", width="stretch") with practice: st.page_link(pages[2], label=tr("Practice"), icon=":material/edit_note:", width="stretch") - with review, st.popover(tr("Review & tools"), width="stretch"): - for page in (pages[1], pages[3], pages[4], pages[5], pages[6]): - st.page_link(page, width="stretch") + with review: + review_pages = { + page.url_path: page + for page in (pages[1], pages[3], pages[4], pages[5], pages[6]) + if page.url_path != navigation.url_path + } + destination = st.selectbox( + tr("Review & tools"), list(review_pages), index=None, + format_func=lambda path: review_pages[path].title, + placeholder=tr("Review & tools"), label_visibility="collapsed", + key=f"flight_review_destination_{navigation.url_path}", + ) + if destination is not None: + st.switch_page(review_pages[destination]) with account, st.popover(tr("Account"), icon=":material/account_circle:", width="stretch"): render_account_controls(account_page) with st.expander(tr("Accessibility settings")): diff --git a/assets/academic_ui.css b/assets/academic_ui.css index 9fa1700..5297913 100644 --- a/assets/academic_ui.css +++ b/assets/academic_ui.css @@ -393,3 +393,21 @@ div.st-key-create_course_button button > div > span { justify-content: flex-star .st-key-flight_header [data-testid="stColumn"] { flex: 1 0 42% !important; width: auto !important; } .st-key-flight_header [data-testid="stColumn"]:first-child { flex-basis: 100% !important; } } + +/* The demo button's label may inherit Streamlit's primary foreground. */ +[data-testid="stMain"] .st-key-dashboard_demo_start button[data-testid="stBaseButton-primary"] { + color: #192f4d !important; + background: #f4d59d !important; + border-color: #f4d59d !important; +} +[data-testid="stMain"] .st-key-dashboard_demo_start button[data-testid="stBaseButton-primary"] * { + color: inherit !important; +} +[data-testid="stMain"] .st-key-dashboard_demo_start button[data-testid="stBaseButton-primary"]:hover { + background: #ebc786 !important; +} +.st-key-flight_header [data-testid="stSelectbox"] [data-baseweb="select"] > div { + background: transparent; + border-color: transparent; + min-height: 44px; +} diff --git a/assets/tutor_assistant.js b/assets/tutor_assistant.js index 11c0386..82c591b 100644 --- a/assets/tutor_assistant.js +++ b/assets/tutor_assistant.js @@ -78,12 +78,17 @@ export default function(component) { const size = 64; if (!state.hasMoved || state.x === null || state.y === null) { state.x = view.left + view.width - size - 24; - // Mobile course actions occupy the lower part of the Dashboard. Start - // below the app header instead; an intentional drag still goes anywhere. - state.y = view.width <= 480 ? view.top + 76 : view.top + view.height - size - 24; + state.y = view.top + view.height - size - 24; } + const header = view.width <= 760 + ? document.querySelector('.st-key-flight_header')?.getBoundingClientRect() + : null; + const upper = header && header.bottom > view.top + ? Math.max(view.top + margin, header.bottom + margin) + : view.top + margin; + const lower = view.top + view.height - size - margin; state.x = clamp(state.x, view.left + margin, view.left + view.width - size - margin); - state.y = clamp(state.y, view.top + margin, view.top + view.height - size - margin); + state.y = clamp(state.y, Math.min(upper, lower), lower); bubble.style.left = `${state.x}px`; bubble.style.top = `${state.y}px`; const panelWidth = Math.min(388, Math.max(200, view.width - 2 * margin)); @@ -313,6 +318,9 @@ export default function(component) { state.validation = ''; setTriggerValue('clear', { request_id: crypto.randomUUID(), session_id: data.session_id, course_id: courseId }); }); + on(document, 'scroll', () => { + if (viewport().width <= 760) position(); + }, { capture: true, passive: true }); on(window, 'resize', position); if (window.visualViewport) { on(window.visualViewport, 'resize', position); diff --git a/tests/test_learning_flow_ux.py b/tests/test_learning_flow_ux.py index 7ddbc71..2b343d3 100644 --- a/tests/test_learning_flow_ux.py +++ b/tests/test_learning_flow_ux.py @@ -218,3 +218,12 @@ def test_practice_result_opens_the_same_topic_in_concept_lab(): assert not app.exception assert app.session_state[f"concept_lab_topic_{course.course_id}"] == topic_id assert app.session_state[f"active_practice_{course.course_id}"]["session"] == session + +def test_top_review_menu_opens_destination_with_a_clear_selection(): + app = signed_in_app(ROOT / "app.py").run() + menu = app.selectbox(key="flight_review_destination_") + menu.set_value("Study_Hub").run() + assert not app.exception + new_menu = app.selectbox(key="flight_review_destination_Study_Hub") + assert new_menu.value is None + assert "Study Plan" not in new_menu.options From 7fbd193191bd30738d9b7b13df06b21a2660b68a Mon Sep 17 00:00:00 2001 From: Charles Chen Date: Sat, 14 Nov 2026 22:56:18 -0500 Subject: [PATCH 03/21] docs(readme): describe the features added for STEMergent Hacks Add a section listing the November 2026 additions (step hints, Concept Lab, Learning Radar, accessibility and Chinese interface, Learning DNA and practice insights, guided Limits review, larger demo banks) with links to their docs. Update Features, the Demo Courses table and its pending-review note, Typical Workflow, the persistence lists, Project Structure and the Documentation links to match the current code. --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 7fc8f98..96a4aea 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,20 @@ Turn course materials into focused exam practice. ExamPilot is a Streamlit learning platform that combines document extraction, AI-assisted course preparation, practice exams, progress tracking, and an interactive knowledge map. -Built for HackRU Fall 2026. +Built for HackRU Fall 2026 and extended in November 2026 for STEMergent Hacks. **Live demo:** https://exampilot-jl9eqsvbgoyedczbroxrzu.streamlit.app/ — register any account and try the built-in demo courses. AI generation is turned off on the public demo. +## Added for STEMergent Hacks (November 2026) + +- **Step hints:** In Topic Practice, a question can reveal up to three hints, one at a time. The number of hints shown is saved with the result and appears in answer review. The 15 original demo questions have hints, and Claude is asked to write them for generated questions. +- **Concept Lab:** Interactive Calculus I experiments for limits, derivatives (secant to tangent), and the corner of |x| at 0, where the function is continuous but not differentiable. Each follows predict, explore, and explain steps; predictions never create grades or mastery evidence. See [Guided Concept Lab](docs/guided_concept_lab.md). +- **Learning Radar:** On the Knowledge Map of the three demo courses, a student can mark a topic "I'm stuck here", optionally with a reason (concept unclear, calculation errors, can't understand the question, or don't know where to start). The Knowledge Map shows how many students are stuck on each flagged topic, and Study Plan lists the three most-flagged topics with a practice shortcut. Counts add real flags to sample data from `data/radar_sample.json`; where sample data is included, the count is labelled "Includes sample data". A topic with no sample data shows "Some students flagged this" instead of a number until it has at least three real flags. +- **Accessibility and language:** A Simplified English toggle shows plainer wording for the 15 original demo questions. A Chinese interface toggle translates most interface text and adds Chinese translations after key terms in practice questions; uploaded material and AI-generated answers keep their original language. +- **Learning DNA and practice insights:** During practice, students can record their confidence and see a review-before-submit check. After grading, results show estimated focus time and hint use, accept a written reflection on any question, with an optional reason for each missed one, and offer a smart review list. Learning DNA separates each topic's computation and conceptual evidence. See [Learning DNA](docs/learning_dna.md) and [Practice insights and reflection](docs/practice_insights.md). +- **Guided Limits review:** After a student misses the Calculus I demo's factorisation limit question in Topic Practice, the result page asks where they got stuck, walks through the factoring step, and checks a new follow-up limit question. If they pick one of the two specific reasons, they can also share it anonymously with Learning Radar. The Dashboard's Try one question card can start this question. +- **Larger demo question banks:** Each demo now has at least 30 questions, and Calculus I grows to 15 topics, 66 questions and 20 relationships. The added questions are drafts pending review (see [Demo Courses](#demo-courses)). See [Calculus knowledge expansion](docs/calculus_knowledge_expansion.md) and [Demo question bank expansion](docs/demo_question_bank.md). + ## Screenshots | Dashboard | Study Plan | @@ -22,13 +32,17 @@ Built for HackRU Fall 2026. - **Course materials:** Extract text from UTF-8 TXT, text-based PDF and PPTX, and PNG/JPG/JPEG images. - **AI-assisted preparation:** Generate candidate topics and multiple-choice questions with Claude, then confirm the topics to practise. -- **Practice:** Take Mock Exams or Topic Practice sessions with scoring, answer review, and explanations. -- **Progress:** Track results and topic mastery separately for each course and practice mode. -- **Knowledge Map:** Explore topic relationships, inspect topic details, view mastery colours, and ask Claude to suggest connections from your saved material (applied only after you review them). +- **Practice:** Take Mock Exams or Topic Practice sessions with scoring, answer review, and explanations. Topic Practice offers step hints; results add practice insights, a smart review list, and written reflections. +- **Progress:** Track results and topic mastery separately for each course and practice mode, with a Learning DNA profile of computation and conceptual evidence. +- **Knowledge Map:** Explore topic relationships, inspect topic details, view mastery colours, and ask Claude to suggest connections from your saved material (applied only after you review them). On the demo courses, Learning Radar shows where students are stuck. +- **Concept Lab:** Explore limits, derivatives, and differentiability in interactive Calculus I experiments. +- **Accessibility and language:** Simplified English wording for the original demo questions, and a Chinese interface that also translates key terms in questions. - **Anki export:** Preview cards and download all questions or questions from weak/developing topics as UTF-8 TSV. - **Accounts and persistence:** Register, log in, and save or restore courses and graded practice records through PostgreSQL. - **Pilot assistant:** Ask course-related questions through a draggable floating assistant. +The features added in November 2026 are described in more detail under [Added for STEMergent Hacks](#added-for-stemergent-hacks-november-2026). + AI-generated topics, questions, answers, explanations, and relationships require human review. ## Demo Courses @@ -37,9 +51,11 @@ Three built-in courses provide practice content without requiring AI generation: | Course | Topics | Questions | Relationships | |---|---:|---:|---:| -| Introduction to Microeconomics | 3 | 3 | 2 | -| Calculus I | 3 | 3 | 2 | -| Python Basics | 3 | 9 | 0 | +| Introduction to Microeconomics | 3 | 30 | 2 | +| Calculus I | 15 | 66 | 20 | +| Python Basics | 3 | 30 | 0 | + +The questions added in November 2026 (27, 63, and 21 respectively) are drafts marked pending review. They are excluded from practice until approved in Study Plan, so the questions available for practice out of the box are 3, 3, and 9. Demo content does not require a Claude API key. The normal application still requires a working account database to register or log in. @@ -192,11 +208,12 @@ See [document processing and Claude usage](docs/claude_usage.md) for supported f 2. Open a built-in Demo or create a course from uploaded materials. 3. Extract and review the text. 4. Generate candidate topics when using your own materials. -5. Review the topics and explicitly confirm the exam scope. -6. Generate questions if needed, then start Mock Exam or Topic Practice. -7. Submit answers and review the score and explanations. -8. Inspect Progress and Knowledge Map. -9. Preview or download Anki cards for further review. +5. Review the topics and explicitly confirm the exam scope. Approve any pending questions you want to practise. +6. Generate questions if needed, then start Mock Exam or Topic Practice. In Topic Practice, reveal hints one at a time if you get stuck. +7. Submit answers and review the score, explanations, practice insights, and smart review list; reflect on missed questions. +8. Try the Calculus I limits, derivatives, and corner experiments in Concept Lab. +9. Inspect Progress (including Learning DNA) and Knowledge Map. On a demo course, mark a topic "I'm stuck here" if it is giving you trouble. +10. Preview or download Anki cards for further review. Pilot is available after login. It uses the selected course's topic summaries and relationships; open a course before asking a question. @@ -204,11 +221,12 @@ Pilot is available after login. It uses the selected course's topic summaries an ### Saved to PostgreSQL -- Course packages +- Course packages, including their learning state: confirmed exam scope, question review decisions, extracted material text (not the original files), practice order, and practice insights such as confidence, hints shown, tracked focus time, and reflections - Exam sessions - Submitted answer results +- Learning Radar flags: account ID, course ID, topic ID, an optional reason, and when the flag was created (table `radar_flags`, created by [`db/migrations/003_learning_radar.sql`](db/migrations/003_learning_radar.sql)) -Database operations use the authenticated account's server-side user ID. Course records are scoped by account. +Database operations use the authenticated account's server-side user ID. Course records are scoped by account. Learning Radar shows other students only per-topic and per-reason totals, not who flagged a topic. On login, the application discovers saved courses and restores their histories. Topic statistics and mastery are recalculated from the restored records. @@ -220,10 +238,12 @@ Saving and restoring require a working database connection. A successful local g - Pilot conversations and input drafts - Account avatars - Uploaded document previews +- Unfinished practice sessions set aside when you start a new one +- Accessibility and interface-language settings Pilot conversations and avatars are not restored from PostgreSQL or synchronised across devices. -Signing out clears the current session. Saved learning records can be restored after signing in again; unsaved records do not have that guarantee. +Signing out clears the current session; only the interface-language choice is kept. Saved learning records can be restored after signing in again; unsaved records do not have that guarantee. ### Restore conflicts @@ -271,12 +291,12 @@ These labels summarise recorded practice performance; they are not a formal asse ```text app.py Application entry point and authentication guard -pages/ Dashboard, study, practice, progress, graph, and Anki +pages/ Dashboard, study, practice, progress, graph, Concept Lab, and Anki services/ AI, extraction, authentication, persistence, and engines models/schemas.py Shared Pydantic data models components/ Interactive knowledge-map components assets/ UI styles, illustrations, and Pilot frontend assets -data/ Built-in Demo course packages +data/ Built-in Demo course packages, hints, simplified wording, Chinese key terms, and Radar sample data db/ Learning-data and account SQL schemas tests/ Automated tests docs/ Setup guides, contracts, and development records @@ -331,5 +351,17 @@ Record the exact commit and environment when reporting real integration results. - [Testing on another computer](docs/other_computer_testing.md) - [Floating Pilot assistant](docs/floating_tutor.md) - [Shared UI typography](docs/ui_typography.md) +- [Guided Concept Lab](docs/guided_concept_lab.md) +- [Learning DNA](docs/learning_dna.md) +- [Practice insights and reflection](docs/practice_insights.md) +- [Calculus knowledge expansion](docs/calculus_knowledge_expansion.md) +- [Demo question bank expansion](docs/demo_question_bank.md) +- [Shared built-in examples](docs/shared_demo_catalog.md) +- [Learning flow UX](docs/learning_flow_ux.md) +- [Student-facing detail audit](docs/student_facing_details.md) +- [Question quality and mistake review](docs/question_quality_review.md) +- [Knowledge Map exploration](docs/knowledge_map_exploration.md) (in Chinese) +- [Learning continuity, mastery evidence, and question review](docs/learning_continuity_review.md) (in Chinese) +- [Database reliability](docs/database_reliability.md) (in Chinese) Some development documents describe earlier branch snapshots and their test results. Their historical status statements should not be treated as the current release status. \ No newline at end of file From a7aa7c3725402c9d4f1e46662426d27e5201e1b2 Mon Sep 17 00:00:00 2001 From: Jiale Li Date: Sat, 14 Nov 2026 23:04:57 -0500 Subject: [PATCH 04/21] Match desktop practice to the paper worksheet reference --- app.py | 8 +- assets/academic_ui.css | 77 ++++++++++++++ pages/2_Practice_Center.py | 173 ++++++++++++++++++++++---------- services/auth_ui.py | 7 +- tests/test_practice_insights.py | 3 + 5 files changed, 209 insertions(+), 59 deletions(-) diff --git a/app.py b/app.py index 0873320..399a90e 100644 --- a/app.py +++ b/app.py @@ -97,8 +97,8 @@ st.session_state.pop(f"scope_initialised_{selected_course.course_id}", None) st.session_state["_learning_page_path"] = navigation.url_path with st.container(key="flight_header"): - brand, home, practice, review, account = st.columns( - [1.65, 0.85, 0.95, 1.2, 0.95], gap="small", vertical_alignment="center" + brand, home, practice, review, analytics, account = st.columns( + [1.65, 0.85, 0.95, 1.25, 1.05, 0.95], gap="small", vertical_alignment="center" ) with brand: st.markdown( @@ -112,7 +112,7 @@ with review: review_pages = { page.url_path: page - for page in (pages[1], pages[3], pages[4], pages[5], pages[6]) + for page in (pages[1], pages[4], pages[5], pages[6]) if page.url_path != navigation.url_path } destination = st.selectbox( @@ -123,6 +123,8 @@ ) if destination is not None: st.switch_page(review_pages[destination]) + with analytics: + st.page_link(pages[3], label=tr("Analytics"), icon=":material/monitoring:", width="stretch") with account, st.popover(tr("Account"), icon=":material/account_circle:", width="stretch"): render_account_controls(account_page) with st.expander(tr("Accessibility settings")): diff --git a/assets/academic_ui.css b/assets/academic_ui.css index 5297913..ff63e47 100644 --- a/assets/academic_ui.css +++ b/assets/academic_ui.css @@ -411,3 +411,80 @@ div.st-key-create_course_button button > div > span { justify-content: flex-star border-color: transparent; min-height: 44px; } + +/* A worksheet uses a broad answer column and a quiet paper margin. */ +[data-testid="stMain"] .st-key-flight_worksheet { padding: .6rem .55rem 1rem; } +[data-testid="stMain"] .st-key-flight_worksheet [class*="st-key-practice_question_"] { + max-width: none; + background: transparent !important; +} +.st-key-flight_worksheet [data-testid="stRadio"] label { border-bottom: 1px solid #e3dbcc; } +.st-key-flight_worksheet [data-testid="stRadio"] label:has(input:checked) { + background: #edf1f2; + border-color: #a2b4be; +} +.st-key-flight_worksheet_margin { + border-left: 1px solid #ded8c9; + padding: 1rem 0 1rem clamp(.75rem,2vw,1.7rem); + min-width: 0; +} +[data-testid="stMain"] .st-key-flight_worksheet_margin h3 { font-family: var(--flight-title); } +.st-key-flight_practice_progress { + border-block: 1px solid #e3dbcc; + padding-block: .4rem; +} +.st-key-flight_practice_progress [role="progressbar"] > div { + background-color: #a66a44; +} +[data-testid="stAppViewContainer"]:has(.st-key-flight_auth_intro) [data-testid="stMainBlockContainer"] { + max-width: 40rem; + padding-top: 1.75rem; +} +.st-key-flight_auth_intro { padding: .5rem .3rem; } +@media (max-width: 760px) { + [data-testid="stHorizontalBlock"]:has(.st-key-flight_worksheet_margin) { + flex-direction: column; + } + [data-testid="stHorizontalBlock"]:has(.st-key-flight_worksheet_margin) > [data-testid="stColumn"] { + flex: 0 1 auto !important; + width: 100% !important; + } + .st-key-flight_worksheet_margin { + border-left: 0; + border-top: 1px solid #ded8c9; + padding: .75rem 0; + } +} + +.flight-waypoints { + display: flex; + position: relative; + justify-content: space-between; + align-items: center; + min-height: 2.35rem; + max-width: 38rem; + isolation: isolate; +} +.flight-waypoints::before { + content: ""; + position: absolute; + z-index: -1; + inset: 50% .4rem auto; + border-top: 1px dashed #aaa284; +} +.flight-waypoint { + display: grid; + place-items: center; + width: .56rem; + height: .56rem; + border: 1px solid #a49a7e; + border-radius: 50%; + background: var(--flight-paper); +} +.flight-waypoint.is-current { + width: 2.25rem; + height: 2.25rem; + color: #985831; + border-color: #d7ad8e; + font-size: 1.25rem; +} diff --git a/pages/2_Practice_Center.py b/pages/2_Practice_Center.py index 1ce556f..d3e9f5e 100644 --- a/pages/2_Practice_Center.py +++ b/pages/2_Practice_Center.py @@ -1,5 +1,6 @@ from services.i18n import tr from html import escape +import time import streamlit as st @@ -14,7 +15,10 @@ start_focus_controls, answer_controls, checklist, capture_submission, result_overview, reflection_controls, ) -from services.practice_insights import session_insights +from services.practice_insights import focus_question, session_insights +from services.auth_session import current_user +from services import learning_radar +from components.knowledge_graph import load_course_radar, render_topic_radar from services.learning_flow import install_practice, resume_draft, remember_widget, hydrate_widgets, open_lab from services.ui_style import apply_app_styles @@ -39,6 +43,7 @@ def submit_practice(course, practice_key): session, questions = active["session"], active["questions"] if "result" in active: return + hydrate_widgets(st.session_state, active) answers = {q.id: st.session_state.get(f"answer_{session.session_id}_{q.id}") for q in questions} try: result = grade_exam(session, questions, answers) @@ -221,59 +226,123 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids submitted = "result" in active_practice if not submitted: - st.subheader(tr("Questions")) hydrate_widgets(st.session_state, active_practice, force=st.session_state.pop(f"rehydrate_practice_{course.course_id}", False)) - with st.container(key="flight_practice_progress"): - answered = sum( - st.session_state.get(f"answer_{session.session_id}_{question.id}") is not None - for question in questions - ) - st.progress(answered / len(questions)) - st.caption(tr("Answered") + f" · {answered} / {len(questions)}") - start_focus_controls(active_practice) - - for question_number, question in enumerate(questions, start=1): - display = display_question(course.course_id, question, st.session_state) - with st.container( - border=True, - key=f"practice_question_{question.id}", - ): - st.caption(tr(f"QUESTION {question_number} OF {len(questions)}")) - st.markdown(f"### {display.question}") - if display.simplified: - st.caption(tr("Simplified wording")) - with st.expander(tr("Show original wording")): - st.write(question.question) - for option in question.options: - st.write(option) - - st.radio( - tr("Choose an answer"), - options=list(range(len(question.options))), - format_func=lambda index, options=display.options: ( - options[index] - ), - index=None, - width="stretch", - key=f"answer_{session.session_id}_{question.id}", - on_change=remember_widget, - args=(st.session_state, course.course_id, session.session_id, f"answer_{session.session_id}_{question.id}"), - ) + question_index = min(active_practice.get("worksheet_index", 0), len(questions) - 1) + selected_question = questions[question_index] + answered = sum( + st.session_state.get(f"answer_{session.session_id}_{question.id}") is not None + for question in questions + ) + if session.mode == "topic": + paper, margin = st.columns([3, 1], gap="large") + visible_questions = [(question_index + 1, selected_question)] + else: + paper = st.container() + margin = None + visible_questions = list(enumerate(questions, start=1)) + with paper, st.container(key="flight_worksheet"): + with st.container(key="flight_practice_progress"): + st.caption(tr("Question") + f" {question_index + 1:02} / {len(questions):02}" if margin is not None else tr("Questions")) + if margin is not None: + stops = min(len(questions), 12) + current_stop = question_index * (stops - 1) // max(1, len(questions) - 1) + markers = "".join( + '✈' if step == current_stop + else '' + for step in range(stops) + ) + st.markdown( + f'', + unsafe_allow_html=True, + ) + else: + st.progress(answered / len(questions)) + st.caption(tr("Answered") + f" · {answered} / {len(questions)}") + with st.expander(tr("Focus controls")): + start_focus_controls(active_practice) - answer_controls(active_practice, question, course.course_id) - - if session.mode == "topic" and (hints := hints_for(question)): - state_key = hint_state_key(session.session_id, question.id) - shown = st.session_state.get(state_key, 0) - for number, hint in enumerate(hints[:shown], start=1): - st.info(tr(f"Hint {number} of {len(hints)}: {display_text(hint, st.session_state)}")) - if shown < len(hints) and st.button( - tr("Show a hint") if shown == 0 else tr("Show next hint"), - key=f"hint_button_{session.session_id}_{question.id}", - ): - st.session_state[state_key] = shown + 1 - remember_widget(st.session_state, course.course_id, session.session_id, state_key) - st.rerun() + for question_number, question in visible_questions: + display = display_question(course.course_id, question, st.session_state) + with st.container( + border=session.mode == "mock", + key=f"practice_question_{question.id}", + ): + st.caption(tr(f"QUESTION {question_number} OF {len(questions)}")) + st.markdown(f"### {display.question}") + if display.simplified: + st.caption(tr("Simplified wording")) + with st.expander(tr("Show original wording")): + st.write(question.question) + for option in question.options: + st.write(option) + + st.radio( + tr("Choose an answer"), + options=list(range(len(question.options))), + format_func=lambda index, options=display.options: ( + options[index] + ), + index=None, + width="stretch", + key=f"answer_{session.session_id}_{question.id}", + on_change=remember_widget, + args=(st.session_state, course.course_id, session.session_id, f"answer_{session.session_id}_{question.id}"), + ) + + answer_controls(active_practice, question, course.course_id) + + if session.mode == "topic" and (hints := hints_for(question)): + state_key = hint_state_key(session.session_id, question.id) + shown = st.session_state.get(state_key, 0) + for number, hint in enumerate(hints[:shown], start=1): + st.info(tr(f"Hint {number} of {len(hints)}: {display_text(hint, st.session_state)}")) + if shown < len(hints) and st.button( + tr("Show a hint") if shown == 0 else tr("Show next hint"), + key=f"hint_button_{session.session_id}_{question.id}", + ): + st.session_state[state_key] = shown + 1 + remember_widget(st.session_state, course.course_id, session.session_id, state_key) + st.rerun() + + if margin is not None and len(questions) > 1: + previous, next_button = st.columns(2) + movement = 0 + if previous.button( + tr("Previous"), icon=":material/arrow_back:", disabled=question_index == 0, + key=f"worksheet_previous_{session.session_id}", + ): + movement = -1 + if next_button.button( + tr("Next"), icon=":material/arrow_forward:", disabled=question_index == len(questions) - 1, + key=f"worksheet_next_{session.session_id}", + ): + movement = 1 + if movement: + new_index = question_index + movement + active_practice["worksheet_index"] = new_index + timer = active_practice.get("focus_timer", {}) + if timer.get("since") is not None: + focus_question(active_practice, questions[new_index].id, time.monotonic()) + elif timer: + timer["question_id"] = questions[new_index].id + st.rerun() + + if margin is not None: + with margin, st.container(key="flight_worksheet_margin"): + if learning_radar.radar_enabled(course.course_id): + st.subheader(tr("Learning Radar")) + user = current_user(st.session_state) + radar, _ = load_course_radar(st.session_state, course.course_id, user.user_id if user else None) + render_topic_radar(radar.topics.get(selected_question.topic_id)) + if st.button(tr("Explore this topic"), key=f"worksheet_radar_{session.session_id}"): + st.session_state[f"graph_pending_focus_{course.course_id}"] = selected_question.topic_id + st.switch_page("pages/4_Knowledge_Graph.py") + st.divider() + topic = next((topic for topic in course.topics if topic.id == selected_question.topic_id), None) + if topic is not None: + st.subheader(tr("Quick Notes")) + st.caption(topic.name) + st.write(display_text(topic.summary, st.session_state)) checklist(active_practice) st.button(tr("Submit answers"), type="primary", on_click=submit_practice, args=(course, practice_key)) diff --git a/services/auth_ui.py b/services/auth_ui.py index 6d15f38..7c5f6c8 100644 --- a/services/auth_ui.py +++ b/services/auth_ui.py @@ -20,8 +20,7 @@ def render_auth_page() -> None: ) st.toggle("中文界面 / Chinese interface", key=LANGUAGE_KEY) - intro, forms = st.columns([1.1, 1], gap="large") - with intro, st.container(key="flight_auth_intro"): + with st.container(key="flight_auth_intro"): st.title(tr("Make your next study session count.")) st.write(tr("Try one practice question after signing in, then follow the next step from your result.")) art_path = Path(__file__).resolve().parents[1] / "assets" / "campus-illustration.svg" @@ -29,11 +28,11 @@ def render_auth_page() -> None: st.markdown( f'', + 'style="width:100%;max-height:190px;object-fit:contain;margin-top:1rem;">', unsafe_allow_html=True, ) - with forms, st.container(border=True, key="auth_forms"): + with st.container(border=True, key="auth_forms"): st.header(tr("Welcome to ExamPilot")) st.caption(tr("Log in or create an account to start studying.")) login_tab, register_tab = st.tabs([tr("Log in"), tr("Create account")]) diff --git a/tests/test_practice_insights.py b/tests/test_practice_insights.py index e382cc6..e568c9f 100644 --- a/tests/test_practice_insights.py +++ b/tests/test_practice_insights.py @@ -134,8 +134,11 @@ def test_submission_persists_confidence_and_hint_snapshots_without_changing_grad app,course=start_app() app.radio(key='answer_s_q0').set_value(0).run() app.selectbox(key='confidence_s_q0').set_value('guessed').run() + app.button(key="worksheet_next_s").click().run() app.radio(key='answer_s_q1').set_value(1).run() app.selectbox(key='confidence_s_q1').set_value('unsure').run() + app.button(key="worksheet_previous_s").click().run() + assert app.radio(key="answer_s_q0").value == 0 assert 'Review before submit' in [h.value for h in app.subheader] next(b for b in app.button if b.label=='Submit answers').click().run() assert not app.exception From c2164f31f1980dade4d7f92e592b0b6d1e2dba03 Mon Sep 17 00:00:00 2001 From: mormal1016 Date: Sun, 15 Nov 2026 12:35:21 +0800 Subject: [PATCH 05/21] fix(i18n): preserve language across page widget cleanup --- services/accessibility.py | 4 ++-- services/auth_ui.py | 4 ++-- services/i18n.py | 13 +++++++++++++ tests/test_accessibility.py | 2 +- tests/test_auth_ui.py | 6 +++--- tests/test_i18n.py | 21 +++++++++++++++++++++ 6 files changed, 42 insertions(+), 8 deletions(-) diff --git a/services/accessibility.py b/services/accessibility.py index 90a4a96..d45f834 100644 --- a/services/accessibility.py +++ b/services/accessibility.py @@ -12,7 +12,7 @@ from collections.abc import Mapping from models.schemas import Question -from services.i18n import tr +from services.i18n import tr, render_language_control SIMPLIFY_KEY = "a11y_simplify" @@ -35,7 +35,7 @@ def render_accessibility_controls() -> None: st.subheader(tr("Accessibility")) st.toggle(tr("Simplified English"), key=SIMPLIFY_KEY) - st.toggle("中文界面 / Chinese interface", key=BILINGUAL_KEY) + render_language_control() st.caption(tr("Interface language only; uploaded material and AI-generated answers retain their original language.")) diff --git a/services/auth_ui.py b/services/auth_ui.py index 6d15f38..3e7a526 100644 --- a/services/auth_ui.py +++ b/services/auth_ui.py @@ -7,7 +7,7 @@ from services.auth_service import login_user, register_user from services.auth_session import start_authenticated_session -from services.i18n import LANGUAGE_KEY, tr +from services.i18n import LANGUAGE_KEY, tr, render_language_control from services.ui_style import apply_app_styles @@ -18,7 +18,7 @@ def render_auth_page() -> None: '
ExamPilot
', unsafe_allow_html=True, ) - st.toggle("中文界面 / Chinese interface", key=LANGUAGE_KEY) + render_language_control() intro, forms = st.columns([1.1, 1], gap="large") with intro, st.container(key="flight_auth_intro"): diff --git a/services/i18n.py b/services/i18n.py index a6af182..5067c09 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -5,6 +5,19 @@ import re LANGUAGE_KEY = "a11y_bilingual_zh" +LANGUAGE_WIDGET_KEY = "_ui_chinese_toggle" + + +def render_language_control() -> None: + """Keep the preference separate from Streamlit's page-scoped widget state.""" + st.session_state[LANGUAGE_WIDGET_KEY] = bool(st.session_state.get(LANGUAGE_KEY, False)) + + def remember_language() -> None: + st.session_state[LANGUAGE_KEY] = st.session_state[LANGUAGE_WIDGET_KEY] + + st.toggle("中文界面 / Chinese interface", key=LANGUAGE_WIDGET_KEY, + on_change=remember_language) + _TRANSLATIONS = { "Home": "首页", "Review & tools": "复习与工具", "Account": "账户", diff --git a/tests/test_accessibility.py b/tests/test_accessibility.py index a773e0f..29787c3 100644 --- a/tests/test_accessibility.py +++ b/tests/test_accessibility.py @@ -87,7 +87,7 @@ def test_accessibility_controls_have_expected_labels_and_keys() -> None: assert "Accessibility" in [element.value for element in app.subheader] assert [(item.label, item.key) for item in app.get("toggle")] == [ ("Simplified English", SIMPLIFY_KEY), - ("中文界面 / Chinese interface", BILINGUAL_KEY), + ("中文界面 / Chinese interface", "_ui_chinese_toggle"), ] diff --git a/tests/test_auth_ui.py b/tests/test_auth_ui.py index 5c5cc27..a22aec7 100644 --- a/tests/test_auth_ui.py +++ b/tests/test_auth_ui.py @@ -8,7 +8,7 @@ from streamlit.testing.v1 import AppTest from services import auth_ui -from services.i18n import LANGUAGE_KEY +from services.i18n import LANGUAGE_KEY, LANGUAGE_WIDGET_KEY from services.auth_service import AuthResult, AuthUser from tests.auth_helpers import TEST_USER, signed_in_app @@ -68,7 +68,7 @@ def test_login_language_switch_translates_interface_without_database_calls(monke monkeypatch.setattr(auth_ui, "login_user", login) monkeypatch.setattr(auth_ui, "register_user", register) app = AppTest.from_file(str(APP_PATH)).run() - next(item for item in app.get("toggle") if item.key == LANGUAGE_KEY).set_value(True).run() + next(item for item in app.get("toggle") if item.key == LANGUAGE_WIDGET_KEY).set_value(True).run() assert not app.exception assert [tab.label for tab in app.tabs] == ["登录", "创建账户"] @@ -85,7 +85,7 @@ def test_chinese_choice_continues_to_dashboard_after_login(monkeypatch) -> None: Mock(return_value=AuthResult(success=True, user=TEST_USER, message="Signed in.")), ) app = AppTest.from_file(str(APP_PATH)).run() - next(item for item in app.get("toggle") if item.key == LANGUAGE_KEY).set_value(True).run() + next(item for item in app.get("toggle") if item.key == LANGUAGE_WIDGET_KEY).set_value(True).run() app.text_input(key="login_username").set_value(TEST_USER.username) app.text_input(key="login_password").set_value(PASSWORD) next(button for button in app.button if button.label == "登录").click().run() diff --git a/tests/test_i18n.py b/tests/test_i18n.py index f2db19c..953eb22 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -58,3 +58,24 @@ def test_chinese_page_headings_without_rewriting_course( assert not app.exception assert app.title[0].value == expected_title assert app.session_state["current_course"].course_id == course.course_id + + +def test_language_survives_widget_cleanup_and_can_switch_back() -> None: + app = AppTest.from_string(""" +import streamlit as st +from services.i18n import render_language_control, tr +if st.session_state.get("show_control", True): + render_language_control() +st.title(tr("Practice")) +""").run() + app.toggle[0].set_value(True).run() + assert app.title[0].value == "练习" + app.session_state["show_control"] = False + app.run().run() + assert app.session_state[LANGUAGE_KEY] is True + assert app.title[0].value == "练习" + app.session_state["show_control"] = True + app.run() + assert app.toggle[0].value is True + app.toggle[0].set_value(False).run() + assert app.title[0].value == "Practice" From 8a84322952c90af21149b36611a3924e4d3837fe Mon Sep 17 00:00:00 2001 From: Charles Chen Date: Sat, 14 Nov 2026 23:37:55 -0500 Subject: [PATCH 06/21] Use one-click choices and hide storage details on student pages - Study Plan: exam scope uses multi-select pills (same key and values); Correct answer and Learning DNA evidence type are horizontal radios. - Review list shows Needs check / Approved / Flagged instead of internal status codes, and nothing for questions without a review decision. - Save, restore and AI messages no longer show raw database reasons, course IDs, key names or configuration details; successful automatic saves and restores are silent; failures still show. - Remove extraction character/page counts, the Progress storage note, Learning DNA excluded counts and the saved-history note; plain Anki wording; unknown suggested topics fall back to "Topic". - Chinese translations for every new or changed string. --- pages/0_Dashboard.py | 44 +----- pages/1_Study_Hub.py | 70 +++++---- pages/3_Performance.py | 8 +- pages/5_Export_Anki.py | 13 +- services/account_sync.py | 70 +++++---- services/ai_service.py | 14 +- services/i18n.py | 28 ++++ services/learning_dna_ui.py | 12 +- services/relationship_suggestions.py | 13 +- tests/test_account_sync.py | 60 +++++++- tests/test_ai_service.py | 16 +- tests/test_generation_availability.py | 4 +- tests/test_learning_continuity.py | 5 +- tests/test_learning_dna.py | 8 +- tests/test_learning_flow_ux.py | 2 +- tests/test_paper_ui_pages.py | 193 +++++++++++++++++++++++++ tests/test_pending_ui.py | 22 +-- tests/test_relationship_suggestions.py | 14 +- tests/test_study_hub_radar.py | 5 +- 19 files changed, 437 insertions(+), 164 deletions(-) create mode 100644 tests/test_paper_ui_pages.py diff --git a/pages/0_Dashboard.py b/pages/0_Dashboard.py index e7e2409..1322616 100644 --- a/pages/0_Dashboard.py +++ b/pages/0_Dashboard.py @@ -5,7 +5,7 @@ import streamlit as st from models.schemas import StudyPackage -from services.account_sync import save_course_to_account +from services.account_sync import SAVE_FAILED_MESSAGE, save_course_to_account from services.course_state import ( initialize_courses, remove_course, @@ -140,7 +140,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: ) st.caption(tr("2 · Upload materials and extract text")) - st.caption(tr("When you save the course, extracted text and source pages are stored with your account. Original files are not stored.")) + st.caption(tr("Only the extracted text is saved with your course, not the original file.")) uploaded_file = st.file_uploader( tr("Upload course materials"), type=["pdf", "pptx", "txt", "png", "jpg", "jpeg"], @@ -205,10 +205,6 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: ".png", ".jpg", ".jpeg" } - st.caption( - tr(f"Extracted text: {len(extracted_text):,} / 50,000 characters") - ) - st.caption(tr("Sources")) for source in document["sources"]: page = source["page"] @@ -227,26 +223,6 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: ) st.caption(tr(f"{source['filename']} · {location}")) - if "pages" in document: - page_label = ( - "PPTX slides" - if document_extension == ".pptx" - else ("Image" if is_image_document else "PDF pages") - ) - with st.expander( - tr(f"{page_label} ({len(document['pages'])})") - ): - for page in document["pages"]: - page_unit = ( - "Slide" - if document_extension == ".pptx" - else ("Image" if is_image_document else "Page") - ) - st.markdown( - tr(f"**{page_unit} {page['page']}** · " - f"{len(page['text']):,} characters") - ) - with st.expander(tr("Preview extracted text")): st.text(extracted_text) @@ -287,9 +263,9 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: new_course = StudyPackage.model_validate( generated["package"] ) - except ValueError as error: + except ValueError: st.error( - tr(f"Could not load generated topics: {error}") + tr("Couldn't use the generated topics. Try generating them again.") ) else: # Retain the material for later question generation. @@ -304,11 +280,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: st.session_state, new_course ) if sync_outcome is not None and not sync_outcome.success: - st.warning( - tr("Course kept in this session but not saved to " - f"your account: {sync_outcome.message} " - "Use Save in Study Plan to retry.") - ) + st.warning(tr(SAVE_FAILED_MESSAGE)) st.success( tr("Topics generated. Review them in Study Hub, " @@ -319,11 +291,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage: if not ai_available: - st.info( - tr("AI topic generation is not available on this server " - "because ANTHROPIC_API_KEY is not configured. The built-in " - "demo courses still work.") - ) + st.info(tr("AI generation is unavailable right now.")) elif not course_name: st.info(tr("Enter a course name to enable topic generation.")) else: diff --git a/pages/1_Study_Hub.py b/pages/1_Study_Hub.py index 4b70ed9..6ee662b 100644 --- a/pages/1_Study_Hub.py +++ b/pages/1_Study_Hub.py @@ -5,6 +5,7 @@ from models.schemas import StudyPackage from services import learning_radar from services.account_sync import ( + SAVE_FAILED_MESSAGE, render_save_restore_controls, save_course_to_account, ) @@ -96,8 +97,6 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: ) if radar.has_sample: st.caption(tr("Includes sample data")) - if not radar.live: - st.caption(tr("Live flags are unavailable right now.")) if not course.topics: @@ -112,7 +111,8 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: with st.container(border=True, key="study_scope_panel"): st.subheader(tr("Choose your exam scope")) - selected_topic_ids = st.multiselect( + # One click per topic; the value stays a list of topic IDs. + selected_topic_ids = st.pills( tr("Knowledge points"), options=[topic.id for topic in course.topics], format_func=lambda topic_id: next( @@ -120,6 +120,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: for topic in course.topics if topic.id == topic_id ), + selection_mode="multi", key=scope_key, ) st.caption( @@ -133,7 +134,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: if not selected_topic_ids: st.error(tr("Select at least one topic.")) elif len(selected_topic_ids) != len(set(selected_topic_ids)): - st.error(tr("Duplicate topic IDs are not allowed.")) + st.error(tr("Each topic can be selected only once.")) elif not set(selected_topic_ids).issubset(valid_topic_ids): st.error(tr("The selection contains an invalid topic.")) else: @@ -179,10 +180,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: ai_available = generation_available() if not ai_available: - st.info( - tr("AI question generation is not available on this server " - "because ANTHROPIC_API_KEY is not configured.") - ) + st.info(tr("AI generation is unavailable right now.")) if st.button( tr("Generate questions"), @@ -211,9 +209,9 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: updated_course = StudyPackage.model_validate( generated["package"] ) - except ValueError as error: + except ValueError: st.error( - tr(f"Could not load generated questions: {error}") + tr("Couldn't use the generated questions. Try generating them again.") ) else: st.session_state[ @@ -224,11 +222,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: st.session_state, updated_course ) if sync_outcome is not None and not sync_outcome.success: - st.warning( - tr("Questions kept in this session but not saved " - f"to your account: {sync_outcome.message} " - "Use Save below to retry.") - ) + st.warning(tr(SAVE_FAILED_MESSAGE)) # Previous practice used the old question set. st.session_state.pop( @@ -243,7 +237,8 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: ) st.caption( - tr(f"Available questions in confirmed scope: {available_count}") + tr(f"{available_count} question ready" if available_count == 1 + else f"{available_count} questions ready") ) if available_count: @@ -273,7 +268,10 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: pending_count = sum(status_for(course, q.id) == "pending" for q in course.questions) if pending_count: - st.caption(f"{pending_count} questions await review before they can be practised.") + st.caption(tr( + f"{pending_count} new question needs your check" if pending_count == 1 + else f"{pending_count} new questions need your check" + )) if st.button(tr("Review pending questions"), key=f"open_question_review_{course.course_id}"): st.session_state[f"question_review_open_{course.course_id}"] = True with st.expander(tr("Course tools"), expanded=st.session_state.get(f"question_review_open_{course.course_id}", False)): @@ -282,29 +280,41 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: editable = sorted([q for q in course.questions if status_for(course, q.id) != "superseded"], key=lambda q: status_for(course, q.id) != "pending") if editable: by_id = {q.id: q for q in editable} + # Plain review labels; questions with no review decision get none. + status_labels = {"pending": "Needs check", "approved": "Approved", "flagged": "Flagged"} + + def review_label(qid): + text = by_id[qid].question[:100] + status = status_labels.get(status_for(course, qid)) + return f"{tr(status)} · {text}" if status else text + question_id = st.selectbox( tr("Question to review"), list(by_id), - format_func=lambda qid: f"[{status_for(course, qid)}] {by_id[qid].question[:100]}", + format_func=review_label, key=f"editor_question_{course.course_id}", ) original = by_id[question_id] - st.caption(tr("Approve only after checking the answer and explanation. Editing creates a new version; past results stay unchanged. Legacy means no review decision was recorded.")) + st.caption(tr("Check the answer and explanation before approving; edits never change past results.")) with st.form(f"question_review_{course.course_id}_{question_id}"): prompt = st.text_area(tr("Question text"), value=original.question) options = [st.text_input(f"Option {chr(65 + index)}", value=value) for index, value in enumerate(original.options)] - correct = st.selectbox(tr("Correct answer"), list(range(4)), index=original.correct_index, format_func=lambda i: chr(65+i)) + correct = st.radio(tr("Correct answer"), list(range(4)), index=original.correct_index, format_func=lambda i: chr(65+i), horizontal=True) explanation = st.text_area(tr("Explanation"), value=original.explanation) with st.expander(tr("Question classification (advanced)")): - dimensions = [None, "computation", "conceptual"] - dimension = st.selectbox( + # "untagged" stands in for None so every radio option is a real value. + dimension_labels = { + "untagged": "Untagged", "computation": "Computation", + "conceptual": "Conceptual understanding", + } + dimensions = list(dimension_labels) + dimension_choice = st.radio( tr("Learning DNA evidence type"), dimensions, - index=dimensions.index(original.cognitive_dimension), - format_func=lambda value: { - None: "Untagged", "computation": "Computation", - "conceptual": "Conceptual understanding", - }[value], - help="Choose what this question tests. Leave uncertain or mixed questions untagged; this label is not a student ability score.", + index=dimensions.index(original.cognitive_dimension or "untagged"), + format_func=lambda value: tr(dimension_labels[value]), + horizontal=True, + help=tr("Choose what this question tests. Leave uncertain or mixed questions untagged; this label is not a student ability score."), ) + dimension = None if dimension_choice == "untagged" else dimension_choice structure = st.text_input( tr("Practice structure label"), value=original.practice_structure or "", max_chars=80, help="A task type such as tangent_equation or derivative_at_point. Use the same label for the same task structure; leave uncertain questions blank.", @@ -321,7 +331,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: save_course(st.session_state, revised) outcome = save_course_to_account(st.session_state, revised) if outcome is not None and not outcome.success: - st.warning(tr("Review kept locally but not saved to your account. Use Save to retry. ") + tr(outcome.message)) + st.warning(tr(SAVE_FAILED_MESSAGE)) else: st.session_state[f"question_review_notice_{course.course_id}"] = "Question review saved." st.rerun() @@ -355,7 +365,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: staged.pop(f"course_document_{course.course_id}", None) outcome = save_course_to_account(staged, updated) if outcome is not None and not outcome.success: - st.error(tr("Material was not deleted from your account. ") + tr(outcome.message)) + st.error(tr("Couldn't delete the material from your account. Nothing was changed.")) else: save_course(st.session_state, updated) st.session_state.pop(f"course_document_{course.course_id}", None) diff --git a/pages/3_Performance.py b/pages/3_Performance.py index 5511ff4..2a4eb3e 100644 --- a/pages/3_Performance.py +++ b/pages/3_Performance.py @@ -51,8 +51,8 @@ sessions=sessions, questions=list(questions_by_id.values()), ) -except ValueError as error: - st.error(tr(f"Could not calculate performance: {error}")) +except ValueError: + st.error(tr("Couldn't calculate your progress from this practice history.")) st.stop() mode_label = st.radio( @@ -189,10 +189,6 @@ "in the selected mode. " "Below 60%: Weak · 60–79.99%: Developing · 80% or above: Mastered." ) ) - st.caption( - tr("Signed-in users' saved practice records can be restored across sessions. " - "Unsaved records remain in the current session only.") - ) if st.button(tr("Start practice"), type="primary"): from services.learning_flow import stage_practice stage_practice(st.session_state, course) diff --git a/pages/5_Export_Anki.py b/pages/5_Export_Anki.py index 0bebef3..b14d30b 100644 --- a/pages/5_Export_Anki.py +++ b/pages/5_Export_Anki.py @@ -26,13 +26,10 @@ def _topic_tag(topic_id: str) -> str: apply_app_styles() st.title(tr("Export to Anki")) -st.caption( - tr("Review course knowledge cards here or download a UTF-8 TSV file " - "for Anki text import.") -) +st.caption(tr("Review course knowledge cards here or download them for Anki.")) with st.expander(tr("Import instructions and limitations")): - st.write(tr("Download the TSV, then use Anki Desktop → File → Import and map Front, Back and Tags. AnkiWeb sync is not supported; Anki Desktop import has not been verified.")) + st.write(tr("Download the file, then in Anki on your computer choose File → Import and match Front, Back and Tags. Cards are not sent to AnkiWeb automatically.")) course = st.session_state.get("current_course") @@ -87,8 +84,8 @@ def _topic_tag(topic_id: str) -> str: sessions=sessions, questions=list(questions_by_id.values()), ) - except ValueError as error: - st.error(tr(f"Could not calculate mastery: {error}")) + except ValueError: + st.error(tr("Couldn't find your weak topics from this practice history.")) st.stop() topic_ids = get_weak_topic_ids(stats, mode) @@ -116,7 +113,7 @@ def _topic_tag(topic_id: str) -> str: summary_column, download_column = st.columns([1.4, 1], vertical_alignment="center") with summary_column: st.markdown(tr("**Your review deck**")) - st.caption(tr(f"{len(cards)} cards · {export_scope} · UTF-8 TSV")) + st.caption(tr(f"{len(cards)} cards · {export_scope}")) with download_column: st.download_button( tr("Download Anki TSV"), diff --git a/services/account_sync.py b/services/account_sync.py index d9f0936..a21f6c6 100644 --- a/services/account_sync.py +++ b/services/account_sync.py @@ -17,10 +17,20 @@ from services.auth_session import current_user from services.exam_engine import grade_exam from services.learning_state import capture_learning_state, restored_learning_state -from services.ui_adapters import PENDING_INTEGRATION_MESSAGES STATE_KEY = "account_sync" +# Student-facing texts. Raw database reasons stay in SyncOutcome.message for +# diagnostics and are never shown on the page. +SAVE_FAILED_MESSAGE = ( + "Couldn't save to your account. Your work is kept on this device for now." +) +RESTORE_FAILED_MESSAGE = ( + "Couldn't restore from your account. Your work on this device is unchanged." +) +NOTHING_SAVED_MESSAGE = "Nothing saved for this course yet." +_COURSE_NOT_FOUND = "Course was not found." + @dataclass(frozen=True) class SyncOutcome: @@ -149,19 +159,17 @@ def _restore_one( state: dict, user_id: str, course_id: str, - label: str, ) -> str | None: - """Restore one course; return an error text, or None on success.""" + """Restore one course; return the internal failure reason, or None on success.""" restored = postgres_store.load_course_history(user_id, course_id) if not restored.success or restored.package is None: state.setdefault("failed_course_ids", set()).add(course_id) - reason = restored.message if not restored.success else "Course was not found." - return f"{label}: {reason}" + return restored.message if not restored.success else _COURSE_NOT_FOUND try: _apply_restored_course(session_state, state, restored) except (KeyError, ValueError): state.setdefault("failed_course_ids", set()).add(course_id) - return f"{label}: Stored exam data could not be matched to its questions." + return "Stored exam data could not be matched to its questions." state.setdefault("failed_course_ids", set()).discard(course_id) return None @@ -190,13 +198,11 @@ def restore_all(session_state: MutableMapping[str, Any]) -> SyncOutcome | None: errors = [] restored_count = 0 for summary in listing.courses: - error = _restore_one( - session_state, state, user_id, summary.course_id, summary.course_name - ) + error = _restore_one(session_state, state, user_id, summary.course_id) if error is None: restored_count += 1 else: - errors.append(error) + errors.append(f"{summary.course_name}: {error}") state["restore_errors"] = errors state["restore_message"] = ( @@ -321,9 +327,11 @@ def restore_course( if user_id is None: return None state = _state(session_state, user_id) - error = _restore_one(session_state, state, user_id, course_id, course_id) + error = _restore_one(session_state, state, user_id, course_id) + if error == _COURSE_NOT_FOUND: + return SyncOutcome(False, NOTHING_SAVED_MESSAGE) if error is not None: - return SyncOutcome(False, error) + return SyncOutcome(False, RESTORE_FAILED_MESSAGE) return SyncOutcome(True, "Course and practice history restored.") @@ -335,22 +343,20 @@ def render_sidebar_status() -> None: return state = _state(session_state, user_id) + # A successful restore needs no message; only failures are shown. if state["restore_errors"]: - st.warning(tr("Some saved records could not be restored. Your current work is unchanged.") - + "\n\n" + "\n".join(f"- {tr(e)}" for e in state["restore_errors"])) + st.warning(tr("Some saved records could not be restored. Your current work is unchanged.")) if st.button(tr("Retry restore"), key="retry_restore", use_container_width=True): with st.spinner(tr("Restoring your saved study records…")): restore_all(session_state) st.rerun() - elif state["restore_message"]: - st.caption(tr(state["restore_message"])) if state.get("restore_conflicts"): - st.warning(tr("Database history is used for statistics. Conflicting local practice records are kept separately in this login session and are not counted or automatically uploaded. Do not log out before resolving them.")) + st.warning(tr("Some practice on this device differs from your saved records and is not counted. Logging out will remove it.")) unsaved = len(state["unsaved_courses"]) + len(state["unsaved_exams"]) if unsaved: - st.warning(tr(f"{unsaved} item(s) are not saved to your account yet. Use Save in Study Plan to retry.")) + st.warning(tr(f"{unsaved} item(s) not saved yet. Use Save in Study Plan to retry.")) def render_save_restore_controls(course: StudyPackage) -> None: @@ -358,7 +364,7 @@ def render_save_restore_controls(course: StudyPackage) -> None: session_state = st.session_state user_id = _user_id(session_state) if user_id is None: - st.caption(tr(PENDING_INTEGRATION_MESSAGES["database"])) + st.caption(tr("Log in to back up this course.")) for column, label, kind in zip(st.columns(2), ("Save", "Restore"), ("save", "restore")): column.button( tr(label), key=f"database_{kind}_{course.course_id}", @@ -368,7 +374,7 @@ def render_save_restore_controls(course: StudyPackage) -> None: state = _state(session_state, user_id) message_key = course.course_id - st.caption(tr("Saves this course and its graded practice to your account. Anonymous records from before login are not migrated.")) + st.caption(tr("Back up this course to your account.")) save_column, restore_column = st.columns(2) save_clicked = save_column.button( tr("Save"), key=f"database_save_{course.course_id}", use_container_width=True, @@ -381,7 +387,11 @@ def render_save_restore_controls(course: StudyPackage) -> None: if save_clicked: with st.spinner(tr("Saving…")): outcome = save_course_with_history(session_state, course) - state["course_messages"][message_key] = outcome + # Show a fixed text; the raw reason from the database stays internal. + state["course_messages"][message_key] = SyncOutcome( + outcome.success, + "Saved to your account." if outcome.success else SAVE_FAILED_MESSAGE, + ) elif restore_clicked: with st.spinner(tr("Restoring…")): outcome = restore_course(session_state, course.course_id) @@ -390,8 +400,14 @@ def render_save_restore_controls(course: StudyPackage) -> None: st.rerun() outcome = state["course_messages"].get(message_key) - if outcome is not None: - (st.success if outcome.success else st.error)(tr(outcome.message)) + if outcome is None: + return + if outcome.success: + st.success(tr(outcome.message)) + elif outcome.message == NOTHING_SAVED_MESSAGE: + st.info(tr(outcome.message)) + else: + st.error(tr(outcome.message)) def render_last_save_status() -> None: @@ -400,9 +416,7 @@ def render_last_save_status() -> None: if user_id is None: return outcome = _state(st.session_state, user_id)["last_save"] - if outcome is None: + # A successful save needs no message on the page. + if outcome is None or outcome.success: return - if outcome.success: - st.caption(tr("Saved to your account.")) - else: - st.warning(tr(f"Not saved to your account: {outcome.message} Your local work is kept; use Save in Study Plan to retry.")) + st.warning(tr(SAVE_FAILED_MESSAGE)) diff --git a/services/ai_service.py b/services/ai_service.py index 19da039..a9cd481 100644 --- a/services/ai_service.py +++ b/services/ai_service.py @@ -42,7 +42,9 @@ TUTOR_TIMEOUT_SECONDS = 60.0 CONNECTION_CHECK_PROMPT = "Reply with only: ExamPilot API OK" -MISSING_API_KEY_MESSAGE = "ANTHROPIC_API_KEY is not configured." +# Shown to students: no key names or configuration details. +AI_UNAVAILABLE_MESSAGE = "AI generation is unavailable right now." +MISSING_API_KEY_MESSAGE = AI_UNAVAILABLE_MESSAGE INVALID_DOCUMENT_MESSAGE = "The course material is invalid. Upload and extract it again." TOO_LONG_MESSAGE = "The course material exceeds 50,000 characters and cannot be analysed." @@ -114,17 +116,17 @@ def _api_error_result(exc: anthropic.APIStatusError) -> dict: """Describe an API error to the user without exposing the raw exception.""" status = exc.status_code if isinstance(exc, anthropic.AuthenticationError): - message = "The Claude API key was rejected. Check ANTHROPIC_API_KEY." + message = AI_UNAVAILABLE_MESSAGE elif isinstance(exc, anthropic.PermissionDeniedError): - message = "This Claude API key is not allowed to use the configured model." + message = AI_UNAVAILABLE_MESSAGE elif isinstance(exc, anthropic.NotFoundError): - message = "The configured Claude model is not available to this account. Check ANTHROPIC_MODEL." + message = AI_UNAVAILABLE_MESSAGE elif isinstance(exc, anthropic.RateLimitError): message = "Claude quota or rate limit reached. Try again later." elif isinstance(status, int) and status >= 500: message = "Claude is temporarily unavailable. Try again later." else: - message = "The Claude API request failed. Check the configuration or try again later." + message = "AI generation is unavailable right now. Try again later." return _failure("API_ERROR", message, status_code=status) @@ -135,7 +137,7 @@ def _request_failure(exc: Exception, activity: str) -> dict: elif isinstance(exc, anthropic.APIConnectionError): message = f"Could not reach Claude while {activity}. Check the network and try again." else: - message = f"An error occurred while {activity}. Check the configuration or try again later." + message = f"An error occurred while {activity}. Try again later." return _failure("GENERATION_ERROR", message) diff --git a/services/i18n.py b/services/i18n.py index a6af182..a009aef 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -317,6 +317,28 @@ "See computation and conceptual understanding separately, with the answers behind each pattern.": "分别查看计算与概念理解,以及各项判断依据的答案。", "These are question-based observations, not a validated cognitive diagnosis. Multiple-choice answers do not demonstrate that you can explain an idea in your own words.": "这些是基于题目的观察,并非经过验证的认知诊断;选择题无法证明你能用自己的话解释概念。", "Answer more different questions in both dimensions before comparing them.": "在两个维度上多做不同题目,再进行比较。", + # paper UI: pages + "Couldn't save to your account. Your work is kept on this device for now.": "未能保存到账户,你的内容暂时保留在此设备上。", + "Couldn't restore from your account. Your work on this device is unchanged.": "未能从账户恢复,此设备上的内容没有改变。", + "Nothing saved for this course yet.": "此课程还没有保存的内容。", + "Some practice on this device differs from your saved records and is not counted. Logging out will remove it.": "此设备上有部分练习与已保存记录不一致,暂不计入统计;退出登录后将被删除。", + "Log in to back up this course.": "登录后可备份此课程。", + "Back up this course to your account.": "将此课程备份到你的账户。", + "Only the extracted text is saved with your course, not the original file.": "课程只保存提取的文字,不保存原始文件。", + "Couldn't use the generated topics. Try generating them again.": "无法使用生成的知识点,请重新生成。", + "Couldn't use the generated questions. Try generating them again.": "无法使用生成的题目,请重新生成。", + "AI generation is unavailable right now.": "AI 生成功能暂时不可用。", + "AI generation is unavailable right now. Try again later.": "AI 生成功能暂时不可用,请稍后重试。", + "Each topic can be selected only once.": "每个知识点只能选择一次。", + "Needs check": "待检查", "Approved": "已批准", "Flagged": "已标记", + "Check the answer and explanation before approving; edits never change past results.": "批准前请检查答案与解析;编辑不会改变以往成绩。", + "Couldn't delete the material from your account. Nothing was changed.": "未能从账户删除资料,内容没有任何改变。", + "Review course knowledge cards here or download them for Anki.": "在此查看课程知识卡片,或下载后导入 Anki。", + "Download the file, then in Anki on your computer choose File → Import and match Front, Back and Tags. Cards are not sent to AnkiWeb automatically.": "下载文件后,在电脑上的 Anki 中选择 文件 → 导入,并将字段对应到 Front、Back 和 Tags。卡片不会自动同步到 AnkiWeb。", + "Uses your latest answer to each question. Fewer than 3 different questions shows as insufficient evidence.": "按每道题的最近一次回答计算;不同题目少于 3 道时显示为证据不足。", + "Learning DNA couldn't read this practice history.": "学习画像无法读取这段练习历史。", + "Couldn't calculate your progress from this practice history.": "无法根据这段练习历史计算学习进度。", + "Couldn't find your weak topics from this practice history.": "无法根据这段练习历史找出薄弱知识点。", } _TRANSLATIONS.update( @@ -460,6 +482,12 @@ (r"^(\d+) correct answer\(s\) were marked Guessed\. Revisit them before treating them as secure knowledge\.$", r"有 \1 道答对的题被标记为猜测;请复习后再认为自己已掌握。"), (r"^(\d+) answer\(s\) used in-app hints\.$", r"\1 道题使用了应用内提示。"), (r"^Hint use was not recorded for (\d+) answer\(s\)\.$", r"\1 道题没有记录提示使用情况。"), + # paper UI: pages + (r"^(\d+) item\(s\) not saved yet\. Use Save in Study Plan to retry\.$", r"还有 \1 项未保存;请在学习计划中点击保存重试。"), + (r"^(\d+) questions? ready$", r"\1 道题可以练习"), + (r"^(\d+) new questions? needs? your check$", r"有 \1 道新题需要你检查"), + (r"^(\d+) cards · (.*)$", r"\1 张卡片 · \2"), + (r"^An error occurred while .+\. Try again later\.$", r"处理请求时出错,请稍后重试。"), ] diff --git a/services/learning_dna_ui.py b/services/learning_dna_ui.py index 0690768..3143f5f 100644 --- a/services/learning_dna_ui.py +++ b/services/learning_dna_ui.py @@ -12,14 +12,12 @@ def render_learning_dna(course, attempts, sessions, questions, mode): with st.expander(tr("How to read this profile")): st.caption(tr("These are question-based observations, not a validated cognitive diagnosis. Multiple-choice answers do not demonstrate that you can explain an idea in your own words.")) try: - profile, excluded = evidence_profile(attempts, sessions, questions, mode) - except ValueError as error: - st.warning(tr(f"Learning DNA could not read this history: {error}")) + profile, _excluded = evidence_profile(attempts, sessions, questions, mode) + except ValueError: + st.warning(tr("Learning DNA couldn't read this practice history.")) return - st.caption(tr("Each question family counts once, using its latest response in this mode. Fewer than 3 different questions means insufficient evidence. Untagged and unanswered responses are excluded.")) + st.caption(tr("Uses your latest answer to each question. Fewer than 3 different questions shows as insufficient evidence.")) by_key = {(p.topic_id, p.dimension): p for p in profile} - if excluded: - st.caption(tr(f"{excluded} latest question-family response(s) excluded because they are untagged or unanswered.")) for topic in course.topics: with st.container(border=True, key=f"learning_dna_{topic.id}"): st.markdown(f"**{topic.name}**") @@ -44,5 +42,3 @@ def render_learning_dna(course, attempts, sessions, questions, mode): if evidence: with st.expander(tr("View evidence") + f": {topic.name}"): st.dataframe(evidence, hide_index=True, width="stretch") - with st.expander(tr("Question labels and saved history")): - st.caption(tr("Tag a question's evidence type under Study Plan → Course tools → Review and edit questions. Saved questions and graded history restore with your course; editing a tag creates a new question version and preserves earlier evidence.")) diff --git a/services/relationship_suggestions.py b/services/relationship_suggestions.py index 63c66c4..6b89d44 100644 --- a/services/relationship_suggestions.py +++ b/services/relationship_suggestions.py @@ -6,6 +6,7 @@ """ from models.schemas import StudyPackage +from services.i18n import tr def suggestions_key(course_id: str) -> str: @@ -17,13 +18,17 @@ def notice_key(course_id: str) -> str: def describe_suggestions(course: StudyPackage, suggestions: list[dict]) -> list[str]: - """Return one human-readable label per suggestion, using topic names.""" + """Return one human-readable label per suggestion, using topic names. + + An unknown topic shows as the plain word "Topic", never its internal ID. + """ names = {topic.id: topic.name for topic in course.topics} + fallback = tr("Topic") labels = [] for suggestion in suggestions: - source = suggestion.get("from_topic", "?") - target = suggestion.get("to_topic", "?") - labels.append(f"{names.get(source, source)} ↔ {names.get(target, target)}") + source = names.get(suggestion.get("from_topic"), fallback) + target = names.get(suggestion.get("to_topic"), fallback) + labels.append(f"{source} ↔ {target}") return labels diff --git a/tests/test_account_sync.py b/tests/test_account_sync.py index 5748bde..77af019 100644 --- a/tests/test_account_sync.py +++ b/tests/test_account_sync.py @@ -367,7 +367,16 @@ def test_single_course_restore_failure_does_not_claim_success(store): seed(store, TEST_USER, course) store.fail_course_ids.add("course-1") outcome = account_sync.restore_course(signed_in_state(), "course-1") - assert not outcome.success and "load failed" in outcome.message + assert not outcome.success + assert outcome.message == account_sync.RESTORE_FAILED_MESSAGE + assert "load failed" not in outcome.message + + +def test_restoring_a_course_with_nothing_saved_hides_its_id(store): + outcome = account_sync.restore_course(signed_in_state(), "course-1") + assert not outcome.success + assert outcome.message == "Nothing saved for this course yet." + assert "course-1" not in outcome.message def test_app_restores_once_per_login_despite_reruns(store): @@ -393,12 +402,17 @@ def test_failed_login_restore_shows_retry_and_keeps_local_state(store): app.run() assert [w.value for w in app.warning if "could not be restored" in w.value] + assert not [w for w in app.warning if "list failed" in w.value] assert len(store.names("list")) == 1 store.fail.clear() app.button(key="retry_restore").click().run() assert not app.exception + assert app.session_state["account_sync"]["restore_errors"] == [] + # A successful retry shows nothing in that spot. AppTest keeps the element + # from before st.rerun() when nothing replaces it, so render once more. + app.run() assert not [w for w in app.warning if "could not be restored" in w.value] assert "s1" in app.session_state["practice_history_course-1"] @@ -449,7 +463,9 @@ def test_practice_submit_saves_course_then_exam_for_signed_in_user(store): ) saved_attempts = store.exams[TEST_USER.user_id]["session-1"][2] assert [a.selected_index for a in saved_attempts] == [1] - assert not [w for w in app.warning if "Not saved" in w.value] + assert not [w for w in app.warning if "Couldn't save" in w.value] + # A successful save is not announced on the result page. + assert not [c for c in app.caption if c.value == "Saved to your account."] def test_practice_submit_failure_warns_and_keeps_local_history(store): @@ -467,7 +483,8 @@ def test_practice_submit_failure_warns_and_keeps_local_history(store): assert not app.exception assert "session-1" in app.session_state["practice_history_course-1"] - assert [w for w in app.warning if "Not saved to your account" in w.value] + assert [w.value for w in app.warning] == [account_sync.SAVE_FAILED_MESSAGE] + assert not [w for w in app.warning if "exam save failed" in w.value] assert not [c for c in app.caption if c.value == "Saved to your account."] @@ -485,14 +502,12 @@ def test_study_hub_save_button_reports_success_and_failure(store): app.button(key="database_save_course-1").click().run() assert not app.exception - assert [s.value for s in app.success] == [ - "Course and practice history saved to your account." - ] + assert [s.value for s in app.success] == ["Saved to your account."] assert course.course_id in store.courses[TEST_USER.user_id] store.fail.add("save_course") app.button(key="database_save_course-1").click().run() - assert [e.value for e in app.error] == ["course save failed"] + assert [e.value for e in app.error] == [account_sync.SAVE_FAILED_MESSAGE] assert not app.success @@ -509,10 +524,39 @@ def test_study_hub_restore_button_replaces_course_and_reports_failure(store): store.fail_course_ids.add("course-1") app.button(key="database_restore_course-1").click().run() - assert [e.value for e in app.error] == ["course-1: load failed"] + assert [e.value for e in app.error] == [account_sync.RESTORE_FAILED_MESSAGE] assert app.session_state["current_course"].course_name == "Saved Name" +def test_study_hub_restore_of_unsaved_course_says_nothing_is_saved(store): + app = study_hub_app(make_course("course-1", "Local Name")) + app.run() + + app.button(key="database_restore_course-1").click().run() + + assert not app.exception + assert [i.value for i in app.info if "Nothing saved" in i.value] == [ + "Nothing saved for this course yet." + ] + assert not app.error + assert not any( + "course-1" in element.value + for element in [*app.info, *app.error, *app.caption] + ) + + +def test_successful_login_restore_shows_no_status_message(store): + course = make_course() + seed(store, TEST_USER, course, make_exam(course, "s1")) + app = signed_in_app(APP_PATH) + app.run() + + assert not app.exception + texts = [item.value for item in [*app.caption, *app.warning, *app.success]] + assert not any("Restored" in text or "restored" in text for text in texts) + assert not any("No saved study records" in text for text in texts) + + def test_regenerated_questions_keep_saved_history_restorable(store): old = make_course("course-1", "Economics") state = signed_in_state() diff --git a/tests/test_ai_service.py b/tests/test_ai_service.py index bfe6990..0801d73 100644 --- a/tests/test_ai_service.py +++ b/tests/test_ai_service.py @@ -164,6 +164,7 @@ def make_relationships(edges=None): def api_error(status_code, message): classes = { + 400: anthropic.BadRequestError, 401: anthropic.AuthenticationError, 403: anthropic.PermissionDeniedError, 404: anthropic.NotFoundError, @@ -581,15 +582,16 @@ def test_generate_topics_missing_api_key_does_not_create_client(monkeypatch): assert result["ok"] is False assert result["error_code"] == "MISSING_API_KEY" - assert result["message"] == "ANTHROPIC_API_KEY is not configured." + assert result["message"] == "AI generation is unavailable right now." @pytest.mark.parametrize( ("status_code", "expected_message"), [ - (401, "API key was rejected"), - (403, "not allowed to use"), - (404, "not available to this account"), + (401, "AI generation is unavailable right now."), + (403, "AI generation is unavailable right now."), + (404, "AI generation is unavailable right now."), + (400, "AI generation is unavailable right now. Try again later."), (429, "quota or rate limit"), (500, "temporarily unavailable"), (503, "temporarily unavailable"), @@ -609,6 +611,8 @@ def test_generate_topics_explains_api_errors_without_leaking( assert result["error_code"] == "API_ERROR" assert result["status_code"] == status_code assert expected_message in result["message"] + assert "ANTHROPIC" not in result["message"] + assert "configur" not in result["message"] assert FAKE_API_KEY not in str(result) assert private_message not in str(result) @@ -1152,7 +1156,7 @@ def test_ask_tutor_rejects_missing_api_key_without_creating_client(monkeypatch): assert result == { "ok": False, "error_code": "MISSING_API_KEY", - "message": "ANTHROPIC_API_KEY is not configured.", + "message": "AI generation is unavailable right now.", } @@ -1263,6 +1267,8 @@ def test_ask_tutor_handles_api_errors_without_exposing_details( assert result["error_code"] == "API_ERROR" assert result["status_code"] == status_code assert expected_message in result["message"] + assert "ANTHROPIC" not in result["message"] + assert "configur" not in result["message"] assert FAKE_API_KEY not in str(result) assert private_message not in str(result) assert "Private question text." not in str(result) diff --git a/tests/test_generation_availability.py b/tests/test_generation_availability.py index 2bcf299..6d43ac4 100644 --- a/tests/test_generation_availability.py +++ b/tests/test_generation_availability.py @@ -9,7 +9,7 @@ ROOT = Path(__file__).resolve().parents[1] DASHBOARD_PATH = ROOT / "pages" / "0_Dashboard.py" STUDY_PLAN_PATH = ROOT / "pages" / "1_Study_Hub.py" -UNAVAILABLE_TEXT = "ANTHROPIC_API_KEY is not configured" +UNAVAILABLE_TEXT = "AI generation is unavailable right now." def dashboard_with_extracted_text(monkeypatch) -> AppTest: @@ -51,6 +51,7 @@ def test_dashboard_disables_topic_generation_without_api_key(monkeypatch): assert generate_topics_button(app).disabled assert any(UNAVAILABLE_TEXT in item.value for item in app.info) + assert not any("ANTHROPIC_API_KEY" in item.value for item in app.info) def test_dashboard_enables_topic_generation_with_api_key(monkeypatch): @@ -70,6 +71,7 @@ def test_study_plan_disables_question_generation_without_api_key(monkeypatch): assert not app.exception assert app.button(key="generate_questions_course-1").disabled assert any(UNAVAILABLE_TEXT in item.value for item in app.info) + assert not any("ANTHROPIC_API_KEY" in item.value for item in app.info) def test_study_plan_enables_question_generation_with_api_key(monkeypatch): diff --git a/tests/test_learning_continuity.py b/tests/test_learning_continuity.py index 2b5d521..49a0804 100644 --- a/tests/test_learning_continuity.py +++ b/tests/test_learning_continuity.py @@ -165,9 +165,10 @@ def test_first_study_page_entry_hydrates_saved_scope_over_stale_widget_default() app.session_state[f"scope_selection_{course.course_id}"] = [] app.run() assert not app.exception - assert app.multiselect[0].value == ["t1"] + scope = app.button_group(key=f"scope_selection_{course.course_id}") + assert scope.value == ["t1"] assert app.session_state[f"confirmed_scope_{course.course_id}"] == ["t1"] - app.multiselect[0].set_value([]).run() + scope.set_value([]).run() assert f"confirmed_scope_{course.course_id}" not in app.session_state diff --git a/tests/test_learning_dna.py b/tests/test_learning_dna.py index 86c283c..41beb23 100644 --- a/tests/test_learning_dna.py +++ b/tests/test_learning_dna.py @@ -142,8 +142,10 @@ def test_review_ui_can_tag_an_untagged_question_without_rewriting_history(): app.session_state['current_course']=course app.run() assert not app.exception - dimension=next(s for s in app.selectbox if s.label=='Learning DNA evidence type') - assert dimension.value is None + dimension=next(s for s in app.radio if s.label=='Learning DNA evidence type') + assert dimension.horizontal + assert dimension.options==['Untagged','Computation','Conceptual understanding'] + assert dimension.value=='untagged' dimension.set_value('conceptual') next(b for b in app.button if b.label=='Save review').click().run() assert not app.exception @@ -189,7 +191,7 @@ def test_progress_for_old_untagged_history_does_not_infer_abilities(): app.session_state['performance_mode_test-dna']='Topic Practice' app.run() assert not app.exception - assert '6 latest question-family response(s) excluded' in ' '.join(c.value for c in app.caption) + assert 'excluded' not in ' '.join(c.value for c in app.caption) assert not any("Dimension" in frame.value.columns for frame in app.dataframe) assert next(m for m in app.metric if m.label=='Computation').value=='—' diff --git a/tests/test_learning_flow_ux.py b/tests/test_learning_flow_ux.py index 2b343d3..7f80a2c 100644 --- a/tests/test_learning_flow_ux.py +++ b/tests/test_learning_flow_ux.py @@ -99,7 +99,7 @@ def test_review_form_is_collapsed_until_requested(): assert not app.exception panel=next(e for e in app.expander if e.label=='Review and edit questions') assert not panel.proto.expanded - assert len(app.multiselect)==1 + assert app.button_group(key='scope_selection_calculus-i-demo') and not app.multiselect assert not app.checkbox app.button(key='open_question_review_calculus-i-demo').click().run() assert not app.exception diff --git a/tests/test_paper_ui_pages.py b/tests/test_paper_ui_pages.py new file mode 100644 index 0000000..c9bfa16 --- /dev/null +++ b/tests/test_paper_ui_pages.py @@ -0,0 +1,193 @@ +"""Student-facing pages use one-click choices and hide storage bookkeeping.""" + +from pathlib import Path +from types import SimpleNamespace + +import streamlit as st +from streamlit.testing.v1 import AppTest + +from models.schemas import Question, StudyPackage +from services.i18n import LANGUAGE_KEY + +ROOT = Path(__file__).resolve().parents[1] +STUDY_PLAN_PATH = ROOT / "pages" / "1_Study_Hub.py" +DASHBOARD_PATH = ROOT / "pages" / "0_Dashboard.py" +PROGRESS_PATH = ROOT / "pages" / "3_Performance.py" +ANKI_PATH = ROOT / "pages" / "5_Export_Anki.py" + + +def make_reviewed_course() -> StudyPackage: + questions = [ + Question( + id=f"q{index}", + topic_id="t1", + question=f"Question {index}?", + options=["a", "b", "c", "d"], + correct_index=1, + explanation="Because.", + ) + for index in range(1, 5) + ] + return StudyPackage( + course_id="c1", + course_name="Course", + topics=[ + {"id": "t1", "name": "Limits", "summary": "Summary."}, + {"id": "t2", "name": "Series", "summary": "Summary."}, + ], + relationships=[], + questions=questions, + learning_state={ + # q2 has no review decision recorded. + "question_reviews": {"q1": "pending", "q3": "flagged", "q4": "approved"}, + }, + ) + + +def study_plan(course: StudyPackage, chinese: bool = False) -> AppTest: + app = AppTest.from_file(str(STUDY_PLAN_PATH)) + app.session_state["current_course"] = course + app.session_state[f"confirmed_scope_{course.course_id}"] = ["t1"] + if chinese: + app.session_state[LANGUAGE_KEY] = True + return app.run() + + +def test_exam_scope_is_one_click_pills_with_topic_ids(): + app = study_plan(make_reviewed_course()) + + assert not app.exception + assert not app.multiselect + scope = app.button_group(key="scope_selection_c1") + assert scope.options == ["Limits", "Series"] + assert scope.value == ["t1"] + + scope.select("t2").run() + assert not app.exception + assert app.session_state["scope_selection_c1"] == ["t1", "t2"] + assert "confirmed_scope_c1" not in app.session_state + + +def test_review_form_uses_horizontal_radios_and_keeps_question_dropdown(): + app = study_plan(make_reviewed_course()) + + assert not app.exception + assert app.selectbox(key="editor_question_c1").label == "Question to review" + correct = next(item for item in app.radio if item.label == "Correct answer") + assert correct.horizontal + assert correct.options == ["A", "B", "C", "D"] + assert correct.value == 1 + dimension = next( + item for item in app.radio if item.label == "Learning DNA evidence type" + ) + assert dimension.horizontal + assert not any( + item.label in {"Correct answer", "Learning DNA evidence type"} + for item in app.selectbox + ) + + +def test_review_list_shows_plain_status_words_instead_of_internal_codes(): + app = study_plan(make_reviewed_course()) + + assert not app.exception + options = app.selectbox(key="editor_question_c1").options + assert options == [ + "Needs check · Question 1?", + "Question 2?", + "Flagged · Question 3?", + "Approved · Question 4?", + ] + assert not any("[" in option for option in options) + captions = [item.value for item in app.caption] + assert "1 new question needs your check" in captions + assert "2 questions ready" in captions + assert not any("legacy" in text.lower() for text in captions) + assert ( + "Check the answer and explanation before approving; edits never change past results." + in captions + ) + + +def test_review_texts_are_translated(): + app = study_plan(make_reviewed_course(), chinese=True) + + assert not app.exception + captions = [item.value for item in app.caption] + assert "有 1 道新题需要你检查" in captions + assert "2 道题可以练习" in captions + assert app.selectbox(key="editor_question_c1").options[0] == "待检查 · Question 1?" + + +def test_saving_a_review_still_maps_the_untagged_choice_to_none(): + app = study_plan(make_reviewed_course()) + next(item for item in app.radio if item.label == "Correct answer").set_value(2) + next(b for b in app.button if b.label == "Save review").click().run() + + assert not app.exception + saved = app.session_state["current_course"] + assert saved.questions[-1].correct_index == 2 + assert saved.questions[-1].cognitive_dimension is None + + +def test_anonymous_course_tools_do_not_mention_the_database(): + app = study_plan(make_reviewed_course()) + + assert not app.exception + captions = [item.value for item in app.caption] + assert "Log in to back up this course." in captions + assert not any("database" in text.lower() for text in captions) + + +def test_dashboard_hides_raw_validation_errors_from_generated_topics(monkeypatch): + from services import ai_service + + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key") + uploaded = SimpleNamespace(name="notes.txt", getvalue=lambda: b"Course notes.") + monkeypatch.setattr(st, "file_uploader", lambda *_args, **_kwargs: uploaded) + monkeypatch.setattr( + ai_service, "generate_topics", + lambda **_kwargs: {"ok": True, "package": {"course_id": "broken"}}, + ) + app = AppTest.from_file(str(DASHBOARD_PATH)).run() + app.button(key="create_course_button").click().run() + app.text_input(key="setup_course_name").set_value("New course").run() + next(button for button in app.button if button.label == "Extract text").click().run() + next(button for button in app.button if button.label == "Generate topics").click().run() + + assert not app.exception + assert [item.value for item in app.error] == [ + "Couldn't use the generated topics. Try generating them again." + ] + assert not any("Extracted text:" in item.value for item in app.caption) + + +def test_progress_page_keeps_legend_but_not_storage_notes(): + from tests.test_demo_courses import load_demo + + app = AppTest.from_file(str(PROGRESS_PATH)) + app.session_state["current_course"] = load_demo("sample_course.json") + app.run() + + assert not app.exception + captions = " ".join(item.value for item in app.caption) + assert "Below 60%: Weak" in captions + assert "Signed-in users" not in captions + assert "excluded" not in captions + assert "Uses your latest answer to each question." in captions + assert not any( + item.label == "Question labels and saved history" for item in app.expander + ) + + +def test_anki_page_uses_plain_wording(): + from tests.test_demo_courses import load_demo + + app = AppTest.from_file(str(ANKI_PATH)) + app.session_state["current_course"] = load_demo("demo_python_basics.json") + app.run() + + assert not app.exception + texts = [item.value for item in [*app.caption, *app.markdown]] + assert not any("UTF-8" in text or "not been verified" in text for text in texts) + assert any(text.endswith("cards · All Questions") for text in texts) diff --git a/tests/test_pending_ui.py b/tests/test_pending_ui.py index 693339b..47ca666 100644 --- a/tests/test_pending_ui.py +++ b/tests/test_pending_ui.py @@ -114,7 +114,10 @@ def test_dashboard_extracts_pdf_and_displays_actual_page_sources(monkeypatch): assert document["sources"] == [{"filename": "course.pdf", "page": 1}] assert document["pages"][0]["page"] == 1 assert any("course.pdf · Page 1" in item.value for item in app.caption) - assert any("PDF pages (1)" in item.label for item in app.expander) + # Page and character counts of the extracted material are not shown. + assert not any("PDF pages" in item.label for item in app.expander) + assert not any("Extracted text:" in item.value for item in app.caption) + assert not any(" characters" in item.value for item in app.markdown) def test_dashboard_image_ocr_uses_image_labels_and_updated_copy(monkeypatch): @@ -131,7 +134,7 @@ def test_dashboard_image_ocr_uses_image_labels_and_updated_copy(monkeypatch): click_extract(app) assert not app.exception - assert any("Image (1)" in item.label for item in app.expander) + assert not any("Image (1)" in item.label for item in app.expander) assert not any("PDF pages" in item.label for item in app.expander) assert any("scan.png · Image 1" in item.value for item in app.caption) assert any( @@ -263,7 +266,7 @@ def test_dashboard_extracts_pptx_and_displays_actual_slide_sources(monkeypatch): assert any( "slides.pptx · Slide 1" == item.value for item in app.caption ) - assert any("PPTX slides (1)" == item.label for item in app.expander) + assert not any("PPTX slides" in item.label for item in app.expander) assert any("50,000 characters" in item.value for item in app.caption) assert any( "UTF-8 TXT" in item.value @@ -278,16 +281,17 @@ def test_single_scope_selector_requires_reconfirmation(): app.session_state["current_course"] = course app.run() assert not any(item.key and item.key.startswith("topic_selected_") for item in app.checkbox) - app.multiselect[0].set_value(["checkbox-course-topic"]).run() + scope = lambda: app.button_group(key="scope_selection_checkbox-course") + scope().set_value(["checkbox-course-topic"]).run() assert not app.exception - assert app.multiselect[0].value == ["checkbox-course-topic"] + assert scope().value == ["checkbox-course-topic"] next(button for button in app.button if button.label == "Confirm exam scope").click().run() assert app.session_state["confirmed_scope_checkbox-course"] == ["checkbox-course-topic"] - app.multiselect[0].set_value([]).run() + scope().set_value([]).run() assert not app.exception - assert app.multiselect[0].value == [] + assert scope().value == [] assert "confirmed_scope_checkbox-course" not in app.session_state - app.multiselect[0].set_value(["checkbox-course-topic"]).run() + scope().set_value(["checkbox-course-topic"]).run() assert not app.exception - assert app.multiselect[0].value == ["checkbox-course-topic"] + assert scope().value == ["checkbox-course-topic"] assert "confirmed_scope_checkbox-course" not in app.session_state diff --git a/tests/test_relationship_suggestions.py b/tests/test_relationship_suggestions.py index 54ee66f..04dc11c 100644 --- a/tests/test_relationship_suggestions.py +++ b/tests/test_relationship_suggestions.py @@ -97,13 +97,17 @@ def test_apply_rejects_suggestions_for_unknown_topics(): ) -def test_describe_uses_topic_names_and_falls_back_to_ids(): +def test_describe_uses_topic_names_and_never_shows_ids(): labels = describe_suggestions( make_course(), - [SUGGESTION, {"from_topic": "topic-1", "to_topic": "gone", "type": "related"}], + [ + SUGGESTION, + {"from_topic": "topic-1", "to_topic": "gone", "type": "related"}, + {"to_topic": "topic-2", "type": "related"}, + ], ) - assert labels == ["Limits ↔ Derivatives", "Limits ↔ gone"] + assert labels == ["Limits ↔ Derivatives", "Limits ↔ Topic", "Topic ↔ Derivatives"] def test_page_hides_suggestions_without_saved_material(): @@ -163,7 +167,7 @@ def test_page_shows_service_error_without_storing_suggestions(monkeypatch): { "ok": False, "error_code": "MISSING_API_KEY", - "message": "ANTHROPIC_API_KEY is not configured.", + "message": "AI generation is unavailable right now.", }, ) app = run_page(make_course(), make_document()) @@ -172,7 +176,7 @@ def test_page_shows_service_error_without_storing_suggestions(monkeypatch): assert not app.exception assert any( - "ANTHROPIC_API_KEY is not configured." in item.value for item in app.error + "AI generation is unavailable right now." in item.value for item in app.error ) assert suggestions_key("course-1") not in app.session_state diff --git a/tests/test_study_hub_radar.py b/tests/test_study_hub_radar.py index 84d5d17..e9e8b26 100644 --- a/tests/test_study_hub_radar.py +++ b/tests/test_study_hub_radar.py @@ -245,7 +245,8 @@ def test_panel_captions_for_sample_and_offline_data(monkeypatch, live, has_sampl assert not app.exception captions = _captions(_panel(app)) assert captions.count(SAMPLE_CAPTION) == (1 if has_sample else 0) - assert captions.count(OFFLINE_CAPTION) == (0 if live else 1) + # Whether live flags loaded is a storage detail students do not see. + assert OFFLINE_CAPTION not in captions assert EMPTY_CAPTION not in captions @@ -471,4 +472,4 @@ def test_page_renders_with_real_backend_when_database_is_unavailable(): "**3. Limits** — 5 students are stuck here", ] assert SAMPLE_CAPTION in _captions(panel) - assert OFFLINE_CAPTION in _captions(panel) + assert OFFLINE_CAPTION not in _captions(panel) From ad8a423bf0141bf1be27a30d7a1570cf5cfee96a Mon Sep 17 00:00:00 2001 From: Charles Chen Date: Sat, 14 Nov 2026 23:41:48 -0500 Subject: [PATCH 07/21] Add Learning Radar spider chart, one-click stuck buttons and radar page - components/radar_chart.py: RadarAxis, course_radar_axes, radar_chart_svg (pure SVG, no JavaScript), render_course_radar_chart and render_stuck_buttons (one button per reason plus "Just stuck"). - Knowledge Map: the reason dropdown is replaced by the one-click buttons; the radar panel draws the chart above the ranking, highlighting the selected topic. - New pages/7_Learning_Radar.py: chart, ranking and a topic picker with the stuck buttons and a link to the topic on the Knowledge Map. - Student view no longer shows topic/connection counts, source-page or live-flag bookkeeping, or raw database reasons in failure messages. - assets/paper_radar.css themes the chart and buttons with the paper palette; Chinese strings added under "paper UI: radar". --- assets/paper_radar.css | 93 ++++++ components/knowledge_graph.py | 47 ++- components/radar_chart.py | 456 ++++++++++++++++++++++++++++ pages/4_Knowledge_Graph.py | 66 ++--- pages/7_Learning_Radar.py | 101 +++++++ services/i18n.py | 14 + tests/test_graph_exploration.py | 16 +- tests/test_knowledge_graph.py | 310 +++++++++++++------ tests/test_learning_radar_page.py | 221 ++++++++++++++ tests/test_radar_chart.py | 475 ++++++++++++++++++++++++++++++ 10 files changed, 1654 insertions(+), 145 deletions(-) create mode 100644 assets/paper_radar.css create mode 100644 components/radar_chart.py create mode 100644 pages/7_Learning_Radar.py create mode 100644 tests/test_learning_radar_page.py create mode 100644 tests/test_radar_chart.py diff --git a/assets/paper_radar.css b/assets/paper_radar.css new file mode 100644 index 0000000..3ea4e77 --- /dev/null +++ b/assets/paper_radar.css @@ -0,0 +1,93 @@ +/* Learning Radar: spider chart (components/radar_chart.py) and the one-click + "I'm stuck here" buttons. The SVG also carries these colours as attributes, + so it still draws correctly if this sheet is not loaded. */ + +.paper-radar { + display: flex; + justify-content: center; + margin: 0.35rem 0 0.15rem; +} + +.paper-radar .paper-radar-chart { + display: block; + max-width: 100%; + height: auto; + overflow: visible; +} + +.paper-radar-chart .radar-disc { + fill: var(--paper-badge, #F0EADA); +} + +.paper-radar-chart .radar-grid, +.paper-radar-chart .radar-spoke { + stroke: var(--paper-line, #EEE7DF); +} + +.paper-radar-chart .radar-tick { + fill: var(--ink-muted, #6B7280); +} + +.paper-radar-chart .radar-shape { + fill: var(--accent-rust, #B5622E); + stroke: var(--accent-rust, #B5622E); +} + +.paper-radar-chart .radar-point, +.paper-radar-chart .radar-ring { + fill: var(--accent-rust, #B5622E); +} + +.paper-radar-chart .radar-ring { + stroke: var(--accent-rust, #B5622E); +} + +.paper-radar-chart .radar-point-focus { + stroke: var(--paper-card, #FFFCF7); +} + +.paper-radar-chart .radar-label { + fill: var(--ink-body, #2A2F33); + font-family: var(--font-title, Georgia, "Times New Roman", serif); +} + +/* Captions under the chart line up with it. */ +[class*="st-key-learning_radar_page_chart"] [data-testid="stCaptionContainer"], +[class*="st-key-learning_radar_panel_chart"] [data-testid="stCaptionContainer"] { + text-align: center; +} + +/* Reason buttons read as a row of small pills. */ +[class*="_stuck_reasons"] button:is( + [data-testid="stBaseButton-secondary"], + [data-testid="stBaseButton-primary"] +) { + min-height: 2.25rem; + padding: 0.3rem 0.85rem; + border: 1px solid var(--paper-line, #EEE7DF); + border-radius: 999px; + background: var(--paper-card, #FFFCF7); + color: var(--ink, #13224F); + font-weight: 550; +} + +[class*="_stuck_reasons"] button:is( + [data-testid="stBaseButton-secondary"], + [data-testid="stBaseButton-primary"] +):not(:disabled):hover { + border-color: var(--accent-rust, #B5622E); + background: var(--paper-select, #FAE5D2); + color: var(--accent-rust, #B5622E); +} + +[class*="_stuck_reasons"] button:is( + [data-testid="stBaseButton-secondary"], + [data-testid="stBaseButton-primary"] +) :is(p, span) { + color: inherit !important; +} + +[class*="_stuck_reasons"] button:focus-visible { + outline: 3px solid var(--accent-blue, #5D81A1); + outline-offset: 2px; +} diff --git a/components/knowledge_graph.py b/components/knowledge_graph.py index 4c46d46..30d3e91 100644 --- a/components/knowledge_graph.py +++ b/components/knowledge_graph.py @@ -230,8 +230,6 @@ def render_topic_details( source_pages = details["source_pages"] if source_pages: st.caption(tr(f"Source pages: {', '.join(map(str, source_pages))}")) - else: - st.caption(tr("Source pages not provided")) st.divider() st.markdown(tr("**Your Progress**")) @@ -333,11 +331,12 @@ def radar_count_text(topic_radar: learning_radar.TopicRadar | None) -> str: return f"{count} students are stuck here" -NO_REASON_LABEL = "No specific reason" -# Choices offered before flagging: no reason (stored as None), then each code. +NO_REASON_LABEL = "Just stuck" +# One-click choices offered before flagging: each reason code, then no reason +# (stored as None). RADAR_REASON_OPTIONS: tuple[str | None, ...] = ( - None, *learning_radar.REASON_LABELS, + None, ) WORDING_HINT = ( "Turn on Accessibility in the sidebar for simpler wording and " @@ -416,17 +415,25 @@ def render_reason_hint(reason: str | None) -> None: def render_saved_reason(reason: str | None) -> None: - """Show the reason the user gave when flagging the selected topic.""" - st.caption(tr("Your reason: ") + tr(radar_reason_label(reason))) + """Show the reason the user gave when flagging; "Just stuck" shows none.""" + if reason is not None: + st.caption(tr("Your reason: ") + tr(radar_reason_label(reason))) render_reason_hint(reason) def render_topic_radar( topic_radar: learning_radar.TopicRadar | None, prerequisite_names: Sequence[str] = (), + *, + show_count: bool = True, ) -> None: - """Show how many students are stuck on the selected topic.""" - st.markdown(tr(radar_count_text(topic_radar))) + """Show how many students are stuck on the selected topic. + + Pass ``show_count=False`` when the count is already on screen (the + "I'm stuck here" buttons show it); the notes below it still appear. + """ + if show_count: + st.markdown(tr(radar_count_text(topic_radar))) if topic_radar is not None and topic_radar.sample_count > 0: st.caption(tr("Includes sample data")) hint = radar_prerequisite_hint(topic_radar, prerequisite_names) @@ -438,10 +445,26 @@ def render_radar_panel( radar: learning_radar.CourseRadar, ranked_topics: list[learning_radar.TopicRadar], topic_names: dict[str, str], + *, + course: StudyPackage | None = None, + focus_topic_id: str | None = None, + chart_key: str = "learning_radar_panel_chart", + title: str = "**Learning Radar**", ) -> None: - """List the course's flagged topics in the order given (most flagged first).""" - st.markdown(tr("**Learning Radar**")) + """List the course's flagged topics in the order given (most flagged first). + + With ``course`` the spider chart is drawn above the list, highlighting + ``focus_topic_id`` when one is given. + """ + st.markdown(tr(title)) st.caption(tr("Topics where students marked \"I'm stuck here\", most flagged first.")) + if course is not None: + # Imported here: components.radar_chart imports this module. + from components.radar_chart import render_radar_figure + + render_radar_figure( + course, radar, focus_topic_id=focus_topic_id, key=chart_key + ) flagged = [ topic_radar for topic_radar in ranked_topics @@ -469,5 +492,3 @@ def render_radar_panel( st.caption(tr("No topics have been flagged yet.")) if radar.has_sample: st.caption(tr("Includes sample data")) - if not radar.live: - st.caption(tr("Live flags are unavailable right now.")) diff --git a/components/radar_chart.py b/components/radar_chart.py new file mode 100644 index 0000000..bd49954 --- /dev/null +++ b/components/radar_chart.py @@ -0,0 +1,456 @@ +"""Learning Radar spider chart and the one-click "I'm stuck here" buttons. + +The chart is plain SVG markup built in Python: no JavaScript and no external +files, so any page can embed it. Colours are written as presentation +attributes (the paper palette) and the same elements carry classes that +``assets/paper_radar.css`` themes with the shared CSS variables. +""" + +from __future__ import annotations + +import html +import math +from collections.abc import MutableMapping, Sequence +from typing import Any, NamedTuple + +import streamlit as st + +from components.knowledge_graph import ( + RADAR_REASON_OPTIONS, + forget_course_radar, + load_course_radar, + radar_count_text, + radar_reason_label, + render_saved_reason, +) +from models.schemas import StudyPackage +from services import learning_radar +from services.i18n import tr + +# A radar chart needs at least three axes to enclose an area. +MIN_RADAR_TOPICS = 3 +# Unflagged topics fill the chart up to this many axes so the shape reads well. +MIN_RADAR_AXES = 5 +STUCK_FAILURE_MESSAGE = "Couldn't update Learning Radar. Try again in a moment." + +# Paper palette; assets/paper_radar.css maps the same roles to CSS variables. +_INK_BODY = "#2A2F33" +_INK_MUTED = "#6B7280" +_RUST = "#B5622E" +_LINE = "#EEE7DF" +_BADGE = "#F0EADA" +_CARD = "#FFFCF7" +_FONT_FAMILY = "Georgia, 'Times New Roman', serif" + +_FONT_SIZE = 12 +_LINE_HEIGHT = 14 +_BASELINE = 11 # first baseline below the top of a label block +_LABEL_GAP = 10 # space between the outer circle and a label +_MARGIN = 4 # space kept free at the edges of the drawing +_WRAP_WIDTH = 88 # labels estimated wider than this wrap onto two lines +_OVERFLOW_SLACK = 6 # a line may overrun its room by this much before "…" +_SIDE_THRESHOLD = 0.2 # |sin| below this: the label sits above or below +_MIN_RADIUS_SHARE = 0.22 +_MAX_RADIUS_SHARE = 0.28 +_PEAK_SHARE = 0.85 # the largest value reaches this share of the radius + +# Rough Georgia advance widths at 12px, enough to wrap and place labels. +_NARROW = frozenset("fijlrtI.,:;'!|()[]-") +_WIDE = frozenset("mwMW") + + +class RadarAxis(NamedTuple): + topic_id: str + label: str + value: int + highlighted: bool + + +def _axis_value(topic_radar: learning_radar.TopicRadar | None) -> int: + """The drawn count: a hidden count (privacy threshold) counts as 0.""" + if topic_radar is None: + return 0 + count = topic_radar.display_count + if isinstance(count, int) and not isinstance(count, bool) and count > 0: + return count + return 0 + + +def course_radar_axes( + course: StudyPackage, + radar: learning_radar.CourseRadar, + *, + focus_topic_id: str | None = None, + limit: int = 6, +) -> list[RadarAxis]: + """Choose the chart's axes and return them in course topic order. + + Priority: flagged topics with a visible count (highest first), then the + focus topic, then other topics in course order until there are + MIN_RADAR_AXES. At most ``limit`` axes are kept, and the focus topic + always keeps a place so it can be highlighted. A limit below three is + raised to three, the fewest axes a radar can show. + """ + topics = list(course.topics) + if len(topics) < MIN_RADAR_TOPICS: + return [] + limit = max(limit, MIN_RADAR_TOPICS) + values = {topic.id: _axis_value(radar.topics.get(topic.id)) for topic in topics} + focus = focus_topic_id if focus_topic_id in values else None + + # sorted() is stable, so tied counts keep the course order. + flagged = sorted( + (topic_id for topic_id, value in values.items() if value > 0), + key=lambda topic_id: -values[topic_id], + ) + chosen = flagged[:limit] + if focus is not None and focus not in chosen: + chosen = [*chosen[: limit - 1], focus] + fill_to = min(MIN_RADAR_AXES, limit) + for topic in topics: + if len(chosen) >= fill_to: + break + if topic.id not in chosen: + chosen.append(topic.id) + + selected = set(chosen) + return [ + RadarAxis( + topic_id=topic.id, + label=topic.name, + value=values[topic.id], + highlighted=topic.id == focus, + ) + for topic in topics + if topic.id in selected + ] + + +def _char_width(char: str) -> float: + if char == " ": + return 3.0 + if char in _NARROW: + return 3.8 + if char in _WIDE: + return 9.5 + if ord(char) > 0x2E7F: # CJK and other full-width text + return 12.0 + if char.isupper(): + return 7.6 + if char.isdigit(): + return 6.6 + return 6.0 + + +def _text_width(text: str, bold: bool = False) -> float: + width = sum(_char_width(char) for char in text) + return width * 1.1 if bold else width + + +def _wrap_label(label: str, bold: bool) -> list[str]: + """One line when short, otherwise the most balanced split into two.""" + words = label.split() + if not words: + return [""] + whole = " ".join(words) + if len(words) == 1 or _text_width(whole, bold) <= _WRAP_WIDTH: + return [whole] + best: list[str] = [whole] + best_width = math.inf + for split in range(1, len(words)): + lines = [" ".join(words[:split]), " ".join(words[split:])] + widest = max(_text_width(line, bold) for line in lines) + if widest < best_width: + best, best_width = lines, widest + return best + + +def _fits(line: str, room: float, bold: bool) -> bool: + return _text_width(line, bold) <= room + _OVERFLOW_SLACK + + +def _fit_line(line: str, room: float, bold: bool) -> str: + """Shorten a line with "…" when it would overrun its room.""" + if _fits(line, room, bold): + return line + for end in range(len(line) - 1, 0, -1): + candidate = line[:end].rstrip() + "…" + if _text_width(candidate, bold) <= room: + return candidate + return "…" + + +def _fit_label(lines: list[str], room: float, bold: bool) -> list[str]: + """Keep the natural lines when they fit, else refill two lines and cut.""" + words = " ".join(lines).split() + if not words or all(_fits(line, room, bold) for line in lines): + return lines + first = words[0] + rest = 1 + while rest < len(words) and _fits(f"{first} {words[rest]}", room, bold): + first = f"{first} {words[rest]}" + rest += 1 + refilled = [first] + if rest < len(words): + refilled.append(" ".join(words[rest:])) + return [_fit_line(line, room, bold) for line in refilled] + + +def _number(value: float) -> str: + text = f"{value:.1f}" + return text[:-2] if text.endswith(".0") else text + + +def radar_chart_svg(axes: Sequence[RadarAxis], *, size: int = 320) -> str: + """Return one ```` element drawing the axes as a spider chart. + + ``size`` is the drawing width in pixels; the height follows from the + labels. Axes start at the top and run clockwise. When every value is 0 + only the grid and the labels are drawn. + """ + axes = list(axes) + width = float(size) + aria_label = html.escape( + ", ".join(f"{axis.label}: {axis.value}" for axis in axes), quote=True + ) + if not axes: + return ( + '' + ) + + count = len(axes) + directions = [ + (math.sin(2 * math.pi * index / count), -math.cos(2 * math.pi * index / count)) + for index in range(count) + ] + natural_lines = [_wrap_label(axis.label, axis.highlighted) for axis in axes] + + # Shrink the circle (within limits) so the side labels fit across the + # drawing width; labels that still do not fit are shortened below. + radius = width * _MAX_RADIUS_SHARE + for (dx, _), lines, axis in zip(directions, natural_lines, axes): + if abs(dx) < _SIDE_THRESHOLD: + continue + needed = max(_text_width(line, axis.highlighted) for line in lines) + radius = min(radius, (width / 2 - _MARGIN - needed) / abs(dx) - _LABEL_GAP) + radius = max(radius, width * _MIN_RADIUS_SHARE) + label_radius = radius + _LABEL_GAP + + # Lay out each label relative to the centre (y grows downwards). + labels = [] + for (dx, dy), lines, axis in zip(directions, natural_lines, axes): + x = width / 2 + dx * label_radius + if abs(dx) < _SIDE_THRESHOLD: + anchor, room = "middle", 2 * (min(x, width - x) - _MARGIN) + elif dx > 0: + anchor, room = "start", width - _MARGIN - x + else: + anchor, room = "end", x - _MARGIN + lines = _fit_label(lines, room, axis.highlighted) + block = len(lines) * _LINE_HEIGHT + # Above the chart a label ends at its point, below it starts there. + top = dy * label_radius + dy * block / 2 - block / 2 + labels.append((x, top, anchor, lines, axis)) + + top_edge = min(-radius, *(top for _, top, _, _, _ in labels)) + bottom_edge = max( + radius, *(top + len(lines) * _LINE_HEIGHT for _, top, _, lines, _ in labels) + ) + height = math.ceil(bottom_edge - top_edge + 2 * _MARGIN) + cx = width / 2 + cy = _MARGIN - top_edge + + parts = [ + '' + ] + + # Grid: two soft discs and three thin rings, then one spoke per axis. + for share in (1, 2 / 3): + parts.append( + f'' + ) + for share in (1 / 3, 2 / 3, 1): + parts.append( + f'' + ) + for dx, dy in directions: + end_x, end_y = cx + dx * radius, cy + dy * radius + parts.append( + f'' + ) + parts.append( + f'' + ) + + peak = max(axis.value for axis in axes) + if peak > 0: + vertices = [ + ( + cx + dx * radius * _PEAK_SHARE * axis.value / peak, + cy + dy * radius * _PEAK_SHARE * axis.value / peak, + ) + for (dx, dy), axis in zip(directions, axes) + ] + points = " ".join(f"{_number(x)},{_number(y)}" for x, y in vertices) + parts.append( + f'' + ) + focus_marks = [] + for (x, y), axis in zip(vertices, axes): + if axis.highlighted: + # Drawn last so the larger dot and its ring sit on top. + focus_marks.append( + f'' + ) + focus_marks.append( + f'' + ) + else: + parts.append( + f'' + ) + parts.extend(focus_marks) + + for x, top, anchor, lines, axis in labels: + weight = ' font-weight="700"' if axis.highlighted else "" + css_class = "radar-label radar-label-focus" if axis.highlighted else "radar-label" + spans = "".join( + f'' + f"{html.escape(line, quote=False)}" + for row, line in enumerate(lines) + ) + parts.append( + f'' + f"{html.escape(axis.label, quote=False)}{spans}" + ) + + parts.append("") + return "".join(parts) + + +def _render_svg(axes: Sequence[RadarAxis]) -> None: + # The wrapping
keeps the markup one raw HTML block for Markdown. + st.markdown( + f'
\n{radar_chart_svg(axes)}\n
', + unsafe_allow_html=True, + ) + + +def render_radar_figure( + course: StudyPackage, + radar: learning_radar.CourseRadar, + *, + focus_topic_id: str | None = None, + limit: int = 6, + key: str, +) -> None: + """Draw the chart and its axis caption only, for panels that print their + own "No topics have been flagged yet." and sample-data notes.""" + axes = course_radar_axes( + course, radar, focus_topic_id=focus_topic_id, limit=limit + ) + with st.container(key=key): + if axes: + _render_svg(axes) + st.caption(tr("Students stuck per topic")) + + +def render_course_radar_chart( + course: StudyPackage, + radar: learning_radar.CourseRadar, + *, + focus_topic_id: str | None = None, + limit: int = 6, + key: str, +) -> None: + """Draw the course's Learning Radar chart with its captions.""" + axes = course_radar_axes( + course, radar, focus_topic_id=focus_topic_id, limit=limit + ) + with st.container(key=key): + if not axes: + return + _render_svg(axes) + st.caption(tr("Students stuck per topic")) + if not any(axis.value > 0 for axis in axes): + st.caption(tr("No topics have been flagged yet.")) + if radar.has_sample: + st.caption(tr("Includes sample data")) + + +def _finish_write( + session_state: MutableMapping[str, Any], + course_id: str, + result: Any, +) -> None: + """Refresh the counts after a saved change; otherwise show a short notice. + + The stored failure reason may describe the database, so it is not shown. + """ + if result.success: + # Show the new count right away instead of waiting for the cache. + forget_course_radar(session_state, course_id) + st.rerun() + st.warning(tr(STUCK_FAILURE_MESSAGE)) + + +def render_stuck_buttons( + session_state: MutableMapping[str, Any], + course_id: str, + topic_id: str, + user_id: str | None, + *, + key: str, +) -> None: + """Show the topic's count and one-click buttons to flag or unflag it. + + Without a signed-in user only the count is shown. + """ + radar, user_flags = load_course_radar(session_state, course_id, user_id) + st.markdown(tr(radar_count_text(radar.topics.get(topic_id)))) + if user_id is None: + return + + if topic_id in user_flags: + st.markdown(tr("You marked this topic.")) + render_saved_reason(user_flags[topic_id]) + if st.button(tr("Not stuck anymore"), key=f"{key}_clear"): + _finish_write( + session_state, + course_id, + learning_radar.clear_flag(user_id, course_id, topic_id), + ) + return + + st.caption(tr("I'm stuck here because…")) + chosen: tuple[str | None] | None = None + with st.container(horizontal=True, gap="small", key=f"{key}_stuck_reasons"): + for reason in RADAR_REASON_OPTIONS: + if st.button( + tr(radar_reason_label(reason)), + key=f"{key}_{reason if reason is not None else 'no_reason'}", + ): + chosen = (reason,) + if chosen is not None: + _finish_write( + session_state, + course_id, + learning_radar.set_flag(user_id, course_id, topic_id, chosen[0]), + ) diff --git a/pages/4_Knowledge_Graph.py b/pages/4_Knowledge_Graph.py index b521129..c4ae3dc 100644 --- a/pages/4_Knowledge_Graph.py +++ b/pages/4_Knowledge_Graph.py @@ -3,20 +3,16 @@ import streamlit as st from components.knowledge_graph import ( - RADAR_REASON_OPTIONS, concept_lab_available, render_knowledge_graph, - forget_course_radar, get_selected_topic_details, load_course_radar, radar_node_badges, - radar_reason_label, render_radar_panel, - render_reason_hint, - render_saved_reason, render_topic_details, render_topic_radar, ) +from components.radar_chart import render_stuck_buttons from services import learning_radar from services.account_sync import save_course_to_account from services.ai_service import generate_relationships @@ -99,7 +95,6 @@ help=tr("Show only this topic and its directly connected neighbors."), ) view_course = local_graph(course, focus_id) if focus_id and local_view else course -st.caption(tr(f"Showing {len(view_course.topics)} of {len(course.topics)} topics · Connections: {len(view_course.relationships)}")) reset_key = f"graph_view_reset_{course.course_id}_{mode}" zoom_key = f"graph_zoom_{course.course_id}_{mode}" @@ -152,10 +147,9 @@ # page, so the course radar and the user's flags are reused for a short time. radar = None radar_user = None -radar_user_flags = {} if learning_radar.radar_enabled(course.course_id): radar_user = current_user(st.session_state) - radar, radar_user_flags = load_course_radar( + radar, _ = load_course_radar( st.session_state, course.course_id, radar_user.user_id if radar_user is not None else None, @@ -202,6 +196,8 @@ radar, learning_radar.top_hard_topics(radar, limit=len(course.topics)), topic_names, + course=course, + focus_topic_id=focus_id, ) if not course.relationships: @@ -283,11 +279,13 @@ count = len(suggestions) noun = "connection" if count == 1 else "connections" if sync_outcome is not None and not sync_outcome.success: + # The stored reason may describe the database, so + # the student sees a short notice instead. st.session_state[notice_state_key] = ( "warning", "Connections kept in this session but not saved " - f"to your account: {sync_outcome.message} Use " - "Save on the Study Plan page to retry.", + "to your account. Use Save on the Study Plan " + "page to retry.", ) else: st.session_state[notice_state_key] = ( @@ -339,7 +337,6 @@ st.caption(tr(label) + ":" + ", ".join(topic_names[item] for item in links[group])) if not any(links.values()): st.caption(tr("No connections recorded for this topic.")) - st.caption(tr("These are course-provided relationships, not a diagnosis of your understanding.")) for linked_id in links["prerequisites"]: if st.button(tr("Review ") + topic_names[linked_id], key=f"graph_prerequisite_{course.course_id}_{linked_id}"): st.session_state[pending_key] = linked_id @@ -356,6 +353,16 @@ if radar is not None: st.divider() st.markdown(tr("**Learning Radar**")) + if radar_user is not None: + # One click flags the topic with a reason; to change the + # reason, remove the flag and flag again. + render_stuck_buttons( + st.session_state, + course.course_id, + selected_node_id, + radar_user.user_id, + key=f"radar_flag_{course.course_id}_{selected_node_id}", + ) render_topic_radar( radar.topics.get(selected_node_id), prerequisite_names=[ @@ -363,42 +370,9 @@ for item in links["prerequisites"] if item in topic_names ], + # The buttons above already show the count. + show_count=radar_user is None, ) - if radar_user is not None: - already_flagged = selected_node_id in radar_user_flags - if already_flagged: - # To change the reason, remove the flag and flag again. - reason = radar_user_flags[selected_node_id] - render_saved_reason(reason) - else: - reason = st.selectbox( - tr("Why are you stuck?"), - options=RADAR_REASON_OPTIONS, - format_func=lambda value: tr(radar_reason_label(value)), - key=f"radar_reason_{course.course_id}_{selected_node_id}", - ) - render_reason_hint(reason) - if st.button( - tr("Not stuck anymore") if already_flagged else tr("I'm stuck here"), - key=f"radar_flag_{course.course_id}_{selected_node_id}", - ): - if already_flagged: - result = learning_radar.clear_flag( - radar_user.user_id, course.course_id, selected_node_id - ) - else: - result = learning_radar.set_flag( - radar_user.user_id, - course.course_id, - selected_node_id, - reason, - ) - if result.success: - # Show the new count right away instead of waiting - # for the cache to expire. - forget_course_radar(st.session_state, course.course_id) - st.rerun() - st.warning(tr(result.message)) if concept_lab_available(course.course_id, selected_node_id): if st.button( tr("Open Concept Lab"), diff --git a/pages/7_Learning_Radar.py b/pages/7_Learning_Radar.py new file mode 100644 index 0000000..7a52ef9 --- /dev/null +++ b/pages/7_Learning_Radar.py @@ -0,0 +1,101 @@ +"""Learning Radar: where students of the built-in demo courses get stuck.""" + +from services.i18n import tr + +import streamlit as st + +from components.knowledge_graph import load_course_radar, render_radar_panel +from components.radar_chart import render_course_radar_chart, render_stuck_buttons +from services import learning_radar +from services.auth_session import current_user +from services.ui_style import apply_app_styles + +# Up to this many topics are offered as one-click pills; more use a dropdown. +MAX_PILL_TOPICS = 8 + +apply_app_styles() + +st.title(tr("Learning Radar")) +st.caption(tr("See where students get stuck, and mark the topics that stop you.")) + +course = st.session_state.get("current_course") + +if course is None: + st.info(tr("Load a course from the dashboard first.")) + st.page_link("pages/0_Dashboard.py", label=tr("Back to Dashboard")) + st.stop() + +if not learning_radar.radar_enabled(course.course_id): + st.info(tr("Learning Radar is available for the built-in demo courses.")) + st.stop() + +user = current_user(st.session_state) +user_id = user.user_id if user is not None else None +# Shared with the Knowledge Map and Study Plan, so reruns reuse one read. +radar, _ = load_course_radar(st.session_state, course.course_id, user_id) +topic_names = {topic.id: topic.name for topic in course.topics} + +picker_key = f"learning_radar_topic_{course.course_id}" +# The picker sits below the chart; its last choice is highlighted above. +picked = st.session_state.get(picker_key) +if picked not in topic_names: + picked = None + +chart_column, ranking_column = st.columns([1.15, 1], gap="large") +with chart_column: + with st.container(border=True, key="learning_radar_chart_panel"): + render_course_radar_chart( + course, + radar, + focus_topic_id=picked, + limit=8, + key="learning_radar_page_chart", + ) +with ranking_column: + with st.container(border=True, key="learning_radar_ranking_panel"): + render_radar_panel( + radar, + learning_radar.top_hard_topics(radar, limit=len(course.topics)), + topic_names, + title="**Most flagged topics**", + ) + +with st.container(border=True, key="learning_radar_mark_panel"): + st.subheader(tr("Where are you stuck?")) + if len(topic_names) <= MAX_PILL_TOPICS: + picked = st.pills( + tr("Pick a topic"), + options=list(topic_names), + format_func=lambda topic_id: topic_names[topic_id], + key=picker_key, + label_visibility="collapsed", + ) + else: + picked = st.selectbox( + tr("Pick a topic"), + options=list(topic_names), + index=None, + format_func=lambda topic_id: topic_names[topic_id], + placeholder=tr("Pick a topic"), + key=picker_key, + label_visibility="collapsed", + ) + + if picked is None: + st.caption(tr("Pick a topic above to mark it.")) + else: + render_stuck_buttons( + st.session_state, + course.course_id, + picked, + user_id, + key=f"learning_radar_stuck_{course.course_id}_{picked}", + ) + if st.button( + tr("Open this topic in Knowledge Map"), + key=f"learning_radar_map_{course.course_id}_{picked}", + icon=":material/hub:", + ): + # The Knowledge Map moves this into its topic picker on load. + st.session_state[f"graph_pending_focus_{course.course_id}"] = picked + st.switch_page("pages/4_Knowledge_Graph.py") diff --git a/services/i18n.py b/services/i18n.py index a6af182..de4b171 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -317,6 +317,20 @@ "See computation and conceptual understanding separately, with the answers behind each pattern.": "分别查看计算与概念理解,以及各项判断依据的答案。", "These are question-based observations, not a validated cognitive diagnosis. Multiple-choice answers do not demonstrate that you can explain an idea in your own words.": "这些是基于题目的观察,并非经过验证的认知诊断;选择题无法证明你能用自己的话解释概念。", "Answer more different questions in both dimensions before comparing them.": "在两个维度上多做不同题目,再进行比较。", + # paper UI: radar + "Learning Radar": "学习雷达", + "See where students get stuck, and mark the topics that stop you.": "查看同学们在哪些知识点卡住,并标记让你卡住的知识点。", + "Learning Radar is available for the built-in demo courses.": "学习雷达仅适用于内置演示课程。", + "**Most flagged topics**": "**被标记最多的知识点**", + "Where are you stuck?": "你卡在哪个知识点?", + "Pick a topic": "选择知识点", + "Pick a topic above to mark it.": "在上方选择一个知识点进行标记。", + "Students stuck per topic": "各知识点卡住的学生人数", + "I'm stuck here because…": "我卡在这里,因为……", + "Just stuck": "就是没搞懂", + "You marked this topic.": "你已标记此知识点。", + "Couldn't update Learning Radar. Try again in a moment.": "暂时无法更新学习雷达,请稍后再试。", + "Connections kept in this session but not saved to your account. Use Save on the Study Plan page to retry.": "关联已保留在当前会话中,但未保存到账户。请在学习计划页面点击保存重试。", } _TRANSLATIONS.update( diff --git a/tests/test_graph_exploration.py b/tests/test_graph_exploration.py index 3b2e159..6e53819 100644 --- a/tests/test_graph_exploration.py +++ b/tests/test_graph_exploration.py @@ -45,7 +45,15 @@ def test_missing_topic_is_rejected(course): fn(course, "not-a-topic") -def test_search_shows_summary_and_local_graph_preserves_original_course(course): +def test_search_shows_summary_and_local_graph_preserves_original_course(course, monkeypatch): + from components import knowledge_graph + + rendered = [] + monkeypatch.setattr( + knowledge_graph, + "agraph", + lambda nodes, edges, config, node_scale: rendered.append(nodes) or None, + ) app = AppTest.from_file(str(ROOT / "pages/4_Knowledge_Graph.py")) app.session_state["current_course"] = course app.run() @@ -53,9 +61,13 @@ def test_search_shows_summary_and_local_graph_preserves_original_course(course): assert not app.exception assert any(header.value == "Summary" for header in app.subheader) assert any("Limits describe" in entry.value for entry in app.markdown) + assert len(rendered[-1]) == 3 app.toggle(key="graph_local_calculus-i-demo").set_value(True).run() assert not app.exception - assert any("Showing 2 of 3" in entry.value for entry in app.caption) + # The local graph draws only the topic and its neighbour; the topic and + # connection counts are no longer printed for students. + assert [node.id for node in rendered[-1]] == ["calc_limits", "calc_derivatives"] + assert not any(entry.value.startswith("Showing ") for entry in app.caption) assert len(app.session_state["current_course"].topics) == 3 app.selectbox(key="graph_focus_calculus-i-demo").set_value(None).run() assert not app.exception diff --git a/tests/test_knowledge_graph.py b/tests/test_knowledge_graph.py index 6894536..cf68b78 100644 --- a/tests/test_knowledge_graph.py +++ b/tests/test_knowledge_graph.py @@ -1,4 +1,5 @@ import json +import re from contextlib import nullcontext from pathlib import Path from unittest.mock import Mock @@ -636,7 +637,7 @@ def test_render_topic_details_displays_topic_statistics(monkeypatch): accuracy_column.metric.assert_called_once_with("Accuracy", "66.67%") -def test_render_topic_details_shows_missing_pages_message(monkeypatch): +def test_render_topic_details_shows_no_source_line_without_pages(monkeypatch): caption = Mock() monkeypatch.setattr( knowledge_graph.st, @@ -658,7 +659,8 @@ def test_render_topic_details_shows_missing_pages_message(monkeypatch): } ) - caption.assert_called_once_with("Source pages not provided") + # Storage bookkeeping is not shown to students. + caption.assert_not_called() def test_render_topic_details_prompts_when_no_topic_is_selected(monkeypatch): @@ -945,6 +947,43 @@ def _radar_buttons(app): ] +# One-click reason buttons, in display order, then the "no reason" button. +REASON_BUTTON_LABELS = [ + "Concept unclear", + "Calculation errors", + "Can't understand the question", + "Don't know where to start", + "Just stuck", +] +GENERIC_FAILURE = "Couldn't update Learning Radar. Try again in a moment." + + +def _flag_key(topic_id, course_id=CALCULUS_ID): + return f"radar_flag_{course_id}_{topic_id}" + + +def _reason_button(app, topic_id, reason=None): + suffix = "no_reason" if reason is None else reason + return app.button(key=f"{_flag_key(topic_id)}_{suffix}") + + +def _clear_button(app, topic_id): + return app.button(key=f"{_flag_key(topic_id)}_clear") + + +def _reason_button_labels(app, topic_id): + prefix = f"{_flag_key(topic_id)}_" + return [ + button.label for button in app.button + if button.key and button.key.startswith(prefix) + and not button.key.endswith("_clear") + ] + + +def _has_clear_button(app, topic_id): + return any(button.key == f"{_flag_key(topic_id)}_clear" for button in app.button) + + def test_radar_panel_lists_flagged_topics_most_flagged_first(monkeypatch): radar = RadarFake( monkeypatch, @@ -1040,13 +1079,14 @@ def test_non_demo_course_shows_no_radar_ui_and_fetches_nothing(monkeypatch): @pytest.mark.parametrize("live", [True, False]) -def test_radar_panel_reports_when_live_flags_are_unavailable(monkeypatch, live): +def test_radar_panel_never_mentions_the_database(monkeypatch, live): RadarFake(monkeypatch, [_topic("calc_derivatives", sample=8)], live=live) app = _graph_page(_calculus_course()) assert not app.exception - assert ("Live flags are unavailable right now." in _captions(app)) is (not live) + assert "Live flags are unavailable right now." not in _captions(app) + assert "1. **Derivatives** — 8 students are stuck here" in _markdown(app) @pytest.mark.parametrize("has_sample", [True, False]) @@ -1116,12 +1156,14 @@ def test_signed_in_user_can_flag_topic_and_sees_new_count(monkeypatch): app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert not app.exception - button = app.button(key=f"radar_flag_{CALCULUS_ID}_calc_derivatives") - assert button.label == "I'm stuck here" - assert "4 students are stuck here" in _markdown(app) + assert _reason_button_labels(app, "calc_derivatives") == REASON_BUTTON_LABELS + assert "I'm stuck here because…" in _captions(app) + assert not _has_clear_button(app, "calc_derivatives") + # The count appears once, above the buttons. + assert _markdown(app).count("4 students are stuck here") == 1 assert radar.calls["get_user_flags"] == [(TEST_USER.user_id, CALCULUS_ID)] - button.click().run() + _reason_button(app, "calc_derivatives").click().run() assert not app.exception assert radar.calls["set_flag"] == [ @@ -1131,9 +1173,9 @@ def test_signed_in_user_can_flag_topic_and_sees_new_count(monkeypatch): assert len(radar.calls["get_course_radar"]) == 2 assert len(radar.calls["get_user_flags"]) == 2 assert "5 students are stuck here" in _markdown(app) - assert app.button( - key=f"radar_flag_{CALCULUS_ID}_calc_derivatives" - ).label == "Not stuck anymore" + assert "You marked this topic." in _markdown(app) + assert _clear_button(app, "calc_derivatives").label == "Not stuck anymore" + assert _reason_button_labels(app, "calc_derivatives") == [] assert app.warning == [] @@ -1147,7 +1189,9 @@ def test_flagged_topic_offers_not_stuck_anymore(monkeypatch): app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert not app.exception - button = app.button(key=f"radar_flag_{CALCULUS_ID}_calc_derivatives") + assert "You marked this topic." in _markdown(app) + assert _reason_button_labels(app, "calc_derivatives") == [] + button = _clear_button(app, "calc_derivatives") assert button.label == "Not stuck anymore" button.click().run() @@ -1159,32 +1203,37 @@ def test_flagged_topic_offers_not_stuck_anymore(monkeypatch): assert radar.calls["set_flag"] == [] assert len(radar.calls["get_course_radar"]) == 2 assert "3 students are stuck here" in _markdown(app) - assert app.button( - key=f"radar_flag_{CALCULUS_ID}_calc_derivatives" - ).label == "I'm stuck here" + assert "You marked this topic." not in _markdown(app) + assert _reason_button_labels(app, "calc_derivatives") == REASON_BUTTON_LABELS -def test_failed_flag_shows_message_and_does_not_raise(monkeypatch): - message = "Live flags are unavailable right now. Please try again later." +@pytest.mark.parametrize("flagged", [False, True]) +def test_failed_write_shows_a_generic_message_and_does_not_raise(monkeypatch, flagged): + message = "Learning Radar is not set up in the database yet; your flag was not saved." radar = RadarFake( monkeypatch, [_topic("calc_derivatives", real=4)], + user_flags={"calc_derivatives": "concept"} if flagged else None, write_result=PersistenceResult(success=False, message=message), ) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") - app.button(key=f"radar_flag_{CALCULUS_ID}_calc_derivatives").click().run() + if flagged: + _clear_button(app, "calc_derivatives").click().run() + else: + _reason_button(app, "calc_derivatives", "calculation").click().run() assert not app.exception - assert radar.calls["set_flag"] == [ + write = "clear_flag" if flagged else "set_flag" + assert radar.calls[write] == [ (TEST_USER.user_id, CALCULUS_ID, "calc_derivatives") ] - assert [item.value for item in app.warning] == [message] + assert [item.value for item in app.warning] == [GENERIC_FAILURE] + shown = _markdown(app) + _captions(app) + _infos(app) + assert not any("database" in value for value in shown) assert len(radar.calls["get_course_radar"]) == 1 assert "4 students are stuck here" in _markdown(app) - assert app.button( - key=f"radar_flag_{CALCULUS_ID}_calc_derivatives" - ).label == "I'm stuck here" + assert _has_clear_button(app, "calc_derivatives") is flagged def test_no_flag_button_without_signed_in_user(monkeypatch): @@ -1225,13 +1274,6 @@ def test_radar_is_reused_until_the_cache_expires(monkeypatch): "Turn on Accessibility in the sidebar for simpler wording and Chinese key terms." ) LIMITS_HINT_TEXT = "Many students are stuck here. Reviewing Limits first may help." -REASON_DISPLAY_LABELS = [ - "No specific reason", - "Concept unclear", - "Calculation errors", - "Can't understand the question", - "Don't know where to start", -] _NOT_PASSED = object() @@ -1279,21 +1321,6 @@ def _econ_course(): ) -def _reason_picker(app, topic_id, course_id=CALCULUS_ID): - return app.selectbox(key=f"radar_reason_{course_id}_{topic_id}") - - -def _reason_picker_keys(app): - return [ - box.key for box in app.selectbox - if box.key and box.key.startswith("radar_reason_") - ] - - -def _flag_button(app, topic_id): - return app.button(key=f"radar_flag_{CALCULUS_ID}_{topic_id}") - - def _infos(app): return [item.value for item in app.info] @@ -1312,14 +1339,14 @@ def _record_graph_nodes(monkeypatch): return rendered -def test_reason_options_list_no_reason_first_then_every_code(): +def test_reason_options_list_every_code_then_just_stuck(): assert knowledge_graph.RADAR_REASON_OPTIONS == ( - None, "concept", "calculation", "wording", "start", + "concept", "calculation", "wording", "start", None, ) assert [ knowledge_graph.radar_reason_label(option) for option in knowledge_graph.RADAR_REASON_OPTIONS - ] == REASON_DISPLAY_LABELS + ] == REASON_BUTTON_LABELS @pytest.mark.parametrize( @@ -1390,20 +1417,29 @@ def test_concept_lab_available_only_for_the_two_calculus_topics( assert knowledge_graph.concept_lab_available(course_id, topic_id) is available +def test_reason_selectbox_is_gone(monkeypatch): + RadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) + + app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") + + assert not app.exception + assert not any( + box.key and box.key.startswith("radar_reason_") for box in app.selectbox + ) + assert not any(box.label == "Why are you stuck?" for box in app.selectbox) + + @pytest.mark.parametrize("reason", ["concept", "calculation", "wording", "start"]) -def test_chosen_reason_reaches_set_flag_and_is_shown_once_flagged(monkeypatch, reason): +def test_one_click_reason_reaches_set_flag_and_is_shown_once_flagged(monkeypatch, reason): radar = ReasonRadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert not app.exception - picker = _reason_picker(app, "calc_derivatives") - assert picker.label == "Why are you stuck?" - assert picker.options == REASON_DISPLAY_LABELS - assert picker.value is None + button = _reason_button(app, "calc_derivatives", reason) + assert button.label == learning_radar.REASON_LABELS[reason] - picker.set_value(reason).run() - _flag_button(app, "calc_derivatives").click().run() + button.click().run() assert not app.exception assert radar.flag_reasons == [reason] @@ -1411,31 +1447,30 @@ def test_chosen_reason_reaches_set_flag_and_is_shown_once_flagged(monkeypatch, r (TEST_USER.user_id, CALCULUS_ID, "calc_derivatives") ] assert f"Your reason: {learning_radar.REASON_LABELS[reason]}" in _captions(app) - assert _flag_button(app, "calc_derivatives").label == "Not stuck anymore" - assert _reason_picker_keys(app) == [] + assert _clear_button(app, "calc_derivatives").label == "Not stuck anymore" + assert _reason_button_labels(app, "calc_derivatives") == [] -@pytest.mark.parametrize("pick_another_first", [False, True]) -def test_no_specific_reason_sends_none(monkeypatch, pick_another_first): +def test_just_stuck_sends_none(monkeypatch): radar = ReasonRadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") - if pick_another_first: - _reason_picker(app, "calc_derivatives").set_value("concept").run() - _reason_picker(app, "calc_derivatives").set_value(None).run() - _flag_button(app, "calc_derivatives").click().run() + button = _reason_button(app, "calc_derivatives") + assert button.label == "Just stuck" + button.click().run() assert not app.exception assert radar.flag_reasons == [None] assert radar.user_flags == {"calc_derivatives": None} - assert "Your reason: No specific reason" in _captions(app) + assert "You marked this topic." in _markdown(app) + assert not any(value.startswith("Your reason:") for value in _captions(app)) @pytest.mark.parametrize( - ("saved", "label"), - [("calculation", "Calculation errors"), (None, "No specific reason")], + ("saved", "caption"), + [("calculation", "Your reason: Calculation errors"), (None, None)], ) -def test_saved_reason_is_shown_and_changed_by_flagging_again(monkeypatch, saved, label): +def test_saved_reason_is_shown_and_changed_by_flagging_again(monkeypatch, saved, caption): radar = ReasonRadarFake( monkeypatch, [_topic("calc_derivatives", real=4)], @@ -1445,31 +1480,31 @@ def test_saved_reason_is_shown_and_changed_by_flagging_again(monkeypatch, saved, app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert not app.exception - assert f"Your reason: {label}" in _captions(app) - assert _flag_button(app, "calc_derivatives").label == "Not stuck anymore" - assert _reason_picker_keys(app) == [] + reason_captions = [value for value in _captions(app) if value.startswith("Your reason:")] + assert reason_captions == ([caption] if caption else []) + assert _clear_button(app, "calc_derivatives").label == "Not stuck anymore" + assert _reason_button_labels(app, "calc_derivatives") == [] # Changing the reason: remove the flag, then flag again with a new one. - _flag_button(app, "calc_derivatives").click().run() + _clear_button(app, "calc_derivatives").click().run() assert not app.exception assert radar.calls["clear_flag"] == [ (TEST_USER.user_id, CALCULUS_ID, "calc_derivatives") ] assert not any(value.startswith("Your reason:") for value in _captions(app)) - assert _reason_picker(app, "calc_derivatives").value is None + assert _reason_button_labels(app, "calc_derivatives") == REASON_BUTTON_LABELS - _reason_picker(app, "calc_derivatives").set_value("start").run() - _flag_button(app, "calc_derivatives").click().run() + _reason_button(app, "calc_derivatives", "start").click().run() assert not app.exception assert radar.flag_reasons == ["start"] assert "Your reason: Don't know where to start" in _captions(app) - assert f"Your reason: {label}" not in _captions(app) + assert _has_clear_button(app, "calc_derivatives") @pytest.mark.parametrize( - ("picked", "shown"), + ("clicked", "shown"), [ ("wording", True), ("concept", False), @@ -1478,26 +1513,26 @@ def test_saved_reason_is_shown_and_changed_by_flagging_again(monkeypatch, saved, (None, False), ], ) -def test_accessibility_pointer_follows_picked_reason(monkeypatch, picked, shown): +def test_accessibility_pointer_follows_clicked_reason(monkeypatch, clicked, shown): ReasonRadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert WORDING_HINT_TEXT not in _infos(app) - _reason_picker(app, "calc_derivatives").set_value(picked).run() + _reason_button(app, "calc_derivatives", clicked).click().run() assert not app.exception assert _infos(app).count(WORDING_HINT_TEXT) == (1 if shown else 0) -def test_accessibility_pointer_disappears_when_another_reason_is_picked(monkeypatch): +def test_accessibility_pointer_disappears_after_unflagging(monkeypatch): ReasonRadarFake(monkeypatch, [_topic("calc_derivatives", real=4)]) app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") - _reason_picker(app, "calc_derivatives").set_value("wording").run() + _reason_button(app, "calc_derivatives", "wording").click().run() assert WORDING_HINT_TEXT in _infos(app) - _reason_picker(app, "calc_derivatives").set_value("concept").run() + _clear_button(app, "calc_derivatives").click().run() assert not app.exception assert WORDING_HINT_TEXT not in _infos(app) @@ -1517,7 +1552,7 @@ def test_accessibility_pointer_follows_saved_reason(monkeypatch, saved, shown): app = _graph_page(_calculus_course(), signed_in=True, focus="calc_derivatives") assert not app.exception - assert _flag_button(app, "calc_derivatives").label == "Not stuck anymore" + assert _clear_button(app, "calc_derivatives").label == "Not stuck anymore" assert _infos(app).count(WORDING_HINT_TEXT) == (1 if shown else 0) @@ -1531,8 +1566,8 @@ def test_signed_out_user_sees_no_reason_controls(monkeypatch): assert not app.exception assert "4 students are stuck here" in _markdown(app) - assert _reason_picker_keys(app) == [] assert _radar_buttons(app) == [] + assert "I'm stuck here because…" not in _captions(app) assert not any(value.startswith("Your reason:") for value in _captions(app)) assert WORDING_HINT_TEXT not in _infos(app) assert radar.calls["get_user_flags"] == [] @@ -1778,7 +1813,114 @@ def test_non_demo_course_shows_no_reason_hint_or_concept_lab_controls(monkeypatc assert all( calls == [] for name, calls in radar.calls.items() if name != "radar_enabled" ) - assert _reason_picker_keys(app) == [] + assert _radar_buttons(app) == [] assert _concept_lab_buttons(app) == [] assert not any(value.startswith("Your reason:") for value in _captions(app)) assert _infos(app) == [] + assert not any("