Spaces:
Paused
Paused
File size: 56,453 Bytes
5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 | 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 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 | """Deterministic examination generation, marking, OCR mapping, and locked PDF reports."""
from __future__ import annotations
from collections import Counter
from datetime import datetime, timezone
from difflib import SequenceMatcher
from hashlib import sha256
from html import escape
from io import BytesIO
from pathlib import Path
import random
import re
import secrets
import tempfile
from typing import Any, Iterable
from PIL import Image
from pypdf import PdfReader, PdfWriter
from pypdf.constants import UserAccessPermissions
from reportlab.lib import colors
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
from engine import TOPICS, generate_question
from evaluator import extract_numbers, run_ocr
from worksheet_exports import plain_math
EXAM_SPECS = {
"Midterm 1": {"count": 10, "label": "Midterm Examination 1"},
"Midterm 2": {"count": 10, "label": "Midterm Examination 2"},
"Final examination": {"count": 25, "label": "Final Examination"},
}
EXAM_TOPIC_CHOICES = tuple(label for label in TOPICS if label != "Mixed mission")
FORMAT_MARKS = {
"Multiple choice": 2,
"Fill in the blank": 2,
"Numerical problem": 6,
"Explanation": 5,
"Theory": 5,
"Mathematical calculation": 6,
"Match the following": 4,
"Diagram interpretation": 4,
"Paragraph analysis": 5,
}
FORMAT_CYCLE = tuple(FORMAT_MARKS)
SMALL_QUESTION_FORMATS = {
"Multiple choice",
"Fill in the blank",
"Match the following",
}
DEFAULT_READING_MINUTES = 10
DEFAULT_TOTAL_SESSION_MINUTES = 130
MAX_ANSWERING_MINUTES = 120
EXAM_CSS = r"""
.exam-mode-shell {
background: linear-gradient(120deg, #fff7ed, #fef2f2 55%, #f5f3ff);
border: 1px solid rgba(190, 24, 93, .2);
border-radius: 18px;
box-shadow: 0 12px 34px rgba(76, 29, 149, .1);
margin: 12px 0 18px;
padding: 14px 16px;
}
.exam-mode-shell h3 { color: #831843; margin: 0 0 4px; }
#exam-section {
background: linear-gradient(145deg, rgba(255,255,255,.98), rgba(245,243,255,.95));
border: 1px solid rgba(109, 40, 217, .18);
border-radius: 24px;
box-shadow: 0 18px 55px rgba(30, 41, 59, .12);
padding: 18px !important;
}
.exam-lock-banner {
background: linear-gradient(105deg, #7f1d1d, #be123c 54%, #6d28d9);
border-radius: 18px;
color: white;
margin-bottom: 14px;
padding: 16px 18px;
}
.exam-lock-banner h2, .exam-lock-banner p { color: white !important; margin: 0 0 5px; }
.exam-question-card {
background: rgba(255,255,255,.98);
border: 1px solid rgba(99,102,241,.18);
border-left: 5px solid #7c3aed;
border-radius: 17px;
box-shadow: 0 9px 26px rgba(30,41,59,.08);
margin: 12px 0;
padding: 14px !important;
}
.exam-question-card h3 { color: #312e81; margin-top: 0; }
.exam-result-panel {
background: linear-gradient(120deg, #ecfeff, #eef2ff);
border: 1px solid rgba(8,145,178,.2);
border-radius: 18px;
padding: 15px !important;
}
.exam-main-timer {
background: #172554;
border: 2px solid #67e8f9;
border-radius: 18px;
color: white;
font-variant-numeric: tabular-nums;
margin: 10px 0 16px;
padding: 13px 16px;
position: sticky;
top: 8px;
z-index: 20;
}
.exam-main-timer strong { color: #67e8f9; font-size: 20px; }
.exam-question-timer {
background: #f8fafc;
border: 1px solid #cbd5e1;
border-radius: 12px;
color: #475569;
font-variant-numeric: tabular-nums;
margin: 4px 0 8px;
padding: 8px 10px;
}
.exam-question-timer.timer-running { background: #ecfeff; border-color: #22d3ee; color: #164e63; }
.exam-question-timer.timer-finished { background: #fff1f2; border-color: #fb7185; color: #9f1239; }
.exam-hidden-trigger {
height: 1px !important;
left: -10000px !important;
min-height: 1px !important;
opacity: 0 !important;
overflow: hidden !important;
pointer-events: none !important;
position: fixed !important;
top: 0 !important;
width: 1px !important;
}
.exam-inline-diagram {
background: linear-gradient(145deg, #eff6ff, #f5f3ff);
border: 1px solid #c7d2fe;
border-radius: 14px;
margin: 10px auto;
max-width: 680px;
overflow: hidden;
padding: 8px;
}
.exam-inline-diagram svg { display: block; height: auto; width: 100%; }
body.exam-mode-active #floating-tutor-viewport-launcher,
body.exam-mode-active #floating-tutor-launcher,
body.exam-mode-active #floating-tutor-panel {
display: none !important;
pointer-events: none !important;
visibility: hidden !important;
}
@media (max-width: 680px) {
#exam-section { padding: 10px !important; }
.exam-question-card { padding: 10px !important; }
}
"""
EXAM_MODE_TOGGLE_JS = r"""
(enabled) => {
document.body.classList.toggle("exam-mode-active", Boolean(enabled));
return enabled;
}
"""
EXAM_START_CAPTURE_JS = r"""
(...values) => {
window.__m1ExamStartEpoch = Date.now();
if (window.__m1ExamClockInterval) window.clearInterval(window.__m1ExamClockInterval);
return values;
}
"""
EXAM_MAIN_TIMER_JS = r"""
(totalMinutes, readingMinutes, attemptId) => {
const totalMs = Math.max(1, Number(totalMinutes) || 130) * 60000;
const readingMs = Math.max(0, Number(readingMinutes) || 10) * 60000;
const started = Number(window.__m1ExamStartEpoch) || Date.now();
const readingEnds = started + readingMs;
const deadline = started + totalMs;
const storageKey = `m1-exam-clock-${attemptId || "active"}`;
try { sessionStorage.setItem(storageKey, JSON.stringify({started, readingEnds, deadline})); } catch (_) {}
const nativeButton = (id) => {
const host = document.getElementById(id);
if (!host) return null;
return host.matches("button") ? host : host.querySelector("button");
};
const display = () => document.getElementById("exam-main-timer-display");
let readingUnlocked = false;
let submitted = false;
const formatTime = (milliseconds) => {
const seconds = Math.max(0, Math.ceil(milliseconds / 1000));
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainder = seconds % 60;
return `${String(hours).padStart(2,"0")}:${String(minutes).padStart(2,"0")}:${String(remainder).padStart(2,"0")}`;
};
const tick = () => {
const now = Date.now();
const root = display();
if (now < readingEnds) {
if (root) root.innerHTML = `<div class="exam-main-timer"><strong>Reading and setup: ${formatTime(readingEnds-now)}</strong><br>Read the full paper and prepare your workspace. Answer fields unlock automatically when this 10-minute phase ends. The total protected-session clock is already running.</div>`;
} else {
if (!readingUnlocked) {
readingUnlocked = true;
const unlock = nativeButton("exam-unlock-trigger");
if (unlock) unlock.click();
}
if (root) root.innerHTML = `<div class="exam-main-timer"><strong>Examination time remaining: ${formatTime(deadline-now)}</strong><br>The main clock remains authoritative even when individual question timers are not started.</div>`;
}
if (now >= deadline && !submitted) {
submitted = true;
window.clearInterval(window.__m1ExamClockInterval);
if (root) root.innerHTML = `<div class="exam-main-timer"><strong>TIME EXPIRED · submitting automatically</strong><br>Answer fields are now locked and the printable result report is being generated.</div>`;
document.querySelectorAll("#exam-section textarea, #exam-section input").forEach(element => { element.disabled = true; });
const autoSubmit = nativeButton("exam-auto-submit-trigger");
if (autoSubmit) autoSubmit.click();
}
};
window.__m1StopExamClock = () => {
if (window.__m1ExamClockInterval) window.clearInterval(window.__m1ExamClockInterval);
window.__m1ExamClockInterval = 0;
Object.values(window.__m1QuestionTimers || {}).forEach(timer => window.clearInterval(timer));
window.__m1QuestionTimers = {};
};
window.__m1ExamClockInterval = window.setInterval(tick, 1000);
tick();
return [];
}
"""
EXAM_MANUAL_SUBMIT_JS = r"""
(...values) => {
if (Boolean(values[3]) && window.__m1StopExamClock) window.__m1StopExamClock();
return values;
}
"""
EXAM_AUTO_SUBMIT_JS = r"""
(...values) => {
if (window.__m1StopExamClock) window.__m1StopExamClock();
return values;
}
"""
EXAM_RESET_TIMER_JS = r"""
() => {
if (window.__m1StopExamClock) window.__m1StopExamClock();
const root = document.getElementById("exam-main-timer-display");
if (root) root.innerHTML = '<div class="exam-main-timer"><strong>Timer not started</strong><br>Start a protected examination to begin the reading and overall-session clocks.</div>';
return [];
}
"""
def question_timer_js(question_number: int) -> str:
"""Return a client-only pacing timer for one question."""
return rf"""
(minutes) => {{
const duration = Math.max(1, Math.min(7, Number(minutes) || 1));
const root = document.getElementById("exam-question-timer-{question_number}");
const host = document.getElementById("exam-question-timer-button-{question_number}");
const button = host ? (host.matches("button") ? host : host.querySelector("button")) : null;
if (button) button.disabled = true;
window.__m1QuestionTimers = window.__m1QuestionTimers || {{}};
if (window.__m1QuestionTimers[{question_number}]) window.clearInterval(window.__m1QuestionTimers[{question_number}]);
const end = Date.now() + duration * 60000;
const tick = () => {{
const remaining = Math.max(0, Math.ceil((end - Date.now()) / 1000));
const mm = String(Math.floor(remaining / 60)).padStart(2, "0");
const ss = String(remaining % 60).padStart(2, "0");
if (root) {{
root.classList.add("timer-running");
root.innerHTML = `<div class="exam-question-timer timer-running"><b>Question {question_number} pacing timer:</b> ${{mm}}:${{ss}}</div>`;
}}
if (remaining <= 0) {{
window.clearInterval(interval);
if (root) root.innerHTML = '<div class="exam-question-timer timer-finished"><b>Question {question_number}: suggested time finished.</b> Move on when possible; the main examination clock continues.</div>';
}}
}};
const interval = window.setInterval(tick, 1000);
window.__m1QuestionTimers[{question_number}] = interval;
tick();
return minutes;
}}
"""
# Each group is a set of acceptable synonyms. Marks are based on how many
# concept groups are evidenced, making marking deterministic and auditable.
CONCEPT_BANK: dict[str, dict[str, dict[str, Any]]] = {
"vertical": {
"Theory": {
"prompt": "State the constant-acceleration assumptions used for vertical motion under gravity.",
"answer": "The object is modelled as a particle; air resistance is neglected; gravity is uniform and acts vertically downward with acceleration g = 9.8 m s^-2.",
"groups": [["particle"], ["air resistance", "drag"], ["constant", "uniform"], ["downward", "vertically down"], ["9.8", "gravity", " g "]],
},
"Explanation": {
"prompt": "Explain why a negative acceleration may be used even while the particle is moving upward.",
"answer": "The sign of acceleration is set by the chosen positive direction, not by the current direction of motion. With upward positive, gravity acts downward, so a = -g while the upward velocity decreases.",
"groups": [["positive direction", "sign convention"], ["gravity"], ["downward"], ["-g", "negative"], ["velocity", "slows", "decreases"]],
},
},
"speed_time": {
"Theory": {
"prompt": "State what the gradient and the area under a speed-time graph represent.",
"answer": "The gradient represents acceleration. The area between the speed-time graph and the time axis represents distance travelled.",
"groups": [["gradient"], ["acceleration"], ["area"], ["distance"], ["time axis", "under the graph"]],
},
"Explanation": {
"prompt": "Explain why a straight sloping section on a speed-time graph represents uniform acceleration.",
"answer": "A straight line has constant gradient, and the gradient of a speed-time graph is acceleration; therefore the acceleration is constant or uniform.",
"groups": [["straight line"], ["constant gradient"], ["gradient"], ["acceleration"], ["constant", "uniform"]],
},
},
"collision": {
"Theory": {
"prompt": "State the principle of conservation of linear momentum and the condition needed to use it.",
"answer": "For a system with zero resultant external impulse, total momentum before an interaction equals total momentum after it, using one consistent direction convention.",
"groups": [["total momentum", "sum of momentum"], ["before"], ["after"], ["external"], ["impulse", "force"], ["direction", "sign"]],
},
"Explanation": {
"prompt": "Explain why momentum can be conserved during a short collision even though each particle experiences a large force.",
"answer": "The impact forces are internal, equal and opposite, so their impulses cancel for the two-particle system. If external impulse is negligible, the system's total momentum is unchanged.",
"groups": [["internal"], ["equal"], ["opposite"], ["impulse", "cancel"], ["external"], ["total momentum", "system momentum"]],
},
},
"beam": {
"Theory": {
"prompt": "State the two conditions required for a rigid body to be in equilibrium.",
"answer": "The resultant force is zero and the resultant moment about any point is zero.",
"groups": [["resultant force", "sum of forces"], ["zero"], ["resultant moment", "sum of moments"], ["any point", "about a point"]],
},
"Explanation": {
"prompt": "Explain why the weight of a uniform beam is taken to act at its midpoint.",
"answer": "A uniform beam has constant mass per unit length, so its centre of mass is at the geometrical midpoint; the resultant weight acts through that centre of mass.",
"groups": [["uniform"], ["mass per unit length", "evenly distributed"], ["centre of mass", "center of mass"], ["midpoint", "middle"], ["weight acts"]],
},
},
"friction": {
"Theory": {
"prompt": "State the friction law at limiting equilibrium and explain when it may be used.",
"answer": "At impending motion, friction has its limiting magnitude F = mu R and acts opposite the impending relative motion. It must not be assumed when the body is not at the point of slipping.",
"groups": [["f =", "mu r", "μr"], ["limiting"], ["impending", "point of moving", "point of slipping"], ["opposite"], ["motion"]],
},
"Explanation": {
"prompt": "Explain why an upward angled pulling force reduces the normal reaction on a block.",
"answer": "The pull has an upward vertical component that supports part of the weight, so vertical equilibrium gives R + P sin(theta) = mg and therefore R is less than mg.",
"groups": [["vertical component"], ["upward"], ["supports", "balances"], ["weight", "mg"], ["reaction", "r"], ["less", "reduces"]],
},
},
"connected": {
"Theory": {
"prompt": "State the modelling consequences of a light inextensible string passing over a smooth pulley.",
"answer": "A light string has the same tension throughout; inextensibility makes connected particles have equal acceleration magnitude; a smooth pulley does not introduce frictional resistance.",
"groups": [["same tension", "equal tension"], ["light string"], ["inextensible", "inextensibility"], ["equal acceleration", "same acceleration"], ["smooth pulley"], ["no friction", "frictionless", "frictional resistance"]],
},
"Explanation": {
"prompt": "Explain how to choose the direction of friction for a particle on a rough plane.",
"answer": "Friction opposes actual or impending relative motion between the surfaces. First determine the likely direction of motion; draw friction along the plane in the opposite direction.",
"groups": [["opposes"], ["motion", "relative motion"], ["impending"], ["surface", "plane"], ["opposite direction"]],
},
},
"vectors": {
"Theory": {
"prompt": "Explain how a velocity vector is used to find speed and bearing.",
"answer": "Speed is the magnitude of the velocity vector, found from the Pythagorean combination of its components. Bearing is measured clockwise from north and must be reported with the correct quadrant.",
"groups": [["magnitude"], ["pythagoras", "pythagorean", "square root"], ["components"], ["clockwise"], ["north"], ["quadrant"]],
},
"Explanation": {
"prompt": "Explain why the signs of vector components must be retained when finding a bearing.",
"answer": "The signs identify east or west and north or south, fixing the quadrant. A calculator's acute reference angle alone cannot determine the clockwise bearing from north.",
"groups": [["sign"], ["east", "west"], ["north", "south"], ["quadrant"], ["clockwise"], ["bearing"]],
},
},
"equilibrium": {
"Theory": {
"prompt": "Describe how to resolve forces along two perpendicular directions for particle equilibrium.",
"answer": "Choose two perpendicular axes, resolve every force into components, and set the algebraic sum of components to zero independently along each axis.",
"groups": [["perpendicular"], ["axes", "directions"], ["resolve", "components"], ["sum"], ["zero"], ["each", "independently"]],
},
"Explanation": {
"prompt": "Explain why a complete free-body diagram should be drawn before writing equilibrium equations.",
"answer": "It isolates the particle, shows every external force with direction, prevents omitted or duplicated forces, and supports consistent resolution and signs.",
"groups": [["isolate", "particle"], ["every force", "all forces", "external force"], ["direction"], ["omit", "missing"], ["resolve", "resolution", "components"], ["sign"]],
},
},
}
def _seed_value(seed: Any) -> int:
if seed not in (None, ""):
try:
return abs(int(seed)) % 2_147_483_647
except (TypeError, ValueError):
return int(sha256(str(seed).encode("utf-8")).hexdigest()[:8], 16)
return int(datetime.now(timezone.utc).timestamp() * 1_000_000) % 2_147_483_647
def _scenario_stem(prompt: str) -> str:
value = str(prompt or "").strip()
match = re.search(r"(?m)^\s*\(a\)", value)
return value[: match.start()].strip() if match else value
def _unit(answer: dict) -> str:
return plain_math(answer.get("unit", "")).strip()
def _display_value(value: float, answer: dict) -> str:
suffix = _unit(answer)
return f"{value:.4g}{(' ' + suffix) if suffix else ''}"
def _unique_distractors(target: float, base: dict, rng: random.Random) -> list[float]:
scale = max(1.0, abs(target))
candidates = []
for error in base.get("common_errors", []):
try:
candidates.append(float(error["value"]))
except (KeyError, TypeError, ValueError):
pass
candidates.extend(
[
-target,
target + 0.2 * scale,
target - 0.2 * scale,
target * 2,
target / 2,
target + rng.choice([-1, 1]) * 0.35 * scale,
]
)
unique: list[float] = []
tolerance = max(0.02, abs(target) * 0.012)
for value in candidates:
if abs(value - target) <= tolerance:
continue
if all(abs(value - previous) > tolerance for previous in unique):
unique.append(value)
if len(unique) == 3:
break
while len(unique) < 3:
value = target + (len(unique) + 1) * max(1, scale * 0.17)
if abs(value - target) > tolerance:
unique.append(value)
return unique
def _diagram_svg(base: dict) -> str:
"""Build a compact, exact line diagram from the generated question model."""
kind = base.get("diagram_kind", "vectors")
data = base.get("diagram_data", {})
common_start = (
'<div class="exam-inline-diagram"><svg viewBox="0 0 640 230" role="img" '
f'aria-label="{escape(base.get("topic_label", "Mechanics diagram"))}">'
'<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#db2777"/></marker></defs>'
'<rect x="0" y="0" width="640" height="230" rx="18" fill="#f8fafc"/>'
)
if kind == "collision":
body = f'''<line x1="50" y1="175" x2="590" y2="175" stroke="#475569" stroke-width="4"/>
<circle cx="180" cy="145" r="38" fill="#22d3ee" stroke="#0e7490" stroke-width="4"/><circle cx="430" cy="145" r="48" fill="#c4b5fd" stroke="#6d28d9" stroke-width="4"/>
<line x1="80" y1="85" x2="165" y2="85" stroke="#db2777" stroke-width="5" marker-end="url(#arrow)"/><line x1="335" y1="85" x2="415" y2="85" stroke="#db2777" stroke-width="5" marker-end="url(#arrow)"/>
<text x="145" y="153" font-size="18" fill="#172554">P: {data.get('m1','m1')} kg</text><text x="390" y="153" font-size="18" fill="#172554">Q: {data.get('m2','m2')} kg</text>
<text x="95" y="70" font-size="17" fill="#9f1239">{data.get('u1','u1')} m/s</text><text x="345" y="70" font-size="17" fill="#9f1239">{data.get('u2','u2')} m/s</text>'''
elif kind == "vertical":
body = f'''<line x1="70" y1="190" x2="570" y2="190" stroke="#475569" stroke-width="5"/><circle cx="320" cy="105" r="23" fill="#f59e0b" stroke="#b45309" stroke-width="4"/>
<line x1="320" y1="150" x2="320" y2="48" stroke="#db2777" stroke-width="5" marker-end="url(#arrow)"/><line x1="380" y1="55" x2="380" y2="135" stroke="#6d28d9" stroke-width="5" marker-end="url(#arrow)"/>
<text x="330" y="48" font-size="17" fill="#9f1239">u = {data.get('u','u')} m/s</text><text x="392" y="95" font-size="17" fill="#5b21b6">g = 9.8 m/s²</text><text x="85" y="215" font-size="16" fill="#475569">ground</text>'''
elif kind == "speed_time":
total = float(data.get("t_acc", 10)) + float(data.get("t_const", 60)) + float(data.get("t_dec", 20))
first = 70 + 480 * float(data.get("t_acc", 10)) / max(1, total)
second = 70 + 480 * (float(data.get("t_acc", 10)) + float(data.get("t_const", 60))) / max(1, total)
body = f'''<line x1="70" y1="190" x2="575" y2="190" stroke="#172554" stroke-width="3" marker-end="url(#arrow)"/><line x1="70" y1="190" x2="70" y2="30" stroke="#172554" stroke-width="3" marker-end="url(#arrow)"/>
<polyline points="70,190 {first:.1f},70 {second:.1f},70 550,190" fill="none" stroke="#7c3aed" stroke-width="6"/>
<text x="500" y="215" font-size="16" fill="#172554">time</text><text x="14" y="38" font-size="16" fill="#172554">speed</text><text x="82" y="62" font-size="16" fill="#5b21b6">{data.get('speed','v')} m/s</text>'''
elif kind == "beam":
body = f'''<line x1="75" y1="120" x2="565" y2="120" stroke="#7c3aed" stroke-width="14"/><path d="M170 120 L140 175 L200 175 Z" fill="#22d3ee"/><path d="M455 120 L425 175 L485 175 Z" fill="#22d3ee"/>
<line x1="320" y1="45" x2="320" y2="105" stroke="#db2777" stroke-width="5" marker-end="url(#arrow)"/><text x="330" y="68" font-size="17" fill="#9f1239">W = {data.get('weight','W')} N</text><text x="77" y="105" font-size="16" fill="#172554">A</text><text x="550" y="105" font-size="16" fill="#172554">B</text>'''
elif kind == "friction":
body = f'''<line x1="65" y1="180" x2="575" y2="180" stroke="#475569" stroke-width="5"/><rect x="230" y="105" width="150" height="75" rx="10" fill="#fde68a" stroke="#b45309" stroke-width="4"/>
<line x1="380" y1="105" x2="500" y2="45" stroke="#db2777" stroke-width="5" marker-end="url(#arrow)"/><line x1="230" y1="145" x2="125" y2="145" stroke="#6d28d9" stroke-width="5" marker-end="url(#arrow)"/>
<text x="410" y="75" font-size="17" fill="#9f1239">P at {data.get('theta','θ')}°</text><text x="100" y="130" font-size="17" fill="#5b21b6">friction</text><text x="265" y="150" font-size="17" fill="#172554">{data.get('mass','m')} kg</text>'''
else:
body = '''<line x1="80" y1="190" x2="570" y2="190" stroke="#172554" stroke-width="3" marker-end="url(#arrow)"/><line x1="320" y1="205" x2="320" y2="30" stroke="#172554" stroke-width="3" marker-end="url(#arrow)"/>
<circle cx="320" cy="150" r="24" fill="#22d3ee" stroke="#0e7490" stroke-width="4"/><line x1="320" y1="150" x2="485" y2="65" stroke="#db2777" stroke-width="6" marker-end="url(#arrow)"/><line x1="320" y1="150" x2="235" y2="55" stroke="#6d28d9" stroke-width="6" marker-end="url(#arrow)"/>
<text x="490" y="60" font-size="17" fill="#9f1239">component 1</text><text x="120" y="48" font-size="17" fill="#5b21b6">component 2</text>'''
return common_start + body + "</svg></div>"
def _make_match_item(base: dict, marks: int, rng: random.Random) -> dict[str, Any]:
left = [
("A", "Gradient of a speed-time graph", "Acceleration"),
("B", "Area under a speed-time graph", "Distance travelled"),
("C", "Impulse on a particle", "Change in momentum"),
("D", "Moment of a force about a point", "Force × perpendicular distance"),
]
right = [definition for _, _, definition in left]
rng.shuffle(right)
numbered = {definition: str(index + 1) for index, definition in enumerate(right)}
pairs = {letter: numbered[definition] for letter, _, definition in left}
left_rows = " \n".join(f"**{letter}.** {term}" for letter, term, _ in left)
right_rows = " \n".join(f"**{index}.** {definition}" for index, definition in enumerate(right, 1))
answer_key = ", ".join(f"{letter}-{number}" for letter, number in pairs.items())
return {
"format": "Match the following",
"marks": marks,
"question": (
f"**Mechanics relationship matching · {base['topic_label']}**\n\n"
"Match each item in Column A with the correct meaning in Column B. Answer as `A-?, B-?, C-?, D-?`.\n\n"
f"| Column A | Column B |\n|---|---|\n| {left_rows.replace(chr(10), '<br>')} | {right_rows.replace(chr(10), '<br>')} |"
),
"answer_key": answer_key,
"solution": [f"Correct matching: {answer_key}."],
"rubric": {"kind": "match", "pairs": pairs},
}
def _make_objective_item(base: dict, question_format: str, marks: int, rng: random.Random) -> dict:
answer = base["expected_answers"][0]
target = float(answer["value"])
stem = _scenario_stem(base["prompt"])
label = plain_math(answer["label"])
if question_format == "Multiple choice":
options = [(target, True)] + [(value, False) for value in _unique_distractors(target, base, rng)]
rng.shuffle(options)
option_rows = []
correct_letter = "A"
for index, (value, correct) in enumerate(options):
letter = chr(65 + index)
option_rows.append(f"**{letter}.** {_display_value(value, answer)}")
if correct:
correct_letter = letter
question_text = f"{stem}\n\nWhich option gives the **{label}**?\n\n" + " \n".join(option_rows)
return {
"format": question_format,
"marks": marks,
"question": question_text,
"answer_key": f"{correct_letter}. {_display_value(target, answer)}",
"solution": base["solution_steps"],
"rubric": {
"kind": "mcq",
"letter": correct_letter,
"value": target,
"tolerance": float(answer.get("tolerance", max(0.02, abs(target) * 0.01))),
},
}
question_text = (
f"{stem}\n\nFill in the blank, including the correct unit where applicable:\n\n"
f"**{label} = __________ {escape(_unit(answer))}**"
)
return {
"format": question_format,
"marks": marks,
"question": question_text,
"answer_key": _display_value(target, answer),
"solution": base["solution_steps"],
"rubric": {
"kind": "numeric",
"expected": [answer],
},
}
def _make_written_item(base: dict, question_format: str, marks: int) -> dict:
if question_format in {"Numerical problem", "Mathematical calculation", "Diagram interpretation"}:
if question_format == "Mathematical calculation":
question_text = (
f"{_scenario_stem(base['prompt'])}\n\n"
"Select and write the relevant mechanics equation, substitute the given values, and calculate:\n\n"
+ " \n".join(
f"- **{plain_math(answer['label'])}**" for answer in base["expected_answers"]
)
)
elif question_format == "Diagram interpretation":
first_answer = base["expected_answers"][0]
question_text = (
f"Study the line diagram and the labelled parameters.\n\n{_diagram_svg(base)}\n\n"
f"Using the diagram and the mechanics model, calculate the **{plain_math(first_answer['label'])}**."
)
else:
question_text = base["prompt"].strip()
expected = (
base["expected_answers"][:1]
if question_format == "Diagram interpretation"
else base["expected_answers"]
)
return {
"format": question_format,
"marks": marks,
"question": question_text,
"answer_key": "; ".join(
f"{plain_math(answer['label'])}: {plain_math(answer['display'])}"
for answer in expected
),
"solution": base["solution_steps"],
"rubric": {"kind": "numeric", "expected": expected},
}
concept_format = "Explanation" if question_format == "Paragraph analysis" else question_format
concept = CONCEPT_BANK[base["topic"]][concept_format]
if question_format == "Paragraph analysis":
question_text = (
"Read the paragraph and answer from the information and mechanics reasoning it contains.\n\n"
f"> {concept['answer']}\n\n"
f"**Question:** {concept['prompt']}"
)
else:
question_text = f"**Context: {base['title']} · {base['topic_label']}**\n\n{concept['prompt']}"
return {
"format": question_format,
"marks": marks,
"question": question_text,
"answer_key": concept["answer"],
"solution": [concept["answer"]],
"rubric": {"kind": "concept", "groups": concept["groups"]},
}
def build_exam(
exam_name: str,
topic_labels: Iterable[str] | None,
seed: Any,
student_name: str,
question_count: int | None = None,
) -> dict[str, Any]:
"""Create a reproducible paper with no answer keys in the public rendering."""
spec = EXAM_SPECS.get(exam_name, EXAM_SPECS["Midterm 1"])
exam_name = exam_name if exam_name in EXAM_SPECS else "Midterm 1"
selected_topics = [label for label in (topic_labels or []) if label in EXAM_TOPIC_CHOICES]
if not selected_topics:
selected_topics = list(EXAM_TOPIC_CHOICES)
try:
requested_count = int(question_count) if question_count is not None else int(spec["count"])
except (TypeError, ValueError):
requested_count = int(spec["count"])
requested_count = max(1, min(40, requested_count))
seed_int = _seed_value(seed)
offset = {"Midterm 1": 11003, "Midterm 2": 22003, "Final examination": 99001}[exam_name]
rng = random.Random(seed_int + offset)
formats = [FORMAT_CYCLE[index % len(FORMAT_CYCLE)] for index in range(requested_count)]
rng.shuffle(formats)
topic_order = list(selected_topics)
rng.shuffle(topic_order)
questions: list[dict[str, Any]] = []
for index in range(requested_count):
topic_label = topic_order[index % len(topic_order)]
item_seed = seed_int + offset + (index + 1) * 7919
difficulty = "Challenge" if exam_name == "Final examination" and index % 3 == 0 else "Exam standard"
base = generate_question(topic_label, difficulty, item_seed)
question_format = formats[index]
marks = FORMAT_MARKS[question_format]
if question_format in {"Multiple choice", "Fill in the blank"}:
item = _make_objective_item(base, question_format, marks, rng)
elif question_format == "Match the following":
item = _make_match_item(base, marks, rng)
else:
item = _make_written_item(base, question_format, marks)
item["default_minutes"] = 1 if question_format in SMALL_QUESTION_FORMATS else 4
item.update(
{
"number": index + 1,
"topic": base["topic"],
"topic_label": base["topic_label"],
"question_id": base["id"],
}
)
questions.append(item)
student = str(student_name or "Student").strip()[:100] or "Student"
total_marks = sum(item["marks"] for item in questions)
attempt_source = f"{student}|{exam_name}|{seed_int}|{requested_count}|{'|'.join(selected_topics)}"
attempt_id = sha256(attempt_source.encode("utf-8")).hexdigest()[:16].upper()
return {
"exam_name": exam_name,
"exam_label": spec["label"],
"student": student,
"seed": seed_int,
"topics": selected_topics,
"count": requested_count,
"total_marks": total_marks,
"attempt_id": attempt_id,
"questions": questions,
}
def safe_attempt_state(exam: dict[str, Any]) -> dict[str, Any]:
"""Return only reconstruction data; answer keys never enter Gradio state."""
state = {
key: exam[key]
for key in ("exam_name", "exam_label", "student", "seed", "topics", "count", "total_marks", "attempt_id")
} | {"started": True, "submitted": False}
for optional_key in (
"question_timings",
"total_session_minutes",
"reading_minutes",
"started_epoch_ms",
"deadline_epoch_ms",
):
if optional_key in exam:
state[optional_key] = exam[optional_key]
return state
def reconstruct_exam(attempt: dict[str, Any] | None) -> dict[str, Any] | None:
if not attempt or not attempt.get("started"):
return None
exam = build_exam(
attempt.get("exam_name", "Midterm 1"),
attempt.get("topics", []),
attempt.get("seed", ""),
attempt.get("student", "Student"),
attempt.get("count"),
)
if exam["attempt_id"] != attempt.get("attempt_id"):
return None
timings = attempt.get("question_timings")
if isinstance(timings, list) and len(timings) == exam["count"]:
for item, minutes in zip(exam["questions"], timings):
item["assigned_minutes"] = max(1, min(7, int(minutes)))
exam["question_timings"] = [item["assigned_minutes"] for item in exam["questions"]]
for key in ("total_session_minutes", "reading_minutes", "started_epoch_ms", "deadline_epoch_ms"):
if key in attempt:
exam[key] = attempt[key]
return exam
def _question_numbers(value: str, maximum: int) -> set[int]:
text = str(value or "").strip()
if not text:
return set()
tokens = re.findall(r"\d+", text)
residue = re.sub(r"(?i)q(?:uestion)?|\d+|[,;\s\-]+", "", text)
if residue:
raise ValueError(f"Use only question numbers separated by commas or spaces; unreadable text: {residue!r}.")
numbers = {int(token) for token in tokens}
invalid = sorted(number for number in numbers if not 1 <= number <= maximum)
if invalid:
raise ValueError(f"Question numbers outside 1–{maximum}: {', '.join(map(str, invalid))}.")
return numbers
def apply_question_timings(
exam: dict[str, Any],
assignments: dict[int, str] | None,
) -> dict[str, Any]:
"""Apply manual 1–7 minute lists over format-based 1/4 minute defaults."""
durations = [int(item.get("default_minutes", 4)) for item in exam["questions"]]
occupied: dict[int, int] = {}
for minute in range(1, 8):
for question_number in _question_numbers((assignments or {}).get(minute, ""), exam["count"]):
if question_number in occupied:
raise ValueError(
f"Question {question_number} appears in both the {occupied[question_number]}-minute and {minute}-minute lists."
)
occupied[question_number] = minute
durations[question_number - 1] = minute
for item, duration in zip(exam["questions"], durations):
item["assigned_minutes"] = duration
exam["question_timings"] = durations
return exam
def render_exam_header(exam: dict[str, Any]) -> str:
topic_text = " · ".join(exam["topics"])
counts = Counter(question["format"] for question in exam["questions"])
formats = " · ".join(f"{name}: {count}" for name, count in counts.items())
timings = exam.get("question_timings", [item.get("assigned_minutes", item.get("default_minutes", 4)) for item in exam["questions"]])
timing_groups: dict[int, list[int]] = {}
for number, minutes in enumerate(timings, 1):
timing_groups.setdefault(int(minutes), []).append(number)
timing_text = " · ".join(
f"{minutes} min: Q{', Q'.join(map(str, numbers))}"
for minutes, numbers in sorted(timing_groups.items())
)
total_session = int(exam.get("total_session_minutes", DEFAULT_TOTAL_SESSION_MINUTES))
reading = int(exam.get("reading_minutes", DEFAULT_READING_MINUTES))
return f"""
## {exam['exam_label']}
**Student:** {escape(exam['student'])}
**Questions:** {exam['count']} · **Total:** {exam['total_marks']} marks · **Attempt:** `{exam['attempt_id']}`
**Trained topics:** {escape(topic_text)}
**Paper balance:** {escape(formats)}
**Protected-session clock:** {total_session} minutes total · first {reading} minutes reserved for reading/setup · answer time {total_session-reading} minutes
**Question pacing:** {escape(timing_text)}
> Enter an answer under every question. For a handwritten sheet, write `Q1`, `Q2`, … clearly before each response. Solutions remain unavailable until the paper is submitted.
"""
def render_exam_question(item: dict[str, Any]) -> str:
return f"""
### Question {item['number']} · {item['format']} · **{item['marks']} marks**
<span class="question-kicker">{escape(item['topic_label'])}</span>
{item['question']}
"""
def _normalise_text(value: str) -> str:
value = plain_math(value).lower()
value = value.replace("μ", "mu")
value = re.sub(r"[^a-z0-9.+\-/ ]+", " ", value)
return re.sub(r"\s+", " ", value).strip()
def _numeric_grade(expected: list[dict], response: str, marks: int) -> tuple[float, str]:
candidates = extract_numbers(response)
if not candidates:
return 0.0, "No readable numerical answer was found."
remaining = list(enumerate(candidates))
matched: list[str] = []
missing: list[str] = []
for answer in expected:
target = float(answer["value"])
tolerance = float(answer.get("tolerance", max(0.02, abs(target) * 0.01)))
if remaining:
candidate_index, candidate = min(remaining, key=lambda pair: abs(pair[1] - target))
if abs(candidate - target) <= tolerance:
matched.append(plain_math(answer["label"]))
remaining = [pair for pair in remaining if pair[0] != candidate_index]
continue
missing.append(plain_math(answer["label"]))
score = marks * len(matched) / max(1, len(expected))
detail = f"Matched: {', '.join(matched) if matched else 'none'}."
if missing:
detail += f" Recheck: {', '.join(missing)}."
return round(score * 2) / 2, detail
def _concept_grade(groups: list[list[str]], response: str, marks: int) -> tuple[float, str]:
normalised = f" {_normalise_text(response)} "
matched_groups = []
missing_groups = []
for group in groups:
matched = next((term for term in group if _normalise_text(term) in normalised), None)
if matched:
matched_groups.append(matched)
else:
missing_groups.append(group[0])
score = marks * len(matched_groups) / max(1, len(groups))
detail = f"Concept evidence: {len(matched_groups)}/{len(groups)} rubric points."
if missing_groups:
detail += " Missing ideas: " + ", ".join(missing_groups) + "."
return round(score * 2) / 2, detail
def _match_grade(pairs: dict[str, str], response: str, marks: int) -> tuple[float, str]:
detected = {
letter.upper(): number
for letter, number in re.findall(
r"(?i)\b([A-D])\s*(?:-|=|:|to)?\s*([1-4])\b", str(response or "")
)
}
correct = [letter for letter, number in pairs.items() if detected.get(letter) == number]
missing = [letter for letter in pairs if letter not in correct]
score = marks * len(correct) / max(1, len(pairs))
detail = f"Correct matches: {', '.join(correct) if correct else 'none'}."
if missing:
detail += f" Recheck: {', '.join(missing)}."
return round(score * 2) / 2, detail
def _grade_item(item: dict[str, Any], response: str) -> tuple[float, str]:
rubric = item["rubric"]
marks = item["marks"]
if not response.strip():
return 0.0, "No answer supplied."
if rubric["kind"] == "mcq":
normalised = _normalise_text(response).upper()
first_letter = re.match(r"\s*([A-D])(?:\b|[.)])", normalised)
if first_letter and first_letter.group(1) == rubric["letter"]:
return float(marks), "Correct option selected."
values = extract_numbers(response)
if any(abs(value - rubric["value"]) <= rubric["tolerance"] for value in values):
return float(marks), "Correct option value supplied."
return 0.0, f"The selected option is not {rubric['letter']}."
if rubric["kind"] == "numeric":
return _numeric_grade(rubric["expected"], response, marks)
if rubric["kind"] == "match":
return _match_grade(rubric["pairs"], response, marks)
return _concept_grade(rubric["groups"], response, marks)
def _answers_agree(typed: str, scanned: str) -> str:
typed_numbers = extract_numbers(typed)
scanned_numbers = extract_numbers(scanned)
if typed_numbers and scanned_numbers:
pairs = zip(typed_numbers, scanned_numbers)
agree = all(abs(left - right) <= max(0.03, abs(left) * 0.012) for left, right in pairs)
if agree and len(typed_numbers) == len(scanned_numbers):
return "Typed and scanned numerical answers agree."
return "Typed and scanned numerical answers differ — typed answer used; manual review advised."
ratio = SequenceMatcher(None, _normalise_text(typed), _normalise_text(scanned)).ratio()
if ratio >= 0.62:
return f"Typed and scanned wording broadly agree ({ratio:.0%} text similarity)."
return f"Typed and scanned wording differ ({ratio:.0%} text similarity) — typed answer used; manual review advised."
def grade_exam(
exam: dict[str, Any],
typed_answers: Iterable[str] | None,
scanned_answers: dict[int, str] | None = None,
) -> dict[str, Any]:
typed = list(typed_answers or [])
scanned = scanned_answers or {}
rows = []
total = 0.0
for index, item in enumerate(exam["questions"]):
typed_answer = str(typed[index] if index < len(typed) else "").strip()
scanned_answer = str(scanned.get(index + 1, "")).strip()
response = typed_answer or scanned_answer
source = "Typed answer" if typed_answer else ("Numbered handwritten answer" if scanned_answer else "No answer")
comparison = _answers_agree(typed_answer, scanned_answer) if typed_answer and scanned_answer else (
"Only the typed answer was supplied." if typed_answer else
"OCR answer used because no typed answer was supplied." if scanned_answer else
"No typed or readable numbered answer was supplied."
)
score, feedback = _grade_item(item, response)
score = min(float(item["marks"]), max(0.0, score))
total += score
rows.append(
{
"number": index + 1,
"format": item["format"],
"marks": item["marks"],
"score": score,
"typed_answer": typed_answer,
"scanned_answer": scanned_answer,
"response": response,
"source": source,
"comparison": comparison,
"feedback": feedback,
"answer_key": item["answer_key"],
"solution": item["solution"],
"question": item["question"],
"topic_label": item["topic_label"],
}
)
total = round(total * 2) / 2
maximum = exam["total_marks"]
percentage = 100 * total / maximum if maximum else 0.0
return {
"student": exam["student"],
"exam_name": exam["exam_name"],
"attempt_id": exam["attempt_id"],
"score": total,
"maximum": maximum,
"percentage": percentage,
"rows": rows,
"graded_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
}
def render_exam_results(grade: dict[str, Any]) -> tuple[str, str]:
score = grade["score"]
maximum = grade["maximum"]
percentage = grade["percentage"]
summary_rows = "\n".join(
f"| {row['number']} | {row['format']} | {row['score']:g}/{row['marks']} | {row['source']} |"
for row in grade["rows"]
)
summary = f"""
## Examination completed
### {score:g}/{maximum} marks · {percentage:.1f}%
| Q | Format | Mark | Evidence used |
|---:|---|---:|---|
{summary_rows}
> Typed answers are authoritative. If OCR disagreed, the difference is flagged for review and did not silently replace the typed response.
"""
sections = []
for row in grade["rows"]:
steps = "\n".join(f"{index}. {step}" for index, step in enumerate(row["solution"], 1))
sections.append(
f"""
### Question {row['number']} · {row['score']:g}/{row['marks']} marks
**Student response ({row['source']}):** {escape(row['response']) if row['response'] else 'No answer'}
**Evaluation:** {row['feedback']}
**Typed/OCR check:** {row['comparison']}
**Answer key:** {row['answer_key']}
**Worked solution / marking guidance**
{steps}
"""
)
solutions = "## Solutions and question-by-question feedback\n\n" + "\n\n---\n\n".join(sections)
return summary, solutions
NUMBERED_ANSWER_RE = re.compile(
r"(?mi)^\s*(?:q(?:uestion)?\s*)?(\d{1,2})\s*[).:\-]\s*(.*)$"
)
def parse_numbered_answers(text: str, maximum: int = 25) -> dict[int, str]:
matches = list(NUMBERED_ANSWER_RE.finditer(str(text or "")))
answers: dict[int, str] = {}
for index, match in enumerate(matches):
number = int(match.group(1))
if not 1 <= number <= maximum:
continue
end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
value = (match.group(2) + "\n" + text[match.end() : end]).strip()
value = re.sub(r"\s+", " ", value)
if value:
answers[number] = (answers.get(number, "") + " " + value).strip()
return answers
def _ocr_pil(image: Image.Image) -> tuple[str, str]:
if image.mode != "RGB":
image = image.convert("RGB")
return run_ocr(image)
def extract_numbered_answer_sheet(files: Any, maximum: int = 25) -> dict[str, Any]:
file_values = files if isinstance(files, (list, tuple)) else ([files] if files else [])
text_blocks: list[str] = []
statuses: list[str] = []
for file_index, value in enumerate(file_values, 1):
path_value = getattr(value, "name", value)
path = Path(str(path_value)) if path_value else None
if not path or not path.is_file():
statuses.append(f"File {file_index}: unavailable.")
continue
try:
if path.suffix.lower() == ".pdf":
import fitz
document = fitz.open(path)
for page_number, page in enumerate(document, 1):
pixmap = page.get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False)
image = Image.open(BytesIO(pixmap.tobytes("png")))
text, status = _ocr_pil(image)
text_blocks.append(text)
statuses.append(f"{path.name}, page {page_number}: {status}")
document.close()
else:
with Image.open(path) as opened:
text, status = _ocr_pil(opened.copy())
text_blocks.append(text)
statuses.append(f"{path.name}: {status}")
except Exception as exc:
statuses.append(f"{path.name}: could not be read ({type(exc).__name__}).")
raw_text = "\n".join(block for block in text_blocks if block).strip()
answers = parse_numbered_answers(raw_text, maximum=maximum)
return {"answers": answers, "raw_text": raw_text, "status": statuses}
def render_ocr_mapping(result: dict[str, Any] | None) -> str:
if not result:
return "No handwritten answer sheet has been read."
answers = result.get("answers", {})
status = " \n".join(escape(line) for line in result.get("status", []))
mapped = "\n".join(
f"- **Q{number}:** {escape(str(answer)[:500])}" for number, answer in sorted(answers.items())
)
if not mapped:
mapped = "No numbered answers were detected. Write each answer under a clear `Q1`, `Q2`, … heading or type it in the corresponding answer box."
return f"""
### Handwritten-sheet reading
{status}
{mapped}
> OCR is evidence support, not an invisible override. Typed answers take priority whenever both are present.
"""
def _pdf_styles() -> dict[str, ParagraphStyle]:
styles = getSampleStyleSheet()
body = ParagraphStyle(
"ExamBody", parent=styles["BodyText"], fontName="Helvetica", fontSize=9.2,
leading=12.4, textColor=colors.HexColor("#172554"), spaceAfter=5,
)
return {
"body": body,
"title": ParagraphStyle("ExamTitle", parent=body, fontName="Helvetica-Bold", fontSize=22, leading=26, textColor=colors.HexColor("#6D28D9"), spaceAfter=10),
"h1": ParagraphStyle("ExamH1", parent=body, fontName="Helvetica-Bold", fontSize=14, leading=18, textColor=colors.HexColor("#0891B2"), spaceBefore=10, spaceAfter=6),
"h2": ParagraphStyle("ExamH2", parent=body, fontName="Helvetica-Bold", fontSize=11, leading=14, textColor=colors.HexColor("#6D28D9"), spaceBefore=9, spaceAfter=4),
"small": ParagraphStyle("ExamSmall", parent=body, fontSize=7.8, leading=10, textColor=colors.HexColor("#475569")),
}
def _pdf_text(value: Any) -> str:
return escape(plain_math(str(value or ""))).replace("\n", "<br/>")
def _write_exam_pdf(raw_path: Path, exam: dict[str, Any], grade: dict[str, Any]) -> None:
styles = _pdf_styles()
document = SimpleDocTemplate(
str(raw_path), pagesize=LETTER, rightMargin=0.72 * inch, leftMargin=0.72 * inch,
topMargin=0.72 * inch, bottomMargin=0.72 * inch,
title=f"{exam['exam_label']} - result", author="M1 Mechanics Quest",
subject="Locked examination questions, solutions, and marks",
)
story: list[Any] = [
Paragraph("M1 Mechanics Quest", styles["title"]),
Paragraph(_pdf_text(exam["exam_label"]), styles["h1"]),
Paragraph(
_pdf_text(
f"Student: {exam['student']} | Attempt: {exam['attempt_id']} | Seed: {exam['seed']} | "
f"Score: {grade['score']:g}/{grade['maximum']} ({grade['percentage']:.1f}%) | Graded: {grade['graded_at']}"
),
styles["body"],
),
]
if "total_session_minutes" in exam:
story.append(Paragraph(
_pdf_text(
f"Protected session: {exam['total_session_minutes']} minutes total, "
f"including {exam.get('reading_minutes', DEFAULT_READING_MINUTES)} minutes reading/setup. "
f"Question pacing (minutes): {exam.get('question_timings', [item.get('assigned_minutes', item.get('default_minutes', 4)) for item in exam['questions']])}"
),
styles["small"],
))
table_data = [["Q", "Format", "Marks", "Score", "Evidence"]]
for row in grade["rows"]:
table_data.append([str(row["number"]), row["format"], str(row["marks"]), f"{row['score']:g}", row["source"]])
table = Table(table_data, colWidths=[0.35 * inch, 1.45 * inch, 0.55 * inch, 0.55 * inch, 2.3 * inch], repeatRows=1)
table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#EDE9FE")),
("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#312E81")),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
("FONTSIZE", (0, 0), (-1, -1), 7.5),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#CBD5E1")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#F8FAFC")]),
]))
story.extend([Spacer(1, 8), table, PageBreak(), Paragraph("Questions, responses, and solutions", styles["h1"])])
for row in grade["rows"]:
story.append(Paragraph(f"Question {row['number']} | {row['format']} | {row['score']:g}/{row['marks']} marks", styles["h2"]))
story.append(Paragraph(_pdf_text(row["question"]), styles["body"]))
story.append(Paragraph(f"<b>Student response ({escape(row['source'])}):</b> {_pdf_text(row['response'] or 'No answer')}", styles["body"]))
story.append(Paragraph(f"<b>Evaluation:</b> {_pdf_text(row['feedback'])}", styles["body"]))
story.append(Paragraph(f"<b>Typed/OCR comparison:</b> {_pdf_text(row['comparison'])}", styles["small"]))
story.append(Paragraph(f"<b>Answer key:</b> {_pdf_text(row['answer_key'])}", styles["body"]))
story.append(Paragraph("<b>Worked solution / marking guidance</b>", styles["body"]))
for index, step in enumerate(row["solution"], 1):
story.append(Paragraph(f"{index}. {_pdf_text(step)}", styles["body"]))
story.append(Spacer(1, 7))
story.append(Paragraph(
"Integrity note: This report is flattened and encrypted with printing permission only. Editing, annotation, form filling, assembly, and extraction permissions are disabled in compliant PDF readers. OCR mismatches require human review.",
styles["small"],
))
document.build(story)
def export_locked_exam_pdf(exam: dict[str, Any], grade: dict[str, Any]) -> str:
output_dir = Path(tempfile.mkdtemp(prefix="m1_exam_report_"))
safe_student = re.sub(r"[^A-Za-z0-9_-]+", "_", exam["student"]).strip("_")[:40] or "Student"
base = f"M1_{exam['exam_name'].replace(' ', '_')}_{safe_student}_{exam['attempt_id']}"
raw_path = output_dir / f"{base}_raw.pdf"
locked_path = output_dir / f"{base}_LOCKED.pdf"
_write_exam_pdf(raw_path, exam, grade)
reader = PdfReader(str(raw_path))
writer = PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata(
{
"/Title": f"{exam['exam_label']} - {exam['student']}",
"/Author": "M1 Mechanics Quest",
"/Subject": "Locked examination questions, solutions, and marks",
"/Keywords": f"attempt {exam['attempt_id']}; locked; read-only",
}
)
permissions = UserAccessPermissions.PRINT | UserAccessPermissions.PRINT_TO_REPRESENTATION
writer.encrypt(
user_password="",
owner_password=secrets.token_urlsafe(36),
permissions_flag=permissions,
algorithm="AES-256",
)
with locked_path.open("wb") as handle:
writer.write(handle)
raw_path.unlink(missing_ok=True)
return str(locked_path)
|