Spaces:
Paused
Paused
File size: 110,320 Bytes
f78142c f8aaa7d e538f4b f78142c 18cf817 af4eb60 18cf817 af4eb60 f78142c 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 f78142c 3705940 aae8a70 f8aaa7d f78142c 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b b919784 f78142c eea1fd8 f30de34 eea1fd8 f30de34 f78142c 08afe79 f78142c af4eb60 f8aaa7d f78142c f8aaa7d f78142c 7c6459b e9a92c8 d6d612b f78142c f8aaa7d f78142c d6d612b 4707b1a d6d612b e9a92c8 4707b1a e9a92c8 4707b1a e9a92c8 3d482be e9f1e84 3d482be e9f1e84 f78142c b919784 f78142c b919784 f78142c 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 18cf817 3705940 d6d612b 3705940 af4eb60 3705940 e538f4b 5eeaf48 e9f1e84 5eeaf48 e9f1e84 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e9f1e84 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 aae8a70 5eeaf48 e538f4b 5eeaf48 e538f4b aae8a70 5eeaf48 e538f4b aae8a70 5eeaf48 e538f4b aae8a70 5eeaf48 e538f4b 5eeaf48 e538f4b aae8a70 5eeaf48 e538f4b aae8a70 e538f4b aae8a70 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b aae8a70 e538f4b aae8a70 e538f4b aae8a70 e538f4b aae8a70 e538f4b aae8a70 f78142c 3705940 d6d612b 5eeaf48 e538f4b aae8a70 f78142c 5eeaf48 e9f1e84 5eeaf48 f78142c 08afe79 f8aaa7d f78142c 08afe79 f78142c 08afe79 f78142c 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 3705940 af4eb60 18cf817 af4eb60 18cf817 af4eb60 18cf817 3705940 af4eb60 3705940 f8aaa7d 3d482be 7c6459b e9a92c8 7c6459b 4707b1a 7c6459b e538f4b aae8a70 f78142c 08afe79 f78142c b919784 f78142c b919784 08afe79 f78142c 5eeaf48 e9f1e84 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e9f1e84 e9a92c8 e9f1e84 d6d612b e9f1e84 4707b1a e9f1e84 d6d612b e9f1e84 d6d612b e9f1e84 e9a92c8 f78142c 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e9f1e84 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 aae8a70 5eeaf48 e538f4b aae8a70 e538f4b aae8a70 e538f4b aae8a70 5eeaf48 e538f4b 5eeaf48 e538f4b 5eeaf48 e538f4b aae8a70 e538f4b aae8a70 e538f4b aae8a70 5eeaf48 e9f1e84 f78142c d6d612b f78142c e9f1e84 f78142c b919784 f78142c f8aaa7d 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b e9f1e84 3705940 af4eb60 3705940 af4eb60 3705940 18cf817 3705940 d6d612b 3705940 e9f1e84 af4eb60 3705940 e9f1e84 5eeaf48 f78142c | 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 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 | """Hugging Face Gradio entrypoint for M1 Mechanics Quest."""
from __future__ import annotations
from pathlib import Path
from html import escape
import json
import time
import gradio as gr
from collision_game import (
COLLISION_GAME_CSS,
COLLISION_GAME_HTML,
CREATIVE_EXPERIMENT_JS,
collision_game_payload,
)
from creative_questions import CREATIVE_SCENARIOS, build_creative_question, creative_status_markdown
from diagrams import make_3d_diagram, make_feedback_animation, make_line_diagram
from engine import DIFFICULTIES, TOPICS, generate_question, render_question, render_solution
from evaluator import evaluate_submission
from exam_engine import (
DEFAULT_READING_MINUTES,
DEFAULT_TOTAL_SESSION_MINUTES,
EXAM_CSS,
EXAM_AUTO_SUBMIT_JS,
EXAM_MAIN_TIMER_JS,
EXAM_MANUAL_SUBMIT_JS,
EXAM_MODE_TOGGLE_JS,
EXAM_RESET_TIMER_JS,
EXAM_SPECS,
EXAM_START_CAPTURE_JS,
EXAM_TOPIC_CHOICES,
apply_question_timings,
build_exam,
export_locked_exam_pdf,
extract_numbered_answer_sheet,
grade_exam,
reconstruct_exam,
render_exam_header,
render_exam_question,
render_exam_results,
render_ocr_mapping,
safe_attempt_state,
parse_numbered_answers,
question_timer_js,
)
from floating_tutor import FLOATING_TUTOR_CSS, FLOATING_TUTOR_VIEWPORT_JS
from gamification import mastery_markdown, new_profile, profile_html, record_hint
from interactive_lab import IMPACT_MODELS, build_custom_collision_question, custom_status_markdown
from obe_engine import (
ACTIVITY_CATEGORIES,
COMPONENTS,
DEFAULT_WEIGHT_PERCENTAGES,
OBE_CSS,
add_extraordinary_activity,
append_assessment_record,
assessment_choices,
calculate_obe_attainment,
certificate_preview,
export_certificate_pdf,
latest_component_scores,
mistake_analysis,
mistake_context_question,
obe_spider_chart,
render_activities,
render_obe_result,
select_assessment,
)
from question_intake import (
SUPPORTED_EXTENSIONS,
bank_choices,
bank_summary_markdown,
export_bank_file,
ingest_question_sources,
load_bank,
load_bank_record,
)
from question_visualizer import (
QUESTION_VISUALIZER_CSS,
QUESTION_VISUALIZER_HTML,
QUESTION_VISUALIZER_JS,
VISUAL_TOPIC_OPTIONS,
infer_visual_payload,
question_visual_payload,
)
from theory import theory_for
from tutor_chat import (
DEFAULT_OPEN_SOURCE_MODEL,
DEFAULT_TUTOR_QUESTIONS,
OPEN_SOURCE_TUTOR_MODELS,
QWEN_ENGINE,
TUTOR_ENGINES,
chat_with_tutor,
clear_tutor_chat,
tutor_context_markdown,
tutor_welcome,
)
from worksheet_exports import export_worksheet_bundle
APP_DIR = Path(__file__).resolve().parent
# Hugging Face's web uploader can flatten or omit nested folders when files are
# selected manually. Styling must never prevent the application from starting,
# so try both expected locations and finally use a self-contained fallback.
FALLBACK_CSS = """
.gradio-container {max-width: 1500px !important; background: linear-gradient(145deg,#f8fbff,#f5f3ff 55%,#fff7fb);}
.hero {padding: 32px; border-radius: 26px; color: white; background: linear-gradient(120deg,#312e81,#6d28d9 48%,#db2777); box-shadow: 0 20px 55px rgba(76,29,149,.24); margin-bottom: 18px;}
.hero h1 {font-size: clamp(34px,5vw,64px); line-height: 1; margin: 15px 0 10px;}
.hero p {max-width: 800px; color: rgba(255,255,255,.86); font-size: 17px;}
.hero-kicker {display:inline-block;padding:7px 12px;border:1px solid rgba(255,255,255,.35);border-radius:999px;background:rgba(255,255,255,.13);font-size:12px;font-weight:800;}
.feature-strip {display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:12px 0 18px;}
.feature-strip div,.profile-card,.question-panel,.coach-panel,.glass-panel {background:rgba(255,255,255,.88);border:1px solid rgba(99,102,241,.16);border-radius:18px;padding:14px;box-shadow:0 12px 35px rgba(30,41,59,.08);}
.feature-strip b {display:block;color:#172554;margin-bottom:3px;}
.question-panel {border-left:5px solid #06b6d4;padding:18px 24px !important;}
.question-kicker {display:inline-block;padding:6px 10px;border-radius:999px;color:#5b21b6;background:#ede9fe;font-weight:800;font-size:12px;}
.question-foot {margin-top:20px;color:#64748b;font-size:12px;border-top:1px dashed #cbd5e1;padding-top:11px;}
.primary-btn {color:white !important;border:none !important;font-weight:800 !important;background:linear-gradient(100deg,#6d28d9,#ec4899) !important;}
.submit-btn {color:white !important;border:none !important;font-weight:800 !important;background:linear-gradient(100deg,#0891b2,#2563eb) !important;}
.profile-level,.profile-stats {display:flex;justify-content:space-between;gap:10px;}.xp-track{height:10px;background:#e2e8f0;border-radius:99px;margin:10px 0;overflow:hidden}.xp-fill{height:100%;background:linear-gradient(90deg,#22d3ee,#8b5cf6,#ec4899)}
.profile-stats div{display:flex;flex-direction:column;align-items:center;padding:8px;background:#f8fafc;border-radius:12px;flex:1}.profile-stats span{font-size:11px;color:#64748b}.heart-text{color:#f43f5e}.badge-chip,.muted-chip{display:inline-block;margin:8px 4px 0 0;padding:5px 9px;border-radius:99px;background:#fef3c7;font-size:11px}.privacy-note{padding:11px 13px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:14px;font-size:12px}.hint-card{padding:13px 15px;border-left:4px solid #f59e0b;background:#fffbeb;border-radius:12px}.footer-note{text-align:center;color:#64748b;font-size:12px;padding:20px}
@media(max-width:760px){.feature-strip{grid-template-columns:repeat(2,1fr)}.hero{padding:24px}.question-panel{padding:14px !important}}
"""
# Gradio normally measures long tab labels and moves the excess into a
# three-dot "More tabs" menu. This app has exactly twelve primary workspaces,
# so keep all of them available in a deliberate six-by-two navigation grid.
# The visually-hidden selector makes Gradio's overflow measurement report zero
# excess width; the role=tablist selector controls the actual visible buttons.
ALWAYS_VISIBLE_TAB_CSS = r"""
#training-tabs .tab-wrapper {
align-items: stretch !important;
backdrop-filter: blur(18px);
background: rgba(248, 250, 252, .96) !important;
border: 1px solid rgba(109, 40, 217, .16);
border-radius: 18px;
box-shadow: 0 12px 30px rgba(30, 41, 59, .10);
height: auto !important;
margin-bottom: 16px !important;
min-height: 112px;
overflow: visible !important;
padding: 7px !important;
position: sticky !important;
top: 0 !important;
z-index: 80 !important;
}
#training-tabs .tab-container[role="tablist"] {
align-items: stretch !important;
display: grid !important;
gap: 7px !important;
grid-template-columns: repeat(6, minmax(0, 1fr)) !important;
grid-template-rows: repeat(2, minmax(48px, auto)) !important;
height: auto !important;
overflow: visible !important;
width: 100% !important;
}
#training-tabs .tab-container[role="tablist"]::after {
display: none !important;
}
#training-tabs .tab-container[role="tablist"] button[role="tab"] {
align-items: center !important;
background: rgba(255, 255, 255, .92) !important;
border: 1px solid #ddd6fe !important;
border-radius: 11px !important;
color: #312e81 !important;
display: flex !important;
font-size: clamp(10px, .86vw, 13px) !important;
font-weight: 800 !important;
height: auto !important;
justify-content: center !important;
line-height: 1.18 !important;
min-height: 48px !important;
overflow-wrap: anywhere !important;
padding: 7px 6px !important;
text-align: center !important;
white-space: normal !important;
width: 100% !important;
}
#training-tabs .tab-container[role="tablist"] button[role="tab"]:hover:not(:disabled) {
background: #f5f3ff !important;
border-color: #a78bfa !important;
transform: translateY(-1px);
}
#training-tabs .tab-container[role="tablist"] button[role="tab"].selected {
background: linear-gradient(110deg, #6d28d9, #db2777) !important;
border-color: transparent !important;
box-shadow: 0 7px 16px rgba(109, 40, 217, .22) !important;
color: white !important;
}
#training-tabs .tab-container[role="tablist"] button[role="tab"].selected::after {
display: none !important;
}
/* Keep all twelve tabs in the visible tablist instead of Gradio's overflow. */
#training-tabs .tab-container.visually-hidden button {
display: none !important;
font-size: 0 !important;
min-width: 0 !important;
padding: 0 !important;
width: 0 !important;
}
#training-tabs .overflow-menu {
display: none !important;
}
@media (max-width: 760px) {
#training-tabs .tab-wrapper { padding: 5px !important; }
#training-tabs .tab-container[role="tablist"] { gap: 4px !important; }
#training-tabs .tab-container[role="tablist"] button[role="tab"] {
font-size: 8.5px !important;
min-height: 54px !important;
padding: 5px 2px !important;
}
}
"""
def load_css(base_dir: Path = APP_DIR) -> str:
for candidate in (base_dir / "assets" / "style.css", base_dir / "style.css"):
try:
if candidate.is_file():
return candidate.read_text(encoding="utf-8")
except OSError:
pass
return FALLBACK_CSS
CSS = (
load_css()
+ "\n"
+ FLOATING_TUTOR_CSS
+ "\n"
+ EXAM_CSS
+ "\n"
+ OBE_CSS
+ "\n"
+ ALWAYS_VISIBLE_TAB_CSS
)
# Gradio enables display mathematics by default, but single-dollar inline
# mathematics is opt-in. Every learner-facing mathematics panel uses this
# shared configuration so symbols, units and exponents render through KaTeX.
LATEX_DELIMITERS = [
{"left": "$$", "right": "$$", "display": True},
{"left": "$", "right": "$", "display": False},
]
INITIAL_SEED = 20260813
INITIAL_PROFILE = new_profile()
INITIAL_QUESTION = generate_question("Mixed mission", "Exam standard", INITIAL_SEED)
INITIAL_CUSTOM_QUESTION = build_custom_collision_question(context="interactive engineering laboratory")
INITIAL_BANK = load_bank()
INITIAL_BANK_RECORD = INITIAL_BANK[-1] if INITIAL_BANK else None
INITIAL_IMPORTED_PAYLOAD = json.dumps(
INITIAL_BANK_RECORD["visual_payload"]
if INITIAL_BANK_RECORD
else infer_visual_payload(
"Two masses of 3 kg and 5 kg are released from a height of 20 m. "
"They fall freely under gravity with acceleration 9.8 m/sΒ².",
"Vertical motion / falling masses",
"Example imported question",
),
separators=(",", ":"),
)
def create_mission(topic: str, difficulty: str, seed: str, profile: dict):
q = generate_question(topic, difficulty, seed)
return (
q,
render_question(q),
question_visual_payload(q),
make_line_diagram(q),
make_3d_diagram(q),
theory_for(q),
"",
"",
0,
str(q["seed"]),
profile_html(profile),
tutor_context_markdown(q),
tutor_welcome(q),
tutor_context_markdown(q),
tutor_welcome(q),
q,
)
def _bank_record_markdown(record: dict | None) -> str:
if not record:
return "Select an imported question to inspect it."
prompt = escape(str(record.get("prompt", "")))
return (
f"<div class=\"question-kicker\">{escape(str(record.get('topic', 'Mechanics')))} Β· "
f"{escape(str(record.get('source', 'question intake')))}</div>\n\n"
f"## {escape(str(record.get('title', 'Imported question')))}\n\n{prompt}"
)
def add_questions_to_bank(
typed_text,
uploaded_files,
audio_question,
title_prefix,
topic_hint,
split_mode,
):
result = ingest_question_sources(
typed_text,
uploaded_files,
audio_question,
title_prefix,
topic_hint,
split_mode,
)
records = result["records"]
selected_id = result.get("selected_id")
record = next((item for item in records if item.get("id") == selected_id), None)
payload = result.get("visual_payload")
return (
result["status"],
result["extracted_text"],
bank_summary_markdown(records),
gr.update(choices=bank_choices(records), value=selected_id),
json.dumps(payload, separators=(",", ":")) if payload else INITIAL_IMPORTED_PAYLOAD,
_bank_record_markdown(record),
)
def open_bank_question(record_id: str):
record = load_bank_record(record_id)
if not record:
return "Question not found in the current bank.", INITIAL_IMPORTED_PAYLOAD
return (
_bank_record_markdown(record),
json.dumps(record.get("visual_payload", {}), separators=(",", ":")),
)
def next_hint(question: dict, index: int, profile: dict):
if not question:
return "Generate a mission first.", 0, profile, profile_html(profile)
hints = question.get("hints", [])
if not hints:
return "No hint is needed for this mission.", 0, profile, profile_html(profile)
idx = min(int(index or 0), len(hints) - 1)
profile = record_hint(profile)
message = f'<div class="hint-card"><b>Hint {idx + 1}/{len(hints)}</b><br>{hints[idx]}</div>'
return message, min(idx + 1, len(hints) - 1), profile, profile_html(profile)
def reveal_solution(question: dict):
return render_solution(question)
def assess_work(question: dict, image, final_answer: str, use_ai_vision: bool, profile: dict):
result = evaluate_submission(question, image, final_answer, profile, use_ai_vision)
animation = make_feedback_animation(question, result["correct"])
return (
result["feedback"],
animation,
result["ocr"],
result["profile"],
profile_html(result["profile"]),
mastery_markdown(result["profile"]),
)
def reset_progress():
p = new_profile()
return p, profile_html(p), mastery_markdown(p)
def chat_in_floating_tutor(
question: dict,
message: str,
tutor_engine: str,
open_source_model: str,
history: list[dict] | None,
):
"""Answer a typed question using the active problem and verified solution."""
updated_history, cleared_text, _, _, status = chat_with_tutor(
question,
message,
None,
None,
tutor_engine,
history,
open_source_model,
)
return updated_history, cleared_text, status
def show_floating_tutor():
"""Open the native Gradio tutor dialog."""
return gr.update(visible=True)
def show_floating_tutor_slot(selected_slot: str):
"""Open one fixed tutor and close the other two to avoid overlap."""
selected = str(selected_slot or "bottom").strip().lower()
return tuple(
gr.update(visible=slot == selected)
for slot in ("top", "middle", "bottom")
)
def hide_floating_tutor():
"""Close the native Gradio tutor dialog."""
return gr.update(visible=False)
def open_full_tutor_tab():
"""Switch to the full tutor and close the compact dialog."""
return gr.update(selected="mechanics-tutor"), gr.update(visible=False)
def sync_floating_tutor_copies(question: dict):
"""Refresh the top and middle copies when the active problem changes."""
context = tutor_context_markdown(question)
welcome = tutor_welcome(question)
return context, welcome, context, welcome
def build_worksheet(topic: str, difficulty: str, count: int, start_seed: str):
try:
base = int(start_seed)
except (TypeError, ValueError):
base = INITIAL_SEED
questions = [generate_question(topic, difficulty, base + i * 7919) for i in range(int(count))]
question_sections = []
for i, q in enumerate(questions, 1):
question_sections.append(
f"## Question {i} Β· {q['topic_label']} ({q['marks']} marks)\n\n{q['prompt'].strip()}\n\n"
)
markdown_file, word_file, pdf_file = export_worksheet_bundle(
questions, difficulty, base
)
preview = "\n\n---\n\n".join(question_sections[:3])
if len(questions) > 3:
preview += f"\n\n*β¦plus {len(questions) - 3} more questions in the downloadable worksheet.*"
return markdown_file, word_file, pdf_file, preview
def update_creative_lab(
scenario: str,
context: str,
difficulty: str,
impact_model: str,
restitution: float,
mass_p: float,
mass_q: float,
distance: float,
friction_p: float,
friction_q: float,
velocity_p: float,
velocity_q: float,
acceleration_p: float,
acceleration_q: float,
train_mass: float,
train_u: float,
train_a: float,
train_accel_time: float,
train_cruise_time: float,
train_braking: float,
train_resistance: float,
rocket_mass: float,
rocket_height: float,
rocket_u: float,
rocket_g: float,
trolley_mass: float,
trolley_force: float,
trolley_angle: float,
trolley_mu: float,
trolley_u: float,
trolley_time: float,
):
question = build_creative_question(
scenario,
context,
difficulty,
impact_model,
restitution,
mass_p,
mass_q,
distance,
friction_p,
friction_q,
velocity_p,
velocity_q,
acceleration_p,
acceleration_q,
train_mass,
train_u,
train_a,
train_accel_time,
train_cruise_time,
train_braking,
train_resistance,
rocket_mass,
rocket_height,
rocket_u,
rocket_g,
trolley_mass,
trolley_force,
trolley_angle,
trolley_mu,
trolley_u,
trolley_time,
)
return (
question,
creative_status_markdown(question),
collision_game_payload(question),
make_line_diagram(question),
make_3d_diagram(question),
render_question(question),
"",
theory_for(question),
"Submit your working to open a motion replay based on your chosen parameters.",
make_feedback_animation(question, None),
"No submission yet.",
tutor_context_markdown(question),
tutor_welcome(question),
question,
)
def show_creative_controls(scenario: str):
return (
gr.update(visible=scenario == CREATIVE_SCENARIOS[0]),
gr.update(visible=scenario == CREATIVE_SCENARIOS[1]),
gr.update(visible=scenario == CREATIVE_SCENARIOS[2]),
gr.update(visible=scenario == CREATIVE_SCENARIOS[3]),
)
def export_custom_question(question: dict):
if not question:
question = INITIAL_CUSTOM_QUESTION
return export_worksheet_bundle(
[question], question.get("difficulty", "Exam standard"), question.get("seed", INITIAL_SEED)
)
MAX_EXAM_QUESTIONS = 40
def switch_exam_mode(enabled: bool):
"""Hide every training surface while the examination section is active."""
active = bool(enabled)
message = (
"π **Examination mode is active.** Training tabs, worksheet tools, theory, progress, and all Ask Teacher bots are unavailable."
if active
else "Training mode is active. Turn on the switch when the student is ready for a protected examination attempt."
)
return (
gr.update(visible=not active),
gr.update(visible=not active),
gr.update(visible=active),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
message,
)
def start_exam_interface(
student_name: str,
exam_name: str,
trained_topics: list[str] | None,
exam_seed: str,
midterm_1_count: int,
midterm_2_count: int,
final_count: int,
total_session_minutes: int,
one_minute_questions: str,
two_minute_questions: str,
three_minute_questions: str,
four_minute_questions: str,
five_minute_questions: str,
six_minute_questions: str,
seven_minute_questions: str,
):
count_map = {
"Midterm 1": int(midterm_1_count),
"Midterm 2": int(midterm_2_count),
"Final examination": int(final_count),
}
question_count = count_map.get(exam_name, int(midterm_1_count))
exam = build_exam(exam_name, trained_topics, exam_seed, student_name, question_count)
manual_timings = {
1: one_minute_questions,
2: two_minute_questions,
3: three_minute_questions,
4: four_minute_questions,
5: five_minute_questions,
6: six_minute_questions,
7: seven_minute_questions,
}
try:
exam = apply_question_timings(exam, manual_timings)
except ValueError as exc:
raise gr.Error(str(exc)) from exc
total_minutes = max(20, min(DEFAULT_TOTAL_SESSION_MINUTES, int(total_session_minutes)))
started_epoch_ms = int(time.time() * 1000)
exam.update(
{
"total_session_minutes": total_minutes,
"reading_minutes": DEFAULT_READING_MINUTES,
"started_epoch_ms": started_epoch_ms,
"deadline_epoch_ms": started_epoch_ms + total_minutes * 60_000,
}
)
attempt = safe_attempt_state(exam)
values: list = [
attempt,
render_exam_header(exam),
(
f"π **{exam['exam_label']} started.** The examination switch and paper settings are locked until submission. "
"All Ask Teacher bots and training sections remain disabled."
),
gr.update(value=True, interactive=False),
gr.update(value=exam["exam_name"], interactive=False),
gr.update(value=exam["topics"], interactive=False),
gr.update(value=str(exam["seed"]), interactive=False),
gr.update(value=exam["student"], interactive=False),
gr.update(interactive=False),
gr.update(interactive=False),
gr.update(interactive=False),
gr.update(value=total_minutes, interactive=False),
*[gr.update(interactive=False) for _ in range(7)],
gr.update(interactive=False),
gr.update(value=False, interactive=True),
gr.update(value=None, interactive=True),
{},
"No handwritten answer sheet has been read.",
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(visible=False),
"",
"",
None,
total_minutes,
DEFAULT_READING_MINUTES,
exam["attempt_id"],
'<div class="exam-main-timer"><strong>Starting protected clockβ¦</strong><br>The reading and setup phase begins immediately.</div>',
]
for index in range(MAX_EXAM_QUESTIONS):
visible = index < exam["count"]
duration = exam["question_timings"][index] if visible else 1
values.extend(
[
gr.update(visible=visible),
render_exam_question(exam["questions"][index]) if visible else "",
gr.update(value="", interactive=False),
duration,
(
f'<div class="exam-question-timer"><b>Suggested time: {duration} minute'
f'{"s" if duration != 1 else ""}.</b> Available after the reading phase.</div>'
if visible else ""
),
gr.update(
value=f"Start Q{index + 1} timer Β· {duration} min",
visible=visible,
interactive=False,
),
]
)
return tuple(values)
def read_exam_answer_sheet(files, attempt: dict | None):
maximum = int((attempt or {}).get("count", MAX_EXAM_QUESTIONS))
result = extract_numbered_answer_sheet(files, maximum=maximum)
return result, render_ocr_mapping(result)
def submit_exam_interface(
attempt: dict | None,
uploaded_answer_sheets,
ocr_state: dict | None,
declaration: bool,
assessment_history: list[dict] | None,
*typed_answers: str,
):
unchanged = [gr.update() for _ in range(MAX_EXAM_QUESTIONS * 2)]
if not declaration:
return (
gr.update(),
gr.update(),
gr.update(),
"β οΈ Tick the examination declaration before submitting the paper.",
attempt or {},
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
ocr_state or {},
gr.update(),
gr.update(),
assessment_history or [],
*unchanged,
)
exam = reconstruct_exam(attempt)
if not exam or (attempt or {}).get("submitted"):
return (
gr.update(),
gr.update(),
gr.update(),
"β οΈ No active unsubmitted examination was found. Start a new examination.",
attempt or {},
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
ocr_state or {},
gr.update(),
gr.update(),
assessment_history or [],
*unchanged,
)
sheet_result = ocr_state or {}
if uploaded_answer_sheets and not sheet_result.get("answers"):
sheet_result = extract_numbered_answer_sheet(
uploaded_answer_sheets, maximum=exam["count"]
)
grade = grade_exam(exam, typed_answers[: exam["count"]], sheet_result.get("answers", {}))
summary, solutions = render_exam_results(grade)
pdf_path = export_locked_exam_pdf(exam, grade)
completed_attempt = dict(attempt or {})
completed_attempt.update(
{
"submitted": True,
"score": grade["score"],
"maximum": grade["maximum"],
"percentage": grade["percentage"],
}
)
frozen_answers = [gr.update(interactive=False) for _ in range(MAX_EXAM_QUESTIONS)]
frozen_timers = [gr.update(interactive=False) for _ in range(MAX_EXAM_QUESTIONS)]
timed_out = int(time.time() * 1000) >= int((attempt or {}).get("deadline_epoch_ms", 2**63 - 1))
updated_history = append_assessment_record(
assessment_history, exam["exam_name"], grade, exam
)
return (
summary,
solutions,
pdf_path,
(
f"{'β° Time expired β automatically submitted and locked' if timed_out else 'β
Submitted and locked'}: "
f"{grade['score']:g}/{grade['maximum']} marks ({grade['percentage']:.1f}%). "
"Solutions are now visible and the read-only PDF report is ready."
),
completed_attempt,
gr.update(value=True, interactive=True),
gr.update(interactive=False),
gr.update(value=False, interactive=False),
gr.update(interactive=False),
gr.update(interactive=False),
gr.update(visible=True),
sheet_result,
render_ocr_mapping(sheet_result),
'<div class="exam-main-timer"><strong>EXAMINATION COMPLETED</strong><br>Answers are locked. The result and printable report have been generated.</div>',
updated_history,
*frozen_answers,
*frozen_timers,
)
def auto_submit_exam_interface(
attempt: dict | None,
uploaded_answer_sheets,
ocr_state: dict | None,
assessment_history: list[dict] | None,
*typed_answers: str,
):
"""Deadline-triggered submission does not require the learner declaration."""
return submit_exam_interface(
attempt,
uploaded_answer_sheets,
ocr_state,
True,
assessment_history,
*typed_answers,
)
def unlock_exam_inputs(attempt: dict | None):
active = bool(attempt and attempt.get("started") and not attempt.get("submitted"))
within_deadline = int(time.time() * 1000) < int((attempt or {}).get("deadline_epoch_ms", 0))
count = int((attempt or {}).get("count", 0)) if active and within_deadline else 0
answer_updates = [gr.update(interactive=index < count) for index in range(MAX_EXAM_QUESTIONS)]
timer_updates = [gr.update(interactive=index < count) for index in range(MAX_EXAM_QUESTIONS)]
return (*answer_updates, *timer_updates)
def reset_exam_interface():
values: list = [
{},
"Choose the examination and trained topics, then start a protected attempt.",
"Examination mode is active. Paper settings are ready for a new attempt.",
gr.update(value=True, interactive=True),
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(value="", interactive=True),
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(value=DEFAULT_TOTAL_SESSION_MINUTES, interactive=True),
*[gr.update(interactive=True) for _ in range(7)],
gr.update(interactive=True),
gr.update(value=False, interactive=True),
gr.update(value=None, interactive=True),
{},
"No handwritten answer sheet has been read.",
gr.update(interactive=True),
gr.update(interactive=True),
gr.update(visible=False),
"",
"",
None,
DEFAULT_TOTAL_SESSION_MINUTES,
DEFAULT_READING_MINUTES,
"",
'<div class="exam-main-timer"><strong>Timer not started</strong><br>Start a protected examination to begin the reading and overall-session clocks.</div>',
]
for _ in range(MAX_EXAM_QUESTIONS):
values.extend(
[
gr.update(visible=False),
"",
gr.update(value="", interactive=False),
1,
"",
gr.update(value="Start question timer", visible=False, interactive=False),
]
)
return tuple(values)
def generate_assignment_interface(
student_name: str,
assignment_title: str,
trained_topics: list[str] | None,
question_count: int,
assignment_seed: str,
):
exam = build_exam(
"Midterm 1",
trained_topics,
assignment_seed,
student_name,
int(question_count),
)
title = str(assignment_title or "Mechanics assignment").strip()[:120] or "Mechanics assignment"
exam["exam_label"] = f"Assignment Β· {title}"
state = safe_attempt_state(exam)
state["assignment_title"] = title
question_sections = "\n\n---\n\n".join(
render_exam_question(question) for question in exam["questions"]
)
paper = f"""
## {escape(exam['exam_label'])}
**Student:** {escape(exam['student'])} Β· **Questions:** {exam['count']} Β· **Total:** {exam['total_marks']} marks Β· **Assignment ID:** `{exam['attempt_id']}`
Enter typed answers using `Q1`, `Q2`, β¦ headings, or upload numbered handwritten images/PDF in the submission portal.
---
{question_sections}
"""
return (
state,
paper,
"Assignment generated. Solutions remain hidden until the submission is evaluated.",
"",
"",
None,
gr.update(value="", interactive=True),
gr.update(value=None, interactive=True),
gr.update(interactive=True),
)
def submit_assignment_interface(
assignment_state: dict | None,
typed_numbered_answers: str,
uploaded_files,
assessment_history: list[dict] | None,
):
exam = reconstruct_exam(assignment_state)
if not exam:
return (
"Generate an assignment before submitting work.",
gr.update(),
gr.update(),
gr.update(),
gr.update(),
gr.update(),
assessment_history or [],
)
exam["exam_label"] = f"Assignment Β· {(assignment_state or {}).get('assignment_title', 'Mechanics assignment')}"
typed_map = parse_numbered_answers(typed_numbered_answers, maximum=exam["count"])
if not typed_map and str(typed_numbered_answers or "").strip() and exam["count"] == 1:
typed_map = {1: str(typed_numbered_answers).strip()}
sheet_result = extract_numbered_answer_sheet(uploaded_files, maximum=exam["count"]) if uploaded_files else {"answers": {}, "raw_text": "", "status": []}
typed_list = [typed_map.get(number, "") for number in range(1, exam["count"] + 1)]
grade = grade_exam(exam, typed_list, sheet_result.get("answers", {}))
summary, solutions = render_exam_results(grade)
pdf_path = export_locked_exam_pdf(exam, grade)
updated_history = append_assessment_record(
assessment_history, "Assignment", grade, exam
)
return (
f"β
Assignment submitted and evaluated: **{grade['score']:g}/{grade['maximum']} marks ({grade['percentage']:.1f}%)**.",
summary,
solutions,
pdf_path,
gr.update(interactive=False),
gr.update(interactive=False),
updated_history,
)
def record_extraordinary_activity_interface(
records: list[dict] | None,
student: str,
title: str,
category: str,
description: str,
marks_obtained: float,
maximum_marks: float,
evidence_files,
):
try:
updated = add_extraordinary_activity(
records,
student,
title,
category,
description,
marks_obtained,
maximum_marks,
evidence_files,
)
except ValueError as exc:
return records or [], render_activities(records), f"β οΈ {exc}", gr.update(), gr.update(), gr.update()
return (
updated,
render_activities(updated),
"β
Extraordinary activity recorded and included in the OBE data source.",
"",
"",
None,
)
def clear_extraordinary_activities_interface():
return [], render_activities([]), "Extraordinary activity records were cleared for this session."
def load_obe_scores_interface(
assessment_history: list[dict] | None,
activities: list[dict] | None,
):
scores = latest_component_scores(assessment_history, activities)
student = next(
(str(record.get("student", "Student")) for record in reversed(assessment_history or [])),
next((str(record.get("student", "Student")) for record in reversed(activities or [])), "Student"),
)
values: list = [student]
for component in COMPONENTS:
values.extend(scores[component])
return (*values, "β
Loaded the latest recorded assessment and activity scores. You may adjust any field before computing attainment.")
def compute_obe_interface(student: str, *values):
score_values = values[: len(COMPONENTS) * 2]
weight_values = values[len(COMPONENTS) * 2 :]
scores = {
component: (score_values[index * 2], score_values[index * 2 + 1])
for index, component in enumerate(COMPONENTS)
}
weights = {
component: weight_values[index]
for index, component in enumerate(COMPONENTS)
}
try:
result = calculate_obe_attainment(student, scores, weights)
except ValueError as exc:
return {}, f"## OBE calculation needs attention\n\nβ οΈ {escape(str(exc))}", obe_spider_chart(), f"β οΈ {exc}"
return (
result,
render_obe_result(result),
obe_spider_chart(result),
f"β
Attainment computed: {result['attainment']:.3f}/3.000. Weight total: {sum(result['weights'].values()):.1f}%.",
)
def refresh_mistake_assessments_interface(history: list[dict] | None):
choices = assessment_choices(history)
value = choices[0][1] if choices else None
status = (
f"Found {len(choices)} completed assessment{'s' if len(choices) != 1 else ''}. Select one and analyse it."
if choices else
"No completed examination or assignment is available yet. Submit one first."
)
return gr.update(choices=choices, value=value), status
def analyse_mistakes_interface(history: list[dict] | None, selection: str):
record = select_assessment(history, selection)
if not record:
return {}, mistake_analysis(None), tutor_welcome(None), "Select a completed assessment first."
question = mistake_context_question(record)
return record, mistake_analysis(record), tutor_welcome(question), "β
Question-level mistakes and improvement priorities are ready."
def chat_about_mistakes_interface(
record: dict | None,
message: str,
tutor_engine: str,
open_source_model: str,
history: list[dict] | None,
):
if not record:
return history or tutor_welcome(None), message, "Select and analyse a completed assessment before asking about mistakes."
response = chat_with_tutor(
mistake_context_question(record),
message,
None,
None,
tutor_engine,
history,
open_source_model,
)
return response[0], response[1], response[4]
def clear_mistake_chat_interface(record: dict | None):
question = mistake_context_question(record) if record else None
return tutor_welcome(question), "Conversation cleared; the selected assessment remains linked."
def generate_certificate_interface(result: dict | None):
if not result:
return (
'<div class="certificate-preview"><h2>Compute OBE attainment first</h2><p>The certificate uses the current OBE result and student name.</p></div>',
None,
"Compute OBE attainment before generating a certificate.",
)
pdf_path = export_certificate_pdf(result)
if not pdf_path:
return certificate_preview(result), None, "A certificate is generated only at 60% attainment or above. Follow the improvement plan and recompute the score."
return certificate_preview(result), pdf_path, "β
Congratulations! The protected, print-enabled certificate PDF is ready."
theme = gr.themes.Soft(
primary_hue="violet",
secondary_hue="pink",
neutral_hue="slate",
font=[gr.themes.GoogleFont("DM Sans"), "Arial", "sans-serif"],
)
with gr.Blocks(title="M1 Mechanics Quest", fill_width=True) as demo:
question_state = gr.State(INITIAL_QUESTION)
profile_state = gr.State(INITIAL_PROFILE)
hint_index_state = gr.State(0)
custom_question_state = gr.State(INITIAL_CUSTOM_QUESTION)
floating_question_state = gr.State(INITIAL_QUESTION)
exam_attempt_state = gr.State({})
exam_ocr_state = gr.State({})
assignment_state = gr.State({})
assessment_history_state = gr.State([])
extraordinary_activities_state = gr.State([])
obe_result_state = gr.State({})
mistake_record_state = gr.State({})
gr.HTML("""
<section class="hero">
<span class="hero-kicker">π Pearson Edexcel IAL Β· Mechanics 1 practice</span>
<h1>M1 Mechanics Quest</h1>
<p>Generate fresh exam-style missions, rotate the mechanics in 3D, upload handwritten working, and turn every correction into XP.</p>
</section>
<section class="feature-strip">
<div><b>β Original questions</b>Seeded, reproducible parameters</div>
<div><b>β Dual diagrams</b>2D exam lines + coloured 3D</div>
<div><b>β Work-photo coach</b>OCR with optional vision review</div>
<div><b>β‘ Game loop</b>XP, streaks, hearts and badges</div>
</section>
""")
with gr.Group(elem_classes=["exam-mode-shell"]):
with gr.Row(equal_height=True):
with gr.Column(scale=4):
gr.Markdown(
"### π‘οΈ Examination lock\nActivate this only when the student is ready. During an active attempt, training tabs and all Ask Teacher bots are unavailable until submission."
)
with gr.Column(scale=2):
exam_mode_toggle = gr.Checkbox(
label="Activate examination section",
value=False,
elem_id="exam-mode-toggle",
)
exam_mode_status = gr.Markdown(
"Training mode is active. Turn on the switch when the student is ready for a protected examination attempt."
)
with gr.Group(visible=True) as training_controls:
with gr.Row(equal_height=False):
with gr.Column(scale=3, elem_classes=["glass-panel", "control-panel"]):
gr.Markdown("### Mission generator")
topic = gr.Dropdown(list(TOPICS), value="Mixed mission", label="Skill zone")
difficulty = gr.Radio(list(DIFFICULTIES), value="Exam standard", label="Challenge level")
seed = gr.Textbox(value=str(INITIAL_SEED), label="Seed", info="Reuse a seed to recreate the same question")
generate_btn = gr.Button("Generate new mission β¦", variant="primary", elem_classes=["primary-btn"])
with gr.Column(scale=2):
profile_panel = gr.HTML(profile_html(INITIAL_PROFILE))
with gr.Tabs(visible=True, elem_id="training-tabs") as app_tabs:
with gr.Tab("π― Mission control"):
question_md = gr.Markdown(
render_question(INITIAL_QUESTION),
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["question-panel"],
)
gr.Markdown("## See, animate, and vary the question concept")
mission_visual = gr.HTML(
value=question_visual_payload(INITIAL_QUESTION),
label="Interactive visual concept",
html_template=QUESTION_VISUALIZER_HTML,
css_template=QUESTION_VISUALIZER_CSS,
js_on_load=QUESTION_VISUALIZER_JS,
apply_default_css=False,
container=False,
)
with gr.Row():
line_plot = gr.Plot(make_line_diagram(INITIAL_QUESTION), label="2D line diagram")
model_plot = gr.Plot(make_3d_diagram(INITIAL_QUESTION), label="3D model")
with gr.Row():
hint_btn = gr.Button("Unlock next hint π‘")
solution_btn = gr.Button("Reveal worked solution", variant="secondary")
hint_md = gr.HTML()
solution_md = gr.Markdown(
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["glass-panel"],
)
gr.Markdown("## Submit your working")
with gr.Row(equal_height=False):
with gr.Column(scale=1):
work_image = gr.Image(
label="Photo or scan of handwritten working",
type="pil",
image_mode="RGB",
sources=["upload", "webcam", "clipboard"],
height=360,
)
with gr.Column(scale=1):
final_answer = gr.Textbox(
label="Confirm final answer(s)",
placeholder="Example: 4.2, 36.8 (use question order)",
lines=2,
info="Recommended because handwriting OCR can confuse signs, powers and fractions.",
)
use_ai_vision = gr.Checkbox(
label="Use optional AI vision tutor",
value=False,
info="Requires OPENAI_API_KEY in Space secrets; the image is sent to that API only when checked.",
)
gr.HTML('<div class="privacy-note">π Local OCR is the default. The optional vision tutor is off unless the learner explicitly enables it.</div>')
assess_btn = gr.Button("Analyse my method β‘", variant="primary", elem_classes=["submit-btn"])
with gr.Row(equal_height=False):
feedback_md = gr.Markdown(
"Submit a worked solution to open the correction replay.",
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["coach-panel"],
)
feedback_plot = gr.Plot(make_feedback_animation(INITIAL_QUESTION, None), label="Animated correction replay")
with gr.Accordion("What the image reader detected", open=False):
ocr_md = gr.Markdown("No submission yet.")
with gr.Tab("π§ͺ Creative mechanics lab"):
gr.Markdown("""
## Build and play the experiment described by the question
Choose an experiment and change its physical parameters. The object, scenery, question, animation, sound effects, diagrams, theory and worked solution all change together from the same validated model.
""")
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["glass-panel"]):
custom_scenario = gr.Dropdown(
list(CREATIVE_SCENARIOS),
value=CREATIVE_SCENARIOS[0],
label="Experiment and question type",
)
custom_context = gr.Textbox(
value="interactive engineering laboratory",
label="Creative setting",
info="Examples: coastal railway, lunar launch site, warehouse lane, robotics arena",
)
with gr.Column(scale=2, elem_classes=["glass-panel"]):
custom_difficulty = gr.Radio(
list(DIFFICULTIES), value="Exam standard", label="Question depth"
)
gr.Markdown("Negative velocity or acceleration means motion or acceleration to the left/downward.")
with gr.Group(visible=True) as collision_controls:
gr.Markdown("### Roller collision parameters")
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["glass-panel"]):
custom_impact_model = gr.Radio(
list(IMPACT_MODELS), value=IMPACT_MODELS[1], label="Impact behaviour"
)
custom_restitution = gr.Slider(
0, 1, value=0.65, step=0.05, label="Coefficient of restitution e",
info="Used only when the rollers separate after impact.",
)
custom_distance = gr.Slider(3, 30, value=12, step=0.5, label="Initial separation d (m)")
with gr.Column(scale=2, elem_classes=["glass-panel"]):
gr.Markdown("#### Roller P Β· cyan")
custom_mass_p = gr.Slider(1, 12, value=4, step=0.5, label="Mass P (kg) Β· changes roller size")
custom_velocity_p = gr.Slider(-20, 20, value=8, step=0.5, label="Initial velocity P (m/s) Β· right positive")
custom_acceleration_p = gr.Slider(-4, 4, value=0.6, step=0.1, label="Net acceleration P (m/sΒ²) Β· right positive")
custom_friction_p = gr.Slider(0, 0.8, value=0.15, step=0.05, label="Coefficient of friction under P")
with gr.Column(scale=2, elem_classes=["glass-panel"]):
gr.Markdown("#### Roller Q Β· pink")
custom_mass_q = gr.Slider(1, 12, value=7, step=0.5, label="Mass Q (kg) Β· changes roller size")
custom_velocity_q = gr.Slider(-20, 20, value=-5, step=0.5, label="Initial velocity Q (m/s) Β· right positive")
custom_acceleration_q = gr.Slider(-4, 4, value=-0.2, step=0.1, label="Net acceleration Q (m/sΒ²) Β· right positive")
custom_friction_q = gr.Slider(0, 0.8, value=0.2, step=0.05, label="Coefficient of friction under Q")
with gr.Group(visible=False) as train_controls:
gr.Markdown("### Electric train parameters")
with gr.Row(equal_height=False):
with gr.Column(elem_classes=["glass-panel"]):
train_mass = gr.Slider(20, 200, value=90, step=5, label="Train mass (tonnes) Β· changes train length")
train_initial_velocity = gr.Slider(0, 35, value=6, step=0.5, label="Initial train speed (m/s)")
train_acceleration = gr.Slider(0.2, 3, value=1.2, step=0.1, label="Acceleration (m/sΒ²)")
train_resistance = gr.Slider(0, 120, value=35, step=5, label="Resistance to motion (kN)")
with gr.Column(elem_classes=["glass-panel"]):
train_acceleration_time = gr.Slider(2, 20, value=10, step=1, label="Acceleration-stage time (s)")
train_cruise_time = gr.Slider(2, 30, value=12, step=1, label="Constant-speed time (s)")
train_braking = gr.Slider(0.2, 4, value=1.5, step=0.1, label="Braking deceleration (m/sΒ²)")
with gr.Group(visible=False) as rocket_controls:
gr.Markdown("### Rocket capsule parameters")
with gr.Row(equal_height=False):
with gr.Column(elem_classes=["glass-panel"]):
rocket_mass = gr.Slider(50, 500, value=180, step=10, label="Capsule mass (kg) Β· changes capsule size")
rocket_height = gr.Slider(0, 50, value=12, step=1, label="Launch-platform height (m)")
with gr.Column(elem_classes=["glass-panel"]):
rocket_velocity = gr.Slider(5, 80, value=32, step=1, label="Launch velocity (m/s)")
rocket_gravity = gr.Slider(5, 12, value=9.8, step=0.1, label="Gravitational acceleration (m/sΒ²)")
with gr.Group(visible=False) as trolley_controls:
gr.Markdown("### Cargo trolley parameters")
with gr.Row(equal_height=False):
with gr.Column(elem_classes=["glass-panel"]):
trolley_mass = gr.Slider(10, 50, value=24, step=1, label="Trolley and cargo mass (kg) Β· changes load size")
trolley_force = gr.Slider(20, 120, value=95, step=5, label="Pulling force (N)")
trolley_angle = gr.Slider(0, 40, value=25, step=1, label="Pulling angle above horizontal (degrees)")
with gr.Column(elem_classes=["glass-panel"]):
trolley_friction = gr.Slider(0, 0.6, value=0.22, step=0.02, label="Coefficient of friction")
trolley_velocity = gr.Slider(1, 20, value=7, step=0.5, label="Initial trolley speed (m/s)")
trolley_time = gr.Slider(1, 10, value=5, step=0.5, label="Observation time (s)")
custom_status = gr.Markdown(
custom_status_markdown(INITIAL_CUSTOM_QUESTION),
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["glass-panel"],
)
gr.Markdown("## Interactive experiment Β· click the model to start")
custom_game = gr.HTML(
value=collision_game_payload(INITIAL_CUSTOM_QUESTION),
label="Interactive question experiment",
html_template=COLLISION_GAME_HTML,
css_template=COLLISION_GAME_CSS,
js_on_load=CREATIVE_EXPERIMENT_JS,
apply_default_css=False,
container=False,
)
with gr.Row():
custom_line_plot = gr.Plot(make_line_diagram(INITIAL_CUSTOM_QUESTION), label="Live 2D question model")
custom_3d_plot = gr.Plot(make_3d_diagram(INITIAL_CUSTOM_QUESTION), label="Live rotatable 3D experiment")
custom_question_md = gr.Markdown(
render_question(INITIAL_CUSTOM_QUESTION),
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["question-panel"],
)
gr.Markdown("## Solve your custom mission")
with gr.Row(equal_height=False):
with gr.Column(scale=1):
custom_work_image = gr.Image(
label="Photo or scan of handwritten working",
type="pil",
image_mode="RGB",
sources=["upload", "webcam", "clipboard"],
height=340,
)
with gr.Column(scale=1):
custom_final_answer = gr.Textbox(
label="Confirm final answer(s)",
placeholder="Enter answers in the order asked",
lines=2,
info="Recommended because handwriting OCR can confuse signs, powers and fractions.",
)
custom_use_ai_vision = gr.Checkbox(
label="Use optional AI vision tutor",
value=False,
info="Requires OPENAI_API_KEY in Space secrets; the image is sent only when checked.",
)
custom_assess_btn = gr.Button(
"Analyse my custom solution β‘", variant="primary", elem_classes=["submit-btn"]
)
with gr.Row(equal_height=False):
custom_feedback_md = gr.Markdown(
"Submit your working to open a motion replay based on your chosen parameters.",
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["coach-panel"],
)
custom_feedback_plot = gr.Plot(
make_feedback_animation(INITIAL_CUSTOM_QUESTION, None),
label="Custom motion replay",
)
with gr.Accordion("What the image reader detected", open=False):
custom_ocr_md = gr.Markdown("No submission yet.")
with gr.Row():
custom_solution_btn = gr.Button("Reveal custom worked solution", variant="secondary")
custom_export_btn = gr.Button("Download this custom mission", variant="primary", elem_classes=["primary-btn"])
custom_solution_md = gr.Markdown(latex_delimiters=LATEX_DELIMITERS, elem_classes=["glass-panel"])
with gr.Row():
custom_md_file = gr.File(label="Custom Markdown (.md)")
custom_docx_file = gr.File(label="Custom Word (.docx)")
custom_pdf_file = gr.File(label="Custom PDF (.pdf)")
with gr.Accordion("Theory behind your custom model", open=False):
custom_theory_md = gr.Markdown(
theory_for(INITIAL_CUSTOM_QUESTION), latex_delimiters=LATEX_DELIMITERS
)
with gr.Tab("β Question intake"):
gr.Markdown("""
## Add questions from any new user guide
Paste text, upload text/image/PDF/Word files, or record a spoken question. The app extracts and deduplicates the questions, identifies the mechanics concept, stores them in the reusable question bank, and builds an editable visual model.
""")
with gr.Row(equal_height=False):
with gr.Column(scale=3, elem_classes=["glass-panel"]):
intake_text = gr.Textbox(
label="Paste one or more questions",
placeholder="Paste a question, or a numbered set such as Q1, Q2, Q3β¦",
lines=8,
)
intake_files = gr.File(
label="Upload text, image, PDF, Word, or audio files",
file_count="multiple",
type="filepath",
file_types=sorted(SUPPORTED_EXTENSIONS),
)
intake_audio = gr.Audio(
label="Speak a question",
sources=["upload", "microphone"],
type="filepath",
)
with gr.Column(scale=2, elem_classes=["glass-panel"]):
intake_title = gr.Textbox(
value="New user-guide question",
label="Question title or collection name",
)
intake_topic_hint = gr.Dropdown(
list(VISUAL_TOPIC_OPTIONS),
value=VISUAL_TOPIC_OPTIONS[0],
label="Concept hint",
info="Keep Automatic unless the source image or OCR is ambiguous.",
)
intake_split_mode = gr.Radio(
["Automatically split numbered questions", "Keep as one question"],
value="Automatically split numbered questions",
label="Multiple-question handling",
)
intake_add_btn = gr.Button(
"Extract, visualize, and add to bank",
variant="primary",
elem_classes=["primary-btn"],
)
gr.Markdown(
"Audio uses a configured speech API when available; otherwise the first transcription downloads and runs a compact local Whisper model."
)
intake_status = gr.Markdown(
"Add a new source to extend the reusable question bank.",
elem_classes=["coach-panel"],
)
with gr.Accordion("Extracted text and intake report", open=False):
intake_extracted = gr.Markdown("No new source processed.")
gr.Markdown("## Imported-question concept studio")
intake_selected_question = gr.Markdown(
_bank_record_markdown(INITIAL_BANK_RECORD),
elem_classes=["question-panel"],
)
intake_visual = gr.HTML(
value=INITIAL_IMPORTED_PAYLOAD,
label="Editable imported-question concept",
html_template=QUESTION_VISUALIZER_HTML,
css_template=QUESTION_VISUALIZER_CSS,
js_on_load=QUESTION_VISUALIZER_JS,
apply_default_css=False,
container=False,
)
gr.Markdown("## Reusable question bank")
intake_bank_summary = gr.Markdown(bank_summary_markdown(INITIAL_BANK))
with gr.Row():
intake_bank_selector = gr.Dropdown(
choices=bank_choices(INITIAL_BANK),
value=INITIAL_BANK_RECORD.get("id") if INITIAL_BANK_RECORD else None,
label="Open a stored question",
scale=4,
)
intake_open_btn = gr.Button("Load selected question", scale=1)
intake_export_btn = gr.Button("Download question bank JSON", scale=1)
intake_bank_file = gr.File(label="Question bank backup (.json)")
with gr.Tab("π¬ Mechanics tutor chat", id="mechanics-tutor"):
gr.Markdown("""
## Clarify the active question or its solution
The tutor is grounded in the generated question, verified solution, expected answers, hints and theory. Ask in text, speak through the microphone, or upload an image of a diagram, equation or handwritten method.
""")
tutor_context = gr.Markdown(
tutor_context_markdown(INITIAL_QUESTION),
elem_classes=["glass-panel"],
elem_id="full-mechanics-tutor",
)
tutor_chat = gr.Chatbot(
value=tutor_welcome(INITIAL_QUESTION),
label="Mechanics Tutor",
height=520,
latex_delimiters=LATEX_DELIMITERS,
)
gr.Markdown("### Suggested questions")
tutor_prompt_buttons = []
with gr.Row():
for prompt in DEFAULT_TUTOR_QUESTIONS[:3]:
tutor_prompt_buttons.append(gr.Button(prompt, size="sm"))
with gr.Row():
for prompt in DEFAULT_TUTOR_QUESTIONS[3:]:
tutor_prompt_buttons.append(gr.Button(prompt, size="sm"))
tutor_text = gr.Textbox(
label="Ask a follow-up question",
placeholder="Example: Why is acceleration negative in this solution?",
lines=3,
)
with gr.Row():
tutor_engine = gr.Radio(
list(TUTOR_ENGINES),
value=QWEN_ENGINE,
label="Tutor engine",
)
tutor_open_source_model = gr.Dropdown(
choices=list(OPEN_SOURCE_TUTOR_MODELS),
value=DEFAULT_OPEN_SOURCE_MODEL,
label="Open-source tutor model",
allow_custom_value=True,
)
gr.Markdown(
"The Qwen route uses the Space secret `HF_TOKEN`. If it is unavailable, the verified local tutor answers automatically. OpenAI remains optional through `OPENAI_API_KEY`.",
elem_classes=["privacy-note"],
)
with gr.Row(equal_height=False):
tutor_audio = gr.Audio(
label="Ask by voice",
sources=["upload", "microphone"],
type="filepath",
)
tutor_image = gr.Image(
label="Upload an equation, diagram, or handwritten method",
type="pil",
image_mode="RGB",
sources=["upload", "webcam", "clipboard"],
height=260,
)
with gr.Row():
tutor_send_btn = gr.Button(
"Send to mechanics tutor",
variant="primary",
elem_classes=["submit-btn"],
)
tutor_clear_btn = gr.Button("Clear conversation")
tutor_input_status = gr.Markdown(
"Text works immediately. Voice is transcribed locally unless a configured speech service is available.",
elem_classes=["privacy-note"],
)
with gr.Tab("π Assignments"):
gr.Markdown(
"""
## Mechanics assignment studio
Generate an original assignment from the trained topics, set the number of questions manually, and collect typed or numbered handwritten submissions. The answer key stays hidden until evaluation.
"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["glass-panel"]):
assignment_student_name = gr.Textbox(
label="Assignment student name",
placeholder="Enter student name",
)
assignment_title = gr.Textbox(
label="Assignment title",
value="M1 Mechanics skills assignment",
)
assignment_topics = gr.Dropdown(
choices=list(EXAM_TOPIC_CHOICES),
value=list(EXAM_TOPIC_CHOICES),
multiselect=True,
label="Assignment topics",
)
assignment_count = gr.Slider(
1, 30, value=10, step=1, label="Assignment question count"
)
assignment_seed = gr.Textbox(
label="Assignment seed (optional)",
placeholder="Leave blank for a new assignment",
)
assignment_generate_btn = gr.Button(
"Generate assignment",
variant="primary",
elem_classes=["primary-btn"],
)
with gr.Column(scale=3, elem_classes=["glass-panel"]):
gr.Markdown(
"Assignments use the same nine validated question formats as protected examinations. Students should number every typed or handwritten response as `Q1`, `Q2`, and so on."
)
assignment_status = gr.Markdown(
"Configure and generate an assignment.",
elem_classes=["privacy-note"],
)
assignment_paper = gr.Markdown(
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["question-panel"],
)
gr.Markdown("## Assignment submission portal")
with gr.Row(equal_height=False):
with gr.Column(scale=3):
assignment_typed_answers = gr.Textbox(
label="Typed numbered assignment answers",
placeholder="Q1. ...\nQ2. ...\nQ3. ...",
lines=14,
max_lines=30,
)
with gr.Column(scale=2):
assignment_submission_files = gr.File(
label="Upload numbered handwritten assignment images or PDF",
file_count="multiple",
type="filepath",
file_types=["image", ".pdf"],
)
assignment_submit_btn = gr.Button(
"Submit and evaluate assignment",
variant="primary",
elem_classes=["submit-btn"],
)
assignment_result = gr.Markdown(elem_classes=["exam-result-panel"])
assignment_solution = gr.Markdown(
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["glass-panel"],
)
assignment_pdf = gr.File(
label="Assignment result PDF Β· questions, marks, and solutions"
)
with gr.Tab("π Extraordinary activities"):
gr.Markdown(
"""
## Extraordinary activity record
Record assessed work outside Midterm 1, Midterm 2, assignments, and the Final examination. Multiple activities can be combined, with optional evidence, and their total feeds the OBE calculation.
"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["obe-card"]):
extraordinary_student = gr.Textbox(
label="Activity student name",
placeholder="Enter student name",
)
extraordinary_title = gr.Textbox(
label="Extraordinary activity title",
placeholder="Example: Working roller-collision model",
)
extraordinary_category = gr.Dropdown(
choices=list(ACTIVITY_CATEGORIES),
value=ACTIVITY_CATEGORIES[0],
label="Activity category",
)
extraordinary_description = gr.Textbox(
label="Activity description",
placeholder="Describe the work, learning outcome, and assessment evidence.",
lines=5,
)
with gr.Column(scale=2, elem_classes=["obe-card"]):
with gr.Row():
extraordinary_score = gr.Number(
value=0,
minimum=0,
label="Activity marks obtained",
)
extraordinary_maximum = gr.Number(
value=10,
minimum=0.01,
label="Maximum activity marks",
)
extraordinary_evidence = gr.File(
label="Optional activity evidence",
file_count="multiple",
type="filepath",
file_types=["image", ".pdf", ".doc", ".docx"],
)
with gr.Row():
extraordinary_record_btn = gr.Button(
"Record extraordinary activity",
variant="primary",
elem_classes=["primary-btn"],
)
extraordinary_clear_btn = gr.Button("Clear activity records")
extraordinary_status = gr.Markdown(
"Add the first extraordinary activity.",
elem_classes=["privacy-note"],
)
extraordinary_summary = gr.Markdown(
render_activities([]),
elem_classes=["glass-panel"],
)
with gr.Tab("π OBE attainment"):
gr.Markdown(
"""
## Outcome-Based Education attainment
The maximum attainment is **3.000**. The default component weights are 10% Midterm 1, 10% Midterm 2, 10% Assignment, 50% Final examination, and 20% Extraordinary activities. You may change them, but the five percentages must total 100%.
"""
)
with gr.Row():
obe_student = gr.Textbox(
label="OBE student name",
placeholder="Student name printed in the OBE result and certificate",
scale=3,
)
obe_load_scores_btn = gr.Button(
"Load latest recorded scores",
scale=1,
elem_classes=["primary-btn"],
)
gr.Markdown("### Component marks")
obe_score_inputs = []
with gr.Row():
for component in COMPONENTS:
with gr.Column(min_width=210, elem_classes=["obe-card"]):
gr.Markdown(f"**{component}**")
obtained = gr.Number(
value=0,
minimum=0,
label=f"{component} marks obtained",
)
maximum = gr.Number(
value=0,
minimum=0,
label=f"{component} maximum marks",
)
obe_score_inputs.extend([obtained, maximum])
gr.Markdown("### Percentage weightage Β· editable")
obe_weight_inputs = []
with gr.Row():
for component in COMPONENTS:
obe_weight_inputs.append(
gr.Number(
value=DEFAULT_WEIGHT_PERCENTAGES[component],
minimum=0,
maximum=100,
label=f"{component} weight (%)",
)
)
with gr.Row():
obe_compute_btn = gr.Button(
"Compute attainment and spider chart",
variant="primary",
elem_classes=["primary-btn"],
)
obe_status = gr.Markdown(
"Weight total: 100%. Load recorded scores or enter marks manually.",
elem_classes=["privacy-note"],
)
with gr.Row(equal_height=False):
obe_result_md = gr.Markdown(
"Compute attainment to see the weighted result.",
elem_classes=["obe-card"],
)
obe_radar_plot = gr.Plot(
obe_spider_chart(),
label="OBE attainment spider chart",
)
gr.Markdown(
"The exact calculation is `3 Γ weight percentage Γ· 100 Γ (marks obtained Γ· maximum marks)` for each component, then all five contributions are added. A missing or zero maximum contributes zero until a valid score is entered."
)
with gr.Tab("π§ Mistake analysis"):
gr.Markdown(
"""
## Examination mistake and improvement studio
Select a completed examination or assignment. The app identifies every lost mark, compares the response with the answer key, reports topic and question-format performance, and builds a focused strengthsβweaknessesβopportunitiesβchallenges plan.
"""
)
with gr.Row():
mistake_refresh_btn = gr.Button("Refresh completed assessments")
mistake_assessment_selector = gr.Dropdown(
choices=[],
label="Completed assessment for mistake analysis",
scale=4,
)
mistake_analyse_btn = gr.Button(
"Analyse mistakes",
variant="primary",
elem_classes=["primary-btn"],
)
mistake_status = gr.Markdown(
"Complete an examination or assignment, then refresh this list.",
elem_classes=["privacy-note"],
)
mistake_report = gr.Markdown(
mistake_analysis(None),
elem_classes=["glass-panel"],
)
gr.Markdown("## Ask the mistake-analysis tutor")
mistake_chat = gr.Chatbot(
value=tutor_welcome(None),
label="Mistake Analysis Tutor",
height=420,
latex_delimiters=LATEX_DELIMITERS,
)
with gr.Row():
mistake_prompt_buttons = [
gr.Button("Explain my first error", size="sm"),
gr.Button("Why did I lose marks?", size="sm"),
gr.Button("Give me an improvement drill", size="sm"),
gr.Button("Challenge this analysis", size="sm"),
]
mistake_chat_text = gr.Textbox(
label="Question about a mistake or the analysis",
placeholder="Example: Why is my sign convention wrong in Question 4?",
lines=3,
)
with gr.Row():
mistake_tutor_engine = gr.Radio(
list(TUTOR_ENGINES),
value=QWEN_ENGINE,
label="Mistake tutor engine",
)
mistake_open_source_model = gr.Dropdown(
choices=list(OPEN_SOURCE_TUTOR_MODELS),
value=DEFAULT_OPEN_SOURCE_MODEL,
label="Mistake tutor open-source model",
allow_custom_value=True,
)
with gr.Row():
mistake_chat_send_btn = gr.Button(
"Ask about my mistakes",
variant="primary",
elem_classes=["submit-btn"],
)
mistake_chat_clear_btn = gr.Button("Clear mistake conversation")
mistake_chat_status = gr.Markdown(
"The tutor becomes grounded in the selected question-level corrections after analysis.",
elem_classes=["privacy-note"],
)
with gr.Tab("π
Certificates"):
gr.Markdown(
"""
## Achievement certificates
Certificates become available at **60% (1.800/3.000)**. The continuous award bands are: standard 60β<80%, silver distinction 80β<90%, gold excellence 90β<96.67%, and diamond achievement from 96.67% (2.900/3.000). The phrase **100 percent achievement** is reserved for an actual 3.000/3.000 result.
"""
)
certificate_generate_btn = gr.Button(
"Generate certificate from current OBE result",
variant="primary",
elem_classes=["primary-btn"],
)
certificate_status = gr.Markdown(
"Compute the student's OBE attainment first.",
elem_classes=["privacy-note"],
)
certificate_html = gr.HTML(
'<div class="certificate-preview"><h2>Certificate preview</h2><p>The current OBE result will determine the medal and ribbon.</p></div>'
)
certificate_pdf = gr.File(
label="Protected achievement certificate PDF"
)
with gr.Tab("π Theory vault"):
theory_md = gr.Markdown(
theory_for(INITIAL_QUESTION),
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["glass-panel"],
)
with gr.Tab("π Progress"):
mastery_md = gr.Markdown(mastery_markdown(INITIAL_PROFILE), elem_classes=["glass-panel"])
reset_btn = gr.Button("Reset session progress", size="sm")
with gr.Tab("π§° Worksheet forge"):
gr.Markdown("""
## Build an original classroom worksheet
Create a mixed or topic-focused set with a teacher solution section. Download the same worksheet as Markdown, an editable Word document, or a print-ready PDF.
""")
worksheet_count = gr.Slider(3, 15, value=8, step=1, label="Number of questions")
worksheet_btn = gr.Button("Forge worksheet", variant="primary", elem_classes=["primary-btn"])
gr.Markdown("### Download worksheet with teacher solutions")
with gr.Row():
worksheet_md_file = gr.File(label="Markdown (.md)")
worksheet_docx_file = gr.File(label="Word document (.docx)")
worksheet_pdf_file = gr.File(label="PDF document (.pdf)")
worksheet_preview = gr.Markdown(latex_delimiters=LATEX_DELIMITERS)
with gr.Group(visible=False, elem_id="exam-section") as exam_section:
gr.HTML(
"""
<section class="exam-lock-banner">
<h2>π‘οΈ Protected examination section</h2>
<p>Training tools, theory, worksheets, progress, and all Ask Teacher bots are locked while an examination is in progress.</p>
</section>
"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=2, elem_classes=["glass-panel"]):
exam_student_name = gr.Textbox(
label="Student name",
placeholder="Enter the student's full name",
)
exam_name = gr.Radio(
choices=list(EXAM_SPECS),
value="Midterm 1",
label="Examination",
)
exam_topics = gr.Dropdown(
choices=list(EXAM_TOPIC_CHOICES),
value=list(EXAM_TOPIC_CHOICES),
multiselect=True,
label="Topics completed in training",
info="The paper is balanced across the selected trained topics.",
)
exam_seed = gr.Textbox(
label="Paper seed (optional)",
placeholder="Leave blank for a new paper, or reuse a seed for moderation",
)
exam_midterm_1_count = gr.Slider(
5, 25, value=10, step=1, label="Midterm 1 question count"
)
exam_midterm_2_count = gr.Slider(
5, 25, value=10, step=1, label="Midterm 2 question count"
)
exam_final_count = gr.Slider(
10, MAX_EXAM_QUESTIONS, value=25, step=1, label="Final examination question count"
)
exam_total_session_minutes = gr.Slider(
20,
DEFAULT_TOTAL_SESSION_MINUTES,
value=DEFAULT_TOTAL_SESSION_MINUTES,
step=1,
label="Total protected-session duration (minutes)",
info="Default 130 minutes: 10 minutes reading/setup plus 120 minutes answering. Maximum answer time is 2 hours.",
)
exam_start_btn = gr.Button(
"Start protected examination",
variant="primary",
elem_classes=["primary-btn"],
)
with gr.Column(scale=3, elem_classes=["glass-panel"]):
gr.Markdown(
"""
### Paper structure
- Default: **Midterm 1 = 10**, **Midterm 2 = 10**, **Final = 25** questions; each count is adjustable
- Nine formats: multiple choice, fill in the blank, numerical problem, explanation, theory, mathematical calculation, match the following, diagram interpretation, and paragraph analysis
- Every question displays its marks
- Small questions default to **1 minute**; descriptive questions default to **4 minutes**
- The overall protected session defaults to **130 minutes**, including the first 10 minutes for reading and setup
Solutions are reconstructed only after submission. The downloaded report contains the paper, responses, score, answer key, and worked solutions in one locked PDF.
"""
)
gr.Markdown(
"**Academic-integrity note:** this interface blocks in-app training and tutor access. Keep the protected browser tab open so the deadline can auto-submit the live answers. Formal invigilation or a managed browser is still required to prevent use of outside websites or devices.",
elem_classes=["privacy-note"],
)
with gr.Accordion("Manual question timing Β· optional 1β7 minute overrides", open=False):
gr.Markdown(
"Enter question numbers separated by commas or spaces. A question may appear in only one list. Leave every list blank to use the automatic 1-minute small-question and 4-minute descriptive-question defaults."
)
exam_timing_inputs = []
with gr.Row():
for minute in range(1, 5):
exam_timing_inputs.append(
gr.Textbox(
label=f"Question numbers for {minute}-minute timing",
placeholder="Example: 1, 4, 7",
)
)
with gr.Row():
for minute in range(5, 8):
exam_timing_inputs.append(
gr.Textbox(
label=f"Question numbers for {minute}-minute timing",
placeholder="Example: 8, 12",
)
)
exam_runtime_total_minutes = gr.Number(value=DEFAULT_TOTAL_SESSION_MINUTES, visible=False)
exam_runtime_reading_minutes = gr.Number(value=DEFAULT_READING_MINUTES, visible=False)
exam_runtime_attempt_id = gr.Textbox(visible=False)
exam_main_timer_display = gr.HTML(
'<div class="exam-main-timer"><strong>Timer not started</strong><br>Start a protected examination to begin the reading and overall-session clocks.</div>',
elem_id="exam-main-timer-display",
container=False,
)
exam_paper_header = gr.Markdown(
"Choose the examination and trained topics, then start a protected attempt.",
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["question-panel"],
)
exam_question_groups = []
exam_question_markdowns = []
exam_answer_boxes = []
exam_question_timer_minutes = []
exam_question_timer_displays = []
exam_question_timer_buttons = []
for exam_index in range(MAX_EXAM_QUESTIONS):
with gr.Group(visible=False, elem_classes=["exam-question-card"]) as exam_question_group:
exam_question_md = gr.Markdown(latex_delimiters=LATEX_DELIMITERS)
exam_timer_minutes = gr.Number(value=1, visible=False)
exam_timer_display = gr.HTML(
'<div class="exam-question-timer">Question timer is available after the reading phase.</div>',
elem_id=f"exam-question-timer-{exam_index + 1}",
container=False,
)
exam_timer_button = gr.Button(
f"Start Q{exam_index + 1} timer",
elem_id=f"exam-question-timer-button-{exam_index + 1}",
interactive=False,
)
exam_answer = gr.Textbox(
label=f"Answer to Question {exam_index + 1}",
placeholder=(
"Type the option, value, calculation, explanation, or theory answer here. "
"Typed text is authoritative if OCR differs."
),
lines=4,
max_lines=10,
interactive=False,
)
exam_question_groups.append(exam_question_group)
exam_question_markdowns.append(exam_question_md)
exam_answer_boxes.append(exam_answer)
exam_question_timer_minutes.append(exam_timer_minutes)
exam_question_timer_displays.append(exam_timer_display)
exam_question_timer_buttons.append(exam_timer_button)
exam_unlock_trigger = gr.Button(
"Unlock after reading phase",
elem_id="exam-unlock-trigger",
elem_classes=["exam-hidden-trigger"],
)
exam_auto_submit_trigger = gr.Button(
"Automatic timed submission",
elem_id="exam-auto-submit-trigger",
elem_classes=["exam-hidden-trigger"],
)
gr.Markdown("## Optional numbered handwritten answer sheet")
with gr.Row(equal_height=False):
with gr.Column(scale=2):
exam_answer_sheets = gr.File(
label="Upload handwritten answer-sheet images or PDF",
file_count="multiple",
type="filepath",
file_types=["image", ".pdf"],
)
exam_read_sheet_btn = gr.Button(
f"Read and map Q1βQ{MAX_EXAM_QUESTIONS}", variant="secondary"
)
with gr.Column(scale=3):
exam_ocr_preview = gr.Markdown(
"No handwritten answer sheet has been read.",
elem_classes=["privacy-note"],
)
exam_declaration = gr.Checkbox(
label="I confirm that this is my own completed work and I am ready to submit permanently.",
value=False,
)
with gr.Row():
exam_submit_btn = gr.Button(
"Submit examination and calculate marks",
variant="primary",
elem_classes=["submit-btn"],
)
exam_reset_btn = gr.Button("Prepare another examination", visible=False)
exam_result_md = gr.Markdown(
elem_classes=["exam-result-panel"],
latex_delimiters=LATEX_DELIMITERS,
)
exam_solution_md = gr.Markdown(
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["glass-panel"],
)
exam_pdf_file = gr.File(
label="Locked PDF Β· paper, responses, marks, and solutions",
)
# Three native Gradio copies remain available on every tab. Keeping every
# launcher and panel inside Gradio preserves open, send, Enter-submit,
# close, clear, history, active-question grounding, and Qwen callbacks.
def build_fixed_tutor_copy(position_name: str):
position = position_name.strip().lower()
suffix = "" if position == "bottom" else f"-{position}"
launcher = gr.Button(
"π¬ Ask Teacher",
variant="primary",
elem_id=f"floating-tutor-launcher{suffix}",
)
with gr.Group(
visible=False,
elem_id=f"floating-tutor-panel{suffix}",
) as panel:
with gr.Row(elem_classes=["floating-tutor-dialog-header"]):
gr.Markdown(
f"### Ask Teacher Β· {position.title()}\n\nMISSION-LINKED QUESTION HELP",
elem_classes=["floating-tutor-dialog-title"],
scale=8,
)
close_btn = gr.Button(
"β",
elem_id=f"floating-tutor-close{suffix}",
elem_classes=["floating-tutor-close"],
size="sm",
scale=1,
)
open_full_btn = gr.Button(
"Open full multimodal tutor β",
elem_id=f"floating-open-full-tutor{suffix}",
elem_classes=["floating-open-full-tutor"],
size="sm",
)
context = gr.Markdown(
tutor_context_markdown(INITIAL_QUESTION),
elem_classes=["floating-tutor-context"],
)
chat = gr.Chatbot(
value=tutor_welcome(INITIAL_QUESTION),
label="Floating Mechanics Tutor",
height=245,
latex_delimiters=LATEX_DELIMITERS,
elem_classes=["floating-tutor-chat"],
)
with gr.Row():
hint_btn = gr.Button("First hint", size="sm")
equation_btn = gr.Button("Equation choice", size="sm")
with gr.Group(elem_classes=["floating-tutor-composer"]):
gr.Markdown(
"**Ask about the active problem** Β· Type below and press Enter or Ask Teacher.",
elem_classes=["floating-tutor-composer-note"],
)
text = gr.Textbox(
label="Ask about the active mechanics problem",
placeholder="Example: Why is momentum conserved in this collision?",
lines=2,
max_lines=4,
)
engine = gr.Dropdown(
choices=list(TUTOR_ENGINES),
value=QWEN_ENGINE,
label="Tutor engine",
)
model = gr.Dropdown(
choices=list(OPEN_SOURCE_TUTOR_MODELS),
value=DEFAULT_OPEN_SOURCE_MODEL,
label="Open-source tutor model",
allow_custom_value=True,
)
with gr.Row():
send_btn = gr.Button(
"Enter Β· Ask Teacher",
variant="primary",
elem_classes=["submit-btn"],
)
clear_btn = gr.Button("Clear", size="sm")
status = gr.Markdown(
"Linked to the problem named above Β· use the full tutor for voice or images.",
elem_classes=["floating-tutor-status"],
)
return {
"position": position,
"launcher": launcher,
"panel": panel,
"close": close_btn,
"open_full": open_full_btn,
"context": context,
"chat": chat,
"hint": hint_btn,
"equation": equation_btn,
"text": text,
"engine": engine,
"model": model,
"send": send_btn,
"clear": clear_btn,
"status": status,
}
floating_top_bot = build_fixed_tutor_copy("top")
floating_middle_bot = build_fixed_tutor_copy("middle")
floating_bottom_bot = build_fixed_tutor_copy("bottom")
floating_bots = [floating_top_bot, floating_middle_bot, floating_bottom_bot]
# Preserve the original bottom-bot variable names used by mission and
# Creative Lab update callbacks.
floating_tutor_launcher = floating_bottom_bot["launcher"]
floating_tutor_panel = floating_bottom_bot["panel"]
floating_tutor_close_btn = floating_bottom_bot["close"]
floating_open_full_btn = floating_bottom_bot["open_full"]
floating_tutor_context = floating_bottom_bot["context"]
floating_tutor_chat = floating_bottom_bot["chat"]
floating_hint_btn = floating_bottom_bot["hint"]
floating_equation_btn = floating_bottom_bot["equation"]
floating_tutor_text = floating_bottom_bot["text"]
floating_tutor_engine = floating_bottom_bot["engine"]
floating_open_source_model = floating_bottom_bot["model"]
floating_tutor_send_btn = floating_bottom_bot["send"]
floating_tutor_clear_btn = floating_bottom_bot["clear"]
floating_tutor_status = floating_bottom_bot["status"]
gr.HTML("""
<div class="footer-note">
M1 Mechanics Quest creates original practice material. It is not affiliated with, endorsed by, or an official product of Pearson Edexcel.
</div>
""")
exam_start_outputs = [
exam_attempt_state,
exam_paper_header,
exam_mode_status,
exam_mode_toggle,
exam_name,
exam_topics,
exam_seed,
exam_student_name,
exam_midterm_1_count,
exam_midterm_2_count,
exam_final_count,
exam_total_session_minutes,
*exam_timing_inputs,
exam_start_btn,
exam_declaration,
exam_answer_sheets,
exam_ocr_state,
exam_ocr_preview,
exam_read_sheet_btn,
exam_submit_btn,
exam_reset_btn,
exam_result_md,
exam_solution_md,
exam_pdf_file,
exam_runtime_total_minutes,
exam_runtime_reading_minutes,
exam_runtime_attempt_id,
exam_main_timer_display,
]
for group, question_markdown, answer_box, timer_minutes, timer_display, timer_button in zip(
exam_question_groups,
exam_question_markdowns,
exam_answer_boxes,
exam_question_timer_minutes,
exam_question_timer_displays,
exam_question_timer_buttons,
):
exam_start_outputs.extend(
[group, question_markdown, answer_box, timer_minutes, timer_display, timer_button]
)
exam_mode_toggle.change(
switch_exam_mode,
inputs=[exam_mode_toggle],
outputs=[
training_controls,
app_tabs,
exam_section,
floating_top_bot["panel"],
floating_middle_bot["panel"],
floating_bottom_bot["panel"],
exam_mode_status,
],
js=EXAM_MODE_TOGGLE_JS,
show_progress="hidden",
)
exam_start_event = exam_start_btn.click(
start_exam_interface,
inputs=[
exam_student_name,
exam_name,
exam_topics,
exam_seed,
exam_midterm_1_count,
exam_midterm_2_count,
exam_final_count,
exam_total_session_minutes,
*exam_timing_inputs,
],
outputs=exam_start_outputs,
js=EXAM_START_CAPTURE_JS,
)
exam_start_event.then(
fn=None,
inputs=[
exam_runtime_total_minutes,
exam_runtime_reading_minutes,
exam_runtime_attempt_id,
],
js=EXAM_MAIN_TIMER_JS,
show_progress="hidden",
)
exam_unlock_trigger.click(
unlock_exam_inputs,
inputs=[exam_attempt_state],
outputs=[*exam_answer_boxes, *exam_question_timer_buttons],
show_progress="hidden",
)
for question_number, (timer_button, timer_minutes) in enumerate(
zip(exam_question_timer_buttons, exam_question_timer_minutes), 1
):
timer_button.click(
fn=None,
inputs=[timer_minutes],
js=question_timer_js(question_number),
show_progress="hidden",
)
exam_read_sheet_btn.click(
read_exam_answer_sheet,
inputs=[exam_answer_sheets, exam_attempt_state],
outputs=[exam_ocr_state, exam_ocr_preview],
)
exam_submit_btn.click(
submit_exam_interface,
inputs=[
exam_attempt_state,
exam_answer_sheets,
exam_ocr_state,
exam_declaration,
assessment_history_state,
*exam_answer_boxes,
],
outputs=[
exam_result_md,
exam_solution_md,
exam_pdf_file,
exam_mode_status,
exam_attempt_state,
exam_mode_toggle,
exam_submit_btn,
exam_declaration,
exam_answer_sheets,
exam_read_sheet_btn,
exam_reset_btn,
exam_ocr_state,
exam_ocr_preview,
exam_main_timer_display,
assessment_history_state,
*exam_answer_boxes,
*exam_question_timer_buttons,
],
js=EXAM_MANUAL_SUBMIT_JS,
)
exam_auto_submit_trigger.click(
auto_submit_exam_interface,
inputs=[
exam_attempt_state,
exam_answer_sheets,
exam_ocr_state,
assessment_history_state,
*exam_answer_boxes,
],
outputs=[
exam_result_md,
exam_solution_md,
exam_pdf_file,
exam_mode_status,
exam_attempt_state,
exam_mode_toggle,
exam_submit_btn,
exam_declaration,
exam_answer_sheets,
exam_read_sheet_btn,
exam_reset_btn,
exam_ocr_state,
exam_ocr_preview,
exam_main_timer_display,
assessment_history_state,
*exam_answer_boxes,
*exam_question_timer_buttons,
],
js=EXAM_AUTO_SUBMIT_JS,
)
exam_reset_btn.click(
reset_exam_interface,
outputs=exam_start_outputs,
js=EXAM_RESET_TIMER_JS,
)
assignment_generate_btn.click(
generate_assignment_interface,
inputs=[
assignment_student_name,
assignment_title,
assignment_topics,
assignment_count,
assignment_seed,
],
outputs=[
assignment_state,
assignment_paper,
assignment_status,
assignment_result,
assignment_solution,
assignment_pdf,
assignment_typed_answers,
assignment_submission_files,
assignment_submit_btn,
],
)
assignment_submit_btn.click(
submit_assignment_interface,
inputs=[
assignment_state,
assignment_typed_answers,
assignment_submission_files,
assessment_history_state,
],
outputs=[
assignment_status,
assignment_result,
assignment_solution,
assignment_pdf,
assignment_typed_answers,
assignment_submission_files,
assessment_history_state,
],
)
extraordinary_record_btn.click(
record_extraordinary_activity_interface,
inputs=[
extraordinary_activities_state,
extraordinary_student,
extraordinary_title,
extraordinary_category,
extraordinary_description,
extraordinary_score,
extraordinary_maximum,
extraordinary_evidence,
],
outputs=[
extraordinary_activities_state,
extraordinary_summary,
extraordinary_status,
extraordinary_title,
extraordinary_description,
extraordinary_evidence,
],
)
extraordinary_clear_btn.click(
clear_extraordinary_activities_interface,
outputs=[
extraordinary_activities_state,
extraordinary_summary,
extraordinary_status,
],
)
obe_load_scores_btn.click(
load_obe_scores_interface,
inputs=[assessment_history_state, extraordinary_activities_state],
outputs=[obe_student, *obe_score_inputs, obe_status],
)
obe_compute_btn.click(
compute_obe_interface,
inputs=[obe_student, *obe_score_inputs, *obe_weight_inputs],
outputs=[obe_result_state, obe_result_md, obe_radar_plot, obe_status],
)
mistake_refresh_btn.click(
refresh_mistake_assessments_interface,
inputs=[assessment_history_state],
outputs=[mistake_assessment_selector, mistake_status],
)
mistake_analyse_btn.click(
analyse_mistakes_interface,
inputs=[assessment_history_state, mistake_assessment_selector],
outputs=[mistake_record_state, mistake_report, mistake_chat, mistake_status],
)
mistake_chat_send_btn.click(
chat_about_mistakes_interface,
inputs=[
mistake_record_state,
mistake_chat_text,
mistake_tutor_engine,
mistake_open_source_model,
mistake_chat,
],
outputs=[mistake_chat, mistake_chat_text, mistake_chat_status],
)
mistake_chat_text.submit(
chat_about_mistakes_interface,
inputs=[
mistake_record_state,
mistake_chat_text,
mistake_tutor_engine,
mistake_open_source_model,
mistake_chat,
],
outputs=[mistake_chat, mistake_chat_text, mistake_chat_status],
)
mistake_chat_clear_btn.click(
clear_mistake_chat_interface,
inputs=[mistake_record_state],
outputs=[mistake_chat, mistake_chat_status],
)
for button, prompt in zip(
mistake_prompt_buttons,
(
"Explain the first place I went wrong and how to correct it.",
"Why did I lose marks across these questions?",
"Give me a short improvement drill for my weakest topic.",
"Explain the evidence behind this mistake analysis so I can challenge it if needed.",
),
):
button.click(lambda selected=prompt: selected, outputs=[mistake_chat_text])
certificate_generate_btn.click(
generate_certificate_interface,
inputs=[obe_result_state],
outputs=[certificate_html, certificate_pdf, certificate_status],
)
generate_mission_event = generate_btn.click(
create_mission,
inputs=[topic, difficulty, seed, profile_state],
outputs=[question_state, question_md, mission_visual, line_plot, model_plot, theory_md, hint_md, solution_md, hint_index_state, seed, profile_panel, tutor_context, tutor_chat, floating_tutor_context, floating_tutor_chat, floating_question_state],
)
generate_mission_event.then(
sync_floating_tutor_copies,
inputs=[floating_question_state],
outputs=[
floating_top_bot["context"],
floating_top_bot["chat"],
floating_middle_bot["context"],
floating_middle_bot["chat"],
],
show_progress="hidden",
)
hint_btn.click(
next_hint,
inputs=[question_state, hint_index_state, profile_state],
outputs=[hint_md, hint_index_state, profile_state, profile_panel],
)
solution_btn.click(reveal_solution, inputs=[question_state], outputs=[solution_md])
assess_btn.click(
assess_work,
inputs=[question_state, work_image, final_answer, use_ai_vision, profile_state],
outputs=[feedback_md, feedback_plot, ocr_md, profile_state, profile_panel, mastery_md],
)
reset_btn.click(reset_progress, outputs=[profile_state, profile_panel, mastery_md])
worksheet_btn.click(
build_worksheet,
inputs=[topic, difficulty, worksheet_count, seed],
outputs=[worksheet_md_file, worksheet_docx_file, worksheet_pdf_file, worksheet_preview],
)
intake_add_btn.click(
add_questions_to_bank,
inputs=[
intake_text,
intake_files,
intake_audio,
intake_title,
intake_topic_hint,
intake_split_mode,
],
outputs=[
intake_status,
intake_extracted,
intake_bank_summary,
intake_bank_selector,
intake_visual,
intake_selected_question,
],
)
intake_open_btn.click(
open_bank_question,
inputs=[intake_bank_selector],
outputs=[intake_selected_question, intake_visual],
)
intake_bank_selector.change(
open_bank_question,
inputs=[intake_bank_selector],
outputs=[intake_selected_question, intake_visual],
)
intake_export_btn.click(export_bank_file, outputs=[intake_bank_file])
tutor_send_btn.click(
chat_with_tutor,
inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_engine, tutor_chat, tutor_open_source_model],
outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status],
)
tutor_text.submit(
chat_with_tutor,
inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_engine, tutor_chat, tutor_open_source_model],
outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status],
)
tutor_clear_btn.click(
clear_tutor_chat,
inputs=[question_state],
outputs=[tutor_chat, tutor_input_status],
)
for button, prompt in zip(tutor_prompt_buttons, DEFAULT_TUTOR_QUESTIONS):
button.click(lambda selected=prompt: selected, outputs=[tutor_text])
floating_panels = [bot["panel"] for bot in floating_bots]
for bot in floating_bots:
bot["launcher"].click(
lambda selected=bot["position"]: show_floating_tutor_slot(selected),
outputs=floating_panels,
show_progress="hidden",
)
bot["close"].click(
hide_floating_tutor,
outputs=[bot["panel"]],
show_progress="hidden",
)
bot["open_full"].click(
open_full_tutor_tab,
outputs=[app_tabs, bot["panel"]],
show_progress="hidden",
)
bot["send"].click(
chat_in_floating_tutor,
inputs=[
floating_question_state,
bot["text"],
bot["engine"],
bot["model"],
bot["chat"],
],
outputs=[bot["chat"], bot["text"], bot["status"]],
)
bot["text"].submit(
chat_in_floating_tutor,
inputs=[
floating_question_state,
bot["text"],
bot["engine"],
bot["model"],
bot["chat"],
],
outputs=[bot["chat"], bot["text"], bot["status"]],
)
bot["clear"].click(
clear_tutor_chat,
inputs=[floating_question_state],
outputs=[bot["chat"], bot["status"]],
)
bot["hint"].click(
lambda: DEFAULT_TUTOR_QUESTIONS[3],
outputs=[bot["text"]],
)
bot["equation"].click(
lambda: DEFAULT_TUTOR_QUESTIONS[1],
outputs=[bot["text"]],
)
custom_inputs = [
custom_scenario,
custom_context,
custom_difficulty,
custom_impact_model,
custom_restitution,
custom_mass_p,
custom_mass_q,
custom_distance,
custom_friction_p,
custom_friction_q,
custom_velocity_p,
custom_velocity_q,
custom_acceleration_p,
custom_acceleration_q,
train_mass,
train_initial_velocity,
train_acceleration,
train_acceleration_time,
train_cruise_time,
train_braking,
train_resistance,
rocket_mass,
rocket_height,
rocket_velocity,
rocket_gravity,
trolley_mass,
trolley_force,
trolley_angle,
trolley_friction,
trolley_velocity,
trolley_time,
]
custom_outputs = [
custom_question_state,
custom_status,
custom_game,
custom_line_plot,
custom_3d_plot,
custom_question_md,
custom_solution_md,
custom_theory_md,
custom_feedback_md,
custom_feedback_plot,
custom_ocr_md,
floating_tutor_context,
floating_tutor_chat,
floating_question_state,
]
for custom_control in custom_inputs:
creative_update_event = custom_control.change(
update_creative_lab,
inputs=custom_inputs,
outputs=custom_outputs,
)
creative_update_event.then(
sync_floating_tutor_copies,
inputs=[floating_question_state],
outputs=[
floating_top_bot["context"],
floating_top_bot["chat"],
floating_middle_bot["context"],
floating_middle_bot["chat"],
],
show_progress="hidden",
)
custom_scenario.change(
show_creative_controls,
inputs=[custom_scenario],
outputs=[collision_controls, train_controls, rocket_controls, trolley_controls],
)
custom_solution_btn.click(
reveal_solution, inputs=[custom_question_state], outputs=[custom_solution_md]
)
custom_assess_btn.click(
assess_work,
inputs=[
custom_question_state,
custom_work_image,
custom_final_answer,
custom_use_ai_vision,
profile_state,
],
outputs=[
custom_feedback_md,
custom_feedback_plot,
custom_ocr_md,
profile_state,
profile_panel,
mastery_md,
],
)
custom_export_btn.click(
export_custom_question,
inputs=[custom_question_state],
outputs=[custom_md_file, custom_docx_file, custom_pdf_file],
)
# Re-pin the three real native Gradio launchers and panels after mount and
# during viewport changes. No chatbot component is cloned or reparented.
demo.load(fn=None, js=FLOATING_TUTOR_VIEWPORT_JS, show_progress="hidden")
if __name__ == "__main__":
demo.queue(default_concurrency_limit=16).launch(theme=theme, css=CSS)
|