Spaces:
Paused
Paused
File size: 28,170 Bytes
aae8a70 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | """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)
|