Spaces:
Paused

MathematicsApps / app.py
jobinv's picture
Upload 27 files
e9f1e84 verified
Raw History Blame Contribute Delete
110 kB
"""Hugging Face Gradio entrypoint for M1 Mechanics Quest.""" from __future__ import annotations from pathlib import Path from html import escape import json import time import gradio as gr from collision_game import ( COLLISION_GAME_CSS, COLLISION_GAME_HTML, CREATIVE_EXPERIMENT_JS, collision_game_payload, ) from creative_questions import CREATIVE_SCENARIOS, build_creative_question, creative_status_markdown from diagrams import make_3d_diagram, make_feedback_animation, make_line_diagram from engine import DIFFICULTIES, TOPICS, generate_question, render_question, render_solution from evaluator import evaluate_submission from exam_engine import ( DEFAULT_READING_MINUTES, DEFAULT_TOTAL_SESSION_MINUTES, EXAM_CSS, EXAM_AUTO_SUBMIT_JS, EXAM_MAIN_TIMER_JS, EXAM_MANUAL_SUBMIT_JS, EXAM_MODE_TOGGLE_JS, EXAM_RESET_TIMER_JS, EXAM_SPECS, EXAM_START_CAPTURE_JS, EXAM_TOPIC_CHOICES, apply_question_timings, build_exam, export_locked_exam_pdf, extract_numbered_answer_sheet, grade_exam, reconstruct_exam, render_exam_header, render_exam_question, render_exam_results, render_ocr_mapping, safe_attempt_state, parse_numbered_answers, question_timer_js, ) from floating_tutor import FLOATING_TUTOR_CSS, FLOATING_TUTOR_VIEWPORT_JS from gamification import mastery_markdown, new_profile, profile_html, record_hint from interactive_lab import IMPACT_MODELS, build_custom_collision_question, custom_status_markdown from obe_engine import ( ACTIVITY_CATEGORIES, COMPONENTS, DEFAULT_WEIGHT_PERCENTAGES, OBE_CSS, add_extraordinary_activity, append_assessment_record, assessment_choices, calculate_obe_attainment, certificate_preview, export_certificate_pdf, latest_component_scores, mistake_analysis, mistake_context_question, obe_spider_chart, render_activities, render_obe_result, select_assessment, ) from question_intake import ( SUPPORTED_EXTENSIONS, bank_choices, bank_summary_markdown, export_bank_file, ingest_question_sources, load_bank, load_bank_record, ) from question_visualizer import ( QUESTION_VISUALIZER_CSS, QUESTION_VISUALIZER_HTML, QUESTION_VISUALIZER_JS, VISUAL_TOPIC_OPTIONS, infer_visual_payload, question_visual_payload, ) from theory import theory_for from tutor_chat import ( DEFAULT_OPEN_SOURCE_MODEL, DEFAULT_TUTOR_QUESTIONS, OPEN_SOURCE_TUTOR_MODELS, QWEN_ENGINE, TUTOR_ENGINES, chat_with_tutor, clear_tutor_chat, tutor_context_markdown, tutor_welcome, ) from worksheet_exports import export_worksheet_bundle APP_DIR = Path(__file__).resolve().parent # Hugging Face's web uploader can flatten or omit nested folders when files are # selected manually. Styling must never prevent the application from starting, # so try both expected locations and finally use a self-contained fallback. FALLBACK_CSS = """ .gradio-container {max-width: 1500px !important; background: linear-gradient(145deg,#f8fbff,#f5f3ff 55%,#fff7fb);} .hero {padding: 32px; border-radius: 26px; color: white; background: linear-gradient(120deg,#312e81,#6d28d9 48%,#db2777); box-shadow: 0 20px 55px rgba(76,29,149,.24); margin-bottom: 18px;} .hero h1 {font-size: clamp(34px,5vw,64px); line-height: 1; margin: 15px 0 10px;} .hero p {max-width: 800px; color: rgba(255,255,255,.86); font-size: 17px;} .hero-kicker {display:inline-block;padding:7px 12px;border:1px solid rgba(255,255,255,.35);border-radius:999px;background:rgba(255,255,255,.13);font-size:12px;font-weight:800;} .feature-strip {display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:12px 0 18px;} .feature-strip div,.profile-card,.question-panel,.coach-panel,.glass-panel {background:rgba(255,255,255,.88);border:1px solid rgba(99,102,241,.16);border-radius:18px;padding:14px;box-shadow:0 12px 35px rgba(30,41,59,.08);} .feature-strip b {display:block;color:#172554;margin-bottom:3px;} .question-panel {border-left:5px solid #06b6d4;padding:18px 24px !important;} .question-kicker {display:inline-block;padding:6px 10px;border-radius:999px;color:#5b21b6;background:#ede9fe;font-weight:800;font-size:12px;} .question-foot {margin-top:20px;color:#64748b;font-size:12px;border-top:1px dashed #cbd5e1;padding-top:11px;} .primary-btn {color:white !important;border:none !important;font-weight:800 !important;background:linear-gradient(100deg,#6d28d9,#ec4899) !important;} .submit-btn {color:white !important;border:none !important;font-weight:800 !important;background:linear-gradient(100deg,#0891b2,#2563eb) !important;} .profile-level,.profile-stats {display:flex;justify-content:space-between;gap:10px;}.xp-track{height:10px;background:#e2e8f0;border-radius:99px;margin:10px 0;overflow:hidden}.xp-fill{height:100%;background:linear-gradient(90deg,#22d3ee,#8b5cf6,#ec4899)} .profile-stats div{display:flex;flex-direction:column;align-items:center;padding:8px;background:#f8fafc;border-radius:12px;flex:1}.profile-stats span{font-size:11px;color:#64748b}.heart-text{color:#f43f5e}.badge-chip,.muted-chip{display:inline-block;margin:8px 4px 0 0;padding:5px 9px;border-radius:99px;background:#fef3c7;font-size:11px}.privacy-note{padding:11px 13px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:14px;font-size:12px}.hint-card{padding:13px 15px;border-left:4px solid #f59e0b;background:#fffbeb;border-radius:12px}.footer-note{text-align:center;color:#64748b;font-size:12px;padding:20px} @media(max-width:760px){.feature-strip{grid-template-columns:repeat(2,1fr)}.hero{padding:24px}.question-panel{padding:14px !important}} """ # Gradio normally measures long tab labels and moves the excess into a # three-dot "More tabs" menu. This app has exactly twelve primary workspaces, # so keep all of them available in a deliberate six-by-two navigation grid. # The visually-hidden selector makes Gradio's overflow measurement report zero # excess width; the role=tablist selector controls the actual visible buttons. ALWAYS_VISIBLE_TAB_CSS = r""" #training-tabs .tab-wrapper { align-items: stretch !important; backdrop-filter: blur(18px); background: rgba(248, 250, 252, .96) !important; border: 1px solid rgba(109, 40, 217, .16); border-radius: 18px; box-shadow: 0 12px 30px rgba(30, 41, 59, .10); height: auto !important; margin-bottom: 16px !important; min-height: 112px; overflow: visible !important; padding: 7px !important; position: sticky !important; top: 0 !important; z-index: 80 !important; } #training-tabs .tab-container[role="tablist"] { align-items: stretch !important; display: grid !important; gap: 7px !important; grid-template-columns: repeat(6, minmax(0, 1fr)) !important; grid-template-rows: repeat(2, minmax(48px, auto)) !important; height: auto !important; overflow: visible !important; width: 100% !important; } #training-tabs .tab-container[role="tablist"]::after { display: none !important; } #training-tabs .tab-container[role="tablist"] button[role="tab"] { align-items: center !important; background: rgba(255, 255, 255, .92) !important; border: 1px solid #ddd6fe !important; border-radius: 11px !important; color: #312e81 !important; display: flex !important; font-size: clamp(10px, .86vw, 13px) !important; font-weight: 800 !important; height: auto !important; justify-content: center !important; line-height: 1.18 !important; min-height: 48px !important; overflow-wrap: anywhere !important; padding: 7px 6px !important; text-align: center !important; white-space: normal !important; width: 100% !important; } #training-tabs .tab-container[role="tablist"] button[role="tab"]:hover:not(:disabled) { background: #f5f3ff !important; border-color: #a78bfa !important; transform: translateY(-1px); } #training-tabs .tab-container[role="tablist"] button[role="tab"].selected { background: linear-gradient(110deg, #6d28d9, #db2777) !important; border-color: transparent !important; box-shadow: 0 7px 16px rgba(109, 40, 217, .22) !important; color: white !important; } #training-tabs .tab-container[role="tablist"] button[role="tab"].selected::after { display: none !important; } /* Keep all twelve tabs in the visible tablist instead of Gradio's overflow. */ #training-tabs .tab-container.visually-hidden button { display: none !important; font-size: 0 !important; min-width: 0 !important; padding: 0 !important; width: 0 !important; } #training-tabs .overflow-menu { display: none !important; } @media (max-width: 760px) { #training-tabs .tab-wrapper { padding: 5px !important; } #training-tabs .tab-container[role="tablist"] { gap: 4px !important; } #training-tabs .tab-container[role="tablist"] button[role="tab"] { font-size: 8.5px !important; min-height: 54px !important; padding: 5px 2px !important; } } """ def load_css(base_dir: Path = APP_DIR) -> str: for candidate in (base_dir / "assets" / "style.css", base_dir / "style.css"): try: if candidate.is_file(): return candidate.read_text(encoding="utf-8") except OSError: pass return FALLBACK_CSS CSS = ( load_css() + "\n" + FLOATING_TUTOR_CSS + "\n" + EXAM_CSS + "\n" + OBE_CSS + "\n" + ALWAYS_VISIBLE_TAB_CSS ) # Gradio enables display mathematics by default, but single-dollar inline # mathematics is opt-in. Every learner-facing mathematics panel uses this # shared configuration so symbols, units and exponents render through KaTeX. LATEX_DELIMITERS = [ {"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}, ] INITIAL_SEED = 20260813 INITIAL_PROFILE = new_profile() INITIAL_QUESTION = generate_question("Mixed mission", "Exam standard", INITIAL_SEED) INITIAL_CUSTOM_QUESTION = build_custom_collision_question(context="interactive engineering laboratory") INITIAL_BANK = load_bank() INITIAL_BANK_RECORD = INITIAL_BANK[-1] if INITIAL_BANK else None INITIAL_IMPORTED_PAYLOAD = json.dumps( INITIAL_BANK_RECORD["visual_payload"] if INITIAL_BANK_RECORD else infer_visual_payload( "Two masses of 3 kg and 5 kg are released from a height of 20 m. " "They fall freely under gravity with acceleration 9.8 m/s².", "Vertical motion / falling masses", "Example imported question", ), separators=(",", ":"), ) def create_mission(topic: str, difficulty: str, seed: str, profile: dict): q = generate_question(topic, difficulty, seed) return ( q, render_question(q), question_visual_payload(q), make_line_diagram(q), make_3d_diagram(q), theory_for(q), "", "", 0, str(q["seed"]), profile_html(profile), tutor_context_markdown(q), tutor_welcome(q), tutor_context_markdown(q), tutor_welcome(q), q, ) def _bank_record_markdown(record: dict | None) -> str: if not record: return "Select an imported question to inspect it." prompt = escape(str(record.get("prompt", ""))) return ( f"<div class=\"question-kicker\">{escape(str(record.get('topic', 'Mechanics')))} · " f"{escape(str(record.get('source', 'question intake')))}</div>\n\n" f"## {escape(str(record.get('title', 'Imported question')))}\n\n{prompt}" ) def add_questions_to_bank( typed_text, uploaded_files, audio_question, title_prefix, topic_hint, split_mode, ): result = ingest_question_sources( typed_text, uploaded_files, audio_question, title_prefix, topic_hint, split_mode, ) records = result["records"] selected_id = result.get("selected_id") record = next((item for item in records if item.get("id") == selected_id), None) payload = result.get("visual_payload") return ( result["status"], result["extracted_text"], bank_summary_markdown(records), gr.update(choices=bank_choices(records), value=selected_id), json.dumps(payload, separators=(",", ":")) if payload else INITIAL_IMPORTED_PAYLOAD, _bank_record_markdown(record), ) def open_bank_question(record_id: str): record = load_bank_record(record_id) if not record: return "Question not found in the current bank.", INITIAL_IMPORTED_PAYLOAD return ( _bank_record_markdown(record), json.dumps(record.get("visual_payload", {}), separators=(",", ":")), ) def next_hint(question: dict, index: int, profile: dict): if not question: return "Generate a mission first.", 0, profile, profile_html(profile) hints = question.get("hints", []) if not hints: return "No hint is needed for this mission.", 0, profile, profile_html(profile) idx = min(int(index or 0), len(hints) - 1) profile = record_hint(profile) message = f'<div class="hint-card"><b>Hint {idx + 1}/{len(hints)}</b><br>{hints[idx]}</div>' return message, min(idx + 1, len(hints) - 1), profile, profile_html(profile) def reveal_solution(question: dict): return render_solution(question) def assess_work(question: dict, image, final_answer: str, use_ai_vision: bool, profile: dict): result = evaluate_submission(question, image, final_answer, profile, use_ai_vision) animation = make_feedback_animation(question, result["correct"]) return ( result["feedback"], animation, result["ocr"], result["profile"], profile_html(result["profile"]), mastery_markdown(result["profile"]), ) def reset_progress(): p = new_profile() return p, profile_html(p), mastery_markdown(p) def chat_in_floating_tutor( question: dict, message: str, tutor_engine: str, open_source_model: str, history: list[dict] | None, ): """Answer a typed question using the active problem and verified solution.""" updated_history, cleared_text, _, _, status = chat_with_tutor( question, message, None, None, tutor_engine, history, open_source_model, ) return updated_history, cleared_text, status def show_floating_tutor(): """Open the native Gradio tutor dialog.""" return gr.update(visible=True) def show_floating_tutor_slot(selected_slot: str): """Open one fixed tutor and close the other two to avoid overlap.""" selected = str(selected_slot or "bottom").strip().lower() return tuple( gr.update(visible=slot == selected) for slot in ("top", "middle", "bottom") ) def hide_floating_tutor(): """Close the native Gradio tutor dialog.""" return gr.update(visible=False) def open_full_tutor_tab(): """Switch to the full tutor and close the compact dialog.""" return gr.update(selected="mechanics-tutor"), gr.update(visible=False) def sync_floating_tutor_copies(question: dict): """Refresh the top and middle copies when the active problem changes.""" context = tutor_context_markdown(question) welcome = tutor_welcome(question) return context, welcome, context, welcome def build_worksheet(topic: str, difficulty: str, count: int, start_seed: str): try: base = int(start_seed) except (TypeError, ValueError): base = INITIAL_SEED questions = [generate_question(topic, difficulty, base + i * 7919) for i in range(int(count))] question_sections = [] for i, q in enumerate(questions, 1): question_sections.append( f"## Question {i} · {q['topic_label']} ({q['marks']} marks)\n\n{q['prompt'].strip()}\n\n" ) markdown_file, word_file, pdf_file = export_worksheet_bundle( questions, difficulty, base ) preview = "\n\n---\n\n".join(question_sections[:3]) if len(questions) > 3: preview += f"\n\n*…plus {len(questions) - 3} more questions in the downloadable worksheet.*" return markdown_file, word_file, pdf_file, preview def update_creative_lab( scenario: str, context: str, difficulty: str, impact_model: str, restitution: float, mass_p: float, mass_q: float, distance: float, friction_p: float, friction_q: float, velocity_p: float, velocity_q: float, acceleration_p: float, acceleration_q: float, train_mass: float, train_u: float, train_a: float, train_accel_time: float, train_cruise_time: float, train_braking: float, train_resistance: float, rocket_mass: float, rocket_height: float, rocket_u: float, rocket_g: float, trolley_mass: float, trolley_force: float, trolley_angle: float, trolley_mu: float, trolley_u: float, trolley_time: float, ): question = build_creative_question( scenario, context, difficulty, impact_model, restitution, mass_p, mass_q, distance, friction_p, friction_q, velocity_p, velocity_q, acceleration_p, acceleration_q, train_mass, train_u, train_a, train_accel_time, train_cruise_time, train_braking, train_resistance, rocket_mass, rocket_height, rocket_u, rocket_g, trolley_mass, trolley_force, trolley_angle, trolley_mu, trolley_u, trolley_time, ) return ( question, creative_status_markdown(question), collision_game_payload(question), make_line_diagram(question), make_3d_diagram(question), render_question(question), "", theory_for(question), "Submit your working to open a motion replay based on your chosen parameters.", make_feedback_animation(question, None), "No submission yet.", tutor_context_markdown(question), tutor_welcome(question), question, ) def show_creative_controls(scenario: str): return ( gr.update(visible=scenario == CREATIVE_SCENARIOS[0]), gr.update(visible=scenario == CREATIVE_SCENARIOS[1]), gr.update(visible=scenario == CREATIVE_SCENARIOS[2]), gr.update(visible=scenario == CREATIVE_SCENARIOS[3]), ) def export_custom_question(question: dict): if not question: question = INITIAL_CUSTOM_QUESTION return export_worksheet_bundle( [question], question.get("difficulty", "Exam standard"), question.get("seed", INITIAL_SEED) ) MAX_EXAM_QUESTIONS = 40 def switch_exam_mode(enabled: bool): """Hide every training surface while the examination section is active.""" active = bool(enabled) message = ( "🔒 **Examination mode is active.** Training tabs, worksheet tools, theory, progress, and all Ask Teacher bots are unavailable." if active else "Training mode is active. Turn on the switch when the student is ready for a protected examination attempt." ) return ( gr.update(visible=not active), gr.update(visible=not active), gr.update(visible=active), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), message, ) def start_exam_interface( student_name: str, exam_name: str, trained_topics: list[str] | None, exam_seed: str, midterm_1_count: int, midterm_2_count: int, final_count: int, total_session_minutes: int, one_minute_questions: str, two_minute_questions: str, three_minute_questions: str, four_minute_questions: str, five_minute_questions: str, six_minute_questions: str, seven_minute_questions: str, ): count_map = { "Midterm 1": int(midterm_1_count), "Midterm 2": int(midterm_2_count), "Final examination": int(final_count), } question_count = count_map.get(exam_name, int(midterm_1_count)) exam = build_exam(exam_name, trained_topics, exam_seed, student_name, question_count) manual_timings = { 1: one_minute_questions, 2: two_minute_questions, 3: three_minute_questions, 4: four_minute_questions, 5: five_minute_questions, 6: six_minute_questions, 7: seven_minute_questions, } try: exam = apply_question_timings(exam, manual_timings) except ValueError as exc: raise gr.Error(str(exc)) from exc total_minutes = max(20, min(DEFAULT_TOTAL_SESSION_MINUTES, int(total_session_minutes))) started_epoch_ms = int(time.time() * 1000) exam.update( { "total_session_minutes": total_minutes, "reading_minutes": DEFAULT_READING_MINUTES, "started_epoch_ms": started_epoch_ms, "deadline_epoch_ms": started_epoch_ms + total_minutes * 60_000, } ) attempt = safe_attempt_state(exam) values: list = [ attempt, render_exam_header(exam), ( f"🔒 **{exam['exam_label']} started.** The examination switch and paper settings are locked until submission. " "All Ask Teacher bots and training sections remain disabled." ), gr.update(value=True, interactive=False), gr.update(value=exam["exam_name"], interactive=False), gr.update(value=exam["topics"], interactive=False), gr.update(value=str(exam["seed"]), interactive=False), gr.update(value=exam["student"], interactive=False), gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), gr.update(value=total_minutes, interactive=False), *[gr.update(interactive=False) for _ in range(7)], gr.update(interactive=False), gr.update(value=False, interactive=True), gr.update(value=None, interactive=True), {}, "No handwritten answer sheet has been read.", gr.update(interactive=True), gr.update(interactive=True), gr.update(visible=False), "", "", None, total_minutes, DEFAULT_READING_MINUTES, exam["attempt_id"], '<div class="exam-main-timer"><strong>Starting protected clock…</strong><br>The reading and setup phase begins immediately.</div>', ] for index in range(MAX_EXAM_QUESTIONS): visible = index < exam["count"] duration = exam["question_timings"][index] if visible else 1 values.extend( [ gr.update(visible=visible), render_exam_question(exam["questions"][index]) if visible else "", gr.update(value="", interactive=False), duration, ( f'<div class="exam-question-timer"><b>Suggested time: {duration} minute' f'{"s" if duration != 1 else ""}.</b> Available after the reading phase.</div>' if visible else "" ), gr.update( value=f"Start Q{index + 1} timer · {duration} min", visible=visible, interactive=False, ), ] ) return tuple(values) def read_exam_answer_sheet(files, attempt: dict | None): maximum = int((attempt or {}).get("count", MAX_EXAM_QUESTIONS)) result = extract_numbered_answer_sheet(files, maximum=maximum) return result, render_ocr_mapping(result) def submit_exam_interface( attempt: dict | None, uploaded_answer_sheets, ocr_state: dict | None, declaration: bool, assessment_history: list[dict] | None, *typed_answers: str, ): unchanged = [gr.update() for _ in range(MAX_EXAM_QUESTIONS * 2)] if not declaration: return ( gr.update(), gr.update(), gr.update(), "⚠️ Tick the examination declaration before submitting the paper.", attempt or {}, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ocr_state or {}, gr.update(), gr.update(), assessment_history or [], *unchanged, ) exam = reconstruct_exam(attempt) if not exam or (attempt or {}).get("submitted"): return ( gr.update(), gr.update(), gr.update(), "⚠️ No active unsubmitted examination was found. Start a new examination.", attempt or {}, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ocr_state or {}, gr.update(), gr.update(), assessment_history or [], *unchanged, ) sheet_result = ocr_state or {} if uploaded_answer_sheets and not sheet_result.get("answers"): sheet_result = extract_numbered_answer_sheet( uploaded_answer_sheets, maximum=exam["count"] ) grade = grade_exam(exam, typed_answers[: exam["count"]], sheet_result.get("answers", {})) summary, solutions = render_exam_results(grade) pdf_path = export_locked_exam_pdf(exam, grade) completed_attempt = dict(attempt or {}) completed_attempt.update( { "submitted": True, "score": grade["score"], "maximum": grade["maximum"], "percentage": grade["percentage"], } ) frozen_answers = [gr.update(interactive=False) for _ in range(MAX_EXAM_QUESTIONS)] frozen_timers = [gr.update(interactive=False) for _ in range(MAX_EXAM_QUESTIONS)] timed_out = int(time.time() * 1000) >= int((attempt or {}).get("deadline_epoch_ms", 2**63 - 1)) updated_history = append_assessment_record( assessment_history, exam["exam_name"], grade, exam ) return ( summary, solutions, pdf_path, ( f"{'⏰ Time expired — automatically submitted and locked' if timed_out else '✅ Submitted and locked'}: " f"{grade['score']:g}/{grade['maximum']} marks ({grade['percentage']:.1f}%). " "Solutions are now visible and the read-only PDF report is ready." ), completed_attempt, gr.update(value=True, interactive=True), gr.update(interactive=False), gr.update(value=False, interactive=False), gr.update(interactive=False), gr.update(interactive=False), gr.update(visible=True), sheet_result, render_ocr_mapping(sheet_result), '<div class="exam-main-timer"><strong>EXAMINATION COMPLETED</strong><br>Answers are locked. The result and printable report have been generated.</div>', updated_history, *frozen_answers, *frozen_timers, ) def auto_submit_exam_interface( attempt: dict | None, uploaded_answer_sheets, ocr_state: dict | None, assessment_history: list[dict] | None, *typed_answers: str, ): """Deadline-triggered submission does not require the learner declaration.""" return submit_exam_interface( attempt, uploaded_answer_sheets, ocr_state, True, assessment_history, *typed_answers, ) def unlock_exam_inputs(attempt: dict | None): active = bool(attempt and attempt.get("started") and not attempt.get("submitted")) within_deadline = int(time.time() * 1000) < int((attempt or {}).get("deadline_epoch_ms", 0)) count = int((attempt or {}).get("count", 0)) if active and within_deadline else 0 answer_updates = [gr.update(interactive=index < count) for index in range(MAX_EXAM_QUESTIONS)] timer_updates = [gr.update(interactive=index < count) for index in range(MAX_EXAM_QUESTIONS)] return (*answer_updates, *timer_updates) def reset_exam_interface(): values: list = [ {}, "Choose the examination and trained topics, then start a protected attempt.", "Examination mode is active. Paper settings are ready for a new attempt.", gr.update(value=True, interactive=True), gr.update(interactive=True), gr.update(interactive=True), gr.update(value="", interactive=True), gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), gr.update(value=DEFAULT_TOTAL_SESSION_MINUTES, interactive=True), *[gr.update(interactive=True) for _ in range(7)], gr.update(interactive=True), gr.update(value=False, interactive=True), gr.update(value=None, interactive=True), {}, "No handwritten answer sheet has been read.", gr.update(interactive=True), gr.update(interactive=True), gr.update(visible=False), "", "", None, DEFAULT_TOTAL_SESSION_MINUTES, DEFAULT_READING_MINUTES, "", '<div class="exam-main-timer"><strong>Timer not started</strong><br>Start a protected examination to begin the reading and overall-session clocks.</div>', ] for _ in range(MAX_EXAM_QUESTIONS): values.extend( [ gr.update(visible=False), "", gr.update(value="", interactive=False), 1, "", gr.update(value="Start question timer", visible=False, interactive=False), ] ) return tuple(values) def generate_assignment_interface( student_name: str, assignment_title: str, trained_topics: list[str] | None, question_count: int, assignment_seed: str, ): exam = build_exam( "Midterm 1", trained_topics, assignment_seed, student_name, int(question_count), ) title = str(assignment_title or "Mechanics assignment").strip()[:120] or "Mechanics assignment" exam["exam_label"] = f"Assignment · {title}" state = safe_attempt_state(exam) state["assignment_title"] = title question_sections = "\n\n---\n\n".join( render_exam_question(question) for question in exam["questions"] ) paper = f""" ## {escape(exam['exam_label'])} **Student:** {escape(exam['student'])} · **Questions:** {exam['count']} · **Total:** {exam['total_marks']} marks · **Assignment ID:** `{exam['attempt_id']}` Enter typed answers using `Q1`, `Q2`, … headings, or upload numbered handwritten images/PDF in the submission portal. --- {question_sections} """ return ( state, paper, "Assignment generated. Solutions remain hidden until the submission is evaluated.", "", "", None, gr.update(value="", interactive=True), gr.update(value=None, interactive=True), gr.update(interactive=True), ) def submit_assignment_interface( assignment_state: dict | None, typed_numbered_answers: str, uploaded_files, assessment_history: list[dict] | None, ): exam = reconstruct_exam(assignment_state) if not exam: return ( "Generate an assignment before submitting work.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), assessment_history or [], ) exam["exam_label"] = f"Assignment · {(assignment_state or {}).get('assignment_title', 'Mechanics assignment')}" typed_map = parse_numbered_answers(typed_numbered_answers, maximum=exam["count"]) if not typed_map and str(typed_numbered_answers or "").strip() and exam["count"] == 1: typed_map = {1: str(typed_numbered_answers).strip()} sheet_result = extract_numbered_answer_sheet(uploaded_files, maximum=exam["count"]) if uploaded_files else {"answers": {}, "raw_text": "", "status": []} typed_list = [typed_map.get(number, "") for number in range(1, exam["count"] + 1)] grade = grade_exam(exam, typed_list, sheet_result.get("answers", {})) summary, solutions = render_exam_results(grade) pdf_path = export_locked_exam_pdf(exam, grade) updated_history = append_assessment_record( assessment_history, "Assignment", grade, exam ) return ( f"✅ Assignment submitted and evaluated: **{grade['score']:g}/{grade['maximum']} marks ({grade['percentage']:.1f}%)**.", summary, solutions, pdf_path, gr.update(interactive=False), gr.update(interactive=False), updated_history, ) def record_extraordinary_activity_interface( records: list[dict] | None, student: str, title: str, category: str, description: str, marks_obtained: float, maximum_marks: float, evidence_files, ): try: updated = add_extraordinary_activity( records, student, title, category, description, marks_obtained, maximum_marks, evidence_files, ) except ValueError as exc: return records or [], render_activities(records), f"⚠️ {exc}", gr.update(), gr.update(), gr.update() return ( updated, render_activities(updated), "✅ Extraordinary activity recorded and included in the OBE data source.", "", "", None, ) def clear_extraordinary_activities_interface(): return [], render_activities([]), "Extraordinary activity records were cleared for this session." def load_obe_scores_interface( assessment_history: list[dict] | None, activities: list[dict] | None, ): scores = latest_component_scores(assessment_history, activities) student = next( (str(record.get("student", "Student")) for record in reversed(assessment_history or [])), next((str(record.get("student", "Student")) for record in reversed(activities or [])), "Student"), ) values: list = [student] for component in COMPONENTS: values.extend(scores[component]) return (*values, "✅ Loaded the latest recorded assessment and activity scores. You may adjust any field before computing attainment.") def compute_obe_interface(student: str, *values): score_values = values[: len(COMPONENTS) * 2] weight_values = values[len(COMPONENTS) * 2 :] scores = { component: (score_values[index * 2], score_values[index * 2 + 1]) for index, component in enumerate(COMPONENTS) } weights = { component: weight_values[index] for index, component in enumerate(COMPONENTS) } try: result = calculate_obe_attainment(student, scores, weights) except ValueError as exc: return {}, f"## OBE calculation needs attention\n\n⚠️ {escape(str(exc))}", obe_spider_chart(), f"⚠️ {exc}" return ( result, render_obe_result(result), obe_spider_chart(result), f"✅ Attainment computed: {result['attainment']:.3f}/3.000. Weight total: {sum(result['weights'].values()):.1f}%.", ) def refresh_mistake_assessments_interface(history: list[dict] | None): choices = assessment_choices(history) value = choices[0][1] if choices else None status = ( f"Found {len(choices)} completed assessment{'s' if len(choices) != 1 else ''}. Select one and analyse it." if choices else "No completed examination or assignment is available yet. Submit one first." ) return gr.update(choices=choices, value=value), status def analyse_mistakes_interface(history: list[dict] | None, selection: str): record = select_assessment(history, selection) if not record: return {}, mistake_analysis(None), tutor_welcome(None), "Select a completed assessment first." question = mistake_context_question(record) return record, mistake_analysis(record), tutor_welcome(question), "✅ Question-level mistakes and improvement priorities are ready." def chat_about_mistakes_interface( record: dict | None, message: str, tutor_engine: str, open_source_model: str, history: list[dict] | None, ): if not record: return history or tutor_welcome(None), message, "Select and analyse a completed assessment before asking about mistakes." response = chat_with_tutor( mistake_context_question(record), message, None, None, tutor_engine, history, open_source_model, ) return response[0], response[1], response[4] def clear_mistake_chat_interface(record: dict | None): question = mistake_context_question(record) if record else None return tutor_welcome(question), "Conversation cleared; the selected assessment remains linked." def generate_certificate_interface(result: dict | None): if not result: return ( '<div class="certificate-preview"><h2>Compute OBE attainment first</h2><p>The certificate uses the current OBE result and student name.</p></div>', None, "Compute OBE attainment before generating a certificate.", ) pdf_path = export_certificate_pdf(result) if not pdf_path: return certificate_preview(result), None, "A certificate is generated only at 60% attainment or above. Follow the improvement plan and recompute the score." return certificate_preview(result), pdf_path, "✅ Congratulations! The protected, print-enabled certificate PDF is ready." theme = gr.themes.Soft( primary_hue="violet", secondary_hue="pink", neutral_hue="slate", font=[gr.themes.GoogleFont("DM Sans"), "Arial", "sans-serif"], ) with gr.Blocks(title="M1 Mechanics Quest", fill_width=True) as demo: question_state = gr.State(INITIAL_QUESTION) profile_state = gr.State(INITIAL_PROFILE) hint_index_state = gr.State(0) custom_question_state = gr.State(INITIAL_CUSTOM_QUESTION) floating_question_state = gr.State(INITIAL_QUESTION) exam_attempt_state = gr.State({}) exam_ocr_state = gr.State({}) assignment_state = gr.State({}) assessment_history_state = gr.State([]) extraordinary_activities_state = gr.State([]) obe_result_state = gr.State({}) mistake_record_state = gr.State({}) gr.HTML(""" <section class="hero"> <span class="hero-kicker">🚀 Pearson Edexcel IAL · Mechanics 1 practice</span> <h1>M1 Mechanics Quest</h1> <p>Generate fresh exam-style missions, rotate the mechanics in 3D, upload handwritten working, and turn every correction into XP.</p> </section> <section class="feature-strip"> <div><b>∞ Original questions</b>Seeded, reproducible parameters</div> <div><b>◈ Dual diagrams</b>2D exam lines + coloured 3D</div> <div><b>✎ Work-photo coach</b>OCR with optional vision review</div> <div><b>⚡ Game loop</b>XP, streaks, hearts and badges</div> </section> """) with gr.Group(elem_classes=["exam-mode-shell"]): with gr.Row(equal_height=True): with gr.Column(scale=4): gr.Markdown( "### 🛡️ Examination lock\nActivate this only when the student is ready. During an active attempt, training tabs and all Ask Teacher bots are unavailable until submission." ) with gr.Column(scale=2): exam_mode_toggle = gr.Checkbox( label="Activate examination section", value=False, elem_id="exam-mode-toggle", ) exam_mode_status = gr.Markdown( "Training mode is active. Turn on the switch when the student is ready for a protected examination attempt." ) with gr.Group(visible=True) as training_controls: with gr.Row(equal_height=False): with gr.Column(scale=3, elem_classes=["glass-panel", "control-panel"]): gr.Markdown("### Mission generator") topic = gr.Dropdown(list(TOPICS), value="Mixed mission", label="Skill zone") difficulty = gr.Radio(list(DIFFICULTIES), value="Exam standard", label="Challenge level") seed = gr.Textbox(value=str(INITIAL_SEED), label="Seed", info="Reuse a seed to recreate the same question") generate_btn = gr.Button("Generate new mission ✦", variant="primary", elem_classes=["primary-btn"]) with gr.Column(scale=2): profile_panel = gr.HTML(profile_html(INITIAL_PROFILE)) with gr.Tabs(visible=True, elem_id="training-tabs") as app_tabs: with gr.Tab("🎯 Mission control"): question_md = gr.Markdown( render_question(INITIAL_QUESTION), latex_delimiters=LATEX_DELIMITERS, elem_classes=["question-panel"], ) gr.Markdown("## See, animate, and vary the question concept") mission_visual = gr.HTML( value=question_visual_payload(INITIAL_QUESTION), label="Interactive visual concept", html_template=QUESTION_VISUALIZER_HTML, css_template=QUESTION_VISUALIZER_CSS, js_on_load=QUESTION_VISUALIZER_JS, apply_default_css=False, container=False, ) with gr.Row(): line_plot = gr.Plot(make_line_diagram(INITIAL_QUESTION), label="2D line diagram") model_plot = gr.Plot(make_3d_diagram(INITIAL_QUESTION), label="3D model") with gr.Row(): hint_btn = gr.Button("Unlock next hint 💡") solution_btn = gr.Button("Reveal worked solution", variant="secondary") hint_md = gr.HTML() solution_md = gr.Markdown( latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"], ) gr.Markdown("## Submit your working") with gr.Row(equal_height=False): with gr.Column(scale=1): work_image = gr.Image( label="Photo or scan of handwritten working", type="pil", image_mode="RGB", sources=["upload", "webcam", "clipboard"], height=360, ) with gr.Column(scale=1): final_answer = gr.Textbox( label="Confirm final answer(s)", placeholder="Example: 4.2, 36.8 (use question order)", lines=2, info="Recommended because handwriting OCR can confuse signs, powers and fractions.", ) use_ai_vision = gr.Checkbox( label="Use optional AI vision tutor", value=False, info="Requires OPENAI_API_KEY in Space secrets; the image is sent to that API only when checked.", ) gr.HTML('<div class="privacy-note">🔒 Local OCR is the default. The optional vision tutor is off unless the learner explicitly enables it.</div>') assess_btn = gr.Button("Analyse my method ⚡", variant="primary", elem_classes=["submit-btn"]) with gr.Row(equal_height=False): feedback_md = gr.Markdown( "Submit a worked solution to open the correction replay.", latex_delimiters=LATEX_DELIMITERS, elem_classes=["coach-panel"], ) feedback_plot = gr.Plot(make_feedback_animation(INITIAL_QUESTION, None), label="Animated correction replay") with gr.Accordion("What the image reader detected", open=False): ocr_md = gr.Markdown("No submission yet.") with gr.Tab("🧪 Creative mechanics lab"): gr.Markdown(""" ## Build and play the experiment described by the question Choose an experiment and change its physical parameters. The object, scenery, question, animation, sound effects, diagrams, theory and worked solution all change together from the same validated model. """) with gr.Row(equal_height=False): with gr.Column(scale=2, elem_classes=["glass-panel"]): custom_scenario = gr.Dropdown( list(CREATIVE_SCENARIOS), value=CREATIVE_SCENARIOS[0], label="Experiment and question type", ) custom_context = gr.Textbox( value="interactive engineering laboratory", label="Creative setting", info="Examples: coastal railway, lunar launch site, warehouse lane, robotics arena", ) with gr.Column(scale=2, elem_classes=["glass-panel"]): custom_difficulty = gr.Radio( list(DIFFICULTIES), value="Exam standard", label="Question depth" ) gr.Markdown("Negative velocity or acceleration means motion or acceleration to the left/downward.") with gr.Group(visible=True) as collision_controls: gr.Markdown("### Roller collision parameters") with gr.Row(equal_height=False): with gr.Column(scale=2, elem_classes=["glass-panel"]): custom_impact_model = gr.Radio( list(IMPACT_MODELS), value=IMPACT_MODELS[1], label="Impact behaviour" ) custom_restitution = gr.Slider( 0, 1, value=0.65, step=0.05, label="Coefficient of restitution e", info="Used only when the rollers separate after impact.", ) custom_distance = gr.Slider(3, 30, value=12, step=0.5, label="Initial separation d (m)") with gr.Column(scale=2, elem_classes=["glass-panel"]): gr.Markdown("#### Roller P · cyan") custom_mass_p = gr.Slider(1, 12, value=4, step=0.5, label="Mass P (kg) · changes roller size") custom_velocity_p = gr.Slider(-20, 20, value=8, step=0.5, label="Initial velocity P (m/s) · right positive") custom_acceleration_p = gr.Slider(-4, 4, value=0.6, step=0.1, label="Net acceleration P (m/s²) · right positive") custom_friction_p = gr.Slider(0, 0.8, value=0.15, step=0.05, label="Coefficient of friction under P") with gr.Column(scale=2, elem_classes=["glass-panel"]): gr.Markdown("#### Roller Q · pink") custom_mass_q = gr.Slider(1, 12, value=7, step=0.5, label="Mass Q (kg) · changes roller size") custom_velocity_q = gr.Slider(-20, 20, value=-5, step=0.5, label="Initial velocity Q (m/s) · right positive") custom_acceleration_q = gr.Slider(-4, 4, value=-0.2, step=0.1, label="Net acceleration Q (m/s²) · right positive") custom_friction_q = gr.Slider(0, 0.8, value=0.2, step=0.05, label="Coefficient of friction under Q") with gr.Group(visible=False) as train_controls: gr.Markdown("### Electric train parameters") with gr.Row(equal_height=False): with gr.Column(elem_classes=["glass-panel"]): train_mass = gr.Slider(20, 200, value=90, step=5, label="Train mass (tonnes) · changes train length") train_initial_velocity = gr.Slider(0, 35, value=6, step=0.5, label="Initial train speed (m/s)") train_acceleration = gr.Slider(0.2, 3, value=1.2, step=0.1, label="Acceleration (m/s²)") train_resistance = gr.Slider(0, 120, value=35, step=5, label="Resistance to motion (kN)") with gr.Column(elem_classes=["glass-panel"]): train_acceleration_time = gr.Slider(2, 20, value=10, step=1, label="Acceleration-stage time (s)") train_cruise_time = gr.Slider(2, 30, value=12, step=1, label="Constant-speed time (s)") train_braking = gr.Slider(0.2, 4, value=1.5, step=0.1, label="Braking deceleration (m/s²)") with gr.Group(visible=False) as rocket_controls: gr.Markdown("### Rocket capsule parameters") with gr.Row(equal_height=False): with gr.Column(elem_classes=["glass-panel"]): rocket_mass = gr.Slider(50, 500, value=180, step=10, label="Capsule mass (kg) · changes capsule size") rocket_height = gr.Slider(0, 50, value=12, step=1, label="Launch-platform height (m)") with gr.Column(elem_classes=["glass-panel"]): rocket_velocity = gr.Slider(5, 80, value=32, step=1, label="Launch velocity (m/s)") rocket_gravity = gr.Slider(5, 12, value=9.8, step=0.1, label="Gravitational acceleration (m/s²)") with gr.Group(visible=False) as trolley_controls: gr.Markdown("### Cargo trolley parameters") with gr.Row(equal_height=False): with gr.Column(elem_classes=["glass-panel"]): trolley_mass = gr.Slider(10, 50, value=24, step=1, label="Trolley and cargo mass (kg) · changes load size") trolley_force = gr.Slider(20, 120, value=95, step=5, label="Pulling force (N)") trolley_angle = gr.Slider(0, 40, value=25, step=1, label="Pulling angle above horizontal (degrees)") with gr.Column(elem_classes=["glass-panel"]): trolley_friction = gr.Slider(0, 0.6, value=0.22, step=0.02, label="Coefficient of friction") trolley_velocity = gr.Slider(1, 20, value=7, step=0.5, label="Initial trolley speed (m/s)") trolley_time = gr.Slider(1, 10, value=5, step=0.5, label="Observation time (s)") custom_status = gr.Markdown( custom_status_markdown(INITIAL_CUSTOM_QUESTION), latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"], ) gr.Markdown("## Interactive experiment · click the model to start") custom_game = gr.HTML( value=collision_game_payload(INITIAL_CUSTOM_QUESTION), label="Interactive question experiment", html_template=COLLISION_GAME_HTML, css_template=COLLISION_GAME_CSS, js_on_load=CREATIVE_EXPERIMENT_JS, apply_default_css=False, container=False, ) with gr.Row(): custom_line_plot = gr.Plot(make_line_diagram(INITIAL_CUSTOM_QUESTION), label="Live 2D question model") custom_3d_plot = gr.Plot(make_3d_diagram(INITIAL_CUSTOM_QUESTION), label="Live rotatable 3D experiment") custom_question_md = gr.Markdown( render_question(INITIAL_CUSTOM_QUESTION), latex_delimiters=LATEX_DELIMITERS, elem_classes=["question-panel"], ) gr.Markdown("## Solve your custom mission") with gr.Row(equal_height=False): with gr.Column(scale=1): custom_work_image = gr.Image( label="Photo or scan of handwritten working", type="pil", image_mode="RGB", sources=["upload", "webcam", "clipboard"], height=340, ) with gr.Column(scale=1): custom_final_answer = gr.Textbox( label="Confirm final answer(s)", placeholder="Enter answers in the order asked", lines=2, info="Recommended because handwriting OCR can confuse signs, powers and fractions.", ) custom_use_ai_vision = gr.Checkbox( label="Use optional AI vision tutor", value=False, info="Requires OPENAI_API_KEY in Space secrets; the image is sent only when checked.", ) custom_assess_btn = gr.Button( "Analyse my custom solution ⚡", variant="primary", elem_classes=["submit-btn"] ) with gr.Row(equal_height=False): custom_feedback_md = gr.Markdown( "Submit your working to open a motion replay based on your chosen parameters.", latex_delimiters=LATEX_DELIMITERS, elem_classes=["coach-panel"], ) custom_feedback_plot = gr.Plot( make_feedback_animation(INITIAL_CUSTOM_QUESTION, None), label="Custom motion replay", ) with gr.Accordion("What the image reader detected", open=False): custom_ocr_md = gr.Markdown("No submission yet.") with gr.Row(): custom_solution_btn = gr.Button("Reveal custom worked solution", variant="secondary") custom_export_btn = gr.Button("Download this custom mission", variant="primary", elem_classes=["primary-btn"]) custom_solution_md = gr.Markdown(latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"]) with gr.Row(): custom_md_file = gr.File(label="Custom Markdown (.md)") custom_docx_file = gr.File(label="Custom Word (.docx)") custom_pdf_file = gr.File(label="Custom PDF (.pdf)") with gr.Accordion("Theory behind your custom model", open=False): custom_theory_md = gr.Markdown( theory_for(INITIAL_CUSTOM_QUESTION), latex_delimiters=LATEX_DELIMITERS ) with gr.Tab("➕ Question intake"): gr.Markdown(""" ## Add questions from any new user guide Paste text, upload text/image/PDF/Word files, or record a spoken question. The app extracts and deduplicates the questions, identifies the mechanics concept, stores them in the reusable question bank, and builds an editable visual model. """) with gr.Row(equal_height=False): with gr.Column(scale=3, elem_classes=["glass-panel"]): intake_text = gr.Textbox( label="Paste one or more questions", placeholder="Paste a question, or a numbered set such as Q1, Q2, Q3…", lines=8, ) intake_files = gr.File( label="Upload text, image, PDF, Word, or audio files", file_count="multiple", type="filepath", file_types=sorted(SUPPORTED_EXTENSIONS), ) intake_audio = gr.Audio( label="Speak a question", sources=["upload", "microphone"], type="filepath", ) with gr.Column(scale=2, elem_classes=["glass-panel"]): intake_title = gr.Textbox( value="New user-guide question", label="Question title or collection name", ) intake_topic_hint = gr.Dropdown( list(VISUAL_TOPIC_OPTIONS), value=VISUAL_TOPIC_OPTIONS[0], label="Concept hint", info="Keep Automatic unless the source image or OCR is ambiguous.", ) intake_split_mode = gr.Radio( ["Automatically split numbered questions", "Keep as one question"], value="Automatically split numbered questions", label="Multiple-question handling", ) intake_add_btn = gr.Button( "Extract, visualize, and add to bank", variant="primary", elem_classes=["primary-btn"], ) gr.Markdown( "Audio uses a configured speech API when available; otherwise the first transcription downloads and runs a compact local Whisper model." ) intake_status = gr.Markdown( "Add a new source to extend the reusable question bank.", elem_classes=["coach-panel"], ) with gr.Accordion("Extracted text and intake report", open=False): intake_extracted = gr.Markdown("No new source processed.") gr.Markdown("## Imported-question concept studio") intake_selected_question = gr.Markdown( _bank_record_markdown(INITIAL_BANK_RECORD), elem_classes=["question-panel"], ) intake_visual = gr.HTML( value=INITIAL_IMPORTED_PAYLOAD, label="Editable imported-question concept", html_template=QUESTION_VISUALIZER_HTML, css_template=QUESTION_VISUALIZER_CSS, js_on_load=QUESTION_VISUALIZER_JS, apply_default_css=False, container=False, ) gr.Markdown("## Reusable question bank") intake_bank_summary = gr.Markdown(bank_summary_markdown(INITIAL_BANK)) with gr.Row(): intake_bank_selector = gr.Dropdown( choices=bank_choices(INITIAL_BANK), value=INITIAL_BANK_RECORD.get("id") if INITIAL_BANK_RECORD else None, label="Open a stored question", scale=4, ) intake_open_btn = gr.Button("Load selected question", scale=1) intake_export_btn = gr.Button("Download question bank JSON", scale=1) intake_bank_file = gr.File(label="Question bank backup (.json)") with gr.Tab("💬 Mechanics tutor chat", id="mechanics-tutor"): gr.Markdown(""" ## Clarify the active question or its solution The tutor is grounded in the generated question, verified solution, expected answers, hints and theory. Ask in text, speak through the microphone, or upload an image of a diagram, equation or handwritten method. """) tutor_context = gr.Markdown( tutor_context_markdown(INITIAL_QUESTION), elem_classes=["glass-panel"], elem_id="full-mechanics-tutor", ) tutor_chat = gr.Chatbot( value=tutor_welcome(INITIAL_QUESTION), label="Mechanics Tutor", height=520, latex_delimiters=LATEX_DELIMITERS, ) gr.Markdown("### Suggested questions") tutor_prompt_buttons = [] with gr.Row(): for prompt in DEFAULT_TUTOR_QUESTIONS[:3]: tutor_prompt_buttons.append(gr.Button(prompt, size="sm")) with gr.Row(): for prompt in DEFAULT_TUTOR_QUESTIONS[3:]: tutor_prompt_buttons.append(gr.Button(prompt, size="sm")) tutor_text = gr.Textbox( label="Ask a follow-up question", placeholder="Example: Why is acceleration negative in this solution?", lines=3, ) with gr.Row(): tutor_engine = gr.Radio( list(TUTOR_ENGINES), value=QWEN_ENGINE, label="Tutor engine", ) tutor_open_source_model = gr.Dropdown( choices=list(OPEN_SOURCE_TUTOR_MODELS), value=DEFAULT_OPEN_SOURCE_MODEL, label="Open-source tutor model", allow_custom_value=True, ) gr.Markdown( "The Qwen route uses the Space secret `HF_TOKEN`. If it is unavailable, the verified local tutor answers automatically. OpenAI remains optional through `OPENAI_API_KEY`.", elem_classes=["privacy-note"], ) with gr.Row(equal_height=False): tutor_audio = gr.Audio( label="Ask by voice", sources=["upload", "microphone"], type="filepath", ) tutor_image = gr.Image( label="Upload an equation, diagram, or handwritten method", type="pil", image_mode="RGB", sources=["upload", "webcam", "clipboard"], height=260, ) with gr.Row(): tutor_send_btn = gr.Button( "Send to mechanics tutor", variant="primary", elem_classes=["submit-btn"], ) tutor_clear_btn = gr.Button("Clear conversation") tutor_input_status = gr.Markdown( "Text works immediately. Voice is transcribed locally unless a configured speech service is available.", elem_classes=["privacy-note"], ) with gr.Tab("📝 Assignments"): gr.Markdown( """ ## Mechanics assignment studio Generate an original assignment from the trained topics, set the number of questions manually, and collect typed or numbered handwritten submissions. The answer key stays hidden until evaluation. """ ) with gr.Row(equal_height=False): with gr.Column(scale=2, elem_classes=["glass-panel"]): assignment_student_name = gr.Textbox( label="Assignment student name", placeholder="Enter student name", ) assignment_title = gr.Textbox( label="Assignment title", value="M1 Mechanics skills assignment", ) assignment_topics = gr.Dropdown( choices=list(EXAM_TOPIC_CHOICES), value=list(EXAM_TOPIC_CHOICES), multiselect=True, label="Assignment topics", ) assignment_count = gr.Slider( 1, 30, value=10, step=1, label="Assignment question count" ) assignment_seed = gr.Textbox( label="Assignment seed (optional)", placeholder="Leave blank for a new assignment", ) assignment_generate_btn = gr.Button( "Generate assignment", variant="primary", elem_classes=["primary-btn"], ) with gr.Column(scale=3, elem_classes=["glass-panel"]): gr.Markdown( "Assignments use the same nine validated question formats as protected examinations. Students should number every typed or handwritten response as `Q1`, `Q2`, and so on." ) assignment_status = gr.Markdown( "Configure and generate an assignment.", elem_classes=["privacy-note"], ) assignment_paper = gr.Markdown( latex_delimiters=LATEX_DELIMITERS, elem_classes=["question-panel"], ) gr.Markdown("## Assignment submission portal") with gr.Row(equal_height=False): with gr.Column(scale=3): assignment_typed_answers = gr.Textbox( label="Typed numbered assignment answers", placeholder="Q1. ...\nQ2. ...\nQ3. ...", lines=14, max_lines=30, ) with gr.Column(scale=2): assignment_submission_files = gr.File( label="Upload numbered handwritten assignment images or PDF", file_count="multiple", type="filepath", file_types=["image", ".pdf"], ) assignment_submit_btn = gr.Button( "Submit and evaluate assignment", variant="primary", elem_classes=["submit-btn"], ) assignment_result = gr.Markdown(elem_classes=["exam-result-panel"]) assignment_solution = gr.Markdown( latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"], ) assignment_pdf = gr.File( label="Assignment result PDF · questions, marks, and solutions" ) with gr.Tab("🌟 Extraordinary activities"): gr.Markdown( """ ## Extraordinary activity record Record assessed work outside Midterm 1, Midterm 2, assignments, and the Final examination. Multiple activities can be combined, with optional evidence, and their total feeds the OBE calculation. """ ) with gr.Row(equal_height=False): with gr.Column(scale=2, elem_classes=["obe-card"]): extraordinary_student = gr.Textbox( label="Activity student name", placeholder="Enter student name", ) extraordinary_title = gr.Textbox( label="Extraordinary activity title", placeholder="Example: Working roller-collision model", ) extraordinary_category = gr.Dropdown( choices=list(ACTIVITY_CATEGORIES), value=ACTIVITY_CATEGORIES[0], label="Activity category", ) extraordinary_description = gr.Textbox( label="Activity description", placeholder="Describe the work, learning outcome, and assessment evidence.", lines=5, ) with gr.Column(scale=2, elem_classes=["obe-card"]): with gr.Row(): extraordinary_score = gr.Number( value=0, minimum=0, label="Activity marks obtained", ) extraordinary_maximum = gr.Number( value=10, minimum=0.01, label="Maximum activity marks", ) extraordinary_evidence = gr.File( label="Optional activity evidence", file_count="multiple", type="filepath", file_types=["image", ".pdf", ".doc", ".docx"], ) with gr.Row(): extraordinary_record_btn = gr.Button( "Record extraordinary activity", variant="primary", elem_classes=["primary-btn"], ) extraordinary_clear_btn = gr.Button("Clear activity records") extraordinary_status = gr.Markdown( "Add the first extraordinary activity.", elem_classes=["privacy-note"], ) extraordinary_summary = gr.Markdown( render_activities([]), elem_classes=["glass-panel"], ) with gr.Tab("📈 OBE attainment"): gr.Markdown( """ ## Outcome-Based Education attainment The maximum attainment is **3.000**. The default component weights are 10% Midterm 1, 10% Midterm 2, 10% Assignment, 50% Final examination, and 20% Extraordinary activities. You may change them, but the five percentages must total 100%. """ ) with gr.Row(): obe_student = gr.Textbox( label="OBE student name", placeholder="Student name printed in the OBE result and certificate", scale=3, ) obe_load_scores_btn = gr.Button( "Load latest recorded scores", scale=1, elem_classes=["primary-btn"], ) gr.Markdown("### Component marks") obe_score_inputs = [] with gr.Row(): for component in COMPONENTS: with gr.Column(min_width=210, elem_classes=["obe-card"]): gr.Markdown(f"**{component}**") obtained = gr.Number( value=0, minimum=0, label=f"{component} marks obtained", ) maximum = gr.Number( value=0, minimum=0, label=f"{component} maximum marks", ) obe_score_inputs.extend([obtained, maximum]) gr.Markdown("### Percentage weightage · editable") obe_weight_inputs = [] with gr.Row(): for component in COMPONENTS: obe_weight_inputs.append( gr.Number( value=DEFAULT_WEIGHT_PERCENTAGES[component], minimum=0, maximum=100, label=f"{component} weight (%)", ) ) with gr.Row(): obe_compute_btn = gr.Button( "Compute attainment and spider chart", variant="primary", elem_classes=["primary-btn"], ) obe_status = gr.Markdown( "Weight total: 100%. Load recorded scores or enter marks manually.", elem_classes=["privacy-note"], ) with gr.Row(equal_height=False): obe_result_md = gr.Markdown( "Compute attainment to see the weighted result.", elem_classes=["obe-card"], ) obe_radar_plot = gr.Plot( obe_spider_chart(), label="OBE attainment spider chart", ) gr.Markdown( "The exact calculation is `3 × weight percentage ÷ 100 × (marks obtained ÷ maximum marks)` for each component, then all five contributions are added. A missing or zero maximum contributes zero until a valid score is entered." ) with gr.Tab("🧭 Mistake analysis"): gr.Markdown( """ ## Examination mistake and improvement studio Select a completed examination or assignment. The app identifies every lost mark, compares the response with the answer key, reports topic and question-format performance, and builds a focused strengths–weaknesses–opportunities–challenges plan. """ ) with gr.Row(): mistake_refresh_btn = gr.Button("Refresh completed assessments") mistake_assessment_selector = gr.Dropdown( choices=[], label="Completed assessment for mistake analysis", scale=4, ) mistake_analyse_btn = gr.Button( "Analyse mistakes", variant="primary", elem_classes=["primary-btn"], ) mistake_status = gr.Markdown( "Complete an examination or assignment, then refresh this list.", elem_classes=["privacy-note"], ) mistake_report = gr.Markdown( mistake_analysis(None), elem_classes=["glass-panel"], ) gr.Markdown("## Ask the mistake-analysis tutor") mistake_chat = gr.Chatbot( value=tutor_welcome(None), label="Mistake Analysis Tutor", height=420, latex_delimiters=LATEX_DELIMITERS, ) with gr.Row(): mistake_prompt_buttons = [ gr.Button("Explain my first error", size="sm"), gr.Button("Why did I lose marks?", size="sm"), gr.Button("Give me an improvement drill", size="sm"), gr.Button("Challenge this analysis", size="sm"), ] mistake_chat_text = gr.Textbox( label="Question about a mistake or the analysis", placeholder="Example: Why is my sign convention wrong in Question 4?", lines=3, ) with gr.Row(): mistake_tutor_engine = gr.Radio( list(TUTOR_ENGINES), value=QWEN_ENGINE, label="Mistake tutor engine", ) mistake_open_source_model = gr.Dropdown( choices=list(OPEN_SOURCE_TUTOR_MODELS), value=DEFAULT_OPEN_SOURCE_MODEL, label="Mistake tutor open-source model", allow_custom_value=True, ) with gr.Row(): mistake_chat_send_btn = gr.Button( "Ask about my mistakes", variant="primary", elem_classes=["submit-btn"], ) mistake_chat_clear_btn = gr.Button("Clear mistake conversation") mistake_chat_status = gr.Markdown( "The tutor becomes grounded in the selected question-level corrections after analysis.", elem_classes=["privacy-note"], ) with gr.Tab("🏅 Certificates"): gr.Markdown( """ ## Achievement certificates Certificates become available at **60% (1.800/3.000)**. The continuous award bands are: standard 60–&lt;80%, silver distinction 80–&lt;90%, gold excellence 90–&lt;96.67%, and diamond achievement from 96.67% (2.900/3.000). The phrase **100 percent achievement** is reserved for an actual 3.000/3.000 result. """ ) certificate_generate_btn = gr.Button( "Generate certificate from current OBE result", variant="primary", elem_classes=["primary-btn"], ) certificate_status = gr.Markdown( "Compute the student's OBE attainment first.", elem_classes=["privacy-note"], ) certificate_html = gr.HTML( '<div class="certificate-preview"><h2>Certificate preview</h2><p>The current OBE result will determine the medal and ribbon.</p></div>' ) certificate_pdf = gr.File( label="Protected achievement certificate PDF" ) with gr.Tab("📚 Theory vault"): theory_md = gr.Markdown( theory_for(INITIAL_QUESTION), latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"], ) with gr.Tab("🏆 Progress"): mastery_md = gr.Markdown(mastery_markdown(INITIAL_PROFILE), elem_classes=["glass-panel"]) reset_btn = gr.Button("Reset session progress", size="sm") with gr.Tab("🧰 Worksheet forge"): gr.Markdown(""" ## Build an original classroom worksheet Create a mixed or topic-focused set with a teacher solution section. Download the same worksheet as Markdown, an editable Word document, or a print-ready PDF. """) worksheet_count = gr.Slider(3, 15, value=8, step=1, label="Number of questions") worksheet_btn = gr.Button("Forge worksheet", variant="primary", elem_classes=["primary-btn"]) gr.Markdown("### Download worksheet with teacher solutions") with gr.Row(): worksheet_md_file = gr.File(label="Markdown (.md)") worksheet_docx_file = gr.File(label="Word document (.docx)") worksheet_pdf_file = gr.File(label="PDF document (.pdf)") worksheet_preview = gr.Markdown(latex_delimiters=LATEX_DELIMITERS) with gr.Group(visible=False, elem_id="exam-section") as exam_section: gr.HTML( """ <section class="exam-lock-banner"> <h2>🛡️ Protected examination section</h2> <p>Training tools, theory, worksheets, progress, and all Ask Teacher bots are locked while an examination is in progress.</p> </section> """ ) with gr.Row(equal_height=False): with gr.Column(scale=2, elem_classes=["glass-panel"]): exam_student_name = gr.Textbox( label="Student name", placeholder="Enter the student's full name", ) exam_name = gr.Radio( choices=list(EXAM_SPECS), value="Midterm 1", label="Examination", ) exam_topics = gr.Dropdown( choices=list(EXAM_TOPIC_CHOICES), value=list(EXAM_TOPIC_CHOICES), multiselect=True, label="Topics completed in training", info="The paper is balanced across the selected trained topics.", ) exam_seed = gr.Textbox( label="Paper seed (optional)", placeholder="Leave blank for a new paper, or reuse a seed for moderation", ) exam_midterm_1_count = gr.Slider( 5, 25, value=10, step=1, label="Midterm 1 question count" ) exam_midterm_2_count = gr.Slider( 5, 25, value=10, step=1, label="Midterm 2 question count" ) exam_final_count = gr.Slider( 10, MAX_EXAM_QUESTIONS, value=25, step=1, label="Final examination question count" ) exam_total_session_minutes = gr.Slider( 20, DEFAULT_TOTAL_SESSION_MINUTES, value=DEFAULT_TOTAL_SESSION_MINUTES, step=1, label="Total protected-session duration (minutes)", info="Default 130 minutes: 10 minutes reading/setup plus 120 minutes answering. Maximum answer time is 2 hours.", ) exam_start_btn = gr.Button( "Start protected examination", variant="primary", elem_classes=["primary-btn"], ) with gr.Column(scale=3, elem_classes=["glass-panel"]): gr.Markdown( """ ### Paper structure - Default: **Midterm 1 = 10**, **Midterm 2 = 10**, **Final = 25** questions; each count is adjustable - Nine formats: multiple choice, fill in the blank, numerical problem, explanation, theory, mathematical calculation, match the following, diagram interpretation, and paragraph analysis - Every question displays its marks - Small questions default to **1 minute**; descriptive questions default to **4 minutes** - The overall protected session defaults to **130 minutes**, including the first 10 minutes for reading and setup Solutions are reconstructed only after submission. The downloaded report contains the paper, responses, score, answer key, and worked solutions in one locked PDF. """ ) gr.Markdown( "**Academic-integrity note:** this interface blocks in-app training and tutor access. Keep the protected browser tab open so the deadline can auto-submit the live answers. Formal invigilation or a managed browser is still required to prevent use of outside websites or devices.", elem_classes=["privacy-note"], ) with gr.Accordion("Manual question timing · optional 1–7 minute overrides", open=False): gr.Markdown( "Enter question numbers separated by commas or spaces. A question may appear in only one list. Leave every list blank to use the automatic 1-minute small-question and 4-minute descriptive-question defaults." ) exam_timing_inputs = [] with gr.Row(): for minute in range(1, 5): exam_timing_inputs.append( gr.Textbox( label=f"Question numbers for {minute}-minute timing", placeholder="Example: 1, 4, 7", ) ) with gr.Row(): for minute in range(5, 8): exam_timing_inputs.append( gr.Textbox( label=f"Question numbers for {minute}-minute timing", placeholder="Example: 8, 12", ) ) exam_runtime_total_minutes = gr.Number(value=DEFAULT_TOTAL_SESSION_MINUTES, visible=False) exam_runtime_reading_minutes = gr.Number(value=DEFAULT_READING_MINUTES, visible=False) exam_runtime_attempt_id = gr.Textbox(visible=False) exam_main_timer_display = gr.HTML( '<div class="exam-main-timer"><strong>Timer not started</strong><br>Start a protected examination to begin the reading and overall-session clocks.</div>', elem_id="exam-main-timer-display", container=False, ) exam_paper_header = gr.Markdown( "Choose the examination and trained topics, then start a protected attempt.", latex_delimiters=LATEX_DELIMITERS, elem_classes=["question-panel"], ) exam_question_groups = [] exam_question_markdowns = [] exam_answer_boxes = [] exam_question_timer_minutes = [] exam_question_timer_displays = [] exam_question_timer_buttons = [] for exam_index in range(MAX_EXAM_QUESTIONS): with gr.Group(visible=False, elem_classes=["exam-question-card"]) as exam_question_group: exam_question_md = gr.Markdown(latex_delimiters=LATEX_DELIMITERS) exam_timer_minutes = gr.Number(value=1, visible=False) exam_timer_display = gr.HTML( '<div class="exam-question-timer">Question timer is available after the reading phase.</div>', elem_id=f"exam-question-timer-{exam_index + 1}", container=False, ) exam_timer_button = gr.Button( f"Start Q{exam_index + 1} timer", elem_id=f"exam-question-timer-button-{exam_index + 1}", interactive=False, ) exam_answer = gr.Textbox( label=f"Answer to Question {exam_index + 1}", placeholder=( "Type the option, value, calculation, explanation, or theory answer here. " "Typed text is authoritative if OCR differs." ), lines=4, max_lines=10, interactive=False, ) exam_question_groups.append(exam_question_group) exam_question_markdowns.append(exam_question_md) exam_answer_boxes.append(exam_answer) exam_question_timer_minutes.append(exam_timer_minutes) exam_question_timer_displays.append(exam_timer_display) exam_question_timer_buttons.append(exam_timer_button) exam_unlock_trigger = gr.Button( "Unlock after reading phase", elem_id="exam-unlock-trigger", elem_classes=["exam-hidden-trigger"], ) exam_auto_submit_trigger = gr.Button( "Automatic timed submission", elem_id="exam-auto-submit-trigger", elem_classes=["exam-hidden-trigger"], ) gr.Markdown("## Optional numbered handwritten answer sheet") with gr.Row(equal_height=False): with gr.Column(scale=2): exam_answer_sheets = gr.File( label="Upload handwritten answer-sheet images or PDF", file_count="multiple", type="filepath", file_types=["image", ".pdf"], ) exam_read_sheet_btn = gr.Button( f"Read and map Q1–Q{MAX_EXAM_QUESTIONS}", variant="secondary" ) with gr.Column(scale=3): exam_ocr_preview = gr.Markdown( "No handwritten answer sheet has been read.", elem_classes=["privacy-note"], ) exam_declaration = gr.Checkbox( label="I confirm that this is my own completed work and I am ready to submit permanently.", value=False, ) with gr.Row(): exam_submit_btn = gr.Button( "Submit examination and calculate marks", variant="primary", elem_classes=["submit-btn"], ) exam_reset_btn = gr.Button("Prepare another examination", visible=False) exam_result_md = gr.Markdown( elem_classes=["exam-result-panel"], latex_delimiters=LATEX_DELIMITERS, ) exam_solution_md = gr.Markdown( latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"], ) exam_pdf_file = gr.File( label="Locked PDF · paper, responses, marks, and solutions", ) # Three native Gradio copies remain available on every tab. Keeping every # launcher and panel inside Gradio preserves open, send, Enter-submit, # close, clear, history, active-question grounding, and Qwen callbacks. def build_fixed_tutor_copy(position_name: str): position = position_name.strip().lower() suffix = "" if position == "bottom" else f"-{position}" launcher = gr.Button( "💬 Ask Teacher", variant="primary", elem_id=f"floating-tutor-launcher{suffix}", ) with gr.Group( visible=False, elem_id=f"floating-tutor-panel{suffix}", ) as panel: with gr.Row(elem_classes=["floating-tutor-dialog-header"]): gr.Markdown( f"### Ask Teacher · {position.title()}\n\nMISSION-LINKED QUESTION HELP", elem_classes=["floating-tutor-dialog-title"], scale=8, ) close_btn = gr.Button( "✕", elem_id=f"floating-tutor-close{suffix}", elem_classes=["floating-tutor-close"], size="sm", scale=1, ) open_full_btn = gr.Button( "Open full multimodal tutor ↗", elem_id=f"floating-open-full-tutor{suffix}", elem_classes=["floating-open-full-tutor"], size="sm", ) context = gr.Markdown( tutor_context_markdown(INITIAL_QUESTION), elem_classes=["floating-tutor-context"], ) chat = gr.Chatbot( value=tutor_welcome(INITIAL_QUESTION), label="Floating Mechanics Tutor", height=245, latex_delimiters=LATEX_DELIMITERS, elem_classes=["floating-tutor-chat"], ) with gr.Row(): hint_btn = gr.Button("First hint", size="sm") equation_btn = gr.Button("Equation choice", size="sm") with gr.Group(elem_classes=["floating-tutor-composer"]): gr.Markdown( "**Ask about the active problem** · Type below and press Enter or Ask Teacher.", elem_classes=["floating-tutor-composer-note"], ) text = gr.Textbox( label="Ask about the active mechanics problem", placeholder="Example: Why is momentum conserved in this collision?", lines=2, max_lines=4, ) engine = gr.Dropdown( choices=list(TUTOR_ENGINES), value=QWEN_ENGINE, label="Tutor engine", ) model = gr.Dropdown( choices=list(OPEN_SOURCE_TUTOR_MODELS), value=DEFAULT_OPEN_SOURCE_MODEL, label="Open-source tutor model", allow_custom_value=True, ) with gr.Row(): send_btn = gr.Button( "Enter · Ask Teacher", variant="primary", elem_classes=["submit-btn"], ) clear_btn = gr.Button("Clear", size="sm") status = gr.Markdown( "Linked to the problem named above · use the full tutor for voice or images.", elem_classes=["floating-tutor-status"], ) return { "position": position, "launcher": launcher, "panel": panel, "close": close_btn, "open_full": open_full_btn, "context": context, "chat": chat, "hint": hint_btn, "equation": equation_btn, "text": text, "engine": engine, "model": model, "send": send_btn, "clear": clear_btn, "status": status, } floating_top_bot = build_fixed_tutor_copy("top") floating_middle_bot = build_fixed_tutor_copy("middle") floating_bottom_bot = build_fixed_tutor_copy("bottom") floating_bots = [floating_top_bot, floating_middle_bot, floating_bottom_bot] # Preserve the original bottom-bot variable names used by mission and # Creative Lab update callbacks. floating_tutor_launcher = floating_bottom_bot["launcher"] floating_tutor_panel = floating_bottom_bot["panel"] floating_tutor_close_btn = floating_bottom_bot["close"] floating_open_full_btn = floating_bottom_bot["open_full"] floating_tutor_context = floating_bottom_bot["context"] floating_tutor_chat = floating_bottom_bot["chat"] floating_hint_btn = floating_bottom_bot["hint"] floating_equation_btn = floating_bottom_bot["equation"] floating_tutor_text = floating_bottom_bot["text"] floating_tutor_engine = floating_bottom_bot["engine"] floating_open_source_model = floating_bottom_bot["model"] floating_tutor_send_btn = floating_bottom_bot["send"] floating_tutor_clear_btn = floating_bottom_bot["clear"] floating_tutor_status = floating_bottom_bot["status"] gr.HTML(""" <div class="footer-note"> M1 Mechanics Quest creates original practice material. It is not affiliated with, endorsed by, or an official product of Pearson Edexcel. </div> """) exam_start_outputs = [ exam_attempt_state, exam_paper_header, exam_mode_status, exam_mode_toggle, exam_name, exam_topics, exam_seed, exam_student_name, exam_midterm_1_count, exam_midterm_2_count, exam_final_count, exam_total_session_minutes, *exam_timing_inputs, exam_start_btn, exam_declaration, exam_answer_sheets, exam_ocr_state, exam_ocr_preview, exam_read_sheet_btn, exam_submit_btn, exam_reset_btn, exam_result_md, exam_solution_md, exam_pdf_file, exam_runtime_total_minutes, exam_runtime_reading_minutes, exam_runtime_attempt_id, exam_main_timer_display, ] for group, question_markdown, answer_box, timer_minutes, timer_display, timer_button in zip( exam_question_groups, exam_question_markdowns, exam_answer_boxes, exam_question_timer_minutes, exam_question_timer_displays, exam_question_timer_buttons, ): exam_start_outputs.extend( [group, question_markdown, answer_box, timer_minutes, timer_display, timer_button] ) exam_mode_toggle.change( switch_exam_mode, inputs=[exam_mode_toggle], outputs=[ training_controls, app_tabs, exam_section, floating_top_bot["panel"], floating_middle_bot["panel"], floating_bottom_bot["panel"], exam_mode_status, ], js=EXAM_MODE_TOGGLE_JS, show_progress="hidden", ) exam_start_event = exam_start_btn.click( start_exam_interface, inputs=[ exam_student_name, exam_name, exam_topics, exam_seed, exam_midterm_1_count, exam_midterm_2_count, exam_final_count, exam_total_session_minutes, *exam_timing_inputs, ], outputs=exam_start_outputs, js=EXAM_START_CAPTURE_JS, ) exam_start_event.then( fn=None, inputs=[ exam_runtime_total_minutes, exam_runtime_reading_minutes, exam_runtime_attempt_id, ], js=EXAM_MAIN_TIMER_JS, show_progress="hidden", ) exam_unlock_trigger.click( unlock_exam_inputs, inputs=[exam_attempt_state], outputs=[*exam_answer_boxes, *exam_question_timer_buttons], show_progress="hidden", ) for question_number, (timer_button, timer_minutes) in enumerate( zip(exam_question_timer_buttons, exam_question_timer_minutes), 1 ): timer_button.click( fn=None, inputs=[timer_minutes], js=question_timer_js(question_number), show_progress="hidden", ) exam_read_sheet_btn.click( read_exam_answer_sheet, inputs=[exam_answer_sheets, exam_attempt_state], outputs=[exam_ocr_state, exam_ocr_preview], ) exam_submit_btn.click( submit_exam_interface, inputs=[ exam_attempt_state, exam_answer_sheets, exam_ocr_state, exam_declaration, assessment_history_state, *exam_answer_boxes, ], outputs=[ exam_result_md, exam_solution_md, exam_pdf_file, exam_mode_status, exam_attempt_state, exam_mode_toggle, exam_submit_btn, exam_declaration, exam_answer_sheets, exam_read_sheet_btn, exam_reset_btn, exam_ocr_state, exam_ocr_preview, exam_main_timer_display, assessment_history_state, *exam_answer_boxes, *exam_question_timer_buttons, ], js=EXAM_MANUAL_SUBMIT_JS, ) exam_auto_submit_trigger.click( auto_submit_exam_interface, inputs=[ exam_attempt_state, exam_answer_sheets, exam_ocr_state, assessment_history_state, *exam_answer_boxes, ], outputs=[ exam_result_md, exam_solution_md, exam_pdf_file, exam_mode_status, exam_attempt_state, exam_mode_toggle, exam_submit_btn, exam_declaration, exam_answer_sheets, exam_read_sheet_btn, exam_reset_btn, exam_ocr_state, exam_ocr_preview, exam_main_timer_display, assessment_history_state, *exam_answer_boxes, *exam_question_timer_buttons, ], js=EXAM_AUTO_SUBMIT_JS, ) exam_reset_btn.click( reset_exam_interface, outputs=exam_start_outputs, js=EXAM_RESET_TIMER_JS, ) assignment_generate_btn.click( generate_assignment_interface, inputs=[ assignment_student_name, assignment_title, assignment_topics, assignment_count, assignment_seed, ], outputs=[ assignment_state, assignment_paper, assignment_status, assignment_result, assignment_solution, assignment_pdf, assignment_typed_answers, assignment_submission_files, assignment_submit_btn, ], ) assignment_submit_btn.click( submit_assignment_interface, inputs=[ assignment_state, assignment_typed_answers, assignment_submission_files, assessment_history_state, ], outputs=[ assignment_status, assignment_result, assignment_solution, assignment_pdf, assignment_typed_answers, assignment_submission_files, assessment_history_state, ], ) extraordinary_record_btn.click( record_extraordinary_activity_interface, inputs=[ extraordinary_activities_state, extraordinary_student, extraordinary_title, extraordinary_category, extraordinary_description, extraordinary_score, extraordinary_maximum, extraordinary_evidence, ], outputs=[ extraordinary_activities_state, extraordinary_summary, extraordinary_status, extraordinary_title, extraordinary_description, extraordinary_evidence, ], ) extraordinary_clear_btn.click( clear_extraordinary_activities_interface, outputs=[ extraordinary_activities_state, extraordinary_summary, extraordinary_status, ], ) obe_load_scores_btn.click( load_obe_scores_interface, inputs=[assessment_history_state, extraordinary_activities_state], outputs=[obe_student, *obe_score_inputs, obe_status], ) obe_compute_btn.click( compute_obe_interface, inputs=[obe_student, *obe_score_inputs, *obe_weight_inputs], outputs=[obe_result_state, obe_result_md, obe_radar_plot, obe_status], ) mistake_refresh_btn.click( refresh_mistake_assessments_interface, inputs=[assessment_history_state], outputs=[mistake_assessment_selector, mistake_status], ) mistake_analyse_btn.click( analyse_mistakes_interface, inputs=[assessment_history_state, mistake_assessment_selector], outputs=[mistake_record_state, mistake_report, mistake_chat, mistake_status], ) mistake_chat_send_btn.click( chat_about_mistakes_interface, inputs=[ mistake_record_state, mistake_chat_text, mistake_tutor_engine, mistake_open_source_model, mistake_chat, ], outputs=[mistake_chat, mistake_chat_text, mistake_chat_status], ) mistake_chat_text.submit( chat_about_mistakes_interface, inputs=[ mistake_record_state, mistake_chat_text, mistake_tutor_engine, mistake_open_source_model, mistake_chat, ], outputs=[mistake_chat, mistake_chat_text, mistake_chat_status], ) mistake_chat_clear_btn.click( clear_mistake_chat_interface, inputs=[mistake_record_state], outputs=[mistake_chat, mistake_chat_status], ) for button, prompt in zip( mistake_prompt_buttons, ( "Explain the first place I went wrong and how to correct it.", "Why did I lose marks across these questions?", "Give me a short improvement drill for my weakest topic.", "Explain the evidence behind this mistake analysis so I can challenge it if needed.", ), ): button.click(lambda selected=prompt: selected, outputs=[mistake_chat_text]) certificate_generate_btn.click( generate_certificate_interface, inputs=[obe_result_state], outputs=[certificate_html, certificate_pdf, certificate_status], ) generate_mission_event = generate_btn.click( create_mission, inputs=[topic, difficulty, seed, profile_state], outputs=[question_state, question_md, mission_visual, line_plot, model_plot, theory_md, hint_md, solution_md, hint_index_state, seed, profile_panel, tutor_context, tutor_chat, floating_tutor_context, floating_tutor_chat, floating_question_state], ) generate_mission_event.then( sync_floating_tutor_copies, inputs=[floating_question_state], outputs=[ floating_top_bot["context"], floating_top_bot["chat"], floating_middle_bot["context"], floating_middle_bot["chat"], ], show_progress="hidden", ) hint_btn.click( next_hint, inputs=[question_state, hint_index_state, profile_state], outputs=[hint_md, hint_index_state, profile_state, profile_panel], ) solution_btn.click(reveal_solution, inputs=[question_state], outputs=[solution_md]) assess_btn.click( assess_work, inputs=[question_state, work_image, final_answer, use_ai_vision, profile_state], outputs=[feedback_md, feedback_plot, ocr_md, profile_state, profile_panel, mastery_md], ) reset_btn.click(reset_progress, outputs=[profile_state, profile_panel, mastery_md]) worksheet_btn.click( build_worksheet, inputs=[topic, difficulty, worksheet_count, seed], outputs=[worksheet_md_file, worksheet_docx_file, worksheet_pdf_file, worksheet_preview], ) intake_add_btn.click( add_questions_to_bank, inputs=[ intake_text, intake_files, intake_audio, intake_title, intake_topic_hint, intake_split_mode, ], outputs=[ intake_status, intake_extracted, intake_bank_summary, intake_bank_selector, intake_visual, intake_selected_question, ], ) intake_open_btn.click( open_bank_question, inputs=[intake_bank_selector], outputs=[intake_selected_question, intake_visual], ) intake_bank_selector.change( open_bank_question, inputs=[intake_bank_selector], outputs=[intake_selected_question, intake_visual], ) intake_export_btn.click(export_bank_file, outputs=[intake_bank_file]) tutor_send_btn.click( chat_with_tutor, inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_engine, tutor_chat, tutor_open_source_model], outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status], ) tutor_text.submit( chat_with_tutor, inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_engine, tutor_chat, tutor_open_source_model], outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status], ) tutor_clear_btn.click( clear_tutor_chat, inputs=[question_state], outputs=[tutor_chat, tutor_input_status], ) for button, prompt in zip(tutor_prompt_buttons, DEFAULT_TUTOR_QUESTIONS): button.click(lambda selected=prompt: selected, outputs=[tutor_text]) floating_panels = [bot["panel"] for bot in floating_bots] for bot in floating_bots: bot["launcher"].click( lambda selected=bot["position"]: show_floating_tutor_slot(selected), outputs=floating_panels, show_progress="hidden", ) bot["close"].click( hide_floating_tutor, outputs=[bot["panel"]], show_progress="hidden", ) bot["open_full"].click( open_full_tutor_tab, outputs=[app_tabs, bot["panel"]], show_progress="hidden", ) bot["send"].click( chat_in_floating_tutor, inputs=[ floating_question_state, bot["text"], bot["engine"], bot["model"], bot["chat"], ], outputs=[bot["chat"], bot["text"], bot["status"]], ) bot["text"].submit( chat_in_floating_tutor, inputs=[ floating_question_state, bot["text"], bot["engine"], bot["model"], bot["chat"], ], outputs=[bot["chat"], bot["text"], bot["status"]], ) bot["clear"].click( clear_tutor_chat, inputs=[floating_question_state], outputs=[bot["chat"], bot["status"]], ) bot["hint"].click( lambda: DEFAULT_TUTOR_QUESTIONS[3], outputs=[bot["text"]], ) bot["equation"].click( lambda: DEFAULT_TUTOR_QUESTIONS[1], outputs=[bot["text"]], ) custom_inputs = [ custom_scenario, custom_context, custom_difficulty, custom_impact_model, custom_restitution, custom_mass_p, custom_mass_q, custom_distance, custom_friction_p, custom_friction_q, custom_velocity_p, custom_velocity_q, custom_acceleration_p, custom_acceleration_q, train_mass, train_initial_velocity, train_acceleration, train_acceleration_time, train_cruise_time, train_braking, train_resistance, rocket_mass, rocket_height, rocket_velocity, rocket_gravity, trolley_mass, trolley_force, trolley_angle, trolley_friction, trolley_velocity, trolley_time, ] custom_outputs = [ custom_question_state, custom_status, custom_game, custom_line_plot, custom_3d_plot, custom_question_md, custom_solution_md, custom_theory_md, custom_feedback_md, custom_feedback_plot, custom_ocr_md, floating_tutor_context, floating_tutor_chat, floating_question_state, ] for custom_control in custom_inputs: creative_update_event = custom_control.change( update_creative_lab, inputs=custom_inputs, outputs=custom_outputs, ) creative_update_event.then( sync_floating_tutor_copies, inputs=[floating_question_state], outputs=[ floating_top_bot["context"], floating_top_bot["chat"], floating_middle_bot["context"], floating_middle_bot["chat"], ], show_progress="hidden", ) custom_scenario.change( show_creative_controls, inputs=[custom_scenario], outputs=[collision_controls, train_controls, rocket_controls, trolley_controls], ) custom_solution_btn.click( reveal_solution, inputs=[custom_question_state], outputs=[custom_solution_md] ) custom_assess_btn.click( assess_work, inputs=[ custom_question_state, custom_work_image, custom_final_answer, custom_use_ai_vision, profile_state, ], outputs=[ custom_feedback_md, custom_feedback_plot, custom_ocr_md, profile_state, profile_panel, mastery_md, ], ) custom_export_btn.click( export_custom_question, inputs=[custom_question_state], outputs=[custom_md_file, custom_docx_file, custom_pdf_file], ) # Re-pin the three real native Gradio launchers and panels after mount and # during viewport changes. No chatbot component is cloned or reparented. demo.load(fn=None, js=FLOATING_TUTOR_VIEWPORT_JS, show_progress="hidden") if __name__ == "__main__": demo.queue(default_concurrency_limit=16).launch(theme=theme, css=CSS)
"""Hugging Face Gradio entrypoint for M1 Mechanics Quest."""
from __future__ import annotations
from pathlib import Path
from html import escape
import json
import time
import gradio as gr
from collision_game import (
COLLISION_GAME_CSS,
COLLISION_GAME_HTML,
CREATIVE_EXPERIMENT_JS,
collision_game_payload,
)
from creative_questions import CREATIVE_SCENARIOS, build_creative_question, creative_status_markdown
from diagrams import make_3d_diagram, make_feedback_animation, make_line_diagram
from engine import DIFFICULTIES, TOPICS, generate_question, render_question, render_solution
from evaluator import evaluate_submission
from exam_engine import (
DEFAULT_READING_MINUTES,
DEFAULT_TOTAL_SESSION_MINUTES,
EXAM_CSS,
EXAM_AUTO_SUBMIT_JS,
EXAM_MAIN_TIMER_JS,
EXAM_MANUAL_SUBMIT_JS,
EXAM_MODE_TOGGLE_JS,
EXAM_RESET_TIMER_JS,
EXAM_SPECS,
EXAM_START_CAPTURE_JS,
EXAM_TOPIC_CHOICES,
apply_question_timings,
build_exam,
export_locked_exam_pdf,
extract_numbered_answer_sheet,
grade_exam,
reconstruct_exam,
render_exam_header,
render_exam_question,
render_exam_results,
render_ocr_mapping,
safe_attempt_state,
parse_numbered_answers,
question_timer_js,
)
from floating_tutor import FLOATING_TUTOR_CSS, FLOATING_TUTOR_VIEWPORT_JS
from gamification import mastery_markdown, new_profile, profile_html, record_hint
from interactive_lab import IMPACT_MODELS, build_custom_collision_question, custom_status_markdown
from obe_engine import (
ACTIVITY_CATEGORIES,
COMPONENTS,
DEFAULT_WEIGHT_PERCENTAGES,
OBE_CSS,
add_extraordinary_activity,
append_assessment_record,
assessment_choices,
calculate_obe_attainment,
certificate_preview,
export_certificate_pdf,
latest_component_scores,
mistake_analysis,
mistake_context_question,
obe_spider_chart,
render_activities,
render_obe_result,
select_assessment,
)
from question_intake import (
SUPPORTED_EXTENSIONS,
bank_choices,
bank_summary_markdown,
export_bank_file,
ingest_question_sources,
load_bank,
load_bank_record,
)
from question_visualizer import (
QUESTION_VISUALIZER_CSS,
QUESTION_VISUALIZER_HTML,
QUESTION_VISUALIZER_JS,
VISUAL_TOPIC_OPTIONS,
infer_visual_payload,
question_visual_payload,
)
from theory import theory_for
from tutor_chat import (
DEFAULT_OPEN_SOURCE_MODEL,
DEFAULT_TUTOR_QUESTIONS,
OPEN_SOURCE_TUTOR_MODELS,
QWEN_ENGINE,
TUTOR_ENGINES,
chat_with_tutor,
clear_tutor_chat,
tutor_context_markdown,
tutor_welcome,
)
from worksheet_exports import export_worksheet_bundle