Spaces:
Paused
Paused
Upload 26 files
Browse filesFiles changed (5)
- README.md+32
- START_HERE.txt+15
- app.py+438-13
- exam_engine.pyAdded+809
- floating_tutor.py+154-3
60 unmodified lines616263646566102 unmodified lines16917017117217317460 unmodified linesit stays in the current viewport while the learner scrolls, opens over the page withoutchanging tabs, keeps its own compact mission-linked conversation, andhyperlinks to the full multimodal tutor;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.102 unmodified linesand OCR-detected checkpoints without a key. The optional OpenAI engine uses`OPENAI_API_KEY`.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start60 unmodified lines61626364656667686970717273747576102 unmodified lines17918018118218318418518618718818919019119219319419519619719819920020120220320420520660 unmodified linesit stays in the current viewport while the learner scrolls, opens over the page withoutchanging tabs, keeps its own compact mission-linked conversation, andhyperlinks to the full multimodal tutor;- a protected **Examination lock** that disables the mission generator, everytraining tab, worksheet tools, theory, progress, and Ask Tutor during anactive attempt;- reproducible **Midterm 1** and **Midterm 2** papers with 10 questions each,plus a 25-question **Final examination**, balanced across multiple choice,fill-in-the-blank, numerical, explanation, and theory formats;- one answer field per question, numbered handwritten image/PDF answer-sheetOCR, deterministic rubric-based marking, typed-versus-OCR mismatch flags,post-submission solutions, and a flattened encrypted PDF containing thequestions, responses, marks, and solutions;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.102 unmodified linesand OCR-detected checkpoints without a key. The optional OpenAI engine uses`OPENAI_API_KEY`.### Protected examinationsTurn on **Activate examination section** above the mission generator. The apphides and disables all training tabs and the floating Ask Tutor launcher. Afterthe learner starts a paper, the examination switch and paper settings staylocked until the attempt is submitted. Midterm 1 and Midterm 2 each contain 10questions and 40 marks; the Final examination contains 25 questions and 100marks. All three include equal coverage of multiple choice, fill-in-the-blank,numerical problem, explanation, and theory formats.The learner can type an answer beneath every question and optionally uploadnumbered handwritten images or a PDF. Write `Q1`, `Q2`, and so on clearly onthe sheet. Typed answers remain authoritative; OCR fills an empty typed answeronly, and any typed/OCR mismatch is shown for human review. Solutions arehidden until submission. The downloadable result is a flattened, encrypted PDFwith printing permission but without editing, annotation, form-filling,assembly, or extraction permissions in compliant PDF readers.This in-app lock prevents access to the application's own learning tools. Amanaged browser or formal invigilation is still necessary to prevent access tooutside websites, phones, notes, or other devices.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start
33 unmodified lines34353637383933 unmodified linesThe local launcher automatically opens the Gradio interface in your browser.NEW QUESTION INTAKE-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/text33 unmodified lines34353637383940414243444546474849505152535433 unmodified linesThe local launcher automatically opens the Gradio interface in your browser.PROTECTED EXAMINATION MODE--------------------------Turn on "Activate examination section" above the mission generator. Trainingtabs and Ask Tutor are hidden. Start Midterm 1, Midterm 2, or the Finalexamination. The two midterms contain 10 questions each; the final contains 25.Each question has its own answer field and displayed marks.Students may also upload numbered handwritten images or a PDF. Write Q1, Q2,and so on clearly. Typed responses have priority; OCR is used only when a typedanswer is empty and any mismatch is flagged. Solutions appear only after finalsubmission. The resulting PDF contains the paper, answers, score, and solutionsand is encrypted against editing while allowing printing in compliant readers.Use formal invigilation or a managed browser if access to outside sites ordevices must also be prevented.NEW QUESTION INTAKE-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/text
17 unmodified lines1819202122232463 unmodified lines88899091929394285 unmodified lines3803813823833843858 unmodified lines3943953963973983999 unmodified lines409410411412413414415416417418419420421422423424425399 unmodified lines82582682782882983073 unmodified lines904905906907908909183 unmodified lines10931094109510961097109817 unmodified linesfrom diagrams import make_3d_diagram, make_feedback_animation, make_line_diagramfrom engine import DIFFICULTIES, TOPICS, generate_question, render_question, render_solutionfrom evaluator import evaluate_submissionfrom floating_tutor import FLOATING_TUTOR_CSSfrom gamification import mastery_markdown, new_profile, profile_html, record_hintfrom interactive_lab import IMPACT_MODELS, build_custom_collision_question, custom_status_markdownfrom question_intake import (63 unmodified linesreturn FALLBACK_CSSCSS = load_css() + "\n" + FLOATING_TUTOR_CSS# Gradio enables display mathematics by default, but single-dollar inline# mathematics is opt-in. Every learner-facing mathematics panel uses this285 unmodified lines)theme = gr.themes.Soft(primary_hue="violet",secondary_hue="pink",8 unmodified lineshint_index_state = gr.State(0)custom_question_state = gr.State(INITIAL_CUSTOM_QUESTION)floating_question_state = gr.State(INITIAL_QUESTION)gr.HTML("""<section class="hero">9 unmodified lines</section>""")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() as app_tabs:with gr.Tab("🎯 Mission control"):question_md = gr.Markdown(render_question(INITIAL_QUESTION),399 unmodified linesworksheet_pdf_file = gr.File(label="PDF document (.pdf)")worksheet_preview = gr.Markdown(latex_delimiters=LATEX_DELIMITERS)# Kept outside gr.Tabs so the launcher and popup remain available on every# tab, including the first page, without changing the learner's current tab.floating_tutor_launcher = gr.Button(73 unmodified lines</div>""")generate_btn.click(create_mission,inputs=[topic, difficulty, seed, profile_state],183 unmodified linesinputs=[custom_question_state],outputs=[custom_md_file, custom_docx_file, custom_pdf_file],)if __name__ == "__main__":17 unmodified lines181920212223242526272829303132333435363738394063 unmodified lines104105106107108109110285 unmodified lines3963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865878 unmodified lines5965975985996006016026039 unmodified lines613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646399 unmodified lines10461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117173 unmodified lines12451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330183 unmodified lines151415151516151715181519152015211522152317 unmodified linesfrom diagrams import make_3d_diagram, make_feedback_animation, make_line_diagramfrom engine import DIFFICULTIES, TOPICS, generate_question, render_question, render_solutionfrom evaluator import evaluate_submissionfrom exam_engine import (EXAM_CSS,EXAM_MODE_TOGGLE_JS,EXAM_SPECS,EXAM_TOPIC_CHOICES,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,)from floating_tutor import FLOATING_TUTOR_CSS, FLOATING_TUTOR_VIEWPORT_JSfrom gamification import mastery_markdown, new_profile, profile_html, record_hintfrom interactive_lab import IMPACT_MODELS, build_custom_collision_question, custom_status_markdownfrom question_intake import (63 unmodified linesreturn FALLBACK_CSSCSS = load_css() + "\n" + FLOATING_TUTOR_CSS + "\n" + EXAM_CSS# Gradio enables display mathematics by default, but single-dollar inline# mathematics is opt-in. Every learner-facing mathematics panel uses this285 unmodified lines)MAX_EXAM_QUESTIONS = 25def 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 Ask Tutor are unavailable."if activeelse "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),message,)def start_exam_interface(student_name: str,exam_name: str,trained_topics: list[str] | None,exam_seed: str,):exam = build_exam(exam_name, trained_topics, exam_seed, student_name)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. ""Ask Tutor and all 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(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,]for index in range(MAX_EXAM_QUESTIONS):visible = index < exam["count"]values.extend([gr.update(visible=visible),render_exam_question(exam["questions"][index]) if visible else "",gr.update(value="", interactive=visible),])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,*typed_answers: str,):unchanged = [gr.update() for _ in range(MAX_EXAM_QUESTIONS)]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(),*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(),*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)]return (summary,solutions,pdf_path,(f"✅ **Submitted and locked:** {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),*frozen_answers,)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(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,]for _ in range(MAX_EXAM_QUESTIONS):values.extend([gr.update(visible=False),"",gr.update(value="", interactive=True),])return tuple(values)theme = gr.themes.Soft(primary_hue="violet",secondary_hue="pink",8 unmodified lineshint_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({})gr.HTML("""<section class="hero">9 unmodified lines</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 Ask Tutor 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),399 unmodified linesworksheet_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 Ask Tutor 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_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- **Midterm 1:** 10 questions- **Midterm 2:** 10 questions- **Final examination:** 25 questions- Question formats: multiple choice, fill in the blank, numerical problem, explanation, and theory- Every question displays its marksSolutions 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. Formal invigilation or a managed browser is still required to prevent use of outside websites or devices.",elem_classes=["privacy-note"],)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 = []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_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=True,)exam_question_groups.append(exam_question_group)exam_question_markdowns.append(exam_question_md)exam_answer_boxes.append(exam_answer)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("Read and map Q1–Q25", 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",)# Kept outside gr.Tabs so the launcher and popup remain available on every# tab, including the first page, without changing the learner's current tab.floating_tutor_launcher = gr.Button(73 unmodified lines</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_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,]for group, question_markdown, answer_box in zip(exam_question_groups, exam_question_markdowns, exam_answer_boxes):exam_start_outputs.extend([group, question_markdown, answer_box])exam_mode_toggle.change(switch_exam_mode,inputs=[exam_mode_toggle],outputs=[training_controls,app_tabs,exam_section,floating_tutor_panel,exam_mode_status,],js=EXAM_MODE_TOGGLE_JS,show_progress="hidden",)exam_start_btn.click(start_exam_interface,inputs=[exam_student_name, exam_name, exam_topics, exam_seed],outputs=exam_start_outputs,)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,*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_answer_boxes,],)exam_reset_btn.click(reset_exam_interface,outputs=exam_start_outputs,)generate_btn.click(create_mission,inputs=[topic, difficulty, seed, profile_state],183 unmodified linesinputs=[custom_question_state],outputs=[custom_md_file, custom_docx_file, custom_pdf_file],)# Install a document-body launcher after Gradio has mounted. It stays in# the visible browser viewport during page or nested-container scrolling# and forwards clicks to the native Gradio event above.demo.load(fn=None, js=FLOATING_TUTOR_VIEWPORT_JS, show_progress="hidden")if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809"""Deterministic examination generation, marking, OCR mapping, and locked PDF reports."""
from __future__ import annotations
from collections import Counterfrom datetime import datetime, timezonefrom difflib import SequenceMatcherfrom hashlib import sha256from html import escapefrom io import BytesIOfrom pathlib import Pathimport randomimport reimport secretsimport tempfilefrom typing import Any, Iterable
from PIL import Imagefrom pypdf import PdfReader, PdfWriterfrom pypdf.constants import UserAccessPermissionsfrom reportlab.lib import colorsfrom reportlab.lib.pagesizes import LETTERfrom reportlab.lib.styles import ParagraphStyle, getSampleStyleSheetfrom reportlab.lib.units import inchfrom reportlab.platypus import PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
from engine import TOPICS, generate_questionfrom evaluator import extract_numbers, run_ocrfrom worksheet_exports import plain_math
EXAM_SPECS = { "Midterm 1": {"count": 10, "label": "Midterm Examination 1"}, "Midterm 2": {"count": 10, "label": "Midterm Examination 2"}, "Final examination": {"count": 25, "label": "Final Examination"},}
EXAM_TOPIC_CHOICES = tuple(label for label in TOPICS if label != "Mixed mission")FORMAT_MARKS = { "Multiple choice": 2, "Fill in the blank": 2, "Numerical problem": 6, "Explanation": 5, "Theory": 5,}FORMAT_CYCLE = tuple(FORMAT_MARKS)
EXAM_CSS = r""".exam-mode-shell { background: linear-gradient(120deg, #fff7ed, #fef2f2 55%, #f5f3ff); border: 1px solid rgba(190, 24, 93, .2); border-radius: 18px; box-shadow: 0 12px 34px rgba(76, 29, 149, .1); margin: 12px 0 18px; padding: 14px 16px;}.exam-mode-shell h3 { color: #831843; margin: 0 0 4px; }#exam-section { background: linear-gradient(145deg, rgba(255,255,255,.98), rgba(245,243,255,.95)); border: 1px solid rgba(109, 40, 217, .18); border-radius: 24px; box-shadow: 0 18px 55px rgba(30, 41, 59, .12); padding: 18px !important;}.exam-lock-banner { background: linear-gradient(105deg, #7f1d1d, #be123c 54%, #6d28d9); border-radius: 18px; color: white; margin-bottom: 14px; padding: 16px 18px;}.exam-lock-banner h2, .exam-lock-banner p { color: white !important; margin: 0 0 5px; }.exam-question-card { background: rgba(255,255,255,.98); border: 1px solid rgba(99,102,241,.18); border-left: 5px solid #7c3aed; border-radius: 17px; box-shadow: 0 9px 26px rgba(30,41,59,.08); margin: 12px 0; padding: 14px !important;}.exam-question-card h3 { color: #312e81; margin-top: 0; }.exam-result-panel { background: linear-gradient(120deg, #ecfeff, #eef2ff); border: 1px solid rgba(8,145,178,.2); border-radius: 18px; padding: 15px !important;}body.exam-mode-active #floating-tutor-viewport-launcher,body.exam-mode-active #floating-tutor-launcher,body.exam-mode-active #floating-tutor-panel { display: none !important; pointer-events: none !important; visibility: hidden !important;}@media (max-width: 680px) { #exam-section { padding: 10px !important; } .exam-question-card { padding: 10px !important; }}"""
EXAM_MODE_TOGGLE_JS = r"""(enabled) => { document.body.classList.toggle("exam-mode-active", Boolean(enabled)); return enabled;}"""
# Each group is a set of acceptable synonyms. Marks are based on how many# concept groups are evidenced, making marking deterministic and auditable.CONCEPT_BANK: dict[str, dict[str, dict[str, Any]]] = { "vertical": { "Theory": { "prompt": "State the constant-acceleration assumptions used for vertical motion under gravity.", "answer": "The object is modelled as a particle; air resistance is neglected; gravity is uniform and acts vertically downward with acceleration g = 9.8 m s^-2.", "groups": [["particle"], ["air resistance", "drag"], ["constant", "uniform"], ["downward", "vertically down"], ["9.8", "gravity", " g "]], }, "Explanation": { "prompt": "Explain why a negative acceleration may be used even while the particle is moving upward.", "answer": "The sign of acceleration is set by the chosen positive direction, not by the current direction of motion. With upward positive, gravity acts downward, so a = -g while the upward velocity decreases.", "groups": [["positive direction", "sign convention"], ["gravity"], ["downward"], ["-g", "negative"], ["velocity", "slows", "decreases"]], }, }, "speed_time": { "Theory": { "prompt": "State what the gradient and the area under a speed-time graph represent.", "answer": "The gradient represents acceleration. The area between the speed-time graph and the time axis represents distance travelled.", "groups": [["gradient"], ["acceleration"], ["area"], ["distance"], ["time axis", "under the graph"]], }, "Explanation": { "prompt": "Explain why a straight sloping section on a speed-time graph represents uniform acceleration.", "answer": "A straight line has constant gradient, and the gradient of a speed-time graph is acceleration; therefore the acceleration is constant or uniform.", "groups": [["straight line"], ["constant gradient"], ["gradient"], ["acceleration"], ["constant", "uniform"]], }, }, "collision": { "Theory": { "prompt": "State the principle of conservation of linear momentum and the condition needed to use it.", "answer": "For a system with zero resultant external impulse, total momentum before an interaction equals total momentum after it, using one consistent direction convention.", "groups": [["total momentum", "sum of momentum"], ["before"], ["after"], ["external"], ["impulse", "force"], ["direction", "sign"]], }, "Explanation": { "prompt": "Explain why momentum can be conserved during a short collision even though each particle experiences a large force.", "answer": "The impact forces are internal, equal and opposite, so their impulses cancel for the two-particle system. If external impulse is negligible, the system's total momentum is unchanged.", "groups": [["internal"], ["equal"], ["opposite"], ["impulse", "cancel"], ["external"], ["total momentum", "system momentum"]], }, }, "beam": { "Theory": { "prompt": "State the two conditions required for a rigid body to be in equilibrium.", "answer": "The resultant force is zero and the resultant moment about any point is zero.", "groups": [["resultant force", "sum of forces"], ["zero"], ["resultant moment", "sum of moments"], ["any point", "about a point"]], }, "Explanation": { "prompt": "Explain why the weight of a uniform beam is taken to act at its midpoint.", "answer": "A uniform beam has constant mass per unit length, so its centre of mass is at the geometrical midpoint; the resultant weight acts through that centre of mass.", "groups": [["uniform"], ["mass per unit length", "evenly distributed"], ["centre of mass", "center of mass"], ["midpoint", "middle"], ["weight acts"]], }, }, "friction": { "Theory": { "prompt": "State the friction law at limiting equilibrium and explain when it may be used.", "answer": "At impending motion, friction has its limiting magnitude F = mu R and acts opposite the impending relative motion. It must not be assumed when the body is not at the point of slipping.", "groups": [["f =", "mu r", "μr"], ["limiting"], ["impending", "point of moving", "point of slipping"], ["opposite"], ["motion"]], }, "Explanation": { "prompt": "Explain why an upward angled pulling force reduces the normal reaction on a block.", "answer": "The pull has an upward vertical component that supports part of the weight, so vertical equilibrium gives R + P sin(theta) = mg and therefore R is less than mg.", "groups": [["vertical component"], ["upward"], ["supports", "balances"], ["weight", "mg"], ["reaction", "r"], ["less", "reduces"]], }, }, "connected": { "Theory": { "prompt": "State the modelling consequences of a light inextensible string passing over a smooth pulley.", "answer": "A light string has the same tension throughout; inextensibility makes connected particles have equal acceleration magnitude; a smooth pulley does not introduce frictional resistance.", "groups": [["same tension", "equal tension"], ["light string"], ["inextensible", "inextensibility"], ["equal acceleration", "same acceleration"], ["smooth pulley"], ["no friction", "frictionless", "frictional resistance"]], }, "Explanation": { "prompt": "Explain how to choose the direction of friction for a particle on a rough plane.", "answer": "Friction opposes actual or impending relative motion between the surfaces. First determine the likely direction of motion; draw friction along the plane in the opposite direction.", "groups": [["opposes"], ["motion", "relative motion"], ["impending"], ["surface", "plane"], ["opposite direction"]], }, }, "vectors": { "Theory": { "prompt": "Explain how a velocity vector is used to find speed and bearing.", "answer": "Speed is the magnitude of the velocity vector, found from the Pythagorean combination of its components. Bearing is measured clockwise from north and must be reported with the correct quadrant.", "groups": [["magnitude"], ["pythagoras", "pythagorean", "square root"], ["components"], ["clockwise"], ["north"], ["quadrant"]], }, "Explanation": { "prompt": "Explain why the signs of vector components must be retained when finding a bearing.", "answer": "The signs identify east or west and north or south, fixing the quadrant. A calculator's acute reference angle alone cannot determine the clockwise bearing from north.", "groups": [["sign"], ["east", "west"], ["north", "south"], ["quadrant"], ["clockwise"], ["bearing"]], }, }, "equilibrium": { "Theory": { "prompt": "Describe how to resolve forces along two perpendicular directions for particle equilibrium.", "answer": "Choose two perpendicular axes, resolve every force into components, and set the algebraic sum of components to zero independently along each axis.", "groups": [["perpendicular"], ["axes", "directions"], ["resolve", "components"], ["sum"], ["zero"], ["each", "independently"]], }, "Explanation": { "prompt": "Explain why a complete free-body diagram should be drawn before writing equilibrium equations.", "answer": "It isolates the particle, shows every external force with direction, prevents omitted or duplicated forces, and supports consistent resolution and signs.", "groups": [["isolate", "particle"], ["every force", "all forces", "external force"], ["direction"], ["omit", "missing"], ["resolve", "resolution", "components"], ["sign"]], }, },}
def _seed_value(seed: Any) -> int: if seed not in (None, ""): try: return abs(int(seed)) % 2_147_483_647 except (TypeError, ValueError): return int(sha256(str(seed).encode("utf-8")).hexdigest()[:8], 16) return int(datetime.now(timezone.utc).timestamp() * 1_000_000) % 2_147_483_647
def _scenario_stem(prompt: str) -> str: value = str(prompt or "").strip() match = re.search(r"(?m)^\s*\(a\)", value) return value[: match.start()].strip() if match else value
def _unit(answer: dict) -> str: return plain_math(answer.get("unit", "")).strip()
def _display_value(value: float, answer: dict) -> str: suffix = _unit(answer) return f"{value:.4g}{(' ' + suffix) if suffix else ''}"
def _unique_distractors(target: float, base: dict, rng: random.Random) -> list[float]: scale = max(1.0, abs(target)) candidates = [] for error in base.get("common_errors", []): try: candidates.append(float(error["value"])) except (KeyError, TypeError, ValueError): pass candidates.extend( [ -target, target + 0.2 * scale, target - 0.2 * scale, target * 2, target / 2, target + rng.choice([-1, 1]) * 0.35 * scale, ] ) unique: list[float] = [] tolerance = max(0.02, abs(target) * 0.012) for value in candidates: if abs(value - target) <= tolerance: continue if all(abs(value - previous) > tolerance for previous in unique): unique.append(value) if len(unique) == 3: break while len(unique) < 3: value = target + (len(unique) + 1) * max(1, scale * 0.17) if abs(value - target) > tolerance: unique.append(value) return unique
def _make_objective_item(base: dict, question_format: str, marks: int, rng: random.Random) -> dict: answer = base["expected_answers"][0] target = float(answer["value"]) stem = _scenario_stem(base["prompt"]) label = plain_math(answer["label"]) if question_format == "Multiple choice": options = [(target, True)] + [(value, False) for value in _unique_distractors(target, base, rng)] rng.shuffle(options) option_rows = [] correct_letter = "A" for index, (value, correct) in enumerate(options): letter = chr(65 + index) option_rows.append(f"**{letter}.** {_display_value(value, answer)}") if correct: correct_letter = letter question_text = f"{stem}\n\nWhich option gives the **{label}**?\n\n" + " \n".join(option_rows) return { "format": question_format, "marks": marks, "question": question_text, "answer_key": f"{correct_letter}. {_display_value(target, answer)}", "solution": base["solution_steps"], "rubric": { "kind": "mcq", "letter": correct_letter, "value": target, "tolerance": float(answer.get("tolerance", max(0.02, abs(target) * 0.01))), }, } question_text = ( f"{stem}\n\nFill in the blank, including the correct unit where applicable:\n\n" f"**{label} = __________ {escape(_unit(answer))}**" ) return { "format": question_format, "marks": marks, "question": question_text, "answer_key": _display_value(target, answer), "solution": base["solution_steps"], "rubric": { "kind": "numeric", "expected": [answer], }, }
def _make_written_item(base: dict, question_format: str, marks: int) -> dict: if question_format == "Numerical problem": return { "format": question_format, "marks": marks, "question": base["prompt"].strip(), "answer_key": "; ".join( f"{plain_math(answer['label'])}: {plain_math(answer['display'])}" for answer in base["expected_answers"] ), "solution": base["solution_steps"], "rubric": {"kind": "numeric", "expected": base["expected_answers"]}, } concept = CONCEPT_BANK[base["topic"]][question_format] return { "format": question_format, "marks": marks, "question": f"**Context: {base['title']} · {base['topic_label']}**\n\n{concept['prompt']}", "answer_key": concept["answer"], "solution": [concept["answer"]], "rubric": {"kind": "concept", "groups": concept["groups"]}, }
def build_exam( exam_name: str, topic_labels: Iterable[str] | None, seed: Any, student_name: str,) -> dict[str, Any]: """Create a reproducible paper with no answer keys in the public rendering.""" spec = EXAM_SPECS.get(exam_name, EXAM_SPECS["Midterm 1"]) exam_name = exam_name if exam_name in EXAM_SPECS else "Midterm 1" selected_topics = [label for label in (topic_labels or []) if label in EXAM_TOPIC_CHOICES] if not selected_topics: selected_topics = list(EXAM_TOPIC_CHOICES) seed_int = _seed_value(seed) offset = {"Midterm 1": 11003, "Midterm 2": 22003, "Final examination": 99001}[exam_name] rng = random.Random(seed_int + offset) formats = list(FORMAT_CYCLE) * (spec["count"] // len(FORMAT_CYCLE)) rng.shuffle(formats) topic_order = list(selected_topics) rng.shuffle(topic_order)
questions: list[dict[str, Any]] = [] for index in range(spec["count"]): topic_label = topic_order[index % len(topic_order)] item_seed = seed_int + offset + (index + 1) * 7919 difficulty = "Challenge" if exam_name == "Final examination" and index % 3 == 0 else "Exam standard" base = generate_question(topic_label, difficulty, item_seed) question_format = formats[index] marks = FORMAT_MARKS[question_format] if question_format in {"Multiple choice", "Fill in the blank"}: item = _make_objective_item(base, question_format, marks, rng) else: item = _make_written_item(base, question_format, marks) item.update( { "number": index + 1, "topic": base["topic"], "topic_label": base["topic_label"], "question_id": base["id"], } ) questions.append(item)
student = str(student_name or "Student").strip()[:100] or "Student" total_marks = sum(item["marks"] for item in questions) attempt_source = f"{student}|{exam_name}|{seed_int}|{'|'.join(selected_topics)}" attempt_id = sha256(attempt_source.encode("utf-8")).hexdigest()[:16].upper() return { "exam_name": exam_name, "exam_label": spec["label"], "student": student, "seed": seed_int, "topics": selected_topics, "count": spec["count"], "total_marks": total_marks, "attempt_id": attempt_id, "questions": questions, }
def safe_attempt_state(exam: dict[str, Any]) -> dict[str, Any]: """Return only reconstruction data; answer keys never enter Gradio state.""" return { key: exam[key] for key in ("exam_name", "exam_label", "student", "seed", "topics", "count", "total_marks", "attempt_id") } | {"started": True, "submitted": False}
def reconstruct_exam(attempt: dict[str, Any] | None) -> dict[str, Any] | None: if not attempt or not attempt.get("started"): return None exam = build_exam( attempt.get("exam_name", "Midterm 1"), attempt.get("topics", []), attempt.get("seed", ""), attempt.get("student", "Student"), ) if exam["attempt_id"] != attempt.get("attempt_id"): return None return exam
def render_exam_header(exam: dict[str, Any]) -> str: topic_text = " · ".join(exam["topics"]) counts = Counter(question["format"] for question in exam["questions"]) formats = " · ".join(f"{name}: {count}" for name, count in counts.items()) return f"""## {exam['exam_label']}
**Student:** {escape(exam['student'])} **Questions:** {exam['count']} · **Total:** {exam['total_marks']} marks · **Attempt:** `{exam['attempt_id']}` **Trained topics:** {escape(topic_text)}
**Paper balance:** {escape(formats)}
> Enter an answer under every question. For a handwritten sheet, write `Q1`, `Q2`, … clearly before each response. Solutions remain unavailable until the paper is submitted."""
def render_exam_question(item: dict[str, Any]) -> str: return f"""### Question {item['number']} · {item['format']} · **{item['marks']} marks**
<span class="question-kicker">{escape(item['topic_label'])}</span>
{item['question']}"""
def _normalise_text(value: str) -> str: value = plain_math(value).lower() value = value.replace("μ", "mu") value = re.sub(r"[^a-z0-9.+\-/ ]+", " ", value) return re.sub(r"\s+", " ", value).strip()
def _numeric_grade(expected: list[dict], response: str, marks: int) -> tuple[float, str]: candidates = extract_numbers(response) if not candidates: return 0.0, "No readable numerical answer was found." remaining = list(enumerate(candidates)) matched: list[str] = [] missing: list[str] = [] for answer in expected: target = float(answer["value"]) tolerance = float(answer.get("tolerance", max(0.02, abs(target) * 0.01))) if remaining: candidate_index, candidate = min(remaining, key=lambda pair: abs(pair[1] - target)) if abs(candidate - target) <= tolerance: matched.append(plain_math(answer["label"])) remaining = [pair for pair in remaining if pair[0] != candidate_index] continue missing.append(plain_math(answer["label"])) score = marks * len(matched) / max(1, len(expected)) detail = f"Matched: {', '.join(matched) if matched else 'none'}." if missing: detail += f" Recheck: {', '.join(missing)}." return round(score * 2) / 2, detail
def _concept_grade(groups: list[list[str]], response: str, marks: int) -> tuple[float, str]: normalised = f" {_normalise_text(response)} " matched_groups = [] missing_groups = [] for group in groups: matched = next((term for term in group if _normalise_text(term) in normalised), None) if matched: matched_groups.append(matched) else: missing_groups.append(group[0]) score = marks * len(matched_groups) / max(1, len(groups)) detail = f"Concept evidence: {len(matched_groups)}/{len(groups)} rubric points." if missing_groups: detail += " Missing ideas: " + ", ".join(missing_groups) + "." return round(score * 2) / 2, detail
def _grade_item(item: dict[str, Any], response: str) -> tuple[float, str]: rubric = item["rubric"] marks = item["marks"] if not response.strip(): return 0.0, "No answer supplied." if rubric["kind"] == "mcq": normalised = _normalise_text(response).upper() first_letter = re.match(r"\s*([A-D])(?:\b|[.)])", normalised) if first_letter and first_letter.group(1) == rubric["letter"]: return float(marks), "Correct option selected." values = extract_numbers(response) if any(abs(value - rubric["value"]) <= rubric["tolerance"] for value in values): return float(marks), "Correct option value supplied." return 0.0, f"The selected option is not {rubric['letter']}." if rubric["kind"] == "numeric": return _numeric_grade(rubric["expected"], response, marks) return _concept_grade(rubric["groups"], response, marks)
def _answers_agree(typed: str, scanned: str) -> str: typed_numbers = extract_numbers(typed) scanned_numbers = extract_numbers(scanned) if typed_numbers and scanned_numbers: pairs = zip(typed_numbers, scanned_numbers) agree = all(abs(left - right) <= max(0.03, abs(left) * 0.012) for left, right in pairs) if agree and len(typed_numbers) == len(scanned_numbers): return "Typed and scanned numerical answers agree." return "Typed and scanned numerical answers differ — typed answer used; manual review advised." ratio = SequenceMatcher(None, _normalise_text(typed), _normalise_text(scanned)).ratio() if ratio >= 0.62: return f"Typed and scanned wording broadly agree ({ratio:.0%} text similarity)." return f"Typed and scanned wording differ ({ratio:.0%} text similarity) — typed answer used; manual review advised."
def grade_exam( exam: dict[str, Any], typed_answers: Iterable[str] | None, scanned_answers: dict[int, str] | None = None,) -> dict[str, Any]: typed = list(typed_answers or []) scanned = scanned_answers or {} rows = [] total = 0.0 for index, item in enumerate(exam["questions"]): typed_answer = str(typed[index] if index < len(typed) else "").strip() scanned_answer = str(scanned.get(index + 1, "")).strip() response = typed_answer or scanned_answer source = "Typed answer" if typed_answer else ("Numbered handwritten answer" if scanned_answer else "No answer") comparison = _answers_agree(typed_answer, scanned_answer) if typed_answer and scanned_answer else ( "Only the typed answer was supplied." if typed_answer else "OCR answer used because no typed answer was supplied." if scanned_answer else "No typed or readable numbered answer was supplied." ) score, feedback = _grade_item(item, response) score = min(float(item["marks"]), max(0.0, score)) total += score rows.append( { "number": index + 1, "format": item["format"], "marks": item["marks"], "score": score, "typed_answer": typed_answer, "scanned_answer": scanned_answer, "response": response, "source": source, "comparison": comparison, "feedback": feedback, "answer_key": item["answer_key"], "solution": item["solution"], "question": item["question"], "topic_label": item["topic_label"], } ) total = round(total * 2) / 2 maximum = exam["total_marks"] percentage = 100 * total / maximum if maximum else 0.0 return { "student": exam["student"], "exam_name": exam["exam_name"], "attempt_id": exam["attempt_id"], "score": total, "maximum": maximum, "percentage": percentage, "rows": rows, "graded_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), }
def render_exam_results(grade: dict[str, Any]) -> tuple[str, str]: score = grade["score"] maximum = grade["maximum"] percentage = grade["percentage"] summary_rows = "\n".join( f"| {row['number']} | {row['format']} | {row['score']:g}/{row['marks']} | {row['source']} |" for row in grade["rows"] ) summary = f"""## Examination completed
### {score:g}/{maximum} marks · {percentage:.1f}%
| Q | Format | Mark | Evidence used ||---:|---|---:|---|{summary_rows}
> Typed answers are authoritative. If OCR disagreed, the difference is flagged for review and did not silently replace the typed response.""" sections = [] for row in grade["rows"]: steps = "\n".join(f"{index}. {step}" for index, step in enumerate(row["solution"], 1)) sections.append( f"""### Question {row['number']} · {row['score']:g}/{row['marks']} marks
**Student response ({row['source']}):** {escape(row['response']) if row['response'] else 'No answer'}
**Evaluation:** {row['feedback']} **Typed/OCR check:** {row['comparison']}
**Answer key:** {row['answer_key']}
**Worked solution / marking guidance**
{steps}""" ) solutions = "## Solutions and question-by-question feedback\n\n" + "\n\n---\n\n".join(sections) return summary, solutions
NUMBERED_ANSWER_RE = re.compile( r"(?mi)^\s*(?:q(?:uestion)?\s*)?(\d{1,2})\s*[).:\-]\s*(.*)$")
def parse_numbered_answers(text: str, maximum: int = 25) -> dict[int, str]: matches = list(NUMBERED_ANSWER_RE.finditer(str(text or ""))) answers: dict[int, str] = {} for index, match in enumerate(matches): number = int(match.group(1)) if not 1 <= number <= maximum: continue end = matches[index + 1].start() if index + 1 < len(matches) else len(text) value = (match.group(2) + "\n" + text[match.end() : end]).strip() value = re.sub(r"\s+", " ", value) if value: answers[number] = (answers.get(number, "") + " " + value).strip() return answers
def _ocr_pil(image: Image.Image) -> tuple[str, str]: if image.mode != "RGB": image = image.convert("RGB") return run_ocr(image)
def extract_numbered_answer_sheet(files: Any, maximum: int = 25) -> dict[str, Any]: file_values = files if isinstance(files, (list, tuple)) else ([files] if files else []) text_blocks: list[str] = [] statuses: list[str] = [] for file_index, value in enumerate(file_values, 1): path_value = getattr(value, "name", value) path = Path(str(path_value)) if path_value else None if not path or not path.is_file(): statuses.append(f"File {file_index}: unavailable.") continue try: if path.suffix.lower() == ".pdf": import fitz
document = fitz.open(path) for page_number, page in enumerate(document, 1): pixmap = page.get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False) image = Image.open(BytesIO(pixmap.tobytes("png"))) text, status = _ocr_pil(image) text_blocks.append(text) statuses.append(f"{path.name}, page {page_number}: {status}") document.close() else: with Image.open(path) as opened: text, status = _ocr_pil(opened.copy()) text_blocks.append(text) statuses.append(f"{path.name}: {status}") except Exception as exc: statuses.append(f"{path.name}: could not be read ({type(exc).__name__}).") raw_text = "\n".join(block for block in text_blocks if block).strip() answers = parse_numbered_answers(raw_text, maximum=maximum) return {"answers": answers, "raw_text": raw_text, "status": statuses}
def render_ocr_mapping(result: dict[str, Any] | None) -> str: if not result: return "No handwritten answer sheet has been read." answers = result.get("answers", {}) status = " \n".join(escape(line) for line in result.get("status", [])) mapped = "\n".join( f"- **Q{number}:** {escape(str(answer)[:500])}" for number, answer in sorted(answers.items()) ) if not mapped: mapped = "No numbered answers were detected. Write each answer under a clear `Q1`, `Q2`, … heading or type it in the corresponding answer box." return f"""### Handwritten-sheet reading
{status}
{mapped}
> OCR is evidence support, not an invisible override. Typed answers take priority whenever both are present."""
def _pdf_styles() -> dict[str, ParagraphStyle]: styles = getSampleStyleSheet() body = ParagraphStyle( "ExamBody", parent=styles["BodyText"], fontName="Helvetica", fontSize=9.2, leading=12.4, textColor=colors.HexColor("#172554"), spaceAfter=5, ) return { "body": body, "title": ParagraphStyle("ExamTitle", parent=body, fontName="Helvetica-Bold", fontSize=22, leading=26, textColor=colors.HexColor("#6D28D9"), spaceAfter=10), "h1": ParagraphStyle("ExamH1", parent=body, fontName="Helvetica-Bold", fontSize=14, leading=18, textColor=colors.HexColor("#0891B2"), spaceBefore=10, spaceAfter=6), "h2": ParagraphStyle("ExamH2", parent=body, fontName="Helvetica-Bold", fontSize=11, leading=14, textColor=colors.HexColor("#6D28D9"), spaceBefore=9, spaceAfter=4), "small": ParagraphStyle("ExamSmall", parent=body, fontSize=7.8, leading=10, textColor=colors.HexColor("#475569")), }
def _pdf_text(value: Any) -> str: return escape(plain_math(str(value or ""))).replace("\n", "<br/>")
def _write_exam_pdf(raw_path: Path, exam: dict[str, Any], grade: dict[str, Any]) -> None: styles = _pdf_styles() document = SimpleDocTemplate( str(raw_path), pagesize=LETTER, rightMargin=0.72 * inch, leftMargin=0.72 * inch, topMargin=0.72 * inch, bottomMargin=0.72 * inch, title=f"{exam['exam_label']} - result", author="M1 Mechanics Quest", subject="Locked examination questions, solutions, and marks", ) story: list[Any] = [ Paragraph("M1 Mechanics Quest", styles["title"]), Paragraph(_pdf_text(exam["exam_label"]), styles["h1"]), Paragraph( _pdf_text( f"Student: {exam['student']} | Attempt: {exam['attempt_id']} | Seed: {exam['seed']} | " f"Score: {grade['score']:g}/{grade['maximum']} ({grade['percentage']:.1f}%) | Graded: {grade['graded_at']}" ), styles["body"], ), ] table_data = [["Q", "Format", "Marks", "Score", "Evidence"]] for row in grade["rows"]: table_data.append([str(row["number"]), row["format"], str(row["marks"]), f"{row['score']:g}", row["source"]]) table = Table(table_data, colWidths=[0.35 * inch, 1.45 * inch, 0.55 * inch, 0.55 * inch, 2.3 * inch], repeatRows=1) table.setStyle(TableStyle([ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#EDE9FE")), ("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#312E81")), ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), ("FONTNAME", (0, 1), (-1, -1), "Helvetica"), ("FONTSIZE", (0, 0), (-1, -1), 7.5), ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#CBD5E1")), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#F8FAFC")]), ])) story.extend([Spacer(1, 8), table, PageBreak(), Paragraph("Questions, responses, and solutions", styles["h1"])]) for row in grade["rows"]: story.append(Paragraph(f"Question {row['number']} | {row['format']} | {row['score']:g}/{row['marks']} marks", styles["h2"])) story.append(Paragraph(_pdf_text(row["question"]), styles["body"])) story.append(Paragraph(f"<b>Student response ({escape(row['source'])}):</b> {_pdf_text(row['response'] or 'No answer')}", styles["body"])) story.append(Paragraph(f"<b>Evaluation:</b> {_pdf_text(row['feedback'])}", styles["body"])) story.append(Paragraph(f"<b>Typed/OCR comparison:</b> {_pdf_text(row['comparison'])}", styles["small"])) story.append(Paragraph(f"<b>Answer key:</b> {_pdf_text(row['answer_key'])}", styles["body"])) story.append(Paragraph("<b>Worked solution / marking guidance</b>", styles["body"])) for index, step in enumerate(row["solution"], 1): story.append(Paragraph(f"{index}. {_pdf_text(step)}", styles["body"])) story.append(Spacer(1, 7)) story.append(Paragraph( "Integrity note: This report is flattened and encrypted with printing permission only. Editing, annotation, form filling, assembly, and extraction permissions are disabled in compliant PDF readers. OCR mismatches require human review.", styles["small"], )) document.build(story)
def export_locked_exam_pdf(exam: dict[str, Any], grade: dict[str, Any]) -> str: output_dir = Path(tempfile.mkdtemp(prefix="m1_exam_report_")) safe_student = re.sub(r"[^A-Za-z0-9_-]+", "_", exam["student"]).strip("_")[:40] or "Student" base = f"M1_{exam['exam_name'].replace(' ', '_')}_{safe_student}_{exam['attempt_id']}" raw_path = output_dir / f"{base}_raw.pdf" locked_path = output_dir / f"{base}_LOCKED.pdf" _write_exam_pdf(raw_path, exam, grade)
reader = PdfReader(str(raw_path)) writer = PdfWriter() for page in reader.pages: writer.add_page(page) writer.add_metadata( { "/Title": f"{exam['exam_label']} - {exam['student']}", "/Author": "M1 Mechanics Quest", "/Subject": "Locked examination questions, solutions, and marks", "/Keywords": f"attempt {exam['attempt_id']}; locked; read-only", } ) permissions = UserAccessPermissions.PRINT | UserAccessPermissions.PRINT_TO_REPRESENTATION writer.encrypt( user_password="", owner_password=secrets.token_urlsafe(36), permissions_flag=permissions, algorithm="AES-256", ) with locked_path.open("wb") as handle: writer.write(handle) raw_path.unlink(missing_ok=True) return str(locked_path)12345678935 unmodified lines4546474849505148 unmodified lines1001011021031041056 unmodified lines112113114115116117"""CSS for the native Gradio floating mechanics-tutor dialog."""from __future__ import annotationsFLOATING_TUTOR_CSS = r"""#floating-tutor-launcher {bottom: 22px !important;left: auto !important;35 unmodified linesright: 22px !important;top: auto !important;width: min(430px, calc(100vw - 28px)) !important;z-index: 1000 !important;}.floating-tutor-dialog-header {align-items: center;48 unmodified lines#floating-tutor-panel .floating-tutor-composer-note { font-size: 11px; margin: 0; }#floating-tutor-panel .floating-tutor-status { font-size: 10px; margin: 0; }@media (max-width: 520px) {#floating-tutor-launcher {bottom: 13px !important;right: 13px !important;6 unmodified lines}}@media (prefers-reduced-motion: reduce) {#floating-tutor-launcher { transform: none !important; }}"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616235 unmodified lines989910010110210310448 unmodified lines1531541551561571581591601611621631641656 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268"""Viewport launcher assets for the native Gradio mechanics-tutor dialog."""from __future__ import annotationsFLOATING_TUTOR_CSS = r"""#floating-tutor-viewport-launcher {align-items: center !important;background: linear-gradient(110deg, #6d28d9, #db2777) !important;border: 1px solid rgba(255, 255, 255, .48) !important;border-radius: 999px !important;bottom: max(18px, env(safe-area-inset-bottom)) !important;box-shadow: 0 14px 34px rgba(76, 29, 149, .36) !important;color: white !important;cursor: pointer !important;display: inline-flex !important;font-family: inherit !important;font-size: 14px !important;font-weight: 850 !important;gap: 7px !important;justify-content: center !important;left: auto !important;line-height: 1.2 !important;margin: 0 !important;min-height: 44px !important;min-width: 142px !important;opacity: 1 !important;padding: 10px 18px !important;pointer-events: auto !important;position: fixed !important;right: max(18px, env(safe-area-inset-right)) !important;top: auto !important;transform: translateZ(0);visibility: visible !important;width: auto !important;z-index: 2147483000 !important;}#floating-tutor-viewport-launcher:hover {box-shadow: 0 17px 40px rgba(76, 29, 149, .44) !important;transform: translateY(-2px) translateZ(0);}#floating-tutor-viewport-launcher:focus-visible {outline: 3px solid rgba(34, 211, 238, .78) !important;outline-offset: 3px !important;}/* The original component remains the native Gradio event source. JavaScriptonly moves it off-screen after the viewport proxy has been installed. */#floating-tutor-launcher.viewport-proxy-active {height: 1px !important;left: -10000px !important;min-height: 1px !important;min-width: 1px !important;opacity: 0 !important;overflow: hidden !important;pointer-events: none !important;position: absolute !important;top: 0 !important;width: 1px !important;}#floating-tutor-launcher {bottom: 22px !important;left: auto !important;35 unmodified linesright: 22px !important;top: auto !important;width: min(430px, calc(100vw - 28px)) !important;z-index: 2147482999 !important;}.floating-tutor-dialog-header {align-items: center;48 unmodified lines#floating-tutor-panel .floating-tutor-composer-note { font-size: 11px; margin: 0; }#floating-tutor-panel .floating-tutor-status { font-size: 10px; margin: 0; }@media (max-width: 520px) {#floating-tutor-viewport-launcher {bottom: max(12px, env(safe-area-inset-bottom)) !important;min-height: 42px !important;min-width: 132px !important;padding: 9px 15px !important;right: max(12px, env(safe-area-inset-right)) !important;}#floating-tutor-launcher {bottom: 13px !important;right: 13px !important;6 unmodified lines}}@media (prefers-reduced-motion: reduce) {#floating-tutor-launcher,#floating-tutor-viewport-launcher { transform: none !important; }}"""# Gradio components can live below transformed or scrolling ancestors, both of# which alter how CSS ``position: fixed`` behaves. This small browser-side# adapter attaches the visible launcher directly to ``document.body`` and# delegates each click to the native Gradio button. The dialog therefore keeps# its normal Python event wiring while the launcher remains viewport-pinned.FLOATING_TUTOR_VIEWPORT_JS = r"""() => {const PROXY_ID = "floating-tutor-viewport-launcher";const NATIVE_ID = "floating-tutor-launcher";const nativeButton = () => {const host = document.getElementById(NATIVE_ID);if (!host) return null;if (host.matches("button")) return host;return host.querySelector("button");};const pinToViewport = (button) => {if (!button) return;const mobile = window.matchMedia("(max-width: 520px)").matches;const inset = mobile ? 12 : 18;const viewport = window.visualViewport;const extraRight = viewport? Math.max(0, window.innerWidth - viewport.offsetLeft - viewport.width): 0;const extraBottom = viewport? Math.max(0, window.innerHeight - viewport.offsetTop - viewport.height): 0;button.style.setProperty("position", "fixed", "important");button.style.setProperty("right", `${inset + extraRight}px`, "important");button.style.setProperty("bottom", `${inset + extraBottom}px`, "important");button.style.setProperty("left", "auto", "important");button.style.setProperty("top", "auto", "important");button.style.setProperty("z-index", "2147483000", "important");};const install = () => {let proxy = document.getElementById(PROXY_ID);if (!proxy) {proxy = document.createElement("button");proxy.id = PROXY_ID;proxy.type = "button";proxy.textContent = "💬 Ask Tutor";proxy.setAttribute("aria-label", "Open Ask Tutor for the active mechanics problem");proxy.setAttribute("aria-controls", "floating-tutor-panel");proxy.addEventListener("click", () => {const target = nativeButton();if (target) target.click();});document.body.appendChild(proxy);}pinToViewport(proxy);const nativeHost = document.getElementById(NATIVE_ID);if (nativeHost) {nativeHost.classList.add("viewport-proxy-active");nativeHost.setAttribute("aria-hidden", "true");const target = nativeButton();if (target) target.tabIndex = -1;}return proxy;};if (!window.__m1TutorViewportLauncherInstalled) {window.__m1TutorViewportLauncherInstalled = true;let frame = 0;const schedulePin = () => {window.cancelAnimationFrame(frame);frame = window.requestAnimationFrame(() => pinToViewport(install()));};window.addEventListener("scroll", schedulePin, {passive: true, capture: true});document.addEventListener("scroll", schedulePin, {passive: true, capture: true});window.addEventListener("resize", schedulePin, {passive: true});window.addEventListener("orientationchange", schedulePin, {passive: true});if (window.visualViewport) {window.visualViewport.addEventListener("scroll", schedulePin, {passive: true});window.visualViewport.addEventListener("resize", schedulePin, {passive: true});}new MutationObserver(() => install()).observe(document.body, {childList: true,subtree: true,});}install();return [];}"""
README.md+32
START_HERE.txt+15
app.py+438-13
exam_engine.pyAdded+809
floating_tutor.py+154-3