Spaces:
Paused
Paused
Upload 27 files
Browse filesFiles changed (4)
- README.md+65
- START_HERE.txt+19
- app.py+502-2
- obe_engine.pyAdded+643
79 unmodified lines808182838485145 unmodified lines23123223323423523679 unmodified lines- a separate **Assignments** studio with an adjustable question count, originalassignment generation, numbered typed/image/PDF submission, evaluation,solutions, and a downloadable report;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.145 unmodified linesnumbered handwritten images/PDF. Evaluation reveals the question-by-questionfeedback and solutions and creates a downloadable result report.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start79 unmodified lines8081828384858687888990919293949596979899100101102103145 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030179 unmodified lines- a separate **Assignments** studio with an adjustable question count, originalassignment generation, numbered typed/image/PDF submission, evaluation,solutions, and a downloadable report;- an **Extraordinary Activities** record for assessed projects, competitions,investigations, presentations, prototypes, tutoring, outreach, and otherwork outside the three protected examinations and assignments, includingoptional image/PDF/Word evidence;- an **Outcome-Based Education (OBE)** calculator on a maximum attainment of3.000, with editable component percentages, automatic latest-score loading,a transparent contribution table, and a fixed 0–3 Plotly spider chart;- default OBE weights of 10% Midterm 1, 10% Midterm 2, 10% Assignment, 50%Final examination, and 20% Extraordinary activities, which correspond tomaximum contributions of 0.3, 0.3, 0.3, 1.5, and 0.6;- a question-by-question **Mistake Analysis** studio that reports the response,marking feedback, correct answer, topic/format success rates, strengths,weaknesses, opportunities, challenges, and a prioritized improvement plan;- a mistake-analysis chatbot grounded in the selected completed assessment,with Qwen, verified-local, and optional OpenAI tutor routes;- congratulatory standard, silver distinction, gold excellence, and diamondachievement certificate previews with rendered ribbon/medal artwork and aprint-enabled, edit-locked, verification-coded PDF download;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.145 unmodified linesnumbered handwritten images/PDF. Evaluation reveals the question-by-questionfeedback and solutions and creates a downloadable result report.### Extraordinary activities, OBE, and attainment evidenceOpen **🌟 Extraordinary activities** to record one or more activities outsideMidterm 1, Midterm 2, assignments, and the Final examination. Each record hasobtained and maximum marks and can include optional evidence. Multiple activitymarks are added before their combined ratio is used by OBE.Completed protected examinations and assignments are stored in sessionassessment history automatically. In **📈 OBE attainment**, click **Load latestrecorded scores** to copy the newest result of each type plus the combinedextraordinary-activity score. Every mark field remains editable for moderation.The calculation for each component is:`3 × component percentage weight ÷ 100 × (marks obtained ÷ maximum marks)`The five weight percentages must total 100. The defaults are 10%, 10%, 10%,50%, and 20%, so a fully attained student receives contributions of 0.3, 0.3,0.3, 1.5, and 0.6, totaling 3.000. A fixed 0–3 spider chart displays theunweighted attainment level reached within each component so component shapesremain directly comparable.### Mistake analysis and certificatesOpen **🧭 Mistake analysis**, refresh completed assessments, select an attempt,and click **Analyse mistakes**. The report reveals each lost-mark response,marker feedback, correct answer, topic-specific next action, performance bytopic and question format, and a strengths/weaknesses/opportunities/challengessummary. Its dedicated chatbot uses the selected correction record as verifiedcontext and can explain or defend the analysis.Open **🏅 Certificates** after computing OBE attainment. To avoid gaps createdby overlapping wording, the app uses these continuous bands:| Attainment | Overall percentage | Certificate ||---:|---:|---|| Below 1.800 | Below 60% | Not generated || 1.800 to below 2.400 | 60% to below 80% | Standard achievement || 2.400 to below 2.700 | 80% to below 90% | Silver distinction || 2.700 to below 2.900 | 90% to below 96.67% | Gold excellence || 2.900 to 3.000 | 96.67% to 100% | Diamond achievement |The exact phrase **100 percent achievement** appears only when attainment is3.000/3.000. Every eligible certificate congratulates the student, shows theactual score, includes programmatically rendered ribbon/medal artwork, and isdownloaded as an encrypted PDF that permits printing but not editing.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start
64 unmodified lines65666768697064 unmodified linestyped answers or numbered handwritten images/PDF. The portal evaluates thesubmission, reveals solutions, and creates a result PDF.NEW QUESTION INTAKE-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/text64 unmodified lines6566676869707172737475767778798081828384858687888964 unmodified linestyped answers or numbered handwritten images/PDF. The portal evaluates thesubmission, reveals solutions, and creates a result PDF.EXTRAORDINARY ACTIVITIES, OBE, AND CERTIFICATES------------------------------------------------Use "Extraordinary activities" for assessed projects, competitions,presentations, investigations, prototypes, tutoring, outreach, or other work.Obtained and maximum marks from multiple records are combined.Completed exams and assignments feed the session assessment history. Open"OBE attainment" and load the newest scores, or enter/moderate them manually.The default percentages are Midterm 1 10%, Midterm 2 10%, Assignment 10%,Final examination 50%, and Extraordinary activities 20%; they must total 100%.The maximum attainment is 3.000 and the spider chart always uses a 0–3 scale.Use "Mistake analysis" to select a completed assessment and reveal every lostmark, correct answer, topic/format performance, strong and weak areas, and animprovement plan. A dedicated Qwen/local/optional-OpenAI chatbot is grounded inthat report. Use "Certificates" after OBE computation. Certificates start at60%, progress through standard, silver, gold, and diamond awards, and downloadas print-enabled, edit-locked PDFs with rendered ribbon and medal artwork.NEW QUESTION INTAKE-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/text
47 unmodified lines48495051525361 unmodified lines115116117118119120121421 unmodified lines54354454554654754813 unmodified lines56256356456556656713 unmodified lines58158258358458558617 unmodified lines60460560660760860913 unmodified lines6236246256266276283 unmodified lines6326336346356366372 unmodified lines640641642643644645101 unmodified lines7477487497507517524 unmodified lines7577587597607617624 unmodified lines7677687697707717721 unmodified line77477577677777877978078178211 unmodified lines794795796797798799495 unmodified lines129512961297129812991300405 unmodified lines17061707170817091710171111 unmodified lines1723172417251726172717285 unmodified lines17341735173617371738173911 unmodified lines17511752175317541755175627 unmodified lines17841785178617871788178917901 unmodified line179217931794179517961797179847 unmodified linesfrom 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 (SUPPORTED_EXTENSIONS,bank_choices,61 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 this421 unmodified linesuploaded_answer_sheets,ocr_state: dict | None,declaration: bool,*typed_answers: str,):unchanged = [gr.update() for _ in range(MAX_EXAM_QUESTIONS * 2)]13 unmodified linesocr_state or {},gr.update(),gr.update(),*unchanged,)exam = reconstruct_exam(attempt)13 unmodified linesocr_state or {},gr.update(),gr.update(),*unchanged,)17 unmodified linesfrozen_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))return (summary,solutions,13 unmodified linessheet_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>',*frozen_answers,*frozen_timers,)3 unmodified linesattempt: dict | None,uploaded_answer_sheets,ocr_state: dict | None,*typed_answers: str,):"""Deadline-triggered submission does not require the learner declaration."""2 unmodified linesuploaded_answer_sheets,ocr_state,True,*typed_answers,)101 unmodified linesassignment_state: dict | None,typed_numbered_answers: str,uploaded_files,):exam = reconstruct_exam(assignment_state)if not exam:4 unmodified linesgr.update(),gr.update(),gr.update(),)exam["exam_label"] = f"Assignment · {(assignment_state or {}).get('assignment_title', 'Mechanics assignment')}"typed_map = parse_numbered_answers(typed_numbered_answers, maximum=exam["count"])4 unmodified linesgrade = grade_exam(exam, typed_list, sheet_result.get("answers", {}))summary, solutions = render_exam_results(grade)pdf_path = export_locked_exam_pdf(exam, grade)return (f"✅ Assignment submitted and evaluated: **{grade['score']:g}/{grade['maximum']} marks ({grade['percentage']:.1f}%)**.",summary,1 unmodified linepdf_path,gr.update(interactive=False),gr.update(interactive=False),)theme = gr.themes.Soft(primary_hue="violet",secondary_hue="pink",11 unmodified linesexam_attempt_state = gr.State({})exam_ocr_state = gr.State({})assignment_state = gr.State({})gr.HTML("""<section class="hero">495 unmodified lineslabel="Assignment result PDF · questions, marks, and solutions")with gr.Tab("📚 Theory vault"):theory_md = gr.Markdown(theory_for(INITIAL_QUESTION),405 unmodified linesexam_answer_sheets,exam_ocr_state,exam_declaration,*exam_answer_boxes,],outputs=[11 unmodified linesexam_ocr_state,exam_ocr_preview,exam_main_timer_display,*exam_answer_boxes,*exam_question_timer_buttons,],5 unmodified linesexam_attempt_state,exam_answer_sheets,exam_ocr_state,*exam_answer_boxes,],outputs=[11 unmodified linesexam_ocr_state,exam_ocr_preview,exam_main_timer_display,*exam_answer_boxes,*exam_question_timer_buttons,],27 unmodified lines)assignment_submit_btn.click(submit_assignment_interface,inputs=[assignment_state, assignment_typed_answers, assignment_submission_files],outputs=[assignment_status,assignment_result,1 unmodified lineassignment_pdf,assignment_typed_answers,assignment_submission_files,],)generate_btn.click(47 unmodified lines4849505152535455565758596061626364656667686970717261 unmodified lines134135136137138139140421 unmodified lines56256356456556656756813 unmodified lines58258358458558658758813 unmodified lines60260360460560660760817 unmodified lines62662762862963063163263363413 unmodified lines6486496506516526536543 unmodified lines6586596606616626636642 unmodified lines667668669670671672673101 unmodified lines7757767777787797807814 unmodified lines7867877887897907917924 unmodified lines7977987998008018028038048051 unmodified line80780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894911 unmodified lines961962963964965966967968969970495 unmodified lines146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699405 unmodified lines210521062107210821092110211111 unmodified lines21232124212521262127212821295 unmodified lines213521362137213821392140214111 unmodified lines215321542155215621572158215927 unmodified lines2187218821892190219121922193219421952196219721981 unmodified line22002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229847 unmodified linesfrom 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 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,61 unmodified linesreturn FALLBACK_CSSCSS = load_css() + "\n" + FLOATING_TUTOR_CSS + "\n" + EXAM_CSS + "\n" + OBE_CSS# Gradio enables display mathematics by default, but single-dollar inline# mathematics is opt-in. Every learner-facing mathematics panel uses this421 unmodified linesuploaded_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)]13 unmodified linesocr_state or {},gr.update(),gr.update(),assessment_history or [],*unchanged,)exam = reconstruct_exam(attempt)13 unmodified linesocr_state or {},gr.update(),gr.update(),assessment_history or [],*unchanged,)17 unmodified linesfrozen_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,13 unmodified linessheet_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,)3 unmodified linesattempt: 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."""2 unmodified linesuploaded_answer_sheets,ocr_state,True,assessment_history,*typed_answers,)101 unmodified linesassignment_state: dict | None,typed_numbered_answers: str,uploaded_files,assessment_history: list[dict] | None,):exam = reconstruct_exam(assignment_state)if not exam:4 unmodified linesgr.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"])4 unmodified linesgrade = 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,1 unmodified linepdf_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 Nonestatus = (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), statusdef 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 Nonereturn 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",11 unmodified linesexam_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">495 unmodified lineslabel="Assignment result PDF · questions, marks, and solutions")with gr.Tab("🌟 Extraordinary activities"):gr.Markdown("""## Extraordinary activity recordRecord 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 attainmentThe 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 studioSelect 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 certificatesCertificates become available at **60% (1.800/3.000)**. The continuous award bands are: standard 60–<80%, silver distinction 80–<90%, gold excellence 90–<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),405 unmodified linesexam_answer_sheets,exam_ocr_state,exam_declaration,assessment_history_state,*exam_answer_boxes,],outputs=[11 unmodified linesexam_ocr_state,exam_ocr_preview,exam_main_timer_display,assessment_history_state,*exam_answer_boxes,*exam_question_timer_buttons,],5 unmodified linesexam_attempt_state,exam_answer_sheets,exam_ocr_state,assessment_history_state,*exam_answer_boxes,],outputs=[11 unmodified linesexam_ocr_state,exam_ocr_preview,exam_main_timer_display,assessment_history_state,*exam_answer_boxes,*exam_question_timer_buttons,],27 unmodified lines)assignment_submit_btn.click(submit_assignment_interface,inputs=[assignment_state,assignment_typed_answers,assignment_submission_files,assessment_history_state,],outputs=[assignment_status,assignment_result,1 unmodified lineassignment_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_btn.click(
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643"""Extraordinary activities, OBE attainment, mistake analytics, and certificates."""
from __future__ import annotations
from collections import defaultdictfrom datetime import datetime, timezonefrom hashlib import sha256from html import escapefrom pathlib import Pathimport reimport secretsimport tempfilefrom typing import Any, Iterable
import plotly.graph_objects as gofrom pypdf import PdfReader, PdfWriterfrom pypdf.constants import UserAccessPermissionsfrom reportlab.lib import colorsfrom reportlab.lib.pagesizes import A4, landscapefrom reportlab.pdfbase.pdfmetrics import stringWidthfrom reportlab.pdfgen import canvas
COMPONENTS = ( "Midterm 1", "Midterm 2", "Assignment", "Final examination", "Extraordinary activities",)DEFAULT_WEIGHT_PERCENTAGES = { "Midterm 1": 10.0, "Midterm 2": 10.0, "Assignment": 10.0, "Final examination": 50.0, "Extraordinary activities": 20.0,}MAX_ATTAINMENT = 3.0
ACTIVITY_CATEGORIES = ( "Mechanics project or model", "Competition or olympiad", "Research or investigation", "Presentation or seminar", "Innovation or prototype", "Peer tutoring or leadership", "Community or outreach activity", "Other extraordinary activity",)
TOPIC_RECOMMENDATIONS = { "Kinematics · vertical motion": "Practise sign conventions first, then select SUVAT equations using a complete u-v-a-s-t table.", "Kinematics · speed–time graph": "Revisit gradient as acceleration and area as distance; label every graph section before calculating.", "Momentum · impulse & collision": "Declare one positive direction, conserve signed momentum, and distinguish impulse from momentum.", "Statics · moments on a beam": "Draw the force diagram, mark perpendicular distances, and take moments about a named point.", "Forces · rough horizontal plane": "Resolve angled forces vertically before using friction; use F = mu R only at limiting equilibrium.", "Forces · connected particles": "Draw separate force diagrams, choose the actual motion direction, and keep one acceleration magnitude.", "Vectors · 2D motion & bearings": "Retain component signs, identify the quadrant, and measure bearings clockwise from north.", "Equilibrium · strings & forces": "Draw every external force and resolve along two deliberate perpendicular directions.",}
OBE_CSS = r""".obe-card { background: linear-gradient(140deg, #f8fafc, #eef2ff 55%, #fdf2f8); border: 1px solid rgba(109,40,217,.18); border-radius: 20px; box-shadow: 0 12px 34px rgba(30,41,59,.09); padding: 16px !important;}.activity-card { background: rgba(255,255,255,.98); border: 1px solid #dbeafe; border-left: 5px solid #f59e0b; border-radius: 14px; margin: 8px 0; padding: 11px 13px;}.mistake-card { background: #fff7ed; border: 1px solid #fed7aa; border-left: 5px solid #f97316; border-radius: 14px; margin: 10px 0; padding: 12px 14px;}.certificate-preview { background: linear-gradient(145deg, #fffef7, #ffffff 50%, #f5f3ff); border: 10px double #6d28d9; border-radius: 12px; box-shadow: 0 20px 50px rgba(30,41,59,.16); color: #172554; margin: 12px auto; max-width: 950px; padding: 36px; position: relative; text-align: center;}.certificate-preview h1 { color: #312e81; font-family: Georgia, serif; font-size: clamp(28px,5vw,48px); margin: 8px; }.certificate-preview h2 { color: #6d28d9; font-family: Georgia, serif; }.certificate-preview .recipient { color: #9f1239; font-family: Georgia, serif; font-size: clamp(24px,4vw,38px); font-weight: 800; }.certificate-medal { height: 150px; margin: 0 auto 12px; position: relative; width: 130px; }.certificate-medal .ribbon-left,.certificate-medal .ribbon-right { clip-path: polygon(0 0,100% 0,80% 100%,50% 78%,20% 100%); height: 100px; position: absolute; top: 0; width: 58px; }.certificate-medal .ribbon-left { left: 18px; transform: rotate(-8deg); }.certificate-medal .ribbon-right { right: 18px; transform: rotate(8deg); }.certificate-medal .coin { align-items:center; border-radius:50%; bottom:0; display:flex; font-size:38px; font-weight:900; height:86px; justify-content:center; left:22px; position:absolute; width:86px; z-index:2; }.medal-standard .ribbon-left,.medal-standard .ribbon-right { background: linear-gradient(90deg,#2563eb,#93c5fd,#1d4ed8); }.medal-standard .coin { background: radial-gradient(circle at 35% 30%,#fef3c7,#d97706); border:7px double #92400e; color:#78350f; }.medal-silver .ribbon-left,.medal-silver .ribbon-right { background: linear-gradient(90deg,#64748b,#f8fafc,#94a3b8); }.medal-silver .coin { background: radial-gradient(circle at 35% 30%,#ffffff,#94a3b8); border:7px double #475569; color:#334155; }.medal-gold .ribbon-left,.medal-gold .ribbon-right { background: linear-gradient(90deg,#b45309,#fde68a,#d97706); }.medal-gold .coin { background: radial-gradient(circle at 35% 30%,#fff7ae,#f59e0b); border:7px double #92400e; color:#78350f; }.medal-diamond .ribbon-left,.medal-diamond .ribbon-right { background: linear-gradient(90deg,#0891b2,#cffafe,#7c3aed); }.medal-diamond .coin { background: linear-gradient(135deg,#ffffff,#a5f3fc 32%,#c4b5fd 68%,#ffffff); border:7px double #6d28d9; border-radius:18px; color:#4c1d95; transform:rotate(45deg); }.medal-diamond .coin span { transform:rotate(-45deg); }"""
def _number(value: Any, default: float = 0.0) -> float: try: return float(value) except (TypeError, ValueError): return default
def add_extraordinary_activity( records: list[dict[str, Any]] | None, student: str, title: str, category: str, description: str, marks_obtained: float, maximum_marks: float, evidence_files: Any = None,) -> list[dict[str, Any]]: maximum = _number(maximum_marks) obtained = _number(marks_obtained) if maximum <= 0: raise ValueError("Maximum activity marks must be greater than zero.") if obtained < 0 or obtained > maximum: raise ValueError("Activity marks obtained must be between zero and the maximum marks.") files = evidence_files if isinstance(evidence_files, (list, tuple)) else ([evidence_files] if evidence_files else []) evidence_names = [Path(str(getattr(item, "name", item))).name for item in files if item] payload = f"{student}|{title}|{category}|{obtained}|{maximum}|{datetime.now(timezone.utc).isoformat()}" record = { "id": "EA-" + sha256(payload.encode("utf-8")).hexdigest()[:10].upper(), "student": str(student or "Student").strip()[:100] or "Student", "title": str(title or "Extraordinary activity").strip()[:160] or "Extraordinary activity", "category": category if category in ACTIVITY_CATEGORIES else ACTIVITY_CATEGORIES[-1], "description": str(description or "").strip()[:1500], "score": obtained, "maximum": maximum, "percentage": 100 * obtained / maximum, "evidence": evidence_names, "recorded_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), } return [*(records or []), record]
def activity_totals(records: list[dict[str, Any]] | None) -> tuple[float, float]: return ( sum(_number(record.get("score")) for record in (records or [])), sum(_number(record.get("maximum")) for record in (records or [])), )
def render_activities(records: list[dict[str, Any]] | None) -> str: items = records or [] if not items: return "No extraordinary activity has been recorded in this session." obtained, maximum = activity_totals(items) cards = [] for index, record in enumerate(items, 1): evidence = ", ".join(escape(name) for name in record.get("evidence", [])) or "No file attached" cards.append( f'''<div class="activity-card"><b>{index}. {escape(record['title'])}</b><br> {escape(record['category'])} · <b>{record['score']:g}/{record['maximum']:g}</b> ({record['percentage']:.1f}%)<br> {escape(record.get('description','')) or 'No description'}<br><small>Evidence: {evidence} · {escape(record['recorded_at'])}</small></div>''' ) return ( f"## Extraordinary activity record\n\n**Combined score:** {obtained:g}/{maximum:g} " f"({(100*obtained/maximum if maximum else 0):.1f}%)\n\n" + "\n".join(cards) )
def latest_component_scores( assessment_history: list[dict[str, Any]] | None, activities: list[dict[str, Any]] | None,) -> dict[str, tuple[float, float]]: latest: dict[str, tuple[float, float]] = {} type_map = { "Midterm 1": "Midterm 1", "Midterm 2": "Midterm 2", "Final examination": "Final examination", "Assignment": "Assignment", } for record in assessment_history or []: record_type = type_map.get(str(record.get("type"))) if record_type: latest[record_type] = (_number(record.get("score")), _number(record.get("maximum"))) latest["Extraordinary activities"] = activity_totals(activities) return {component: latest.get(component, (0.0, 0.0)) for component in COMPONENTS}
def calculate_obe_attainment( student: str, scores: dict[str, tuple[float, float]], weight_percentages: dict[str, float],) -> dict[str, Any]: weights = {component: _number(weight_percentages.get(component)) for component in COMPONENTS} if any(value < 0 for value in weights.values()): raise ValueError("OBE component weights cannot be negative.") if abs(sum(weights.values()) - 100.0) > 0.01: raise ValueError(f"OBE component percentages must total 100%; the current total is {sum(weights.values()):.2f}%.") components: list[dict[str, Any]] = [] total_attainment = 0.0 for component in COMPONENTS: obtained, maximum = scores.get(component, (0.0, 0.0)) if maximum < 0 or obtained < 0: raise ValueError(f"{component} marks cannot be negative.") if maximum and obtained > maximum: raise ValueError(f"{component} obtained marks cannot exceed maximum marks.") ratio = obtained / maximum if maximum > 0 else 0.0 component_attainment = MAX_ATTAINMENT * ratio maximum_contribution = MAX_ATTAINMENT * weights[component] / 100.0 contribution = maximum_contribution * ratio total_attainment += contribution components.append( { "component": component, "obtained": obtained, "maximum": maximum, "ratio": ratio, "percentage": 100 * ratio, "weight_percentage": weights[component], "maximum_contribution": maximum_contribution, "contribution": contribution, "component_attainment": component_attainment, } ) total_attainment = min(MAX_ATTAINMENT, max(0.0, total_attainment)) return { "student": str(student or "Student").strip()[:100] or "Student", "attainment": total_attainment, "overall_percentage": 100 * total_attainment / MAX_ATTAINMENT, "components": components, "weights": weights, "computed_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), }
def render_obe_result(result: dict[str, Any]) -> str: rows = "\n".join( f"| {row['component']} | {row['obtained']:g}/{row['maximum']:g} | {row['percentage']:.1f}% | " f"{row['weight_percentage']:.1f}% | {row['contribution']:.3f}/{row['maximum_contribution']:.3f} |" for row in result["components"] ) return f"""## OBE attainment result
### {result['attainment']:.3f}/3.000 · {result['overall_percentage']:.2f}%
| Component | Marks | Performance | Weight | Attainment contribution ||---|---:|---:|---:|---:|{rows}
The contribution formula is `3 × component weight% × (marks obtained / maximum marks)`. The default final-examination weight is 50%, giving a maximum contribution of 1.5 attainment points."""
def obe_spider_chart(result: dict[str, Any] | None = None) -> go.Figure: labels = list(COMPONENTS) if result: values = [row["component_attainment"] for row in result["components"]] student = result["student"] else: values = [0.0] * len(labels) student = "Student" figure = go.Figure() figure.add_trace( go.Scatterpolar( r=values + values[:1], theta=labels + labels[:1], fill="toself", name=student, line=dict(color="#7c3aed", width=3), fillcolor="rgba(124,58,237,.22)", hovertemplate="%{theta}: %{r:.3f}/3<extra></extra>", ) ) figure.update_layout( title=dict(text="Student attainment by OBE component · fixed 0–3 scale", x=0.5), polar=dict( bgcolor="rgba(248,250,252,.9)", radialaxis=dict(visible=True, range=[0, 3], tickvals=[0, 0.6, 1.2, 1.8, 2.4, 3.0]), ), showlegend=False, height=560, margin=dict(l=70, r=70, t=80, b=70), paper_bgcolor="white", font=dict(family="DM Sans, Arial", color="#172554"), ) return figure
def append_assessment_record( history: list[dict[str, Any]] | None, assessment_type: str, grade: dict[str, Any], exam: dict[str, Any],) -> list[dict[str, Any]]: record = { "id": exam["attempt_id"], "type": assessment_type, "student": grade["student"], "score": grade["score"], "maximum": grade["maximum"], "percentage": grade["percentage"], "graded_at": grade["graded_at"], "rows": grade["rows"], } cleaned = [item for item in (history or []) if item.get("id") != record["id"] or item.get("type") != assessment_type] return [*cleaned, record]
def assessment_choices(history: list[dict[str, Any]] | None) -> list[tuple[str, str]]: return [ ( f"{record.get('type','Assessment')} · {record.get('student','Student')} · " f"{_number(record.get('score')):g}/{_number(record.get('maximum')):g} · {record.get('graded_at','')}", f"{record.get('type','Assessment')}::{record.get('id','')}", ) for record in reversed(history or []) ]
def select_assessment(history: list[dict[str, Any]] | None, selection: str) -> dict[str, Any] | None: if not selection or "::" not in selection: return None assessment_type, record_id = selection.split("::", 1) return next( ( record for record in reversed(history or []) if record.get("type") == assessment_type and record.get("id") == record_id ), None, )
def mistake_analysis(record: dict[str, Any] | None) -> str: if not record: return "Complete or select an assessment to analyse mistakes." rows = record.get("rows", []) topic_totals: dict[str, list[float]] = defaultdict(lambda: [0.0, 0.0]) format_totals: dict[str, list[float]] = defaultdict(lambda: [0.0, 0.0]) mistakes = [] for row in rows: topic = str(row.get("topic_label", "Mechanics")) question_format = str(row.get("format", "Question")) topic_totals[topic][0] += _number(row.get("score")) topic_totals[topic][1] += _number(row.get("marks")) format_totals[question_format][0] += _number(row.get("score")) format_totals[question_format][1] += _number(row.get("marks")) if _number(row.get("score")) + 1e-9 < _number(row.get("marks")): mistakes.append(row)
topic_rates = { topic: (100 * values[0] / values[1] if values[1] else 0.0) for topic, values in topic_totals.items() } format_rates = { name: (100 * values[0] / values[1] if values[1] else 0.0) for name, values in format_totals.items() } strong = [topic for topic, rate in sorted(topic_rates.items(), key=lambda item: -item[1]) if rate >= 75] weak = [topic for topic, rate in sorted(topic_rates.items(), key=lambda item: item[1]) if rate < 60] if not weak and topic_rates: weak = [min(topic_rates, key=topic_rates.get)] challenge_formats = [name for name, rate in sorted(format_rates.items(), key=lambda item: item[1]) if rate < 70]
mistake_cards = [] for row in mistakes: mistake_cards.append( f'''<div class="mistake-card"><b>Question {row['number']} · {escape(row['topic_label'])} · {row['score']:g}/{row['marks']} marks</b><br> <b>Your answer:</b> {escape(str(row.get('response') or 'No answer'))}<br> <b>What went wrong:</b> {escape(str(row.get('feedback','')))}<br> <b>Correct answer:</b> {escape(str(row.get('answer_key','')))}<br> <b>Next action:</b> {escape(TOPIC_RECOMMENDATIONS.get(row['topic_label'], 'Rebuild the physical model, show the governing equation, and check signs and units.'))}</div>''' ) mistake_html = "\n".join(mistake_cards) if mistake_cards else '<div class="activity-card"><b>No marked mistakes.</b> Every assessed answer received full credit.</div>' topic_table = "\n".join(f"| {topic} | {rate:.1f}% |" for topic, rate in sorted(topic_rates.items(), key=lambda item: -item[1])) format_table = "\n".join(f"| {name} | {rate:.1f}% |" for name, rate in sorted(format_rates.items(), key=lambda item: -item[1])) suggestions = "\n".join( f"- **{topic}:** {TOPIC_RECOMMENDATIONS.get(topic, 'Practise a complete model-equation-substitution-unit workflow.')}" for topic in weak[:4] ) or "- Maintain the current method quality and attempt more challenge questions." return f"""## Mistake analysis · {escape(str(record.get('type','Assessment')))}
**Student:** {escape(str(record.get('student','Student')))} · **Score:** {record.get('score',0):g}/{record.get('maximum',0):g} ({record.get('percentage',0):.1f}%)
### Question-by-question corrections
{mistake_html}
### Topic performance
| Topic | Success rate ||---|---:|{topic_table}
### Question-format performance
| Format | Success rate ||---|---:|{format_table}
### Strengths, weaknesses, opportunities, and challenges
- **Strengths:** {escape(', '.join(strong) if strong else 'Persistence and willingness to complete the assessment')}- **Weak areas:** {escape(', '.join(weak) if weak else 'No significant weak topic detected')}- **Opportunities:** targeted correction practice, timed mini-tests, diagram-first modelling, and tutor clarification using the chat below- **Challenges:** {escape(', '.join(challenge_formats) if challenge_formats else 'Maintaining accuracy under examination timing')}
### Highest-priority improvement plan
{suggestions}"""
def mistake_context_question(record: dict[str, Any]) -> dict[str, Any]: wrong = [row for row in record.get("rows", []) if _number(row.get("score")) < _number(row.get("marks"))] prompt = "\n\n".join( f"Q{row['number']} ({row['topic_label']}): Student answered {row.get('response') or 'nothing'}. " f"Marker feedback: {row.get('feedback')}. Correct answer: {row.get('answer_key')}." for row in wrong[:12] ) or "The student obtained full credit on every question." solution_steps = [ TOPIC_RECOMMENDATIONS.get(row["topic_label"], "Check the model, signs, equation, substitution, and units.") for row in wrong[:8] ] or ["Attempt challenge questions while retaining the same clear method."] return { "id": f"MISTAKE-{record.get('id','SESSION')}", "seed": 0, "topic": "mixed", "topic_label": "Assessment mistake analysis", "difficulty": "Exam review", "title": f"{record.get('type','Assessment')} correction clinic", "prompt": prompt, "marks": int(_number(record.get("maximum"))), "expected_answers": [], "solution_steps": solution_steps, "mark_scheme": [], "theory_key": "collision", "hints": solution_steps, "diagram_kind": "vectors", "diagram_data": {}, "common_errors": [], }
def certificate_band(result: dict[str, Any]) -> dict[str, str] | None: attainment = _number(result.get("attainment")) percentage = _number(result.get("overall_percentage")) if attainment < 1.8 or percentage < 60: return None if attainment >= 2.90: perfect = attainment >= 2.995 return { "key": "diamond", "award": "Diamond Achievement Award", "statement": ( "Extraordinary and incredible performance with 100 percent achievement" if perfect else "Extraordinary and incredible performance in M1 Mechanics" ), "knowledge": "Dominant command of the subject", "icon": "◆", } if attainment >= 2.70: return { "key": "gold", "award": "Excellence Award", "statement": "Outstanding performance in M1 Mechanics", "knowledge": "Exceptional knowledge of the subject", "icon": "★", } if attainment >= 2.40: return { "key": "silver", "award": "Certificate with Distinction", "statement": "Performance with distinction in M1 Mechanics", "knowledge": "Strong knowledge of the subject", "icon": "✦", } return { "key": "standard", "award": "Certificate of Achievement", "statement": "Successful achievement in M1 Mechanics", "knowledge": "Developing and demonstrated subject knowledge", "icon": "✓", }
def certificate_preview(result: dict[str, Any]) -> str: band = certificate_band(result) if not band: return ( '<div class="certificate-preview"><h2>Certificate not yet available</h2>' '<p>An overall attainment of at least 1.800/3.000 (60%) is required. Continue the improvement plan and recompute OBE attainment.</p></div>' ) student = escape(str(result.get("student", "Student"))) return f''' <section class="certificate-preview"> <div class="certificate-medal medal-{band['key']}"> <div class="ribbon-left"></div><div class="ribbon-right"></div> <div class="coin"><span>{band['icon']}</span></div> </div> <div style="letter-spacing:.15em;font-weight:900;color:#7c3aed">M1 MECHANICS QUEST</div> <h1>{escape(band['award'])}</h1> <p>This certificate is proudly presented to</p> <div class="recipient">{student}</div> <h2>Congratulations!</h2> <p>{escape(band['statement'])}.</p> <p><b>Overall attainment:</b> {result['attainment']:.3f}/3.000 · <b>Overall performance:</b> {result['overall_percentage']:.2f}%</p> <p>{escape(band['knowledge'])}.</p> <small>Computed {escape(str(result.get('computed_at','')))} · certificate verification is embedded in the downloadable PDF.</small> </section> '''
def _fit_text(c: canvas.Canvas, text: str, maximum_width: float, starting_size: float, font: str) -> float: size = starting_size while size > 14 and stringWidth(text, font, size) > maximum_width: size -= 1 return size
def _draw_medal(c: canvas.Canvas, key: str, x: float, y: float) -> None: palettes = { "standard": (colors.HexColor("#2563EB"), colors.HexColor("#F59E0B"), colors.HexColor("#92400E")), "silver": (colors.HexColor("#94A3B8"), colors.HexColor("#E2E8F0"), colors.HexColor("#475569")), "gold": (colors.HexColor("#D97706"), colors.HexColor("#FDE68A"), colors.HexColor("#92400E")), "diamond": (colors.HexColor("#0891B2"), colors.HexColor("#C4B5FD"), colors.HexColor("#6D28D9")), } ribbon, medal, edge = palettes[key] c.setFillColor(ribbon) c.saveState() c.translate(x, y) c.rotate(-8) c.rect(-42, 30, 36, 95, fill=1, stroke=0) c.rotate(16) c.rect(6, 30, 36, 95, fill=1, stroke=0) c.restoreState() c.setFillColor(medal) c.setStrokeColor(edge) c.setLineWidth(6) if key == "diamond": c.saveState() c.translate(x, y) c.rotate(45) c.roundRect(-38, -38, 76, 76, 10, fill=1, stroke=1) c.restoreState() c.setFillColor(edge) c.setFont("Helvetica-Bold", 30) c.drawCentredString(x, y - 10, "D") else: c.circle(x, y, 44, fill=1, stroke=1) c.setFillColor(edge) c.setFont("Helvetica-Bold", 30) c.drawCentredString(x, y - 10, "A")
def export_certificate_pdf(result: dict[str, Any]) -> str | None: band = certificate_band(result) if not band: return None output_dir = Path(tempfile.mkdtemp(prefix="m1_certificate_")) safe_student = re.sub(r"[^A-Za-z0-9_-]+", "_", str(result.get("student", "Student"))).strip("_")[:50] or "Student" verification_source = f"{safe_student}|{result['attainment']:.6f}|{result.get('computed_at','')}" verification = "M1C-" + sha256(verification_source.encode("utf-8")).hexdigest()[:16].upper() raw = output_dir / f"{safe_student}_{band['key']}_certificate_raw.pdf" locked = output_dir / f"{safe_student}_{band['key']}_certificate.pdf" width, height = landscape(A4) c = canvas.Canvas(str(raw), pagesize=(width, height)) c.setTitle(f"{band['award']} - {result['student']}") c.setAuthor("M1 Mechanics Quest") c.setFillColor(colors.HexColor("#FFFEF7")) c.rect(0, 0, width, height, fill=1, stroke=0) c.setStrokeColor(colors.HexColor("#6D28D9")) c.setLineWidth(8) c.rect(28, 28, width - 56, height - 56, fill=0, stroke=1) c.setStrokeColor(colors.HexColor("#C4B5FD")) c.setLineWidth(2) c.rect(42, 42, width - 84, height - 84, fill=0, stroke=1) _draw_medal(c, band["key"], width / 2, height - 142) c.setFillColor(colors.HexColor("#6D28D9")) c.setFont("Helvetica-Bold", 12) c.drawCentredString(width / 2, height - 205, "M1 MECHANICS QUEST") c.setFillColor(colors.HexColor("#172554")) c.setFont("Times-Bold", 28) c.drawCentredString(width / 2, height - 244, band["award"]) c.setFont("Helvetica", 13) c.drawCentredString(width / 2, height - 278, "This certificate is proudly presented to") student = str(result.get("student", "Student")) c.setFillColor(colors.HexColor("#9F1239")) c.setFont("Times-BoldItalic", _fit_text(c, student, width - 170, 32, "Times-BoldItalic")) c.drawCentredString(width / 2, height - 322, student) c.setFillColor(colors.HexColor("#172554")) c.setFont("Helvetica-Bold", 16) c.drawCentredString(width / 2, height - 357, "Congratulations!") c.setFont("Helvetica", 13) c.drawCentredString(width / 2, height - 386, band["statement"] + ".") c.setFont("Helvetica-Bold", 14) c.drawCentredString( width / 2, height - 419, f"Overall attainment {result['attainment']:.3f}/3.000 | Overall performance {result['overall_percentage']:.2f}%", ) c.setFont("Helvetica", 12) c.drawCentredString(width / 2, height - 448, band["knowledge"] + ".") c.setStrokeColor(colors.HexColor("#94A3B8")) c.line(110, 92, 290, 92) c.line(width - 290, 92, width - 110, 92) c.setFont("Helvetica", 9) c.drawCentredString(200, 78, "Instructor / authorised signatory") c.drawCentredString(width - 200, 78, "Programme / institution seal") c.setFont("Helvetica", 7.5) c.setFillColor(colors.HexColor("#475569")) c.drawCentredString(width / 2, 58, f"Verification: {verification} | Computed: {result.get('computed_at','')}") c.save()
reader = PdfReader(str(raw)) writer = PdfWriter() for page in reader.pages: writer.add_page(page) writer.add_metadata({"/Title": f"{band['award']} - {student}", "/Subject": f"Verification {verification}"}) permissions = UserAccessPermissions.PRINT | UserAccessPermissions.PRINT_TO_REPRESENTATION writer.encrypt("", secrets.token_urlsafe(36), permissions_flag=permissions, algorithm="AES-256") with locked.open("wb") as handle: writer.write(handle) raw.unlink(missing_ok=True) return str(locked)
README.md+65
START_HERE.txt+19
app.py+502-2
obe_engine.pyAdded+643