Spaces:
Paused
Paused
Download obe_engine.py from jobinv/MathematicsApps: direct link, hf CLI and curl.
- Browser
- Download file 28.2 kB
-
https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/obe_engine.py
- Command line
-
hf download hf://spaces/jobinv/MathematicsApps/obe_engine.py
-
curl -L -o obe_engine.py https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/obe_engine.py
28.2 kB
| """Extraordinary activities, OBE attainment, mistake analytics, and certificates.""" | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| from datetime import datetime, timezone | |
| from hashlib import sha256 | |
| from html import escape | |
| from pathlib import Path | |
| import re | |
| import secrets | |
| import tempfile | |
| from typing import Any, Iterable | |
| import plotly.graph_objects as go | |
| from pypdf import PdfReader, PdfWriter | |
| from pypdf.constants import UserAccessPermissions | |
| from reportlab.lib import colors | |
| from reportlab.lib.pagesizes import A4, landscape | |
| from reportlab.pdfbase.pdfmetrics import stringWidth | |
| from 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) | |