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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
"""Memory Studio: a local-first, editable mnemonic workbench.



The default route needs no model: it uses deterministic Major-System tools,

curated starting words, and a complete linked story. An optional small

Hugging Face text model can draft candidates, stories, and word-card text on

this computer. A separate optional local image model can draw a cue. AI output

is always an editable draft, never an authority.



Run:

    python -m venv .venv

    # Windows PowerShell: .venv\\Scripts\\Activate.ps1

    # macOS/Linux: source .venv/bin/activate

    pip install -r requirements.txt

    python memory_studio.py



Optional model selection (PowerShell):

    $env:MEMORY_MODEL = "HuggingFaceTB/SmolLM2-1.7B-Instruct"

    $env:MEMORY_IMAGE_MODEL = "your-org/your-diffusers-model"

    python memory_studio.py

"""

from __future__ import annotations

import getpass
import hashlib
import os
import re
import secrets
import shutil
import tempfile
import random
import threading
import time
from collections import Counter
from datetime import date
from pathlib import Path
from typing import Any

# Disable Gradio analytics before importing it. Keep all inference and content
# on this machine; the app never creates a sharing link.
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"

import gradio as gr

from local_image import (
    DEFAULT_IMAGE_SIZE,
    DEFAULT_IMAGE_STEPS,
    IMAGE_MODEL_CARD_URL,
    IMAGE_MODEL_DOWNLOAD_NOTE,
    IMAGE_MODEL_ID,
    IMAGE_MODEL_LICENSE_NOTE,
    IMAGE_SIZE_OPTIONS,
    IMAGE_STYLES,
    LocalImageError,
    MAX_IMAGE_STEPS,
    MIN_IMAGE_STEPS,
    dependencies_available as image_dependencies_available,
    generate_cue_image,
    image_model_status_markdown,
    warm_up as warm_up_image_model,
)
import local_llm
from local_llm import use_zero_gpu, warm_up as warm_up_text_model
from local_llm import (
    MODEL_ID,
    MODEL_LICENSE_NOTE,
    LocalModelError,
    ask_list_cues,
    ask_number_candidates,
    STORY_EXAMPLE_LINES,
    ask_story_lines,
    ask_word_fields,
    dependencies_available,
    model_status_markdown,
    parse_indexed_cues,
    parse_number_rows,
    parse_word_sections,
)
from mind_map import key_word_tips, outline_markdown, parse_outline, render_svg
from pronunciation import warm_up as warm_up_dictionary, words_for_code
import mind_map
import names_dates
import palace_routes
import peg_trainer
import study_library
from mind_map import MAX_MAIN_BRANCHES, MAX_SUB_BRANCHES
from mnemonic_core import (
    MAJOR_HELP,
    MAX_LIST_ITEMS,
    MAX_WORD_CONTEXT_LENGTH,
    MAX_WORD_TERM_LENGTH,
    WORD_FIELD_NAMES,
    ChainItem,
    NumberRow,
    assemble_word_card,
    build_ordered_chain,
    ANCHOR_MODES,
    ANCHOR_PALACE,
    CHUNK_MODES,
    CHUNK_PAIRS,
    CHUNK_SPACES,
    CHUNK_TRIPLES,
    auto_story_lines,
    chain_scene_parts,
    chain_scene_prompt,
    link_scene_prompts,
    build_anchor_markdown,
    build_review_ics,
    build_review_markdown,
    build_recall_markdown,
    check_word_for_chunk,
    curated_candidate,
    curated_major_rows,
    number_blockers,
    number_input_note,
    parse_item_list,
    parse_palace_stops,
    split_number,
    table_to_rows,
    validate_list_rows,
    validate_number_rows,
    word_card_practice,
    word_default_drafts,
)

NUMBER_HEADERS = ["Chunk", "Word", "Image cue", "Story line", "Check", "Source"]
LIST_HEADERS = ["#", "Item", "Image cue", "Story line"]
STORY_LINE_COLUMN = 3  # same index in both tables
WORD_HEADERS = ["Field", "Draft (edit freely)"]

# A Hugging Face Space is a public demo: requests run on the Space, not on the
# visitor's device. Detect it so the UI never claims on-device privacy it cannot
# keep. Set MEMORY_PUBLIC_DEMO=1 to force the same wording elsewhere.
PUBLIC_DEMO = (
    os.getenv("MEMORY_PUBLIC_DEMO", "").strip().lower() in {"1", "true", "yes"}
    or bool(os.getenv("SPACE_ID", "").strip())
)

LISTEN_HOST = os.getenv("MEMORY_HOST", "").strip() or (
    "0.0.0.0" if PUBLIC_DEMO else "127.0.0.1"
)
LOCAL_ONLY = LISTEN_HOST in {"127.0.0.1", "localhost", "::1"}
BIND_NOTE = (
    "The Gradio server binds to `127.0.0.1`; `share=False`; no public link is "
    "created."
    if LOCAL_ONLY
    else f"The server listens on `{LISTEN_HOST}` because `MEMORY_HOST` is set, so "
    "other devices on your network can open it. Unset `MEMORY_HOST` to keep it "
    "on this computer only. `share=False`; no public link is created."
)

PRIVACY_SECTION = (
    """- This is the **online version**. Prompts, numbers, lists, and image cues

  are sent to Hugging Face and processed on the Space's servers, not on your

  device.

- The Space has no user accounts and this app does not write study material to

  disk. Hugging Face may keep standard server and runtime logs.

- Do not enter secrets, private notes, or anything you would not post publicly.

- Model weights are public downloads, and generation uses the Space's shared

  free GPU. There is no paid inference API or API key.

- For truly on-device use, run the same app locally: the repository is the same

  code, and local mode binds to `127.0.0.1` with `share=False`.

- Gradio analytics and Hugging Face Hub telemetry are disabled in this app."""
    if PUBLIC_DEMO
    else f"""- {BIND_NOTE}

- Gradio analytics and Hugging Face Hub telemetry are disabled in this app.

- The app does not persist or intentionally log submitted study material. Model

  loading prints only the model ID and device.

- Image cues and generated pictures stay on this computer; they are not

  uploaded. Gradio may keep temporary display files while the app runs, so

  download a picture if you want to keep it.

- Inference is on-device after the model download. There is no paid endpoint,

  API key, metered service, or mandatory account."""
)

NUMBER_ACCURACY = (
    "The Major System is phonetic. Words are checked against the CMU "
    "Pronouncing Dictionary (American English); words it does not know fall "
    "back to an approximate spelling check. Say each word aloud in your own "
    "accent and replace any that do not fit. Only the bold image words in the "
    "story carry digits; the other words in each story line are glue, not "
    "digits. Replace any word, picture, or line with a personal one."
)
LIST_ACCURACY = (
    "Image cues are memory aids, not definitions. Keep the exact item order and "
    "verify technical meanings in a source you trust. Replace any cue or story "
    "link with one that is more vivid for you."
)

# ---------------------------------------------------------------------------
# Look and feel
# ---------------------------------------------------------------------------

# System fonts only: the app makes no third-party font requests.
APP_THEME = gr.themes.Soft(
    primary_hue=gr.themes.colors.indigo,
    secondary_hue=gr.themes.colors.fuchsia,
    neutral_hue=gr.themes.colors.slate,
    radius_size=gr.themes.sizes.radius_lg,
    font=[
        "system-ui",
        "-apple-system",
        "Segoe UI",
        "Roboto",
        "Helvetica Neue",
        "Arial",
        "sans-serif",
    ],
    font_mono=["ui-monospace", "SFMono-Regular", "Consolas", "monospace"],
)

APP_CSS = """

.gradio-container { max-width: 1180px !important; margin: 0 auto !important; }

/* On Hugging Face Spaces the app runs inside an iframe that the host page

   marks scrolling="no" and sizes to the content height at load. A picture

   drawn later can push the page past that fixed height, leaving the picture

   cut off with no way to reach the rest. When the app detects it is embedded

   it caps itself to the frame height and scrolls inside the frame, so every

   part of a draft stays reachable. */

.ms-embedded .gradio-container {

  max-height: 100vh;

  max-height: 100dvh;

  overflow-y: auto !important;

  /* Keep the scroll behaviour but hide the scrollbar track and thumb, so the

     embedded app does not show its own scrollbar next to the host page's. */

  scrollbar-width: none;

  -ms-overflow-style: none;

}

.ms-embedded .gradio-container::-webkit-scrollbar {

  display: none;

}

#ms-hero {

  position: relative;

  overflow: hidden;

  padding: 34px 36px;

  border-radius: 22px;

  color: #ffffff;

  background:

    radial-gradient(900px 380px at 88% -30%, rgba(255,255,255,.30), transparent 62%),

    linear-gradient(135deg, #312e81 0%, #6d28d9 56%, #a21caf 100%);

  box-shadow: 0 20px 44px -26px rgba(49, 46, 129, .85);

}

/* Gradio paints every descendant of a prose block with the body text colour

   (.gradio-container .prose *). That rule outranks a bare class, so the

   banner text that sits on the purple gradient keeps its id-scoped colour. */

#ms-hero .ms-kicker {

  text-transform: uppercase;

  letter-spacing: .16em;

  font-size: .72rem;

  font-weight: 700;

  color: #ffffff;

  opacity: .88;

}

#ms-hero h1 {

  margin: .45rem 0 .6rem;

  color: #ffffff;

  font-size: clamp(1.7rem, 4vw, 2.7rem);

  line-height: 1.08;

}

#ms-hero p {

  margin: 0;

  max-width: 46rem;

  color: rgba(255,255,255,.94);

  font-size: 1rem;

  line-height: 1.55;

}

.ms-chips { display: flex; flex-wrap: wrap; gap: .45rem; margin-top: 1.1rem; }

#ms-hero .ms-chip {

  border: 1px solid rgba(255,255,255,.35);

  background: rgba(255,255,255,.14);

  border-radius: 999px;

  padding: .28rem .72rem;

  color: #ffffff;

  font-size: .78rem;

  font-weight: 600;

}

.ms-card {

  border: 1px solid var(--border-color-primary, #e2e8f0);

  background: var(--block-background-fill, #ffffff);

  border-radius: 16px;

  padding: 18px 18px 10px;

  height: 100%;

}

.ms-card h3 { margin: .1rem 0 .35rem; font-size: 1.02rem; }

.ms-card p { margin: .2rem 0 .6rem; opacity: .85; font-size: .9rem; line-height: 1.45; }

.ms-step { display: flex; gap: .75rem; align-items: flex-start; margin: .55rem 0; }

#ms-how .ms-step-num {

  flex: 0 0 1.75rem;

  height: 1.75rem;

  border-radius: 50%;

  background: #4f46e5;

  color: #ffffff;

  font-weight: 700;

  font-size: .85rem;

  display: flex;

  align-items: center;

  justify-content: center;

}

.ms-muted { opacity: .78; font-size: .88rem; }

.ms-note.block,

.ms-note:not(.prose) {

  border-left: 3px solid #8b5cf6 !important;

  padding: .3rem 0 .3rem .8rem;

}

/* Gradio applies elem_classes to both the block and the inner prose node. */

.ms-note.prose { border-left: 0 !important; padding: 0 !important; }

.ms-mindmap { border-radius: 18px; overflow: hidden; }

.ms-mindmap svg { display: block; }

/* Keep a drawn picture fully visible: Gradio's preview sizes the image to the

   frame, and a frame sized with width:auto can leave the picture at zero width

   until it finishes decoding. Let the picture use its own natural size, scaled

   down to fit the block, so it is never collapsed or cropped. */

#ms-image .image-frame img {

  width: auto;

  height: auto;

  max-width: 100%;

  max-height: min(70vh, 100%);

  object-fit: contain;

}

.ms-answer { border: 1px dashed var(--border-color-primary, #cbd5e1); border-radius: 12px; padding: 10px 14px; }

@media (max-width: 640px) {

  .html-container:has(#ms-hero) { padding-left: 0 !important; padding-right: 0 !important; }

  #ms-hero { padding: 18px 16px; border-radius: 16px; }

  #ms-hero .ms-kicker {

    font-size: .58rem;

    letter-spacing: .08em;

    line-height: 1.35;

  }

  #ms-hero h1 {

    font-size: 1.5rem;

    line-height: 1.12;

    margin: .3rem 0 .45rem;

  }

  #ms-hero p { font-size: .9rem; line-height: 1.45; }

  .ms-chips { margin-top: .8rem; gap: .35rem; }

  .ms-chip { font-size: .7rem; padding: .22rem .6rem; }

  .ms-card { padding: 14px 14px 8px; }



  /* Touch targets: Gradio's small buttons are 26 px tall by default. */

  button.sm {

    min-height: 40px;

    padding: .4rem .7rem;

    font-size: .82rem;

    line-height: 1.2;

  }

  [role="tab"] { min-height: 38px; }

  .label-wrap { min-height: 40px !important; padding: 0 .25rem; }

  button:has(svg) { min-width: 36px; min-height: 36px; }

  .reset-button { min-width: 36px; min-height: 36px; }

  .add-row-button { min-height: 40px !important; }

  .settings { min-height: 32px; }



  /* Primary field/action rows read better as one column on phones. */

  .ms-stack { flex-direction: column !important; gap: .55rem !important; }

  .ms-stack > * { width: 100% !important; min-width: 0 !important; }



  /* Dataframes keep readable columns and scroll inside their card instead of

     stretching the page. contain:inline-size stops the table's intrinsic

     width from propagating up through the flex ancestors. */

  .table-wrap { contain: inline-size; width: 100% !important; }

  .virtual-table-viewport { max-width: 100% !important; overflow-x: auto !important; }

  .header-table th { font-size: .75rem; padding-left: .25rem; padding-right: .25rem; }

  .header-table .cell-wrap { padding: 4px 2px !important; }

  .header-table .header-content { gap: 0 !important; }

  .header-table .header {

    white-space: nowrap;

    word-break: normal;

    overflow-wrap: normal;

  }

  .header-cell button[aria-label="Open cell menu"] { display: none !important; }



  /* 16 px inputs stop iOS Safari from zooming when a field is focused. */

  input,

  textarea,

  select { font-size: 16px !important; }

}

"""

# Mark the page when it runs inside a host frame (Hugging Face Spaces embeds the
# app this way). The flag turns on the scroll rules above so late content, such
# as a picture drawn after the frame was sized, always stays reachable.
APP_HEAD = """

<script>

  if (window.self !== window.top) {

    document.documentElement.classList.add("ms-embedded");

  }

</script>

"""

# ---------------------------------------------------------------------------
# One-click examples and study-sheet export
# ---------------------------------------------------------------------------

NUMBER_EXAMPLE = "314159"
LIST_EXAMPLE = "milk, eggs, coffee, bread, apples"
WORD_EXAMPLE_TERM = "Pomodoro"
WORD_EXAMPLE_CONTEXT = (
    "A focus method: work for 25 minutes, then take a 5-minute break."
)


def _example_number(

    saved: Any = None, chunking: str = CHUNK_PAIRS

) -> tuple[str, bool, str, list[list[str]], str]:
    status, rows, story = draft_number_candidates(
        NUMBER_EXAMPLE, False, saved, chunking
    )
    return NUMBER_EXAMPLE, False, status, rows, story


def _example_list() -> tuple[str, bool, str, list[list[str]], str]:
    status, rows, story = draft_list_candidates(LIST_EXAMPLE, False)
    return LIST_EXAMPLE, False, status, rows, story


def _example_word() -> tuple[str, str, bool, str, list[list[str]], str]:
    rows = [
        ["Meaning anchor", WORD_EXAMPLE_CONTEXT],
        [
            "Sound / keyword association",
            "Sound cue (not a meaning): “pomo” + “doro” → a pom-pom bouncing "
            "along a dough row.",
        ],
        [
            "Visual image",
            "A giant tomato-shaped kitchen timer wearing boxing gloves, pounding "
            "a row of dough on a counter.",
        ],
        [
            "Mini-story",
            "The timer rings, karate-chops the dough row, flips an hourglass, then "
            "takes a five-minute tea break.",
        ],
        [
            "Memory Palace placement",
            "Kitchen counter beside the stove: hear the bell, smell warm dough, and "
            "watch the sand run out.",
        ],
        [
            "Active-recall question",
            "Without looking: what does Pomodoro mean, and which two sounds and "
            "image hold it?",
        ],
    ]
    status, filled_rows, card = assemble_word_outputs(
        WORD_EXAMPLE_TERM, WORD_EXAMPLE_CONTEXT, rows
    )
    return (
        WORD_EXAMPLE_TERM,
        WORD_EXAMPLE_CONTEXT,
        False,
        status,
        filled_rows,
        card,
    )


SHEET_ROOT = Path(tempfile.gettempdir()) / "memory-studio-sheets"
SHEET_MAX_AGE_SECONDS = 3600


def _hidden_file() -> Any:
    """Hide a study-sheet download that no longer matches the table."""
    return gr.update(value=None, visible=False)


def _prune_old_sheets() -> None:
    """Delete study-sheet folders older than an hour; ignore any failure."""
    cutoff = time.time() - SHEET_MAX_AGE_SECONDS
    try:
        for folder in SHEET_ROOT.iterdir():
            if folder.is_dir() and folder.stat().st_mtime < cutoff:
                shutil.rmtree(folder, ignore_errors=True)
    except OSError:
        pass


def _study_sheet(

    markdown_text: str, stem: str, extra: tuple[tuple[str, str], ...] = ()

) -> Any:
    """Write a downloadable Markdown sheet only when the user asks for one."""
    text = (markdown_text or "").strip()
    if not text:
        raise gr.Error("Build the story (or assemble the card) first, then download it.")
    safe = re.sub(r"[^a-z0-9]+", "-", (stem or "study-sheet").casefold())
    safe = safe.strip("-")[:40] or "study-sheet"
    SHEET_ROOT.mkdir(parents=True, exist_ok=True)
    _prune_old_sheets()
    folder = Path(tempfile.mkdtemp(prefix="sheet-", dir=SHEET_ROOT))
    path = folder / f"{safe}.md"
    path.write_text(text + "\n", encoding="utf-8")
    calendar = folder / f"{safe}-reviews.ics"
    calendar.write_text(
        build_review_ics(date.today(), safe.replace("-", " ")),
        encoding="utf-8",
        newline="",
    )
    paths = [str(path), str(calendar)]
    for suffix, content in extra:
        extra_path = folder / f"{safe}{suffix}"
        extra_path.write_text(content, encoding="utf-8")
        paths.append(str(extra_path))
    return gr.update(value=paths, visible=True)


def _number_sheet(text: str) -> Any:
    return _study_sheet(text, "number-story")


def _list_sheet(text: str) -> Any:
    return _study_sheet(text, "ordered-list-story")


def _word_sheet(text: str) -> Any:
    return _study_sheet(text, "word-card")


# ---------------------------------------------------------------------------
# Practice mode (no model, no scoring server-side; state stays in the session)
# ---------------------------------------------------------------------------

PRACTICE_NUMBER = "Numbers and chunks"
PRACTICE_LIST = "Ordered list"
PRACTICE_KINDS = (PRACTICE_NUMBER, PRACTICE_LIST)


def _chain_practice_items(

    entries: list[tuple[str, str, str]],

) -> list[dict[str, str]]:
    """Cards that walk the chain forward: recall each image from the previous.



    ``entries`` are ordered (label, image cue, digit code) tuples; the code is

    empty for list items. This mirrors how the story is recalled: start at the

    first image, follow each link, then decode the digits.

    """
    items: list[dict[str, str]] = []
    for index, (label, cue, code) in enumerate(entries):
        if index == 0:
            prompt = "What is the **first** image in the chain?"
        else:
            prompt = f"What image comes after **{entries[index - 1][0]}**?"
        if code:
            prompt += " Then decode its digits."
        answer = f"**{label}**"
        if cue:
            answer += f": {cue}"
        if code:
            answer += f" → `{code}`"
        items.append({"prompt": prompt, "answer": answer})
    return items


def _practice_items(

    kind: str, text: str, saved: Any = None

) -> tuple[list[dict[str, str]], str]:
    """Cards from pasted text: saved words, else curated. Returns (cards, full)."""
    if kind == PRACTICE_NUMBER:
        chunks = split_number(text)
        personal = _saved_words_for(chunks, saved)
        entries = []
        for chunk in chunks:
            word, cue = (
                personal.get(chunk)
                or curated_candidate(chunk)
                or ("(no word)", "")
            )
            entries.append((word, cue, chunk))
        return _chain_practice_items(entries), "".join(chunks)
    entries = [(item, "", "") for item in parse_item_list(text)]
    return _chain_practice_items(entries), ""


def _practice_outputs(

    items: list[dict[str, str]], full: str = "", note: str = ""

) -> tuple[Any, ...]:
    state: dict[str, Any] = {
        "items": items,
        "index": 0,
        "known": 0,
        "missed": [],
        "revealed": False,
        "full": full,
    }
    prompt = _practice_prompt(items[0])
    if note:
        prompt = f"{note}\n\n{prompt}"
    return (
        state,
        _practice_progress(state),
        prompt,
        _hidden_answer(),
        gr.update(visible=True),
        gr.update(visible=False),
        gr.update(value="", visible=False),
    )


def _practice_error(message: str) -> tuple[Any, ...]:
    return (
        {},
        "",
        message,
        _hidden_answer(),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(value="", visible=False),
    )


def _number_table_cards(

    number_text: str, table: Any, chunking: str = CHUNK_PAIRS

) -> tuple[list[dict[str, str]], str, list[str]]:
    """Cards from the learner's own checked Numbers table.



    Returns (cards, digits, problems); raises ValueError for a bad number.

    """
    chunks = split_number(number_text, chunking)
    reviewed, errors = validate_number_rows(chunks, table)
    problems = errors or number_blockers(reviewed)
    if problems:
        return [], "", problems
    entries = [(row.word, row.link or row.image, row.chunk) for row in reviewed]
    return _chain_practice_items(entries), "".join(chunks), []


def _list_table_cards(

    table: Any,

) -> tuple[list[dict[str, str]], list[str], list[str]]:
    """Cards from the learner's own list table. Returns (cards, items, problems)."""
    reviewed, errors = validate_list_rows(table)
    if errors:
        return [], [], errors
    entries = [(row.item, row.link or row.cue, "") for row in reviewed]
    return _chain_practice_items(entries), [row.item for row in reviewed], []


def practice_number_table(

    number_text: str, table: Any, chunking: str = CHUNK_PAIRS

) -> tuple[Any, ...]:
    """Practice the learner's own checked words, in chain order."""
    try:
        cards, digits, problems = _number_table_cards(number_text, table, chunking)
    except ValueError as exc:
        return (gr.update(), f"**Input issue:** {exc}", gr.update(), gr.update(),
                *_practice_error(""))
    if problems:
        message = _issue_markdown(
            "Fix the table before practicing",
            problems + ["Practice uses your own words, so every row must pass."],
        )
        return (gr.update(), message, gr.update(), gr.update(), *_practice_error(""))
    return (
        gr.Tabs(selected="practice"),
        gr.update(),
        PRACTICE_NUMBER,
        digits,
        *_practice_outputs(
            cards, digits, "_Practicing the words from your Numbers table._"
        ),
    )


def practice_list_table(list_text: str, table: Any) -> tuple[Any, ...]:
    """Practice the learner's own list table and cues, in order."""
    cards, items, problems = _list_table_cards(table)
    if problems:
        message = _issue_markdown("Fix the table before practicing", problems)
        return (gr.update(), message, gr.update(), gr.update(), *_practice_error(""))
    return (
        gr.Tabs(selected="practice"),
        gr.update(),
        PRACTICE_LIST,
        "\n".join(items),
        *_practice_outputs(
            cards, "", "_Practicing the items and cues from your Ordered list table._"
        ),
    )


def _practice_progress(state: dict[str, Any]) -> str:
    items = state.get("items") or []
    total = len(items)
    position = min(state.get("index", 0) + 1, total)
    known = state.get("known", 0)
    missed = len(state.get("missed") or [])
    return (
        f"**Card {position} of {total}** · {known} recalled · "
        f"{missed} to review"
    )


def _practice_prompt(item: dict[str, str]) -> str:
    return f"### {item['prompt']}\n\nSay the answer out loud, then reveal it."


def _hidden_answer() -> Any:
    return gr.update(value="", visible=False)


def start_practice(kind: str, text: str, saved: Any = None) -> tuple[Any, ...]:
    try:
        if kind not in PRACTICE_KINDS:
            raise ValueError("Choose numbers or an ordered list.")
        items, full = _practice_items(kind, str(text or "").strip(), saved)
    except ValueError as exc:
        return _practice_error(f"**Input issue:** {exc}")
    note = (
        "_Pasted number: practicing your saved words where you have them, "
        "otherwise the curated starter words. To practice a table you just "
        "edited, use **Practice these cards** in the Numbers tab._"
        if kind == PRACTICE_NUMBER
        else ""
    )
    return _practice_outputs(items, full, note)


def reveal_practice(state: dict[str, Any]) -> tuple[Any, ...]:
    items = (state or {}).get("items") or []
    index = (state or {}).get("index", 0)
    if not items or index >= len(items):
        # Nothing to reveal, or the session already finished.
        return (
            state,
            gr.update(),
            gr.update(visible=False),
            gr.update(visible=False),
        )
    updated = {**state, "revealed": True}
    return (
        updated,
        gr.update(value=items[index]["answer"], visible=True),
        gr.update(visible=False),
        gr.update(visible=True),
    )


def _practice_summary_text(state: dict[str, Any]) -> str:
    """The end-of-session summary, or "" while the session is still running."""
    state = state or {}
    items = state.get("items") or []
    total = len(items)
    if not items or state.get("index", 0) < total:
        return ""
    known = state.get("known", 0)
    missed = state.get("missed") or []
    lines = [
        "### Session complete",
        "",
        f"You recalled **{known}/{total}** card(s) on this pass.",
    ]
    if state.get("full"):
        lines.extend(["", f"Full number, decoded in order: `{state['full']}`"])
    if missed:
        lines.extend(["", "#### Review these", ""])
        for item_index in missed:
            item = items[item_index]
            lines.append(f"- {item['prompt']} → {item['answer']}")
    else:
        lines.extend(["", "Nothing to review. Try a longer set or a new number."])
    lines.extend(
        [
            "",
            "_Cards stayed in the original order, just like the story. "
            "Repeat the set until every card feels automatic._",
        ]
    )
    return "\n".join(lines)


def grade_practice(state: dict[str, Any], knew: bool) -> tuple[Any, ...]:
    items = (state or {}).get("items") or []
    if not items or not state.get("revealed"):
        return (
            state,
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
            gr.update(),
        )

    index = state["index"]
    total = len(items)
    known = state["known"] + (1 if knew else 0)
    missed = list(state.get("missed") or [])
    if not knew:
        missed.append(index)
    next_index = index + 1

    if next_index >= total:
        finished = {
            **state,
            "index": next_index,
            "known": known,
            "missed": missed,
            "revealed": False,
        }
        return (
            finished,
            f"**{total} of {total} reviewed** · {known} recalled · "
            f"{len(missed)} to review",
            gr.update(value="", visible=False),
            _hidden_answer(),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(value=_practice_summary_text(finished), visible=True),
        )

    updated = {
        **state,
        "index": next_index,
        "known": known,
        "missed": missed,
        "revealed": False,
    }
    return (
        updated,
        _practice_progress(updated),
        _practice_prompt(items[next_index]),
        _hidden_answer(),
        gr.update(visible=True),
        gr.update(visible=False),
        gr.update(value="", visible=False),
    )


def append_image_history(

    image: Any, history: list[Any] | None

) -> tuple[list[Any], Any]:
    """Keep the last eight drafts, newest first (as the gallery's label says)."""
    items = list(history or [])
    if image is None:
        return items, gr.update()
    items = [image, *items][:8]
    return items, items


# ---------------------------------------------------------------------------
# My library: saved items with review dates, kept only in the learner's browser
# ---------------------------------------------------------------------------

LIBRARY_EMPTY = (
    "Your library is empty. Build a number story, a list story, or a word card, "
    "give it a name, and click **Save to my library**. This tab then tells you "
    "which reviews are due."
)


def _library_view(library: Any) -> tuple[Any, ...]:
    """Refresh every library display: summary, table, picker, Start banner."""
    today = date.today()
    items = study_library.clean_library(library)
    due = study_library.due_count(items, today)
    pairs = study_library.choices(items, today)
    if not items:
        summary = LIBRARY_EMPTY
        banner = (
            "**My library:** save a story or card and this spot shows which "
            "reviews are due."
        )
    else:
        next_id, next_item = study_library.sorted_items(items, today)[0]
        summary = (
            f"### {due} due today · {len(items)} saved\n\n"
            + (
                "Pick an item and click **Review this item**. Due items are listed "
                "first."
                if due
                else f"Nothing is due. Next up: **{_md_cell(next_item['name'])}**, "
                f"{study_library.due_text(next_item, today)}."
            )
        )
        banner = (
            f"### 📅 {due} review(s) due today\n\nOpen **My library** to keep "
            "them on schedule."
            if due
            else f"**My library:** nothing due today. Next review: "
            f"**{_md_cell(next_item['name'])}**, "
            f"{study_library.due_text(next_item, today)}."
        )
    return (
        summary,
        study_library.table_rows(items, today),
        gr.Dropdown(choices=pairs, value=pairs[0][1] if pairs else None),
        banner,
        gr.update(visible=due > 0),
    )


def _library_unchanged() -> tuple[Any, ...]:
    return tuple(gr.update() for _ in range(5))


def _save_to_library(

    library: Any,

    kind: str,

    name: str,

    key: str,

    cards: list[dict[str, str]],

    full: str,

    default_name: str,

) -> tuple[Any, ...]:
    """Add or update a library item. A blank ``name`` keeps an existing item's

    name, and gives a new item ``default_name``."""
    today = date.today()
    try:
        items, item_id, updated = study_library.add_item(
            library, kind, str(name or ""), key, cards, full, today, default_name
        )
    except ValueError as exc:
        return (library, f"**Library full:** {exc}", *_library_unchanged())
    item = items[item_id]
    title = _md_cell(item["name"])
    if updated:
        message = (
            f"### Updated in My library\n\n**{title}** now uses the cards in this "
            "table. Its review schedule did not change: next is the "
            f"{study_library.step_label(item['step'])}, "
            f"{study_library.due_text(item, today)}."
        )
    else:
        message = (
            f"### Saved to My library\n\n**{title}** ({len(cards)} card(s)) is "
            "ready for its first review in about 10 minutes: open **My library** "
            "and click **Review this item**. After that, the library brings it "
            "back after 1 day, 1 week, 1 month, and 4 months."
        )
    message += (
        "\n\n_The library is kept only in this browser; clearing site data "
        "removes it._"
    )
    return (items, message, *_library_view(items))


def save_number_to_library(

    number_text: str,

    table: Any,

    name: str,

    library: Any,

    chunking: str = CHUNK_PAIRS,

) -> tuple[Any, ...]:
    """Save the checked Numbers table as a library item."""
    try:
        cards, digits, problems = _number_table_cards(number_text, table, chunking)
    except ValueError as exc:
        return (library, f"**Input issue:** {exc}", *_library_unchanged())
    if problems:
        return (
            library,
            _issue_markdown("Fix the table before saving", problems),
            *_library_unchanged(),
        )
    return _save_to_library(
        library,
        study_library.KIND_NUMBER,
        name,
        study_library.content_key(study_library.KIND_NUMBER, digits),
        cards,
        digits,
        f"Number · {len(digits)} digits",
    )


def save_list_to_library(

    list_text: str, table: Any, name: str, library: Any

) -> tuple[Any, ...]:
    """Save the checked Ordered list table as a library item."""
    cards, items, problems = _list_table_cards(table)
    if problems:
        return (
            library,
            _issue_markdown("Fix the table before saving", problems),
            *_library_unchanged(),
        )
    return _save_to_library(
        library,
        study_library.KIND_LIST,
        name,
        study_library.content_key(
            study_library.KIND_LIST, "\n".join(item.casefold() for item in items)
        ),
        cards,
        "",
        f"List · {len(items)} items",
    )


def save_word_to_library(

    term: str, context: str, table: Any, name: str, library: Any

) -> tuple[Any, ...]:
    """Save the filled-in word card as a library item."""
    try:
        term_text, context_text = _validate_word_inputs(term, context)
        cards = word_card_practice(term_text, context_text, table)
    except ValueError as exc:
        return (library, f"**Input issue:** {exc}", *_library_unchanged())
    return _save_to_library(
        library,
        study_library.KIND_WORD,
        name,
        study_library.content_key(study_library.KIND_WORD, term_text.casefold()),
        cards,
        "",
        term_text,
    )


def review_library_item(item_id: Any, library: Any) -> tuple[Any, ...]:
    """Open the chosen library item in the Practice tab."""
    items = study_library.clean_library(library)
    item = items.get(str(item_id or ""))
    if item is None:
        return (
            gr.update(),
            "Choose an item from your library first.",
            *(gr.update() for _ in range(7)),
        )
    today = date.today()
    due = study_library.is_due(item, today)
    note = (
        f"_Reviewing **{_md_cell(item['name'])}** from My library: "
        f"{study_library.step_label(item['step'])}"
        + (
            ", due today. Your result moves it along the schedule._"
            if due
            else f". It is not due until {study_library.due_text(item, today)}, "
            "so this practice will not change its schedule._"
        )
    )
    outputs = list(_practice_outputs(item["cards"], item["full"], note))
    outputs[0] = {**outputs[0], "library_id": str(item_id), "library_due": due}
    return (gr.Tabs(selected="practice"), "", *outputs)


def remove_library_item(item_id: Any, library: Any) -> tuple[Any, ...]:
    items = study_library.clean_library(library)
    item = items.pop(str(item_id or ""), None)
    if item is None:
        return (library, "Choose an item to remove.", *_library_unchanged())
    return (
        items,
        f"Removed **{_md_cell(item['name'])}** from your library.",
        *_library_view(items),
    )


def _library_review_note(

    state: dict[str, Any], library: Any

) -> tuple[dict[str, Any], Any, str, bool]:
    """When a library practice session ends, log it and set the next review.



    Returns (state, library, note for the summary or "", library changed).

    """
    state = state or {}
    cards = state.get("items") or []
    item_id = state.get("library_id")
    finished = cards and state.get("index", 0) >= len(cards)
    if not item_id or not finished or state.get("library_recorded"):
        return state, library, "", False
    state = {**state, "library_recorded": True}
    today = date.today()
    items = study_library.clean_library(library)
    item = items.get(item_id)
    if item is None:
        return state, library, "", False
    missed = bool(state.get("missed"))
    title = _md_cell(item["name"])
    if not state.get("library_due"):
        note = (
            f"**My library:** **{title}** was not due, so its schedule did not "
            f"change. Next review: {study_library.due_text(item, today)}."
        )
        return state, library, note, False
    item = items[item_id] = study_library.record_review(item, not missed, today)
    if missed:
        note = (
            f"**My library:** some cards were missed, so repair those pictures "
            "(edit the table, then **Save to my library** again to update the "
            f"cards). **{title}** comes back tomorrow, and the review rhythm "
            "restarts from the 1-day review."
        )
    else:
        note = (
            f"**My library:** review logged. **{title}** is next due for its "
            f"{study_library.step_label(item['step'])}, "
            f"{study_library.due_text(item, today)}."
        )
    return state, items, note, True


def grade_and_record(

    state: dict[str, Any], library: Any, knew: bool

) -> tuple[Any, ...]:
    """Grade one card and, if that ends a library review, log it, in one step.



    Outputs: the seven practice outputs, then the library and its five views.

    """
    outputs = list(grade_practice(state, knew))
    summary = _practice_summary_text(outputs[0])
    new_state, library, note, changed = _library_review_note(outputs[0], library)
    outputs[0] = new_state
    if note:
        outputs[6] = gr.update(value=f"{summary}\n\n{note}", visible=True)
    views = _library_view(library) if changed else _library_unchanged()
    return (*outputs, library, *views)


# ---------------------------------------------------------------------------
# 00-99 trainer: drill the learner's own number words, both ways
# ---------------------------------------------------------------------------

TRAINER_IDLE = (
    "**Choose the numbers to drill, then click Start drill.** Answers are typed "
    "and checked against your saved words (or the starter words where you have "
    "none). Press Enter to answer; an empty answer counts as a miss."
)


def _trainer_words(codes: list[str], saved: Any) -> dict[str, tuple[str, str, bool]]:
    """code -> (word, cue, is your saved word), saved words first."""
    personal = _saved_words_for(codes, saved)
    words: dict[str, tuple[str, str, bool]] = {}
    for code in codes:
        if code in personal:
            words[code] = (*personal[code], True)
        else:
            curated = curated_candidate(code)
            if curated:
                words[code] = (*curated, False)
    return words


def _trainer_prompt(card: dict[str, Any]) -> str:
    if card["direction"] == peg_trainer.TO_NUMBER:
        return (
            f"### Which number is **{_md_cell(card['word'])}**?\n\n"
            "Type the digits (keep a leading zero) and press Enter."
        )
    return (
        f"### What is your word for **{card['code']}**?\n\n"
        "Type the word and press Enter."
    )


def _trainer_progress(state: dict[str, Any]) -> str:
    cards = state.get("cards") or []
    results = state.get("results") or []
    right = sum(result["correct"] for result in results)
    position = min(len(results) + 1, len(cards))
    return (
        f"**Card {position} of {len(cards)}** · {right} right · "
        f"{len(results) - right} missed"
    )


def trainer_hardest(stats: Any, saved: Any) -> list[list[str]]:
    codes = list(peg_trainer.clean_stats(stats))
    words = {code: entry[0] for code, entry in _trainer_words(codes, saved).items()}
    return peg_trainer.hardest_rows(stats, words)


def _trainer_session(cards: list[dict[str, Any]], note: str) -> tuple[Any, ...]:
    """Outputs that open a drill: state, progress, prompt, feedback, answer box,

    answer row, summary, retry button."""
    state = {"cards": cards, "results": [], "shown": time.time(), "seconds": 0.0}
    return (
        state,
        _trainer_progress(state),
        f"{note}\n\n{_trainer_prompt(cards[0])}" if note else _trainer_prompt(cards[0]),
        "",
        gr.update(value=""),
        gr.update(visible=True),
        gr.update(value="", visible=False),
        gr.update(visible=False),
    )


def _trainer_error(message: str) -> tuple[Any, ...]:
    return (
        {},
        "",
        message,
        "",
        gr.update(value=""),
        gr.update(visible=False),
        gr.update(value="", visible=False),
        gr.update(visible=False),
    )


def start_trainer(

    range_text: str,

    direction: str,

    count: str,

    hardest_first: bool,

    saved: Any,

    stats: Any,

) -> tuple[Any, ...]:
    """Start a drill over the chosen numbers."""
    try:
        codes = peg_trainer.parse_codes(range_text)
    except ValueError as exc:
        return _trainer_error(f"**Input issue:** {exc}")
    if direction not in peg_trainer.DIRECTIONS:
        direction = peg_trainer.TO_WORD
    words = _trainer_words(codes, saved)
    limit = int(count) if str(count).isdigit() else None
    chosen = peg_trainer.select_codes(
        [code for code in codes if code in words], limit, stats, bool(hardest_first)
    )
    cards = []
    for code in chosen:
        word, cue, own = words[code]
        card_direction = (
            random.choice((peg_trainer.TO_WORD, peg_trainer.TO_NUMBER))
            if direction == peg_trainer.MIXED
            else direction
        )
        cards.append(
            {"code": code, "word": word, "cue": cue, "own": own, "direction": card_direction}
        )
    own_count = sum(card["own"] for card in cards)
    note = f"_{len(cards)} card(s), shuffled"
    if hardest_first and peg_trainer.clean_stats(stats):
        note += ", weakest numbers first"
    note += (
        f". {own_count} use your saved words"
        + (", the rest the starter words" if own_count < len(cards) else "")
        + "._"
    )
    if own_count < len(cards):
        note += (
            "\n\n_Tip: a peg list sticks best with words you chose. Save your own "
            "words in the Numbers tab and the trainer uses them._"
        )
    return _trainer_session(cards, note)


def retry_trainer_misses(state: dict[str, Any]) -> tuple[Any, ...]:
    """Drill the cards missed in the last session again, reshuffled."""
    cards = (state or {}).get("cards") or []
    missed_codes = [r["code"] for r in (state or {}).get("results") or [] if not r["correct"]]
    retry = [dict(card) for card in cards if card["code"] in missed_codes]
    if not retry:
        return _trainer_error("Nothing missed in the last drill. Start a new one.")
    random.shuffle(retry)
    return _trainer_session(retry, f"_Retrying the {len(retry)} card(s) you missed._")


def check_trainer_answer(

    state: dict[str, Any], answer: str, stats: Any, saved: Any

) -> tuple[Any, ...]:
    """Mark one typed answer, record it, and show the next card."""
    state = state or {}
    cards = state.get("cards") or []
    results = list(state.get("results") or [])
    if not cards or len(results) >= len(cards):
        return (
            state,
            stats,
            *(gr.update() for _ in range(7)),
            gr.update(),
        )
    card = cards[len(results)]
    correct, note = peg_trainer.check_answer(
        card["direction"], card["code"], card["word"], answer
    )
    elapsed = min(time.time() - state.get("shown", time.time()), peg_trainer.MAX_SECONDS_PER_CARD)
    stats = peg_trainer.record_result(stats, card["code"], correct)
    results.append({"code": card["code"], "correct": correct})
    seconds = state.get("seconds", 0.0) + elapsed
    state = {**state, "results": results, "shown": time.time(), "seconds": seconds}

    pair = f"**{card['code']} = {_md_cell(card['word'])}**"
    if correct:
        feedback = f"✓ {pair} · {elapsed:.1f} s"
    else:
        typed = _md_cell(str(answer or "").strip()[:60])
        opening = f"✗ You typed _{typed}_." if typed and note != "skipped" else "✗ Skipped."
        feedback = f"{opening} {pair}"
        if card["cue"]:
            feedback += f": {_md_cell(card['cue'])}"
        feedback += ". See it once more before the next card."
        if note and note != "skipped":
            feedback += f"\n\n{note}"

    if len(results) < len(cards):
        return (
            state,
            stats,
            _trainer_progress(state),
            _trainer_prompt(cards[len(results)]),
            feedback,
            gr.update(value=""),
            gr.update(visible=True),
            gr.update(value="", visible=False),
            gr.update(visible=False),
            trainer_hardest(stats, saved),
        )

    right = sum(result["correct"] for result in results)
    missed = [cards[i] for i, result in enumerate(results) if not result["correct"]]
    lines = [
        "### Drill complete",
        "",
        f"You got **{right}/{len(cards)}** right, averaging "
        f"**{seconds / len(cards):.1f} s** per card.",
    ]
    if missed:
        lines.extend(
            [
                "",
                "#### Missed",
                "",
                "| Number | Word | Picture |",
                "|---:|---|---|",
                *(
                    f"| `{c['code']}` | **{_md_cell(c['word'])}** | {_md_cell(c['cue'])} |"
                    for c in missed
                ),
                "",
                "Picture each one vividly, then click **Retry the missed ones**.",
            ]
        )
    lines.extend(
        [
            "",
            "_A peg is automatic when it comes back right in about 3 seconds or "
            "less. Drill a small range until it is, then widen it._",
        ]
    )
    return (
        state,
        stats,
        f"**{len(cards)} of {len(cards)} answered** · {right} right · "
        f"{len(cards) - right} missed",
        "",
        feedback,
        gr.update(value=""),
        gr.update(visible=False),
        gr.update(value="\n".join(lines), visible=True),
        gr.update(visible=bool(missed)),
        trainer_hardest(stats, saved),
    )


def reset_trainer_stats() -> tuple[Any, list[list[str]], str]:
    return {}, [], "Trainer results cleared from this browser."


def start_with_trainer(saved: Any, stats: Any) -> tuple[Any, ...]:
    """Start here: a 10-card drill over 00-19, number to word."""
    return (
        gr.Tabs(selected="trainer"),
        "00-19",
        peg_trainer.TO_WORD,
        "10",
        False,
        *start_trainer("00-19", peg_trainer.TO_WORD, "10", False, saved, stats),
    )


# ---------------------------------------------------------------------------
# Names & faces, and Dates (no model; deterministic drafts you edit)
# ---------------------------------------------------------------------------

PEOPLE_EXAMPLE = (
    "Margaret Chen | big round glasses | finance team\n"
    "Benjamin Okafor | shaved head, wide smile | Sam's party\n"
    "Olivia Ruiz | freckles | climbing gym"
)
EVENTS_EXAMPLE = (
    "Battle of Hastings | 1066\n"
    "Moon landing | 20 July 1969\n"
    "Mum's birthday | 14 March"
)


def _practice_from_cards(

    cards: list[dict[str, str]], note: str

) -> tuple[Any, ...]:
    """Open cards in the Practice tab: (tabs, status, kind, text, *practice)."""
    return (
        gr.Tabs(selected="practice"),
        gr.update(),
        gr.update(),
        gr.update(),
        *_practice_outputs(cards, "", note),
    )


def _practice_blocked(message: str) -> tuple[Any, ...]:
    return (gr.update(), message, gr.update(), gr.update(), *_practice_error(""))


def draft_people(text: str) -> tuple[str, list[list[str]], str]:
    try:
        people = names_dates.parse_people(text)
        rows, notes = names_dates.draft_people_rows(people)
    except ValueError as exc:
        return f"**Input issue:** {exc}", [], ""
    for row in rows:
        if not row[1]:
            row[1] = names_dates.FEATURE_HINT
    parts = [
        "### Draft ready",
        "",
        f"{len(rows)} person(s). For each one, pick **one** face feature you will "
        "notice next time, check the **Sound-alike** (say it aloud: does it "
        "sound like the name to you?), and make the **Link scene** your own. "
        "Then click **Check and build the cards**.",
        "",
        "_Sound-alikes come from the pronunciation dictionary (American "
        "English). Pieces are joined with + and name parts with /._",
    ]
    if notes:
        parts.extend(["", "#### Other sound-alikes and gaps", ""])
        parts.extend(f"- {note}" for note in notes)
    return "\n".join(parts), rows, ""


def _people_checked(

    text: str, table: Any

) -> tuple[list[list[str]], list[str], str]:
    """(rows, notes, error markdown) for the Names table."""
    try:
        people = names_dates.parse_people(text)
    except ValueError as exc:
        return [], [], f"**Input issue:** {exc}"
    rows, errors, notes = names_dates.validate_people_rows(
        [name for name, _f, _c in people], table
    )
    if errors:
        return [], notes, _issue_markdown("Fix these first", errors)
    return rows, notes, ""


def build_people(text: str, table: Any) -> tuple[str, Any, str]:
    rows, notes, error = _people_checked(text, table)
    if error:
        return error, _current_rows(table), ""
    status = ["### Cards ready", "", f"{len(rows)} person(s), in the order you entered."]
    if notes:
        status.extend(["", *[f"- {note}" for note in notes]])
    card = (
        f"{names_dates.people_markdown(rows)}\n\n"
        f"{build_review_markdown(date.today())}"
    )
    return "\n".join(status), rows, card


def practice_people(text: str, table: Any) -> tuple[Any, ...]:
    rows, _notes, error = _people_checked(text, table)
    if error:
        return _practice_blocked(error)
    return _practice_from_cards(
        names_dates.people_practice(rows),
        "_Practicing your Names & faces cards: read the clue, say the name._",
    )


def save_people_to_library(

    text: str, table: Any, name: str, library: Any

) -> tuple[Any, ...]:
    rows, _notes, error = _people_checked(text, table)
    if error:
        return (library, error, *_library_unchanged())
    return _save_to_library(
        library,
        study_library.KIND_NAMES,
        name,
        study_library.content_key(
            study_library.KIND_NAMES, "\n".join(row[0].casefold() for row in rows)
        ),
        names_dates.people_practice(rows),
        "",
        f"Names · {len(rows)} people",
    )


def _date_word_lookup(saved: Any) -> Any:
    def word_for(chunk: str) -> tuple[str, str] | None:
        return _saved_words_for([chunk], saved).get(chunk) or curated_candidate(chunk)

    return word_for


def draft_events(text: str, saved: Any = None) -> tuple[str, list[list[str]], str]:
    try:
        events = names_dates.parse_events(text)
        rows, notes = names_dates.draft_event_rows(events, _date_word_lookup(saved))
    except ValueError as exc:
        return f"**Input issue:** {exc}", [], ""
    parts = [
        "### Draft ready",
        "",
        f"{len(rows)} event(s). Each date's digits are split into chunks in the "
        "order you typed them (month names become two digits, so March = 03), "
        "and each chunk gets your saved word or the starter word. Edit the "
        "**Words** (comma-separated, one per chunk) and the **Link scene**, then "
        "click **Check and build the cards**.",
    ]
    if notes:
        parts.extend(["", *[f"- {note}" for note in notes]])
    return "\n".join(parts), rows, ""


def _events_checked(

    text: str, table: Any

) -> tuple[list[dict[str, Any]], list[str], str]:
    try:
        events = names_dates.parse_events(text)
        reviewed, errors, notes = names_dates.validate_event_rows(events, table)
    except ValueError as exc:
        return [], [], f"**Input issue:** {exc}"
    if errors:
        return [], notes, _issue_markdown(
            "Fix these first",
            errors + ["The cards were not built because a wrong word would change the date."],
        )
    return reviewed, notes, ""


def build_events(text: str, table: Any) -> tuple[str, Any, str]:
    reviewed, notes, error = _events_checked(text, table)
    if error:
        return error, _current_rows(table), ""
    status = [
        "### Cards ready",
        "",
        f"All {len(reviewed)} date(s) pass the Major-System check, in the order "
        "you entered.",
    ]
    if notes:
        status.extend(["", *[f"- {note}" for note in notes]])
    card = (
        f"{names_dates.events_markdown(reviewed)}\n\n"
        f"{build_review_markdown(date.today())}"
    )
    return "\n".join(status), names_dates.event_rows_for_table(reviewed), card


def practice_events(text: str, table: Any) -> tuple[Any, ...]:
    reviewed, _notes, error = _events_checked(text, table)
    if error:
        return _practice_blocked(error)
    return _practice_from_cards(
        names_dates.event_practice(reviewed),
        "_Practicing your Dates cards: see the event, recall the pictures, "
        "decode the date._",
    )


def save_events_to_library(

    text: str, table: Any, name: str, library: Any

) -> tuple[Any, ...]:
    reviewed, _notes, error = _events_checked(text, table)
    if error:
        return (library, error, *_library_unchanged())
    return _save_to_library(
        library,
        study_library.KIND_DATES,
        name,
        study_library.content_key(
            study_library.KIND_DATES,
            "\n".join(f"{r['event'].casefold()}|{r['when']}" for r in reviewed),
        ),
        names_dates.event_practice(reviewed),
        "",
        f"Dates · {len(reviewed)} events",
    )


# ---------------------------------------------------------------------------
# Saved palace routes, and a warning when a route is reused too soon
# ---------------------------------------------------------------------------


def _route_controls() -> tuple[Any, ...]:
    """The palace box: saved-route picker, stops, and save-as-route row.



    Returns (picker, delete button, stops box, name box, save button, note).

    """
    with gr.Row(elem_classes="ms-stack"):
        pick = gr.Dropdown(
            label="My routes",
            choices=[],
            value=None,
            info="Pick a saved route to fill in its stops.",
            scale=3,
        )
        delete = gr.Button(
            "Delete route", size="sm", variant="stop", scale=0, min_width=140
        )
    stops = gr.Textbox(
        label="One familiar place per line, in order",
        placeholder="front door\nhallway\nkitchen\n...",
        lines=3,
        info=(
            "One stop per image keeps the order complete. Leave empty to build "
            "the story without a palace."
        ),
    )
    with gr.Row(elem_classes="ms-stack"):
        name = gr.Textbox(
            label="Save these stops as a route",
            placeholder="e.g. Home, Walk to work",
            max_lines=1,
            scale=3,
        )
        save = gr.Button("Save route", size="sm", scale=0, min_width=140)
    note = gr.Markdown(elem_classes="ms-muted")
    return pick, delete, stops, name, save, note


def _route_dropdown(palaces: Any, value: str | None = None) -> Any:
    return gr.Dropdown(choices=palace_routes.choices(palaces), value=value)


def refresh_route_pickers(palaces: Any) -> tuple[Any, Any]:
    return _route_dropdown(palaces), _route_dropdown(palaces)


def use_saved_route(route_id: Any, palaces: Any) -> tuple[Any, Any, Any, str]:
    """Fill the palace box with a saved route and switch the anchor to it."""
    route = palace_routes.clean(palaces)["routes"].get(str(route_id or ""))
    if route is None:
        return gr.update(), gr.update(), gr.update(), ""
    return (
        gr.update(value=ANCHOR_PALACE),
        gr.update(value="\n".join(route["stops"]), visible=True),
        gr.update(value=route["name"]),
        f"Using **{_md_cell(route['name'])}**, {len(route['stops'])} stops. "
        "Edit the stops below for this story, or save them under a new name.",
    )


def save_route_handler(

    name: str, palace_text: str, palaces: Any

) -> tuple[Any, ...]:
    """Save the stops in the palace box under a name."""
    try:
        stops = parse_palace_stops(palace_text)
        data, route_id, updated = palace_routes.save_route(palaces, name, stops)
    except ValueError as exc:
        return (palaces, gr.update(), gr.update(), f"**Route not saved:** {exc}")
    route = data["routes"][route_id]
    message = (
        f"{'Updated' if updated else 'Saved'} **{_md_cell(route['name'])}** "
        f"({len(route['stops'])} stops) in this browser. Pick it from **My "
        "routes** in the Numbers or Ordered list tab."
    )
    return (data, _route_dropdown(data), _route_dropdown(data), message)


def delete_route_handler(route_id: Any, palaces: Any) -> tuple[Any, ...]:
    data, removed = palace_routes.delete_route(palaces, route_id)
    if removed is None:
        return (palaces, gr.update(), gr.update(), "Pick a saved route to delete.")
    return (
        data,
        _route_dropdown(data),
        _route_dropdown(data),
        f"Deleted the route **{_md_cell(removed)}**. Stories already built "
        "are not changed.",
    )


def _palace_item(

    kind: str, input_text: str, table: Any, library: Any, chunking: str

) -> tuple[str, str] | None:
    """(item key, label) for the item just built, or None if it is not valid.



    The label never quotes the content: it is the item's library name, if the

    learner saved it, else its size ("a 9-digit number").

    """
    try:
        if kind == study_library.KIND_NUMBER:
            _cards, digits, problems = _number_table_cards(
                input_text, table, chunking
            )
            key = study_library.content_key(kind, digits)
            label = f"a {len(digits)}-digit number"
        else:
            _cards, items, problems = _list_table_cards(table)
            key = study_library.content_key(
                kind, "\n".join(item.casefold() for item in items)
            )
            label = f"a {len(items)}-item list"
    except ValueError:
        return None
    if problems:
        return None
    for item in study_library.clean_library(library).values():
        if item["kind"] == kind and item["key"] == key:
            label = f"**{_md_cell(item['name'])}**"
            break
    return key, label


def note_palace_use(

    kind: str,

    input_text: str,

    table: Any,

    anchor_mode: str,

    palace_text: str,

    status: str,

    palaces: Any,

    library: Any,

    chunking: str = CHUNK_PAIRS,

) -> tuple[Any, Any]:
    """After a palace build: warn if the route holds another recent item, then

    record that this item now lives there."""
    if anchor_mode != ANCHOR_PALACE or not str(status or "").startswith(
        "### Check complete"
    ):
        return palaces, gr.update()
    try:
        stops = parse_palace_stops(palace_text)
    except ValueError:
        return palaces, gr.update()
    found = _palace_item(kind, input_text, table, library, chunking)
    if not stops or found is None:
        return palaces, gr.update()
    key, label = found
    today = date.today()
    others = palace_routes.recent_other_uses(palaces, stops, key, today)
    data = palace_routes.record_use(palaces, stops, key, label, today)
    if not others:
        return data, gr.update()
    name = palace_routes.route_name(data, stops)
    route = f"**{_md_cell(name)}**" if name else "This palace route"
    # Prefer the item's current library name, in case it was saved after its build.
    library_names = {
        item["key"]: f"**{_md_cell(item['name'])}**"
        for item in study_library.clean_library(library).values()
    }
    held = "; ".join(
        f"{library_names.get(use['item'], use['label'])} "
        f"({palace_routes.days_ago(use['date'], today)})"
        for use in others[:3]
    )
    warning = (
        f"**Palace check:** {route} already holds {held}. New pictures on the "
        "same stops tend to blur with the old ones (\"ghosting\"). If you want to "
        "keep both, give this one its own route; otherwise wait about "
        f"{palace_routes.GHOST_DAYS} days before reusing these stops."
    )
    return data, f"{status}\n\n{warning}"


# ---------------------------------------------------------------------------
# Start-here shortcuts (switch tab and fill in an editable example)
# ---------------------------------------------------------------------------


def start_with_numbers(

    saved: Any = None, chunking: str = CHUNK_PAIRS

) -> tuple[Any, ...]:
    """Open the Numbers tab with the example drafted (see example_number_view)."""
    return (gr.update(selected="numbers"), *example_number_view(saved, chunking))


def start_with_list() -> tuple[Any, ...]:
    """Open the Ordered list tab with the example drafted."""
    return (gr.update(selected="list"), *example_list_view())


def start_with_word() -> tuple[Any, ...]:
    term, context, use_model, status, rows, card = _example_word()
    return (
        gr.update(selected="word"),
        term,
        context,
        use_model,
        status,
        rows,
        card,
    )


def start_with_practice() -> tuple[Any, ...]:
    return (
        gr.update(selected="practice"),
        PRACTICE_NUMBER,
        NUMBER_EXAMPLE,
        *start_practice(PRACTICE_NUMBER, NUMBER_EXAMPLE),
    )


def start_practice_example() -> tuple[Any, ...]:
    return (
        PRACTICE_NUMBER,
        NUMBER_EXAMPLE,
        *start_practice(PRACTICE_NUMBER, NUMBER_EXAMPLE),
    )


def _md_cell(text: str) -> str:
    return (text or "").replace("|", "\\|").replace("\n", " ").strip()


def _issue_markdown(title: str, items: list[str]) -> str:
    if not items:
        return f"### {title}"
    return "\n".join([f"### {title}", ""] + [f"- {item}" for item in items])


def _current_rows(table: Any) -> list[list[str]]:
    return table_to_rows(table)


def _chain_items_from_table(table: Any, kind: str) -> list[ChainItem]:
    items: list[ChainItem] = []
    for row in _current_rows(table):
        row = list(row) + [""] * 6
        code = row[0] if kind == "number" else ""
        if row[1]:
            items.append(
                ChainItem(label=row[1], cue=row[2], code=code, link=row[STORY_LINE_COLUMN])
            )
    return items


def _scene_choice_label(index: int, code: str, subject: str, detail: str) -> str:
    if len(detail) > 70:
        detail = detail[:67].rstrip() + "…"
    if len(subject) > 32:
        subject = subject[:29].rstrip() + "…"
    head = " · ".join(part for part in (str(index), code, subject) if part)
    return f"{head}: {detail}"


def _scene_choices(table: Any, kind: str) -> list[tuple[str, str]]:
    """Picture prompts: each link as one frozen moment, plus the whole chain

    in one picture when it is short enough for the image model."""
    items = _chain_items_from_table(table, kind)
    if not items:
        return []
    autos = auto_story_lines(items)
    moments = link_scene_prompts(items)
    choices: list[tuple[str, str]] = []
    whole = chain_scene_prompt(items)
    seen = {whole}
    count = f"{len(items)} image" + ("" if len(items) == 1 else "s")
    choices.append((f"Whole chain in one picture ({count})", whole))
    # Long chains crowd one picture, so also offer parts of four.
    for first, last, prompt in chain_scene_parts(items):
        if prompt not in seen:
            seen.add(prompt)
            choices.append((f"Images {first}-{last} in one picture", prompt))
    for index, item in enumerate(items):
        link = " ".join(item.link.split())
        # A line the learner (or model) wrote describes their own scene.
        prompt = link if index and link and link != autos[index] else moments[index]
        if prompt in seen:
            continue
        seen.add(prompt)
        choices.append(
            (_scene_choice_label(index + 1, item.code, item.label, prompt), prompt)
        )
    return choices


def number_scene_choices(table: Any, story: str) -> tuple[Any, Any, Any]:
    """Show one optional illustration picker after a number story is built."""
    choices = _scene_choices(table, "number") if (story or "").strip() else []
    return (
        gr.Group(visible=bool(choices)),
        gr.Dropdown(choices=choices, value=choices[0][1] if choices else None),
        _hidden_file(),
    )


def list_scene_choices(table: Any, story: str) -> tuple[Any, Any, Any]:
    """Show one optional illustration picker after a list story is built."""
    choices = _scene_choices(table, "list") if (story or "").strip() else []
    return (
        gr.Group(visible=bool(choices)),
        gr.Dropdown(choices=choices, value=choices[0][1] if choices else None),
        _hidden_file(),
    )


def remember_story_lines(table: Any) -> list[str]:
    """Record the generated lines just drafted, so a rebuild can tell them

    apart from lines the learner has since edited."""
    return [
        (list(row) + [""] * 6)[STORY_LINE_COLUMN] for row in _current_rows(table)
    ]


def _add_story_lines(rows: list[list[str]], kind: str) -> None:
    """Insert a generated story line into each drafted row (column 3)."""
    items = [
        ChainItem(label=row[1], cue=row[2], code=row[0] if kind == "number" else "")
        for row in rows
    ]
    for row, line in zip(rows, auto_story_lines(items)):
        row.insert(STORY_LINE_COLUMN, line)


MAX_STORY_LINE_WORDS = 45


def _names_image(label: str, text: str) -> bool:
    """True if ``text`` names the image word, allowing a plural (lip/lips)."""
    needle = re.escape(" ".join(label.casefold().split()))
    pattern = r"(?<![a-z0-9])" + needle + r"(?:s|es)?(?![a-z0-9])"
    return bool(needle) and re.search(pattern, (text or "").casefold()) is not None


def _resolve_story_lines(

    items: list[ChainItem],

    last_generated: Any,

    start_place: str,

    use_model: bool,

    kind: str,

) -> tuple[list[str], list[str | None], list[str]]:
    """Decide each row's story line.



    A blank cell, or one still holding the line the app generated last time,

    gets a fresh generated line (so it follows any word you changed). Anything

    else is your line and is kept. The optional model may fill only the

    generated lines. Returns (lines, generated-record, status notes).

    """
    autos = auto_story_lines(items, start_place)
    previous = list(last_generated) if isinstance(last_generated, list) else []
    lines: list[str] = []
    record: list[str | None] = []
    for index, item in enumerate(items):
        cell = " ".join(item.link.split())
        prior = previous[index] if index < len(previous) else None
        if not cell or cell == prior:
            lines.append(autos[index])
            record.append(autos[index])
        else:
            lines.append(cell)
            record.append(None)

    notes: list[str] = []
    generated = [index for index, value in enumerate(record) if value is not None]
    if use_model and generated:
        try:
            raw = ask_story_lines([(item.label, item.cue) for item in items], kind)
            parsed = parse_indexed_cues(raw, len(items))
            replaced = 0
            for index in generated:
                line = " ".join(parsed.get(index, "").split())
                if (
                    line
                    and line not in STORY_EXAMPLE_LINES
                    and _names_image(items[index].label, line)
                    # A link must also touch the previous picture...
                    and (index == 0 or _names_image(items[index - 1].label, line))
                    # ...must not give away the next one before its turn...
                    and (
                        index + 1 >= len(items)
                        or _names_image(items[index].label, items[index + 1].label)
                        or not _names_image(items[index + 1].label, line)
                    )
                    # ...and must stay short enough to read in one breath.
                    and len(line.split()) <= MAX_STORY_LINE_WORDS
                ):
                    lines[index] = line
                    record[index] = None  # keep it like your own line
                    replaced += 1
            notes.append(
                f"The local model wrote {replaced} of {len(generated)} story "
                "line(s); each one links its own image to the one before it. "
                "The rest use the built-in "
                "lines. Edit any line, or clear it to get a fresh one."
                if replaced
                else "The local model's story lines were not usable (each line "
                "must link its own image to the one before it, without giving "
                "away the next one), so the built-in "
                "lines are shown."
            )
        except LocalModelError as exc:
            notes.append(
                f"The local model was not used: {exc.public_message} The built-in "
                "story lines are shown."
            )
        except Exception:
            notes.append(
                "The local model was not used because an unexpected error "
                "occurred. The built-in story lines are shown."
            )

    for index, value in enumerate(record):
        if value is not None:
            continue
        needed = [items[index].label]
        if index:
            needed.insert(0, items[index - 1].label)
        missing = [
            label for label in needed if not _names_image(label, lines[index])
        ]
        if missing:
            notes.append(
                f"Row {index + 1}'s story line does not mention "
                + " or ".join(f"**{label}**" for label in missing)
                + ". If you changed a word, update the line or clear it to get a "
                "fresh one."
            )
    return lines, record, notes


def word_card_scene(term: str, context: str, table: Any) -> tuple[Any, Any]:
    """Send the word card's own picture (Visual image + Mini-story) to the

    Image tab. Worksheet prompts that were never filled in are not used."""
    prompts = {
        field.casefold(): text
        for field, text in word_default_drafts((term or "").strip(), (context or "").strip())
    }
    fields: dict[str, str] = {}
    for row in _current_rows(table):
        row = list(row) + ["", ""]
        key = row[0].strip().casefold()
        value = " ".join(row[1].split())
        if value and value != prompts.get(key):
            fields.setdefault(key, value)
    image = fields.get("visual image", "")
    story = fields.get("mini-story", "")
    if not image and not story:
        gr.Warning(
            "Fill in the Visual image (or Mini-story) row with your own picture "
            "first, then draw the card."
        )
        return gr.update(), gr.update()
    first_story_sentence = re.split(r"(?<=[.!?])\s", story, maxsplit=1)[0] if story else ""
    cue = ". ".join(part.rstrip(". ") for part in (image, first_story_sentence) if part)
    return gr.Tabs(selected="image"), cue


def illustrate_scene(scene: Any) -> tuple[Any, Any]:
    """Open the Image tab with one checked scene cue, ready to edit and draw."""
    cue = str(scene or "").strip()
    if not cue:
        return gr.update(), gr.update()
    return gr.Tabs(selected="image"), cue


def _list_cue_prompts(items: list[str]) -> list[str]:
    """No-model creative prompts, not generated definitions or facts."""
    templates = (
        "Make it huge, brightly colored, and moving; add a loud sound.",
        "Give it an impossible texture and a strong smell; make it wobble.",
        "Shrink it, then make it explode back to giant size.",
        "Put it in a ridiculous container that is much too small.",
        "Make it spin, bounce, or roll toward the next image.",
        "Give it a face and a comic expression; make it shout.",
        "Cover it in something unexpected: glitter, slime, or snow.",
        "Turn it into a giant version that blocks a doorway.",
        "Give it a bright spotlight and a dramatic entrance.",
        "Make it interact with the previous image in a surprising way.",
    )
    return [templates[index % len(templates)] for index in range(len(items))]


# ---------------------------------------------------------------------------
# Personal word list (kept in the learner's own browser via gr.BrowserState)
# ---------------------------------------------------------------------------

SAVED_WORDS_KEY = "memory-studio-saved-words-v1"


def _browser_secret() -> str:
    """Key that encrypts saved words in the browser's local storage.



    Gradio's default key changes on every restart, which would make saved words

    unreadable. Locally a stable key is derived from this install (nothing is

    written to disk). A hosted demo uses a per-process key unless

    MEMORY_BROWSER_SECRET is set, so visitors' saved words reset on restart.

    """
    configured = os.getenv("MEMORY_BROWSER_SECRET", "").strip()
    if configured:
        return configured
    if PUBLIC_DEMO:
        return secrets.token_urlsafe(24)
    try:
        user = getpass.getuser()
    except Exception:
        user = "local"
    seed = f"memory-studio:{Path(__file__).resolve()}:{user}"
    return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:32]


def _saved_words_for(

    chunks: list[str], saved: Any

) -> dict[str, tuple[str, str]]:
    """Saved (word, cue) pairs for these chunks that still pass the check."""
    found: dict[str, tuple[str, str]] = {}
    if not isinstance(saved, dict):
        return found
    for chunk in chunks:
        entry = saved.get(chunk)
        if not isinstance(entry, (list, tuple)) or not entry:
            continue
        word = str(entry[0] or "").strip()[:80]
        cue = str(entry[1] or "").strip()[:300] if len(entry) > 1 else ""
        if word and check_word_for_chunk(word, chunk)[0]:
            found[chunk] = (word, cue)
    return found


def saved_word_rows(saved: Any) -> list[list[str]]:
    if not isinstance(saved, dict):
        return []
    rows = []
    for chunk in sorted(saved, key=lambda key: (len(str(key)), str(key))):
        entry = saved[chunk]
        if isinstance(entry, (list, tuple)) and entry:
            cue = str(entry[1]) if len(entry) > 1 else ""
            rows.append([str(chunk), str(entry[0]), cue])
    return rows


def save_number_words(

    number_text: str, table: Any, saved: Any, chunking: str = CHUNK_PAIRS

) -> tuple[Any, str, list[list[str]]]:
    """Remember every checked word in the table as the learner's default."""
    current = dict(saved) if isinstance(saved, dict) else {}
    try:
        chunks = split_number(number_text, chunking)
    except ValueError as exc:
        return current, f"**Input issue:** {exc}", saved_word_rows(current)
    reviewed, errors = validate_number_rows(chunks, table)
    if errors:
        return (
            current,
            _issue_markdown("Table needs attention", errors),
            saved_word_rows(current),
        )
    stored, skipped = [], []
    for row in reviewed:
        if row.word and row.check.startswith("match"):
            current[row.chunk] = [row.word, row.image]
            stored.append(row.chunk)
        else:
            skipped.append(row.chunk)
    lines = [
        "### Words saved in this browser",
        "",
        f"Saved {len(stored)} word(s): "
        + (", ".join(f"`{chunk}`" for chunk in stored) or "none")
        + ". They are used first the next time a draft meets the same chunk.",
    ]
    if skipped:
        lines.append(
            "Not saved (word missing or failing the check): "
            + ", ".join(f"`{chunk}`" for chunk in skipped)
            + "."
        )
    lines.append(
        "Saved words stay in this browser's local storage; they are not "
        "written to the app's disk."
    )
    return current, "\n".join(lines), saved_word_rows(current)


def forget_saved_words() -> tuple[Any, str, list[list[str]]]:
    return {}, "### Saved words cleared\n\nThis browser no longer stores any words.", []


def lookup_major_words(code_text: str) -> str:
    """List common dictionary words that encode a chunk, most frequent first."""
    code = re.sub(r"\s", "", code_text or "")
    if not re.fullmatch(r"\d{1,4}", code):
        return "**Input issue:** enter 1 to 4 digits, for example `31`."
    words = words_for_code(code, 40)
    if not words:
        return (
            f"No common dictionary word encodes `{code}`. Try two short words "
            "(for example an adjective + noun), or a personal name you can picture."
        )
    return "\n".join(
        [
            f"**Common words for `{code}`** (most frequent first):",
            "",
            ", ".join(words),
            "",
            "_Pick a concrete thing you can picture, then type it into the "
            "table's Word column. Pronunciations are American English; say the "
            "word aloud in your accent._",
        ]
    )


# Endings that usually mark an adverb, a verb form, or an abstract noun.
_ABSTRACT_ENDINGS = (
    "ly", "ing", "ed", "ness", "ity", "tion", "sion", "ment", "ous", "ive",
    "ful", "less", "ize", "ise",
)


def _picturable_first(words: list[str]) -> list[str]:
    """Most common first, but move the first likely-concrete word to the front.



    A rough spelling heuristic: it prefers "angel" over "initially". The

    learner still sees every option and picks the picture.

    """
    for index, word in enumerate(words):
        if not word.endswith(_ABSTRACT_ENDINGS):
            return [word, *words[:index], *words[index + 1 :]]
    return list(words)


def draft_number_candidates(

    number_text: str,

    use_model: bool,

    saved: Any = None,

    chunking: str = CHUNK_PAIRS,

) -> tuple[str, list[list[str]], str]:
    """Draft an editable table: saved words first, then model, then curated

    (00-99) or common dictionary words (longer chunks)."""
    try:
        chunks = split_number(number_text, chunking)
    except ValueError as exc:
        return f"**Input issue:** {exc}", [], ""
    personal = _saved_words_for(chunks, saved)
    model_chunks = [chunk for chunk in dict.fromkeys(chunks) if chunk not in personal]

    accepted: dict[str, tuple[str, str]] = {}
    rejected: list[tuple[str, str, str]] = []
    missing: list[str] = []
    model_note = ""

    if use_model and not model_chunks:
        model_note = (
            "Every chunk already has one of your saved words, so the local "
            "model was not needed."
        )
    elif use_model:
        try:
            raw = ask_number_candidates(model_chunks)
            candidates = parse_number_rows(raw, model_chunks)
            if not candidates:
                model_note = (
                    "The local model returned no parseable rows. Curated starting "
                    "words are shown instead."
                )
            for chunk, (word, image) in candidates.items():
                ok, check = check_word_for_chunk(word, chunk)
                if ok:
                    accepted[chunk] = (word, image)
                else:
                    rejected.append((chunk, word, check))
            missing = [chunk for chunk in model_chunks if chunk not in candidates]
            if candidates:
                model_note = (
                    f"The local model returned candidates for "
                    f"{len(candidates)}/{len(model_chunks)} chunk(s). "
                    f"{len(accepted)} passed the Major-System check."
                )
        except LocalModelError as exc:
            model_note = (
                "Optional local model was not used: "
                f"{exc.public_message}"
            )
        except Exception:
            model_note = (
                "Optional local model was not used because an unexpected error "
                "occurred. Curated starting words are shown."
            )
    else:
        model_note = (
            "No-model mode: chunks without a saved word use a curated starting "
            "word (00-99) or a common dictionary word (longer chunks). Replace "
            "any word or cue with a personal association."
        )

    rows: list[list[str]] = []
    dictionary_options: dict[str, list[str]] = {}
    for chunk in chunks:
        if chunk in personal:
            word, image = personal[chunk]
            _ok, check = check_word_for_chunk(word, chunk)
            rows.append([chunk, word, image, check, "your saved word"])
            continue
        if chunk in accepted:
            word, image = accepted[chunk]
            _ok, check = check_word_for_chunk(word, chunk)
            rows.append([chunk, word, image, check, "local model + check"])
            continue
        curated = curated_candidate(chunk)
        if curated:
            word, image = curated
            source = "curated starter"
            if chunk in missing:
                source += " (model missed chunk)"
            _ok, check = check_word_for_chunk(word, chunk)
            rows.append([chunk, word, image, check, source])
            continue
        # Longer chunks (000-999): a common dictionary word, if any.
        options = dictionary_options.setdefault(
            chunk, _picturable_first(words_for_code(chunk, 6))
        )
        if options:
            word = options[0]
            _ok, check = check_word_for_chunk(word, chunk)
            rows.append([chunk, word, f"a giant {word}", check, "common word"])
        else:
            rows.append([chunk, "", "", "needs a word", "your entry"])
    _add_story_lines(rows, "number")
    for row in rows:
        if not row[1]:
            row[STORY_LINE_COLUMN] = ""  # written once the learner adds a word

    status_parts = [
        "### Draft ready",
        "",
        f"{len(chunks)} chunk(s). Review the **Word**, **Image cue**, and "
        "**Story line** columns, "
        "edit any cell, then click **Check my edits and build the story**. "
        "Words are checked with a pronunciation dictionary, or an approximate "
        "spelling check for words it does not know.",
        "",
        model_note,
    ]
    if personal:
        status_parts.extend(
            ["", f"{sum(chunk in personal for chunk in chunks)} chunk(s) use your saved words."]
        )
    status_parts.extend(
        [
            "",
            "**Chunks:** " + " · ".join(f"`{chunk}`" for chunk in chunks),
        ]
    )
    input_note = number_input_note(number_text)
    if input_note:
        status_parts.extend(["", input_note])

    used_dictionary = {
        chunk: options
        for chunk, options in dictionary_options.items()
        if options and any(row[0] == chunk and row[5] == "common word" for row in rows)
    }
    if used_dictionary:
        status_parts.extend(
            [
                "",
                "#### Words from the dictionary",
                "",
                "There is no curated word for these chunks, so the most common "
                "word is drafted. Common words include verbs and abstract words; "
                "swap in the one you can picture best.",
                "",
                "| Chunk | Drafted | Other options |",
                "|---:|---|---|",
            ]
        )
        for chunk, options in used_dictionary.items():
            status_parts.append(
                f"| `{chunk}` | {_md_cell(options[0])} | "
                f"{_md_cell(', '.join(options[1:]) or '(none)')} |"
            )
    no_word = list(dict.fromkeys(row[0] for row in rows if not row[1]))
    if no_word:
        status_parts.extend(
            [
                "",
                "**Needs your word:** no common word encodes "
                + ", ".join(f"`{chunk}`" for chunk in no_word)
                + ". Type a word whose consonant sounds give those digits (the "
                "check uses the full pronunciation dictionary), or "
                + (
                    "add a space inside that group in the number and draft again."
                    if chunking == CHUNK_SPACES
                    else "set **How to split** to **Where I put spaces** and "
                    "group those digits your own way."
                ),
            ]
        )

    if rejected:
        status_parts.extend(
            [
                "",
                "#### Model candidates not auto-accepted",
                "",
                "The starting suggestion stayed in the table. If you believe the "
                "checker is wrong, copy the model word into the Word column and "
                "verify it aloud.",
                "",
                "| Chunk | Model word | Checker result |",
                "|---:|---|---|",
            ]
        )
        for chunk, word, check in rejected:
            status_parts.append(f"| `{chunk}` | {_md_cell(word)} | {_md_cell(check)} |")

    if missing and accepted:
        status_parts.extend(
            [
                "",
                "Model rows missing for: "
                + ", ".join(f"`{chunk}`" for chunk in missing)
                + ". Starting words were used for those chunks.",
            ]
        )

    status_parts.extend(
        [
            "",
            "**Order is locked to the digits.** Do not add or remove rows; "
            "regenerate if the number changes.",
        ]
    )
    return "\n".join(status_parts), rows, ""


def build_number_story(

    number_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any = None,

    chunking: str = CHUNK_PAIRS,

) -> tuple[Any, ...]:
    """Build the number story; also returns the generated-line record."""
    result = _build_number_story(
        number_text, table, use_model, anchor_mode, palace_text, last_lines, chunking
    )
    return result if len(result) == 4 else (*result, gr.update())


def _build_number_story(

    number_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any,

    chunking: str,

) -> tuple[Any, ...]:
    """Re-check edited rows, preserve order, and build complete story outputs."""
    current_rows = _current_rows(table)
    try:
        chunks = split_number(number_text, chunking)
    except ValueError as exc:
        return f"**Input issue:** {exc}", current_rows, ""

    reviewed, errors = validate_number_rows(chunks, table)
    if errors:
        return _issue_markdown("Table needs attention", errors), current_rows, ""

    blockers = number_blockers(reviewed)
    reviewed_rows = [row.as_list() for row in reviewed]
    if blockers:
        return (
            _issue_markdown(
                "Fix these before using the story",
                blockers
                + [
                    "The story was not built because an unchecked word would "
                    "silently change the digits."
                ],
            ),
            reviewed_rows,
            "",
        )

    try:
        stops = parse_palace_stops(palace_text)
    except ValueError as exc:
        return f"**Input issue:** {exc}", reviewed_rows, ""

    chain_items = [
        ChainItem(label=row.word, cue=row.image, code=row.chunk, link=row.link)
        for row in reviewed
    ]
    start_place = stops[0] if anchor_mode == ANCHOR_PALACE and stops else ""
    lines, record, notes = _resolve_story_lines(
        chain_items, last_lines, start_place, use_model, "number"
    )
    for row, item, line in zip(reviewed, chain_items, lines):
        row.link = item.link = line
    reviewed_rows = [row.as_list() for row in reviewed]

    status_parts = [
        "### Check complete",
        "",
        f"All {len(reviewed)} chunk(s) pass the Major-System check. "
        "The story keeps the digit order.",
    ]
    input_note = number_input_note(number_text)
    if input_note:
        status_parts.extend(["", input_note])
    for note in notes:
        status_parts.extend(["", note])
    story_parts = [
        "## Number \u2192 Major System",
        "",
        f"**Input:** `{number_text.strip()}`",
        "",
        build_ordered_chain(chain_items, start_place=start_place),
    ]

    palace = build_anchor_markdown(chain_items, anchor_mode, stops)
    if palace:
        story_parts.extend(["", palace])

    story_parts.extend(
        [
            "",
            build_recall_markdown("number", len(reviewed)),
            "",
            build_review_markdown(date.today()),
            "",
            "### Accuracy note",
            "",
            NUMBER_ACCURACY,
        ]
    )
    return "\n".join(status_parts), reviewed_rows, "\n".join(story_parts), record


def draft_list_candidates(

    list_text: str, use_model: bool

) -> tuple[str, list[list[str]], str]:
    """Draft editable image cues while preserving the learner's item order."""
    try:
        items = parse_item_list(list_text)
    except ValueError as exc:
        return f"**Input issue:** {exc}", [], ""

    prompts = _list_cue_prompts(items)
    cues = list(prompts)
    model_note = ""
    supplied_count = 0

    if use_model:
        try:
            raw = ask_list_cues(items)
            parsed = parse_indexed_cues(raw, len(items))
            supplied_count = len(parsed)
            for index, cue in parsed.items():
                if cue.casefold().strip() == items[index].casefold().strip():
                    continue
                cues[index] = cue
            missing_indices = [
                index + 1 for index in range(len(items)) if index not in parsed
            ]
            if parsed:
                model_note = (
                    f"The local model supplied {supplied_count}/{len(items)} cue(s). "
                    "Rows without a usable model cue keep a no-model editing prompt."
                )
                if missing_indices:
                    model_note += (
                        " Missing cue index/indices: "
                        + ", ".join(str(index) for index in missing_indices)
                        + "."
                    )
            else:
                model_note = (
                    "The local model returned no parseable cues. No-model editing "
                    "prompts are shown instead."
                )
        except LocalModelError as exc:
            model_note = (
                "Optional local model was not used: "
                f"{exc.public_message}"
            )
        except Exception:
            model_note = (
                "Optional local model was not used because an unexpected error "
                "occurred. No-model editing prompts are shown."
            )
    else:
        model_note = (
            "No-model mode: each cue is a creative prompt to complete, not a "
            "generated description. Edit any cue with your own concrete image."
        )

    rows = [
        [str(index), item, cue]
        for index, (item, cue) in enumerate(zip(items, cues), 1)
    ]
    _add_story_lines(rows, "list")
    status_parts = [
        "### Draft ready",
        "",
        f"{len(items)} item(s). The table order is the story order. Edit the "
        "**Image cue** and **Story line** columns freely, then click **Check my "
        "edits and build the story**.",
        "",
        model_note,
        "",
        "Keep every item row. If you need to correct an item label, update the "
        "list input as well so the source and table agree.",
    ]
    return "\n".join(status_parts), rows, ""


def build_list_story(

    list_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any = None,

) -> tuple[Any, ...]:
    """Build the list story; also returns the generated-line record."""
    result = _build_list_story(
        list_text, table, use_model, anchor_mode, palace_text, last_lines
    )
    return result if len(result) == 4 else (*result, gr.update())


def _build_list_story(

    list_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any,

) -> tuple[Any, ...]:
    """Build a complete ordered list story from the edited cue table."""
    current_rows = _current_rows(table)
    try:
        items = parse_item_list(list_text)
    except ValueError as exc:
        return f"**Input issue:** {exc}", current_rows, ""

    reviewed, errors = validate_list_rows(table)
    if errors:
        return _issue_markdown("Table needs attention", errors), current_rows, ""

    if len(reviewed) != len(items):
        return (
            _issue_markdown(
                "Table needs attention",
                [
                    f"The table has {len(reviewed)} row(s) but the list has "
                    f"{len(items)} item(s). Do not add or remove rows; regenerate "
                    "from the list input if the list changed.",
                ],
            ),
            current_rows,
            "",
        )

    original_counts = Counter(item.casefold() for item in items)
    table_counts = Counter(row.item.casefold() for row in reviewed)
    missing_counts = original_counts - table_counts
    if missing_counts:
        missing_labels = []
        for label, count in missing_counts.items():
            suffix = f" (x{count})" if count > 1 else ""
            missing_labels.append(f"**{label}**{suffix}")
        return (
            _issue_markdown(
                "An original list item is missing",
                [
                    "The table no longer contains: " + ", ".join(missing_labels) + ".",
                    "To prevent an accidental omission, the story was not built. "
                    "Restore the item(s), or edit the list input and regenerate so "
                    "the source and table agree.",
                ],
            ),
            [row.as_list() for row in reviewed],
            "",
        )

    extra_counts = table_counts - original_counts
    extra_note = ""
    if extra_counts:
        extra_labels = []
        for label, count in extra_counts.items():
            suffix = f" (x{count})" if count > 1 else ""
            extra_labels.append(f"**{label}**{suffix}")
        extra_note = (
            "The table contains extra item(s) not in the list input: "
            + ", ".join(extra_labels)
            + ". They are kept in the story; update the list input if you want "
            "the source to match."
        )

    try:
        stops = parse_palace_stops(palace_text)
    except ValueError as exc:
        return f"**Input issue:** {exc}", [row.as_list() for row in reviewed], ""

    chain_items = [
        ChainItem(label=row.item, cue=row.cue, link=row.link) for row in reviewed
    ]
    start_place = stops[0] if anchor_mode == ANCHOR_PALACE and stops else ""
    lines, record, notes = _resolve_story_lines(
        chain_items, last_lines, start_place, use_model, "list"
    )
    for row, item, line in zip(reviewed, chain_items, lines):
        row.link = item.link = line
    status_parts = [
        "### Check complete",
        "",
        f"All {len(reviewed)} item(s) are present in the table order.",
    ]
    if extra_note:
        status_parts.extend(["", extra_note])
    for note in notes:
        status_parts.extend(["", note])
    story_parts = [
        "## Ordered list \u2192 story",
        "",
        build_ordered_chain(chain_items, start_place=start_place),
    ]
    palace = build_anchor_markdown(chain_items, anchor_mode, stops)
    if palace:
        story_parts.extend(["", palace])
    story_parts.extend(
        [
            "",
            build_recall_markdown("list", len(reviewed)),
            "",
            build_review_markdown(date.today()),
            "",
            "### Accuracy note",
            "",
            LIST_ACCURACY,
        ]
    )
    return (
        "\n".join(status_parts),
        [row.as_list() for row in reviewed],
        "\n".join(story_parts),
        record,
    )


def _validate_word_inputs(term: str, context: str) -> tuple[str, str]:
    term_text = (term or "").strip()
    context_text = (context or "").strip()
    if not term_text:
        raise ValueError("Enter a word or concept first.")
    if len(term_text) > MAX_WORD_TERM_LENGTH:
        raise ValueError(
            f"Keep the word or concept under {MAX_WORD_TERM_LENGTH} characters."
        )
    if len(context_text) > MAX_WORD_CONTEXT_LENGTH:
        raise ValueError(
            f"Keep the optional context under {MAX_WORD_CONTEXT_LENGTH} characters."
        )
    return term_text, context_text


def _replace_word_field(

    rows: list[list[str]], field: str, value: str

) -> None:
    for row in rows:
        if row[0] == field:
            row[1] = value
            return


def draft_word_fields(

    term: str, context: str, use_model: bool

) -> tuple[str, list[list[str]], str]:
    """Create an editable, no-fact-invention word card worksheet or model draft."""
    try:
        term_text, context_text = _validate_word_inputs(term, context)
    except ValueError as exc:
        return f"**Input issue:** {exc}", [], ""

    rows = [list(pair) for pair in word_default_drafts(term_text, context_text)]
    if not use_model:
        return (
            "\n".join(
                [
                    "### No-model worksheet ready",
                    "",
                    "Each row is an editing prompt, not a generated association or "
                    "definition. Fill in the Draft column with your own sound-alike, "
                    "image, story, location, and recall question, then assemble the "
                    "card.",
                    "",
                    "No definition was invented. Add context you trust, or keep the "
                    "card label-only.",
                ]
            ),
            rows,
            "",
        )

    try:
        raw = ask_word_fields(term_text, context_text)
        sections, preamble = parse_word_sections(raw)
    except LocalModelError as exc:
        return (
            "\n".join(
                [
                    "### No-model worksheet ready",
                    "",
                    "Optional local model was not used: "
                    f"{exc.public_message}",
                    "",
                    "The editable prompts below are still usable.",
                ]
            ),
            rows,
            "",
        )
    except Exception:
        return (
            "\n".join(
                [
                    "### No-model worksheet ready",
                    "",
                    "The local model draft could not be read because an unexpected "
                    "error occurred. The editable prompts below are still usable.",
                ]
            ),
            rows,
            "",
        )

    supplied: list[str] = []
    for field in WORD_FIELD_NAMES:
        if field == "Meaning anchor":
            continue
        value = sections.get(field, "").strip()
        if value:
            _replace_word_field(rows, field, value)
            supplied.append(field)

    model_meaning = sections.get("Meaning anchor", "").strip()
    unverified_meaning = False
    if not context_text and model_meaning:
        if "no definition supplied" not in model_meaning.casefold():
            rows.append(
                [
                    "Unverified model meaning (do not treat as fact)",
                    model_meaning,
                ]
            )
            unverified_meaning = True
    elif context_text and model_meaning:
        pass  # The learner's supplied context remains the factual anchor.

    if not sections:
        unstructured = preamble or raw.strip()
        if unstructured:
            rows.append(["Model draft (unstructured)", unstructured])
        status_note = (
            "The model did not follow the field labels; its text is preserved in "
            "the extra row. The six rows above remain editable prompts."
        )
    else:
        status_note = (
            f"The model supplied {len(supplied)}/{len(WORD_FIELD_NAMES) - 1} "
            "non-meaning field(s). Missing fields keep editing prompts."
        )
        if preamble:
            rows.append(["Model notes (unstructured)", preamble])

    status_parts = [
        "### Draft ready",
        "",
        status_note,
        "",
        "Edit every cell freely, then click **Assemble my card**. The app cannot "
        "verify definitions; check technical meanings in a source you trust.",
    ]
    if context_text:
        status_parts.append(
            "Your supplied context is used as the meaning anchor. The model's "
            "meaning text was not substituted for it."
        )
    else:
        status_parts.append(
            "No context was supplied, so no definition was accepted as fact."
        )
    if unverified_meaning:
        status_parts.append(
            "The model's own meaning text is shown separately and labeled "
            "unverified. Do not treat it as a definition."
        )
    return "\n".join(status_parts), rows, ""


def assemble_word_outputs(

    term: str, context: str, table: Any

) -> tuple[str, list[list[str]], str]:
    """Assemble the edited word-card fields into a Markdown card."""
    current_rows = _current_rows(table)
    try:
        term_text, context_text = _validate_word_inputs(term, context)
        card, missing = assemble_word_card(term_text, context_text, table)
    except ValueError as exc:
        return f"**Input issue:** {exc}", current_rows, ""

    status_parts = [
        "### Card assembled",
        "",
        "Review the accuracy note at the bottom. Definitions are not verified by "
        "this app.",
    ]
    if missing:
        status_parts.extend(
            [
                "",
                "Not filled in: " + ", ".join(missing) + ". Add these for a "
                "complete card.",
            ]
        )
    card = f"{card}\n\n{build_review_markdown(date.today())}"
    return "\n".join(status_parts), current_rows, card


# ---------------------------------------------------------------------------
# Mind Map (deterministic SVG; no model)
# ---------------------------------------------------------------------------

MIND_MAP_EXAMPLE_TOPIC = "Memory"
MIND_MAP_EXAMPLE = """Imagination

  exaggerate

  colour

  movement

Association

  link

  pegs

  palace

Review

  10 minutes

  1 day

  1 week

Numbers

  Major System

  shapes

"""
MAX_MIND_TOPIC_LENGTH = 40


def _mind_map_parts(topic: str, outline: str) -> tuple[str, list[tuple[str, list[str]]]]:
    topic_text = " ".join((topic or "").split())
    if not topic_text:
        raise ValueError("Enter a central topic: a short word or phrase.")
    if len(topic_text) > MAX_MIND_TOPIC_LENGTH:
        raise ValueError(
            f"Keep the central topic under {MAX_MIND_TOPIC_LENGTH} characters."
        )
    return topic_text, parse_outline(outline)


MIND_VIEW_FULL = "Full map"
MIND_VIEW_DETAILS = "Hide the details"
MIND_VIEW_ALL = "Hide every branch"
MIND_VIEWS = (MIND_VIEW_FULL, MIND_VIEW_DETAILS, MIND_VIEW_ALL)
_MIND_HIDE = {
    MIND_VIEW_FULL: mind_map.HIDE_NONE,
    MIND_VIEW_DETAILS: mind_map.HIDE_DETAILS,
    MIND_VIEW_ALL: mind_map.HIDE_ALL,
}


def build_mind_map(

    topic: str, outline: str, view: str = MIND_VIEW_FULL

) -> tuple[str, str]:
    """Draw the outline as a Mind Map (or a recall view of it)."""
    try:
        topic_text, branches = _mind_map_parts(topic, outline)
    except ValueError as exc:
        return f"**Input issue:** {exc}", ""
    hide = _MIND_HIDE.get(view, mind_map.HIDE_NONE)
    if hide:
        hidden = (
            "every branch word" if hide == mind_map.HIDE_ALL else "the details"
        )
        status = (
            f"### Recall test: {hidden} hidden\n\n"
            "Each **?** keeps its colour, place, and length. Say or write the "
            "hidden word for every **?**, going clockwise from the top, then "
            "switch **Show** back to **Full map** to check. Repair any branch you "
            "missed with a small picture."
        )
        svg = mind_map.render_svg(topic_text, branches, hide)
        return status, f'<div class="ms-mindmap">{svg}</div>'

    lines = [
        "### Mind Map ready",
        "",
        f"{len(branches)} main branch(es) and "
        f"{sum(len(subs) for _label, subs in branches)} detail(s). Every line of "
        "your outline is drawn, in order, clockwise from the top.",
    ]
    tips = key_word_tips(topic_text, branches)
    if tips:
        lines.extend(["", *[f"- {tip}" for tip in tips]])
    lines.extend(
        [
            "",
            "**Recall it:** cover the map and redraw it on paper from memory: the "
            "centre first, then each main branch in its colour, then the details. "
            "Compare, and add a small picture to any branch you missed.",
        ]
    )
    svg = render_svg(topic_text, branches)
    return "\n".join(lines), f'<div class="ms-mindmap">{svg}</div>'


def mind_map_files(topic: str, outline: str) -> Any:
    try:
        topic_text, branches = _mind_map_parts(topic, outline)
    except ValueError as exc:
        raise gr.Error(str(exc)) from exc
    sheet = (
        outline_markdown(topic_text, branches)
        + "\n\n"
        + build_review_markdown(date.today())
    )
    svg = render_svg(topic_text, branches)
    return _study_sheet(sheet, "mind-map", extra=((".svg", svg + "\n"),))


def practice_mind_map(topic: str, outline: str) -> tuple[Any, ...]:
    """Open the map's recall cards in the Practice tab."""
    try:
        topic_text, branches = _mind_map_parts(topic, outline)
    except ValueError as exc:
        return _practice_blocked(f"**Input issue:** {exc}")
    return _practice_from_cards(
        mind_map.practice_cards(topic_text, branches),
        f"_Practicing your **{_md_cell(topic_text)}** Mind Map: the main "
        "branches first, then each branch's details._",
    )


def save_mind_map_to_library(

    topic: str, outline: str, name: str, library: Any

) -> tuple[Any, ...]:
    try:
        topic_text, branches = _mind_map_parts(topic, outline)
    except ValueError as exc:
        return (library, f"**Input issue:** {exc}", *_library_unchanged())
    return _save_to_library(
        library,
        study_library.KIND_MINDMAP,
        name,
        study_library.content_key(study_library.KIND_MINDMAP, topic_text.casefold()),
        mind_map.practice_cards(topic_text, branches),
        "",
        topic_text,
    )


def mind_map_center_cue(topic: str) -> tuple[Any, Any]:
    """Send the central topic to the Image tab as a cue for one bold symbol."""
    topic_text = " ".join((topic or "").split())
    if not topic_text:
        return gr.update(), gr.update()
    return (
        gr.Tabs(selected="image"),
        f"one bold, colourful symbol that stands for {topic_text}, centred on a "
        "plain page",
    )


EXAMPLE_IMAGE_CUE = (
    "a giant wedge of cheese wearing a golden crown, dancing on a rooftop "
    "at sunset"
)
EXAMPLE_IMAGE_CUE_TWO = (
    "a bright red doormat floating above a chessboard, lit by a single "
    "spotlight"
)


def load_example_image_cue() -> str:
    return EXAMPLE_IMAGE_CUE


def load_second_image_cue() -> str:
    return EXAMPLE_IMAGE_CUE_TWO


def _size_option(pixels: int) -> str:
    """Return the dropdown label for a pixel size."""
    return next(
        (option for option in IMAGE_SIZE_OPTIONS if option.startswith(str(pixels))),
        IMAGE_SIZE_OPTIONS[0],
    )


def _size_from_label(label: str) -> int:
    token = str(label or "").strip().split(" ")[0]
    return int(token) if token.isdigit() else DEFAULT_IMAGE_SIZE


def draw_local_image(

    cue: str, style: str, size_label: str, steps: float, seed: float

) -> tuple[str, Any | None]:
    """Draw one optional local image draft from an editable cue."""
    size = _size_from_label(size_label)
    try:
        seed_value = int(seed)
    except (TypeError, ValueError):
        seed_value = -1
    try:
        image, info = generate_cue_image(
            cue,
            style=style,
            size=size,
            steps=int(steps),
            seed=seed_value,
        )
    except ValueError as exc:
        return f"**Input issue:** {exc}", None
    except LocalImageError as exc:
        return f"**Image model issue:** {exc.public_message}", None
    except Exception:
        return (
            "**Image issue:** The local image model could not draw this cue. Try "
            "a shorter cue, a smaller size, fewer steps, or use the text-only "
            "route.",
            None,
        )

    status = "\n".join(
        [
            "### Local image draft" if not PUBLIC_DEMO else "### Image draft",
            "",
            (
                f"Generated in **{info['seconds']}s** with `{info['model']}` on "
                f"`{info['device']}`."
                if PUBLIC_DEMO
                else f"Generated on this computer in **{info['seconds']}s** with "
                f"`{info['model']}` on `{info['device']}`."
            ),
            "",
            f"Seed `{info['seed']}`, {info['size']} × {info['size']} px, "
            f"{info['steps']} steps.",
            "",
            "This is an AI visual draft, not a factual illustration. Regenerate "
            "with a new seed or edit the cue if it misses the mnemonic point.",
        ]
    )
    if info.get("dropped"):
        status += (
            "\n\n**The cue was longer than the image model can read**, so these "
            f"words were not drawn: _{info['dropped']}_. Shorten the cue to one "
            "subject, one action, and one place."
        )
    return status, image


def _gpu_quota_message(exc: Exception) -> str | None:
    """A friendly status if ``exc`` is a ZeroGPU quota or availability error."""
    text = str(exc).casefold()
    if "quota" in text or "zerogpu" in text or "no gpu" in text:
        return (
            "**The free GPU is not available to you right now.** This Space gives "
            "each visitor a small daily ZeroGPU allowance, and it is used up (or "
            "the GPU is busy). Try again later, sign in to Hugging Face for a "
            "larger allowance, or run the app on your own computer. Everything "
            "except drawing still works."
        )
    return None


def _gpu_wrapped(handler: Any) -> Any:
    """Ask ZeroGPU for a GPU slice around one Draw when hosted on a Space.



    The decorator does nothing outside a ZeroGPU Space, and the local app never

    imports it. The image model is preloaded once for the Space, so only the

    sampling itself runs inside the allocated window.

    """
    if not PUBLIC_DEMO:
        return handler
    try:
        import spaces
    except Exception:
        return handler
    gpu_handler = spaces.GPU(duration=60)(handler)

    def guarded(*args: Any) -> Any:
        try:
            return gpu_handler(*args)
        except Exception as exc:
            message = _gpu_quota_message(exc)
            if message is None:
                raise
            return message, None

    return guarded


image_draw_handler = _gpu_wrapped(draw_local_image)


def draw_and_keep(

    cue: str,

    style: str,

    size_label: str,

    steps: float,

    seed: float,

    history: list[Any] | None,

) -> tuple[Any, ...]:
    """Draw, then add the picture to the recent drafts, in one round trip.



    Only the drawing runs inside the GPU window. Outputs: status, image,

    history, gallery.

    """
    status, image = image_draw_handler(cue, style, size_label, steps, seed)
    return (status, image, *append_image_history(image, history))


# ---------------------------------------------------------------------------
# Combined handlers: each click is one server round trip, not a .then chain
# ---------------------------------------------------------------------------


def _number_view(

    status: str, rows: Any, story: str, *before: Any

) -> tuple[Any, ...]:
    """A drafted Numbers table plus its follow-ups.



    Outputs: (*before, status, table, story, illustrate box, scene picker,

    study sheet, generated-line record).

    """
    return (
        *before,
        status,
        rows,
        story,
        *number_scene_choices(rows, story),
        remember_story_lines(rows),
    )


def draft_number_view(

    number_text: str,

    use_model: bool,

    saved: Any = None,

    chunking: str = CHUNK_PAIRS,

) -> tuple[Any, ...]:
    return _number_view(
        *draft_number_candidates(number_text, use_model, saved, chunking)
    )


def example_number_view(

    saved: Any = None, chunking: str = CHUNK_PAIRS

) -> tuple[Any, ...]:
    """Outputs: number, model box, then the _number_view outputs."""
    number, use_model, status, rows, story = _example_number(saved, chunking)
    return _number_view(status, rows, story, number, use_model)


def build_number_view(

    number_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any,

    chunking: str,

    palaces: Any,

    library: Any,

) -> tuple[Any, ...]:
    """Build the story, refresh the scene picker, and run the palace check.



    Outputs: status, table, story, line record, illustrate box, scene picker,

    study sheet, palace routes.

    """
    status, rows, story, record = build_number_story(
        number_text, table, use_model, anchor_mode, palace_text, last_lines, chunking
    )
    palaces, noted = note_palace_use(
        study_library.KIND_NUMBER,
        number_text,
        rows,
        anchor_mode,
        palace_text,
        status,
        palaces,
        library,
        chunking,
    )
    if isinstance(noted, str):
        status = noted
    return (status, rows, story, record, *number_scene_choices(rows, story), palaces)


def _list_view(status: str, rows: Any, story: str, *before: Any) -> tuple[Any, ...]:
    """A drafted list table plus its follow-ups (same order as _number_view)."""
    return (
        *before,
        status,
        rows,
        story,
        *list_scene_choices(rows, story),
        remember_story_lines(rows),
    )


def draft_list_view(list_text: str, use_model: bool) -> tuple[Any, ...]:
    return _list_view(*draft_list_candidates(list_text, use_model))


def example_list_view() -> tuple[Any, ...]:
    """Outputs: list text, model box, then the _list_view outputs."""
    text, use_model, status, rows, story = _example_list()
    return _list_view(status, rows, story, text, use_model)


def build_list_view(

    list_text: str,

    table: Any,

    use_model: bool,

    anchor_mode: str,

    palace_text: str,

    last_lines: Any,

    palaces: Any,

    library: Any,

) -> tuple[Any, ...]:
    """Build the list story, refresh the scene picker, run the palace check."""
    status, rows, story, record = build_list_story(
        list_text, table, use_model, anchor_mode, palace_text, last_lines
    )
    palaces, noted = note_palace_use(
        study_library.KIND_LIST,
        list_text,
        rows,
        anchor_mode,
        palace_text,
        status,
        palaces,
        library,
    )
    if isinstance(noted, str):
        status = noted
    return (status, rows, story, record, *list_scene_choices(rows, story), palaces)


def build_mind_map_view(

    topic: str, outline: str, view: str = MIND_VIEW_FULL

) -> tuple[Any, Any, Any]:
    """Draw the map and hide a download that no longer matches it."""
    return (*build_mind_map(topic, outline, view), _hidden_file())


def example_mind_map_view() -> tuple[Any, ...]:
    """Outputs: topic, outline, view, status, map, files."""
    return (
        MIND_MAP_EXAMPLE_TOPIC,
        MIND_MAP_EXAMPLE,
        MIND_VIEW_FULL,
        *build_mind_map_view(MIND_MAP_EXAMPLE_TOPIC, MIND_MAP_EXAMPLE),
    )


def load_browser_views(

    saved: Any, library: Any, palaces: Any, stats: Any

) -> tuple[Any, ...]:
    """Fill every view kept in browser storage when the page opens.



    Outputs: saved-word table, the five library views, both route pickers,

    trainer's hardest-numbers table.

    """
    return (
        saved_word_rows(saved),
        *_library_view(library),
        *refresh_route_pickers(palaces),
        trainer_hardest(stats, saved),
    )


# One key for every browser-stored value, made once per process.
BROWSER_SECRET = _browser_secret()
# Read the pronunciation dictionary in the background, so the first draft
# does not wait for it. It reads only the bundled files.
threading.Thread(
    target=warm_up_dictionary, name="dictionary-warm-up", daemon=True
).start()
# Requests that do not touch a model run side by side. The text model and the
# image pipeline each hold their own lock, and Draw keeps a limit of one.
QUEUE_CONCURRENCY = 4


# delete_cache: every hour, drop Gradio's copies of files older than a day.
with gr.Blocks(
    title="Memory Studio · picture it, remember it",
    delete_cache=(3600, 86400),
) as demo:
    # Saved words live in this browser's local storage, never on the server.
    personal_words = gr.BrowserState(
        {}, storage_key=SAVED_WORDS_KEY, secret=BROWSER_SECRET
    )
    # So do library items and their review dates.
    library_state = gr.BrowserState(
        {}, storage_key=study_library.LIBRARY_KEY, secret=BROWSER_SECRET
    )
    # And the 00-99 trainer's per-number results (counts only, no study text).
    trainer_stats = gr.BrowserState(
        {}, storage_key=peg_trainer.TRAINER_STATS_KEY, secret=BROWSER_SECRET
    )
    # And saved palace routes, plus which item was last placed on each route.
    palace_state = gr.BrowserState(
        {}, storage_key=palace_routes.PALACES_KEY, secret=BROWSER_SECRET
    )
    gr.HTML(
        f"""

        <div id="ms-hero">

          <div class="ms-kicker">Memory Studio · picture it, remember it</div>

          <h1>Turn numbers, words, and lists into pictures you can recall.</h1>

          <p>

            Build editable mnemonic cards with the Major System, link them into a

            complete ordered story, and optionally place them along a Memory

            Palace. Every suggestion stays yours to inspect and replace.

          </p>

          <div class="ms-chips">

            <span class="ms-chip">No model required</span>

            <span class="ms-chip">Edit every suggestion</span>

            <span class="ms-chip">Download a study sheet</span>

          </div>

        </div>

        """
    )
    if PUBLIC_DEMO:
        gr.Markdown(
            "**Online version: where your text goes.** What you type is "
            "processed on this Hugging Face Space's servers, not on your device. "
            "The app does not save it, but avoid pasting secrets or private "
            "notes. For full privacy, run Memory Studio on your own computer "
            "(see **Guide & privacy**).",
            elem_classes="ms-note",
        )

    with gr.Tabs(selected="start", overflow_behavior="wrap") as tabs:
        with gr.TabItem("Start here", id="start"):
            with gr.Row(elem_classes="ms-stack"):
                start_due = gr.Markdown(elem_classes="ms-note")
                start_open_library = gr.Button(
                    "Open My library",
                    variant="primary",
                    size="sm",
                    scale=0,
                    min_width=170,
                    visible=False,
                )
            gr.Markdown(
                """

                ### Pick a starting point

                Every option below works without a model and fills the next tab

                with an editable example.

                """
            )
            with gr.Row(equal_height=True):
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 🔢 Numbers\n"
                        "Split a number into pairs, threes, or your own groups "
                        "and give each chunk a vivid word and image."
                    )
                    start_numbers = gr.Button(
                        "Try 314159", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 📝 Ordered list\n"
                        "Turn a shopping list, recipe, or outline into a linked "
                        "story that keeps its order."
                    )
                    start_list = gr.Button(
                        "Try a grocery list", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 🧩 Word card\n"
                        "Build a sound-alike, a scene, and a recall question for "
                        "any word or concept."
                    )
                    start_word = gr.Button(
                        "Try “Pomodoro”", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 🎯 Recall practice\n"
                        "Test yourself card by card, in the original order, with "
                        "no model involved."
                    )
                    start_practice_card = gr.Button(
                        "Start practicing", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 🗺️ Mind Map\n"
                        "Put a topic in the centre and its key words on coloured "
                        "branches, all on one page."
                    )
                    start_mind_map = gr.Button(
                        "Try a Mind Map", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 🔁 00–99 trainer\n"
                        "Drill your number words both ways until each one comes "
                        "back in a couple of seconds."
                    )
                    start_trainer_card = gr.Button(
                        "Drill 00–19", variant="primary", size="sm"
                    )
                with gr.Column(elem_classes="ms-card", min_width=220):
                    gr.Markdown(
                        "### 👥 Names & dates\n"
                        "Link a name to a face feature, or a date to its event, "
                        "with pictures you can recall."
                    )
                    start_names_card = gr.Button(
                        "Try names & faces", variant="primary", size="sm"
                    )

            gr.Markdown("### How it works")
            gr.HTML(
                """

                <div class="ms-step">

                  <div class="ms-step-num">1</div>

                  <div><strong>Draft</strong><br>

                  <span class="ms-muted">Use the deterministic curated words or an

                  optional local-AI draft. Nothing is final.</span></div>

                </div>

                <div class="ms-step">

                  <div class="ms-step-num">2</div>

                  <div><strong>Edit</strong><br>

                  <span class="ms-muted">Replace any word, image cue, or route with

                  one that is vivid for you. The app re-checks the order.</span></div>

                </div>

                <div class="ms-step">

                  <div class="ms-step-num">3</div>

                  <div><strong>Build &amp; practice</strong><br>

                  <span class="ms-muted">Get a linked story you can read aloud, a recall

                  prompt, and a Markdown study sheet you can keep.</span></div>

                </div>

                """,
                elem_id="ms-how",
            )
            gr.Markdown(
                "**No model needed.** The deterministic route downloads nothing "
                "and never calls a model. Optional AI drafts are off by default; "
                "turn one on inside a tab only when you want a suggestion.",
                elem_classes="ms-note",
            )

            gr.Markdown(
                """

                ### 🎨 Buzan's golden rules for making a picture stick



                Tony Buzan's **"golden rules"** turn an ordinary picture into one

                you can recall at will. Use them whenever you draft or edit an

                image cue or story line.



                *   **Movement**: make it do something: flying, bursting,

                    rolling, colliding.

                *   **Association**: glue this picture to the one before it

                    (or to its palace spot) so one triggers the next.

                *   **Sensuality**: give it a sound, smell, taste, or feel;

                    the more senses it uses, the deeper it sticks.

                *   **Humour**: funny, ridiculous, or embarrassing pictures

                    are remembered far longer than boring ones.

                *   **Imagination**: exaggerate. Make it huge, glowing,

                    upside-down, or doing the impossible.

                *   **Number**: give it a number or count so you recall its

                    position in the sequence.

                *   **Symbolism**: stand for its meaning with a single, clear

                    object (a crown = royalty, a key = unlocking).

                *   **Colour**: make it brightly coloured; one vivid colour

                    beats ten grey ones.

                *   **Order**: keep items in a fixed sequence so you can

                    jump straight to position 17 without counting from one.

                *   **Positive**: positive or aspirational images last better

                    than dark or frightening ones.

                *   **Exaggeration**: nothing should be life-size; make it

                    colossal or microscopic, fast or slow-motion.

                *   **Sexuality**: use magnetism, romance, or tension if it

                    fits your picture (keep it tasteful and respectful).



                In practice: pick three of these for every image cue: one for

                what it does, one for how it looks, and one for how it links to

                the picture before it.

                """,
                elem_classes="ms-note",
            )

            with gr.Accordion("Optional AI status", open=False):
                gr.Markdown(model_status_markdown(hosted=PUBLIC_DEMO))
                gr.Markdown(image_model_status_markdown(hosted=PUBLIC_DEMO))

        with gr.TabItem("My library", id="library"):
            gr.Markdown(
                """

                ### Reviews that come back on time

                Save a story or card here and the library follows Buzan's review

                rhythm for you: about 10 minutes after you learn it, then 1 day,

                1 week, 1 month, and 4 months later. Recall each item from memory

                when it is due.

                """
            )
            library_summary = gr.Markdown(LIBRARY_EMPTY)
            library_table = gr.Dataframe(
                headers=["Name", "Type", "Next step", "Due", "Reviews done"],
                datatype=["str", "str", "str", "str", "str"],
                type="array",
                value=[],
                interactive=False,
                wrap=True,
            )
            with gr.Row(elem_classes="ms-stack"):
                library_pick = gr.Dropdown(
                    label="Item", choices=[], value=None, scale=3
                )
                library_review = gr.Button(
                    "Review this item",
                    variant="primary",
                    size="sm",
                    scale=0,
                    min_width=170,
                )
                library_remove = gr.Button(
                    "Remove from library",
                    variant="stop",
                    size="sm",
                    scale=0,
                    min_width=170,
                )
            library_status = gr.Markdown()
            gr.Markdown(
                "**How the schedule moves.** A review counts when the item is due. "
                "Recall every card and the item moves to the next step. Miss any "
                "card and it comes back tomorrow, restarting from the 1-day "
                "review, so repair the weak pictures first. After the 4-month "
                "review, the library checks it every 6 months.\n\n"
                "**Where it is kept.** Only in this browser's local storage, like "
                "your saved words. It is not written to the app's disk, and "
                "clearing site data removes it. Names are shown here instead of "
                "the content, so the list does not give the answers away."
                + (
                    " In the online version the library can reset when the Space "
                    "restarts."
                    if PUBLIC_DEMO and not os.getenv("MEMORY_BROWSER_SECRET")
                    else ""
                ),
                elem_classes="ms-muted",
            )

        with gr.TabItem("Numbers", id="numbers"):
            gr.Markdown(
                """

                ### 1 · Enter a number

                Leading zeros are kept. Up to 40 digits are split into chunks,

                each with one picture; the table order is locked to the digit

                order.

                """,
            )
            gr.Markdown(
                """

                #### ✨ Make every picture vivid: Buzan's golden rules

                Pick three rules per image cue:

                **Movement** (make it do something) • **Association** (link it

                to the picture before it) • **Sensuality** (give it a sound,

                smell, or feel) • **Humour** (make it funny or absurd)

                • **Imagination** (exaggerate: huge, glowing, upside-down)

                • **Number** (give it a position) • **Symbolism** (one clear

                object) • **Colour** (one bright colour) • **Order** (fixed

                sequence) • **Positive** (positive images last longer)

                • **Exaggeration** (colossal or microscopic) • **Sexuality**

                (magnetism or tension, tasteful and respectful).



                In practice: one rule for *what it does*, one for *how it looks*,

                one for *how it links to the previous picture*.

                """,
                elem_classes="ms-muted",
            )
            with gr.Row(elem_classes="ms-stack"):
                number_input = gr.Textbox(
                    label="Number",
                    placeholder="Try 314159, 0042, or 0412 555 019",
                    lines=1,
                    scale=4,
                )
                number_example = gr.Button(
                    "Try 314159", size="sm", scale=0, min_width=140
                )
            number_chunking = gr.Radio(
                label="How to split",
                choices=list(CHUNK_MODES),
                value=CHUNK_PAIRS,
                info=(
                    "Pairs use the 00-99 words. Threes give fewer, longer words "
                    "(314 = meter). Where I put spaces follows your own groups, "
                    "for example 0412 555 019 or 19/11/2026; a group of four or "
                    "more digits is split into pairs."
                ),
            )
            number_use_model = gr.Checkbox(
                label="Optional: draft rows with the local text model",
                value=False,
                info=(
                    "First AI draft may download public model weights. Leave "
                    "unchecked for the deterministic curated set."
                ),
            )
            number_generate = gr.Button(
                "Draft candidate rows", variant="primary"
            )
            number_status = gr.Markdown()
            number_table = gr.Dataframe(
                headers=NUMBER_HEADERS,
                datatype=["str"] * len(NUMBER_HEADERS),
                type="array",
                value=[],
                interactive=True,
                wrap=True,
                column_widths=["8%", "12%", "24%", "38%", "11%", "7%"],
                label="Review and edit every Word, Image cue, and Story line",
            )
            # The story lines the app generated last, to tell them from edits.
            number_story_lines = gr.State([])
            with gr.Accordion("My saved words (this browser)", open=False):
                gr.Markdown(
                    "After a story builds, **Save these words** remembers each "
                    "checked word as your personal default for that chunk. Drafts "
                    "use your saved words first, and the **00–99 trainer** tab "
                    "drills them. They are stored only in this browser's local "
                    "storage.",
                    elem_classes="ms-muted",
                )
                number_saved_table = gr.Dataframe(
                    headers=["Chunk", "Word", "Image cue"],
                    datatype=["str", "str", "str"],
                    type="array",
                    value=[],
                    interactive=False,
                    wrap=True,
                )
                number_forget = gr.Button(
                    "Forget all saved words", size="sm", variant="stop"
                )
            with gr.Accordion("Find other words for a chunk", open=False):
                with gr.Row(elem_classes="ms-stack"):
                    number_lookup_code = gr.Textbox(
                        label="Digits (1-4)",
                        placeholder="31",
                        max_lines=1,
                        scale=3,
                    )
                    number_lookup_button = gr.Button(
                        "Find words", size="sm", scale=0, min_width=140
                    )
                number_lookup_result = gr.Markdown()
            number_lookup_button.click(
                lookup_major_words,
                inputs=[number_lookup_code],
                outputs=[number_lookup_result],
            )
            number_lookup_code.submit(
                lookup_major_words,
                inputs=[number_lookup_code],
                outputs=[number_lookup_result],
            )
            with gr.Accordion(
                "Optional: anchor each image to a palace or pegs", open=False
            ):
                number_anchor = gr.Radio(
                    label="Anchor",
                    choices=list(ANCHOR_MODES),
                    value=ANCHOR_PALACE,
                    info=(
                        "A palace uses places you know. Pegs are fixed numbered "
                        "images, so you can jump straight to any position."
                    ),
                )
                with gr.Column() as number_palace_box:
                    (
                        number_route_pick,
                        number_route_delete,
                        number_palace,
                        number_route_name,
                        number_route_save,
                        number_route_note,
                    ) = _route_controls()
                number_anchor.change(
                    lambda mode: gr.update(visible=mode == ANCHOR_PALACE),
                    inputs=[number_anchor],
                    outputs=[number_palace_box],
                )
            with gr.Row():
                number_build = gr.Button(
                    "Check my edits and build the story",
                    variant="primary",
                    scale=3,
                )
            with gr.Group(visible=False) as number_illustrate_box:
                gr.Markdown(
                    "**Optional picture.** The story is the mnemonic; a picture "
                    "is a hint for one tricky scene. Pick a scene to open its cue "
                    "in the Image tab, where you can edit it and draw.",
                    elem_classes="ms-muted",
                )
                with gr.Row(elem_classes="ms-stack"):
                    number_scene = gr.Dropdown(
                        label="Scene to draw",
                        choices=[],
                        value=None,
                        scale=3,
                    )
                    number_illustrate = gr.Button(
                        "Open in Image tab",
                        size="sm",
                        scale=0,
                        min_width=180,
                    )
            number_story = gr.Markdown()

            with gr.Row(elem_classes="ms-stack"):
                number_library_name = gr.Textbox(
                    label="Name in My library (optional)",
                    placeholder="e.g. Pi, bike lock, Mum's phone",
                    max_lines=1,
                    scale=3,
                )
                number_library_save = gr.Button(
                    "Save to my library",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=180,
                )
            with gr.Row():
                number_practice = gr.Button(
                    "Practice these cards",
                    size="sm",
                    variant="primary",
                    scale=0,
                    min_width=180,
                )
                number_save_words = gr.Button(
                    "Save these words",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=160,
                )
                number_sheet_button = gr.Button(
                    "Download study sheet (.md)",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=200,
                )
                number_clear = gr.ClearButton(
                    [
                        number_input,
                        number_status,
                        number_table,
                        number_story,
                        number_palace,
                        number_library_name,
                    ],
                    value="Clear",
                    size="sm",
                    scale=0,
                    min_width=110,
                )
            number_sheet = gr.File(
                label="Study sheet",
                show_label=False,
                interactive=False,
                visible=False,
                file_count="multiple",
            )

            number_draft_outputs = [
                number_status,
                number_table,
                number_story,
                number_illustrate_box,
                number_scene,
                number_sheet,
                number_story_lines,
            ]
            for number_draft_event in (number_generate.click, number_input.submit):
                number_draft_event(
                    draft_number_view,
                    inputs=[
                        number_input,
                        number_use_model,
                        personal_words,
                        number_chunking,
                    ],
                    outputs=number_draft_outputs,
                )
            number_example.click(
                example_number_view,
                inputs=[personal_words, number_chunking],
                outputs=[number_input, number_use_model, *number_draft_outputs],
            )
            number_build.click(
                build_number_view,
                inputs=[
                    number_input,
                    number_table,
                    number_use_model,
                    number_anchor,
                    number_palace,
                    number_story_lines,
                    number_chunking,
                    palace_state,
                    library_state,
                ],
                outputs=[
                    number_status,
                    number_table,
                    number_story,
                    number_story_lines,
                    number_illustrate_box,
                    number_scene,
                    number_sheet,
                    palace_state,
                ],
            )
            number_clear.click(
                lambda: (
                    gr.Group(visible=False),
                    gr.Dropdown(choices=[], value=None),
                    _hidden_file(),
                ),
                inputs=None,
                outputs=[number_illustrate_box, number_scene, number_sheet],
            )
            number_sheet_button.click(
                _number_sheet, inputs=[number_story], outputs=[number_sheet]
            )

        with gr.TabItem("00–99 trainer", id="trainer"):
            gr.Markdown(
                """

                ### Make your number words automatic

                The Major System pays off once every number calls up the same

                word instantly, and every word its number. Drill a small range,

                then widen it. Answers are checked against your saved words, or

                the starter words where you have none.

                """
            )
            with gr.Row(elem_classes="ms-stack"):
                trainer_range = gr.Textbox(
                    label="Numbers to drill",
                    value="00-99",
                    placeholder="00-99, 00-19, 0-9, or 7, 42, 85",
                    max_lines=1,
                    scale=2,
                )
                trainer_direction = gr.Radio(
                    label="Direction",
                    choices=list(peg_trainer.DIRECTIONS),
                    value=peg_trainer.TO_WORD,
                    scale=2,
                )
                trainer_count = gr.Dropdown(
                    label="Cards",
                    choices=list(peg_trainer.COUNT_CHOICES),
                    value="20",
                    scale=1,
                    min_width=110,
                )
            with gr.Row(elem_classes="ms-stack"):
                trainer_hardest_first = gr.Checkbox(
                    label="Weakest numbers first (uses your past results)",
                    value=False,
                )
                trainer_start = gr.Button(
                    "Start drill", variant="primary", scale=0, min_width=170
                )
            trainer_progress = gr.Markdown()
            trainer_prompt = gr.Markdown(TRAINER_IDLE)
            with gr.Row(visible=False, elem_classes="ms-stack") as trainer_answer_row:
                trainer_answer = gr.Textbox(
                    label="Your answer",
                    max_lines=1,
                    scale=3,
                )
                trainer_check = gr.Button(
                    "Check", variant="primary", scale=0, min_width=110
                )
                trainer_skip = gr.Button(
                    "I don't know", scale=0, min_width=140
                )
            trainer_feedback = gr.Markdown(elem_classes="ms-answer")
            trainer_summary = gr.Markdown(visible=False)
            trainer_retry = gr.Button(
                "Retry the missed ones", variant="primary", visible=False
            )
            with gr.Accordion("Numbers you miss most (this browser)", open=False):
                gr.Markdown(
                    "Based on your last five answers for each number. Results "
                    "stay in this browser's local storage, like your saved words.",
                    elem_classes="ms-muted",
                )
                trainer_hardest_table = gr.Dataframe(
                    headers=["Number", "Word", "Last 5", "All time"],
                    datatype=["str", "str", "str", "str"],
                    type="array",
                    value=[],
                    interactive=False,
                    wrap=True,
                )
                with gr.Row():
                    trainer_reset = gr.Button(
                        "Clear trainer results", size="sm", variant="stop", scale=0
                    )
                    trainer_reset_status = gr.Markdown()
            trainer_state = gr.State({})

            trainer_session_outputs = [
                trainer_state,
                trainer_progress,
                trainer_prompt,
                trainer_feedback,
                trainer_answer,
                trainer_answer_row,
                trainer_summary,
                trainer_retry,
            ]

        with gr.TabItem("Word card", id="word"):
            gr.Markdown(
                """

                ### 1 · Enter a word or concept

                Add context or a definition **you trust** to keep the factual

                anchor honest. Without context, the app will not invent a

                definition: the card stays label-only and the meaning row remains

                an editing prompt.

                """
            )
            with gr.Row(elem_classes="ms-stack"):
                word_term = gr.Textbox(
                    label="Word or concept",
                    placeholder="Try a term, a name, or a short phrase",
                    lines=1,
                    scale=4,
                )
                word_example = gr.Button(
                    "Try “Pomodoro”", size="sm", scale=0, min_width=160
                )
            word_context = gr.Textbox(
                label="Optional context or definition you trust",
                placeholder=(
                    "Paste a definition from a source you trust, or a short note "
                    "about what this term means in your context."
                ),
                lines=4,
                info=(
                    "Used only as the factual anchor. Leave blank for a label-only "
                    "mnemonic."
                ),
            )
            word_use_model = gr.Checkbox(
                label="Optional: draft card fields with the local text model",
                value=False,
                info="Leave unchecked for an editable no-model worksheet.",
            )
            word_draft = gr.Button("Draft card fields", variant="primary")
            word_status = gr.Markdown()
            word_table = gr.Dataframe(
                headers=WORD_HEADERS,
                datatype=["str"] * len(WORD_HEADERS),
                type="array",
                value=[],
                interactive=True,
                wrap=True,
                column_widths=["32%", "68%"],
                label="Edit any field freely",
            )
            word_assemble = gr.Button("Assemble my card", variant="primary")
            word_card = gr.Markdown()

            with gr.Row():
                word_picture = gr.Button(
                    "Draw this card",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=160,
                )
                word_library_save = gr.Button(
                    "Save to my library",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=180,
                )
                word_sheet_button = gr.Button(
                    "Download study sheet (.md)",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=200,
                )
                word_clear = gr.ClearButton(
                    [
                        word_term,
                        word_context,
                        word_status,
                        word_table,
                        word_card,
                    ],
                    value="Clear",
                    size="sm",
                    scale=0,
                    min_width=110,
                )
            word_sheet = gr.File(
                label="Study sheet",
                show_label=False,
                interactive=False,
                visible=False,
                file_count="multiple",
            )

            word_draft.click(
                draft_word_fields,
                inputs=[word_term, word_context, word_use_model],
                outputs=[word_status, word_table, word_card],
            )
            word_term.submit(
                draft_word_fields,
                inputs=[word_term, word_context, word_use_model],
                outputs=[word_status, word_table, word_card],
            )
            word_example.click(
                _example_word,
                inputs=None,
                outputs=[
                    word_term,
                    word_context,
                    word_use_model,
                    word_status,
                    word_table,
                    word_card,
                ],
            )
            word_assemble.click(
                assemble_word_outputs,
                inputs=[word_term, word_context, word_table],
                outputs=[word_status, word_table, word_card],
            )
            word_sheet_button.click(
                _word_sheet, inputs=[word_card], outputs=[word_sheet]
            )
            for word_event in (
                word_draft.click,
                word_term.submit,
                word_assemble.click,
                word_example.click,
                word_clear.click,
            ):
                word_event(_hidden_file, inputs=None, outputs=[word_sheet])

        with gr.TabItem("Ordered list", id="list"):
            gr.Markdown(
                f"""

                ### 1 · Enter an ordered list

                Put one item per line, or use commas on a single line. Numbered and

                bulleted lists are accepted. Up to {MAX_LIST_ITEMS} items are

                supported. The table order is the story order; the build step

                refuses to silently drop an original item.

                """
            )
            list_input = gr.Textbox(
                label="Ordered list",
                placeholder="milk\neggs\ncoffee\n\nor: milk, eggs, coffee",
                lines=6,
            )
            list_use_model = gr.Checkbox(
                label="Optional: draft image cues with the local text model",
                value=False,
                info="Leave unchecked for editable creative prompts.",
            )
            with gr.Row(elem_classes="ms-stack"):
                list_generate = gr.Button(
                    "Draft image cues", variant="primary", scale=2
                )
                list_example = gr.Button(
                    "Try a grocery list", size="sm", scale=0, min_width=180
                )
            list_status = gr.Markdown()
            list_table = gr.Dataframe(
                headers=LIST_HEADERS,
                datatype=["str"] * len(LIST_HEADERS),
                type="array",
                value=[],
                interactive=True,
                wrap=True,
                column_widths=["6%", "20%", "30%", "44%"],
                label="Review and edit the image cues and story lines",
            )
            list_story_lines = gr.State([])
            with gr.Accordion(
                "Optional: anchor each image to a palace or pegs", open=False
            ):
                list_anchor = gr.Radio(
                    label="Anchor",
                    choices=list(ANCHOR_MODES),
                    value=ANCHOR_PALACE,
                    info=(
                        "A palace uses places you know. Pegs are fixed numbered "
                        "images, so you can jump straight to any position."
                    ),
                )
                with gr.Column() as list_palace_box:
                    (
                        list_route_pick,
                        list_route_delete,
                        list_palace,
                        list_route_name,
                        list_route_save,
                        list_route_note,
                    ) = _route_controls()
                list_anchor.change(
                    lambda mode: gr.update(visible=mode == ANCHOR_PALACE),
                    inputs=[list_anchor],
                    outputs=[list_palace_box],
                )
            list_build = gr.Button(
                "Check my edits and build the story", variant="primary"
            )
            with gr.Group(visible=False) as list_illustrate_box:
                gr.Markdown(
                    "**Optional picture.** The story is the mnemonic; a picture "
                    "is a hint for one tricky scene. Pick a scene to open its cue "
                    "in the Image tab, where you can edit it and draw.",
                    elem_classes="ms-muted",
                )
                with gr.Row(elem_classes="ms-stack"):
                    list_scene = gr.Dropdown(
                        label="Scene to draw",
                        choices=[],
                        value=None,
                        scale=3,
                    )
                    list_illustrate = gr.Button(
                        "Open in Image tab",
                        size="sm",
                        scale=0,
                        min_width=180,
                    )
            list_story = gr.Markdown()

            with gr.Row(elem_classes="ms-stack"):
                list_library_name = gr.Textbox(
                    label="Name in My library (optional)",
                    placeholder="e.g. Speech outline, Saturday shopping",
                    max_lines=1,
                    scale=3,
                )
                list_library_save = gr.Button(
                    "Save to my library",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=180,
                )
            with gr.Row():
                list_practice = gr.Button(
                    "Practice these cards",
                    size="sm",
                    variant="primary",
                    scale=0,
                    min_width=180,
                )
                list_sheet_button = gr.Button(
                    "Download study sheet (.md)",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=200,
                )
                list_clear = gr.ClearButton(
                    [
                        list_input,
                        list_status,
                        list_table,
                        list_story,
                        list_palace,
                        list_library_name,
                    ],
                    value="Clear",
                    size="sm",
                    scale=0,
                    min_width=110,
                )
            list_sheet = gr.File(
                label="Study sheet",
                show_label=False,
                interactive=False,
                visible=False,
                file_count="multiple",
            )

            list_draft_outputs = [
                list_status,
                list_table,
                list_story,
                list_illustrate_box,
                list_scene,
                list_sheet,
                list_story_lines,
            ]
            for list_draft_event in (list_generate.click, list_input.submit):
                list_draft_event(
                    draft_list_view,
                    inputs=[list_input, list_use_model],
                    outputs=list_draft_outputs,
                )
            list_example.click(
                example_list_view,
                inputs=None,
                outputs=[list_input, list_use_model, *list_draft_outputs],
            )
            list_build.click(
                build_list_view,
                inputs=[
                    list_input,
                    list_table,
                    list_use_model,
                    list_anchor,
                    list_palace,
                    list_story_lines,
                    palace_state,
                    library_state,
                ],
                outputs=[
                    list_status,
                    list_table,
                    list_story,
                    list_story_lines,
                    list_illustrate_box,
                    list_scene,
                    list_sheet,
                    palace_state,
                ],
            )
            list_clear.click(
                lambda: (
                    gr.Group(visible=False),
                    gr.Dropdown(choices=[], value=None),
                    _hidden_file(),
                ),
                inputs=None,
                outputs=[list_illustrate_box, list_scene, list_sheet],
            )
            list_sheet_button.click(
                _list_sheet, inputs=[list_story], outputs=[list_sheet]
            )

        with gr.TabItem("Names & dates", id="namesdates"):
            with gr.Tabs():
                with gr.TabItem("Names & faces", id="names"):
                    gr.Markdown(
                        """

                        ### Remember who is who

                        One person per line: **name | face feature | where you

                        met** (the last two are optional here, but each card needs

                        at least one). The app drafts a sound-alike for the name;

                        you link it to the feature you will see next time.

                        """
                    )
                    with gr.Row(elem_classes="ms-stack"):
                        people_input = gr.Textbox(
                            label="People",
                            placeholder=(
                                "Margaret Chen | big round glasses | finance team"
                            ),
                            lines=4,
                            scale=4,
                        )
                        people_example = gr.Button(
                            "Try an example", size="sm", scale=0, min_width=150
                        )
                    gr.Markdown(
                        "_Names are personal details. They stay in this session "
                        "unless you save the cards to My library in this "
                        "browser; the app never writes them to its disk or logs._",
                        elem_classes="ms-muted",
                    )
                    people_draft = gr.Button("Draft name cards", variant="primary")
                    people_status = gr.Markdown()
                    people_table = gr.Dataframe(
                        headers=names_dates.NAME_HEADERS,
                        datatype=["str"] * len(names_dates.NAME_HEADERS),
                        type="array",
                        value=[],
                        interactive=True,
                        wrap=True,
                        column_widths=["16%", "18%", "18%", "33%", "15%"],
                        label="Edit every face feature, sound-alike, and scene",
                    )
                    people_build = gr.Button(
                        "Check and build the cards", variant="primary"
                    )
                    people_card = gr.Markdown()
                    with gr.Row(elem_classes="ms-stack"):
                        people_library_name = gr.Textbox(
                            label="Name in My library (optional)",
                            placeholder="e.g. New team, Sam's party",
                            max_lines=1,
                            scale=3,
                        )
                        people_library_save = gr.Button(
                            "Save to my library",
                            size="sm",
                            scale=0,
                            min_width=180,
                        )
                    with gr.Row():
                        people_practice = gr.Button(
                            "Practice these cards",
                            size="sm",
                            variant="primary",
                            scale=0,
                            min_width=180,
                        )
                        people_sheet_button = gr.Button(
                            "Download study sheet (.md)",
                            size="sm",
                            scale=0,
                            min_width=200,
                        )
                    people_sheet = gr.File(
                        show_label=False,
                        interactive=False,
                        visible=False,
                        file_count="multiple",
                    )
                    people_draft.click(
                        draft_people,
                        inputs=[people_input],
                        outputs=[people_status, people_table, people_card],
                    )
                    people_example.click(
                        lambda: (PEOPLE_EXAMPLE, *draft_people(PEOPLE_EXAMPLE)),
                        inputs=None,
                        outputs=[people_input, people_status, people_table, people_card],
                    )
                    people_build.click(
                        build_people,
                        inputs=[people_input, people_table],
                        outputs=[people_status, people_table, people_card],
                    )
                    people_sheet_button.click(
                        lambda text: _study_sheet(text, "names-and-faces"),
                        inputs=[people_card],
                        outputs=[people_sheet],
                    )

                with gr.TabItem("Dates", id="dates"):
                    gr.Markdown(
                        """

                        ### Remember when it happened

                        One event per line: **event | date**. Years, numeric

                        dates, and month names work (1066, 14/03, 20 July 1969).

                        The digits keep the order you typed, become Major System

                        words (your saved words first), and link to the event.

                        """
                    )
                    with gr.Row(elem_classes="ms-stack"):
                        events_input = gr.Textbox(
                            label="Events",
                            placeholder="Battle of Hastings | 1066",
                            lines=4,
                            scale=4,
                        )
                        events_example = gr.Button(
                            "Try an example", size="sm", scale=0, min_width=150
                        )
                    events_draft = gr.Button("Draft date cards", variant="primary")
                    events_status = gr.Markdown()
                    events_table = gr.Dataframe(
                        headers=names_dates.DATE_HEADERS,
                        datatype=["str"] * len(names_dates.DATE_HEADERS),
                        type="array",
                        value=[],
                        interactive=True,
                        wrap=True,
                        column_widths=["18%", "14%", "12%", "18%", "38%"],
                        label="Edit the Words (one per chunk, comma-separated) and scenes",
                    )
                    events_build = gr.Button(
                        "Check and build the cards", variant="primary"
                    )
                    events_card = gr.Markdown()
                    with gr.Row(elem_classes="ms-stack"):
                        events_library_name = gr.Textbox(
                            label="Name in My library (optional)",
                            placeholder="e.g. History exam, Family birthdays",
                            max_lines=1,
                            scale=3,
                        )
                        events_library_save = gr.Button(
                            "Save to my library",
                            size="sm",
                            scale=0,
                            min_width=180,
                        )
                    with gr.Row():
                        events_practice = gr.Button(
                            "Practice these cards",
                            size="sm",
                            variant="primary",
                            scale=0,
                            min_width=180,
                        )
                        events_sheet_button = gr.Button(
                            "Download study sheet (.md)",
                            size="sm",
                            scale=0,
                            min_width=200,
                        )
                    events_sheet = gr.File(
                        show_label=False,
                        interactive=False,
                        visible=False,
                        file_count="multiple",
                    )
                    events_draft.click(
                        draft_events,
                        inputs=[events_input, personal_words],
                        outputs=[events_status, events_table, events_card],
                    )
                    events_example.click(
                        lambda saved: (EVENTS_EXAMPLE, *draft_events(EVENTS_EXAMPLE, saved)),
                        inputs=[personal_words],
                        outputs=[events_input, events_status, events_table, events_card],
                    )
                    events_build.click(
                        build_events,
                        inputs=[events_input, events_table],
                        outputs=[events_status, events_table, events_card],
                    )
                    events_sheet_button.click(
                        lambda text: _study_sheet(text, "dates"),
                        inputs=[events_card],
                        outputs=[events_sheet],
                    )

        with gr.TabItem("Mind Map", id="mindmap"):
            gr.Markdown(
                f"""

                ### Map a topic on one page

                The topic goes in the centre, main ideas become thick coloured

                branches, and details hang off thinner ones. Write **one key word

                per line**. Lines with no indent are main branches; indented lines

                (two spaces or a tab) are details of the line above. Up to

                {MAX_MAIN_BRANCHES} main branches with {MAX_SUB_BRANCHES} details

                each. No model is used.

                """
            )
            with gr.Row(elem_classes="ms-stack"):
                mind_topic = gr.Textbox(
                    label="Central topic",
                    placeholder="Memory",
                    max_lines=1,
                    scale=3,
                )
                mind_example = gr.Button(
                    "Try an example", size="sm", scale=0, min_width=160
                )
            mind_outline = gr.Textbox(
                label="Branches: one key word per line, details indented",
                placeholder="Imagination\n  colour\n  movement\nAssociation\n  link",
                lines=10,
            )
            mind_build = gr.Button("Draw my Mind Map", variant="primary")
            mind_status = gr.Markdown()
            mind_show = gr.Radio(
                label="Show",
                choices=list(MIND_VIEWS),
                value=MIND_VIEW_FULL,
                info=(
                    "Test yourself: hide the details or every branch word, "
                    "recall each ?, then switch back to check."
                ),
            )
            mind_view = gr.HTML()
            with gr.Row(elem_classes="ms-stack"):
                mind_library_name = gr.Textbox(
                    label="Name in My library (optional)",
                    placeholder="Defaults to the central topic",
                    max_lines=1,
                    scale=3,
                )
                mind_library_save = gr.Button(
                    "Save to my library", size="sm", scale=0, min_width=180
                )
            with gr.Row():
                mind_practice = gr.Button(
                    "Practice these cards",
                    size="sm",
                    variant="primary",
                    scale=0,
                    min_width=180,
                )
                mind_center = gr.Button(
                    "Draw a central image",
                    size="sm",
                    scale=0,
                    min_width=190,
                )
                mind_download = gr.Button(
                    "Download (.svg + .md)",
                    size="sm",
                    variant="secondary",
                    scale=0,
                    min_width=200,
                )
            mind_files = gr.File(
                label="Mind Map files",
                show_label=False,
                interactive=False,
                visible=False,
                file_count="multiple",
            )
            for mind_event in (mind_build.click, mind_topic.submit):
                mind_event(
                    build_mind_map_view,
                    inputs=[mind_topic, mind_outline, mind_show],
                    outputs=[mind_status, mind_view, mind_files],
                )
            # .input: only the learner's own switch redraws, not a reset below.
            mind_show.input(
                build_mind_map,
                inputs=[mind_topic, mind_outline, mind_show],
                outputs=[mind_status, mind_view],
            )
            mind_example.click(
                example_mind_map_view,
                inputs=None,
                outputs=[
                    mind_topic,
                    mind_outline,
                    mind_show,
                    mind_status,
                    mind_view,
                    mind_files,
                ],
            )
            mind_download.click(
                mind_map_files,
                inputs=[mind_topic, mind_outline],
                outputs=[mind_files],
            )

        with gr.TabItem("Practice", id="practice"):
            gr.Markdown(
                """

                ### Test yourself, in order

                The best way in is **Practice these cards** in any builder

                (Numbers, Ordered list, Names & dates, Mind Map), or **Review

                this item** in My library: they use your own words and cues. You

                can also paste a number or list here; a pasted number uses your

                saved words, else the starter words. No model is involved.

                """
            )
            with gr.Row(elem_classes="ms-stack"):
                practice_kind = gr.Dropdown(
                    label="What are you practicing?",
                    choices=list(PRACTICE_KINDS),
                    value=PRACTICE_NUMBER,
                    scale=1,
                )
                practice_text = gr.Textbox(
                    label="Number or ordered list",
                    placeholder="314159   or   milk, eggs, coffee",
                    lines=3,
                    scale=2,
                )
            with gr.Row(elem_classes="ms-stack"):
                practice_start_btn = gr.Button(
                    "Start practice", variant="primary", scale=2
                )
                practice_example_btn = gr.Button(
                    "Try 314159", size="sm", scale=0, min_width=150
                )
            practice_progress = gr.Markdown()
            practice_prompt = gr.Markdown(
                "**Enter a number or list above, then click Start practice.** "
                "Cards stay in the original order and are never scored on a server."
            )
            practice_answer = gr.Markdown(
                visible=False, elem_classes="ms-answer"
            )
            practice_reveal = gr.Button("Reveal answer", visible=False)
            with gr.Row(visible=False) as practice_grade_row:
                practice_knew_btn = gr.Button("I knew it", variant="primary")
                practice_missed_btn = gr.Button("Missed it")
            practice_summary = gr.Markdown(visible=False)
            practice_state = gr.State({})

            practice_outputs = [
                practice_state,
                practice_progress,
                practice_prompt,
                practice_answer,
                practice_reveal,
                practice_grade_row,
                practice_summary,
            ]
            practice_start_btn.click(
                start_practice,
                inputs=[practice_kind, practice_text, personal_words],
                outputs=practice_outputs,
            )
            practice_text.submit(
                start_practice,
                inputs=[practice_kind, practice_text, personal_words],
                outputs=practice_outputs,
            )
            practice_reveal.click(
                reveal_practice,
                inputs=[practice_state],
                outputs=[
                    practice_state,
                    practice_answer,
                    practice_reveal,
                    practice_grade_row,
                ],
            )
            library_view_outputs = [
                library_summary,
                library_table,
                library_pick,
                start_due,
                start_open_library,
            ]
            practice_knew_btn.click(
                lambda state, library: grade_and_record(state, library, True),
                inputs=[practice_state, library_state],
                outputs=[*practice_outputs, library_state, *library_view_outputs],
            )
            practice_missed_btn.click(
                lambda state, library: grade_and_record(state, library, False),
                inputs=[practice_state, library_state],
                outputs=[*practice_outputs, library_state, *library_view_outputs],
            )
            practice_example_btn.click(
                start_practice_example,
                inputs=None,
                outputs=[practice_kind, practice_text, *practice_outputs],
            )

        image_intro_note = (
            "This Space preloads the weights at startup "
            f"({IMAGE_MODEL_DOWNLOAD_NOTE}) and runs them on a shared free GPU; "
            "a busy queue or the daily GPU quota can delay a picture."
            if PUBLIC_DEMO
            else (
                f"First use downloads public weights ({IMAGE_MODEL_DOWNLOAD_NOTE}). "
                f"On CPU, {DEFAULT_IMAGE_SIZE} × {DEFAULT_IMAGE_SIZE} with "
                f"{DEFAULT_IMAGE_STEPS} steps is a practical starting point; larger "
                "sizes and more steps take longer. Everything stays on this computer."
            )
        )
        with gr.TabItem("Image (optional)", id="image"):
            gr.Markdown(
                f"""

                ### Draw a mnemonic image from a cue

                Paste an image cue from a story, or write a new scene. In the

                Numbers or Ordered list tab, build the story first, then pick a

                scene and click **Open in Image tab** to send its cue here.

                Draw one scene at a time: the image model reads only about 75

                tokens (roughly 50 words), so long cues are shortened and the

                dropped words are listed.



                This tab is **optional**: the text-only and no-model routes never

                load the image model.



                **Model:** `{IMAGE_MODEL_ID}`. {image_intro_note}

                """
            )
            gr.Markdown(image_model_status_markdown(hosted=PUBLIC_DEMO))
            gr.HTML(
                """

                <div class="ms-note">

                  <strong>Cue-writing tips</strong>

                  <ul class="ms-muted" style="margin:.4rem 0 0; padding-left:1.1rem;">

                    <li>Name one subject, one action, and one place; extra detail

                    often gets dropped.</li>

                    <li>Make it exaggerated: huge, glowing, floating, or absurd.</li>

                    <li>Keep the digits or item order in the story, not in the

                    picture. The image is a cue, not a definition.</li>

                  </ul>

                </div>

                """
            )
            with gr.Row(elem_classes="ms-stack"):
                image_cue = gr.Textbox(
                    label="Image cue / scene",
                    placeholder=(
                        "Try: a giant wedge of cheese wearing a golden crown, "
                        "dancing on a rooftop at sunset"
                    ),
                    lines=3,
                    scale=3,
                )
                with gr.Column(scale=2):
                    image_style = gr.Dropdown(
                        label="Visual style",
                        choices=list(IMAGE_STYLES),
                        value=IMAGE_STYLES[0],
                    )
                    image_size = gr.Dropdown(
                        label="Size",
                        choices=list(IMAGE_SIZE_OPTIONS),
                        value=_size_option(DEFAULT_IMAGE_SIZE),
                    )
                    image_steps = gr.Slider(
                        label="Denoising steps",
                        minimum=MIN_IMAGE_STEPS,
                        maximum=MAX_IMAGE_STEPS,
                        step=1,
                        value=DEFAULT_IMAGE_STEPS,
                        info=(
                            "More steps can add detail but take longer. "
                            + (
                                "The shared GPU handles this quickly."
                                if PUBLIC_DEMO
                                else f"On CPU, {DEFAULT_IMAGE_STEPS} steps is a practical starting point."
                            )
                        ),
                    )
                    image_seed = gr.Number(
                        label="Seed (-1 = random)",
                        value=-1,
                        precision=0,
                        info="Keep a seed to reproduce or compare an image.",
                    )
            with gr.Row(elem_classes="ms-stack"):
                image_draw = gr.Button(
                    "Draw on this Space" if PUBLIC_DEMO else "Draw locally",
                    variant="primary",
                    scale=2,
                )
                image_example = gr.Button("Example: crown cheese", size="sm")
                image_example_two = gr.Button("Example: red doormat", size="sm")
            image_status = gr.Markdown()
            image_output = gr.Image(
                label="Image draft" if PUBLIC_DEMO else "Local image draft",
                type="pil",
                height=420,
                interactive=False,
                buttons=["download", "fullscreen"],
                elem_id="ms-image",
            )
            image_history = gr.State([])
            with gr.Accordion(
                "Recent drafts (this session, newest first)", open=False
            ):
                image_gallery = gr.Gallery(
                    label="Recent drafts",
                    columns=4,
                    height=260,
                    object_fit="cover",
                    show_label=False,
                    interactive=False,
                )
                gr.Markdown(
                    "Only the last eight drafts are kept in this browser "
                    "session. Download any picture you want to keep.",
                    elem_classes="ms-muted",
                )

            number_illustrate.click(
                illustrate_scene,
                inputs=[number_scene],
                outputs=[tabs, image_cue],
            )
            list_illustrate.click(
                illustrate_scene,
                inputs=[list_scene],
                outputs=[tabs, image_cue],
            )

            image_draw.click(
                draw_and_keep,
                concurrency_limit=1,
                inputs=[
                    image_cue,
                    image_style,
                    image_size,
                    image_steps,
                    image_seed,
                    image_history,
                ],
                outputs=[image_status, image_output, image_history, image_gallery],
            ).then(
                # Bring the finished picture into view. Inside a host frame this
                # scrolls the app, so a draft added below the fold is seen at once.
                fn=None,
                js="() => { const el = document.getElementById('ms-image'); if (el) el.scrollIntoView({ block: 'center', behavior: 'smooth' }); }",
            )
            image_example.click(load_example_image_cue, outputs=[image_cue])
            image_example_two.click(load_second_image_cue, outputs=[image_cue])

            with gr.Accordion("Image model, license, and limits", open=False):
                gr.Markdown(
                    f"""

                    - **Model:** `{IMAGE_MODEL_ID}`

                    - **License:** {IMAGE_MODEL_LICENSE_NOTE}

                    - **Model card:** <{IMAGE_MODEL_CARD_URL}>

                    - **First use:** downloads {IMAGE_MODEL_DOWNLOAD_NOTE} of public

                      weights; later runs use the local cache. No token or account

                      is required for this public repository.

                    - **Device:** CUDA or Apple MPS if available, otherwise CPU.

                      CPU generation can take tens of seconds to a few minutes.

                    - **Resources:** expect a few GB of RAM while the model is

                      loaded. Close other memory-heavy apps if generation fails.

                    - **Safety:** this model does **not** bundle a safety checker

                      when loaded here. It can produce distorted or inappropriate

                      images and may reflect biases in its training data. Treat

                      outputs as personal memory sketches, not factual

                      illustrations, and follow the license use restrictions.

                    - **Privacy:** the app does not print or save your cue.

                      Images are displayed by the local Gradio server and are not

                      uploaded; use the download button if you want to keep one.

                    """
                )

        with gr.TabItem("Guide & privacy", id="guide"):
            gr.Markdown(
                re.sub(
                    r"(?m)^ {16}",
                    "",
                    f"""

                ## How to use the workbench



                1. **Draft** suggestions with the no-model route or the optional

                   local text model. The **Start here** tab fills in an example

                   with one click.

                2. **Inspect and edit** the table. Replace any word, image, or cue

                   with a personal association.

                3. **Build** the story. The app re-checks number words, refuses to

                   silently drop list items, and writes a linked story: each image

                   does something to the previous one, with a sound or feeling.

                   Rewrite any line in the **Story line** column and rebuild; your

                   lines are kept. The story is the mnemonic.

                4. **Anchor** (optional) each image to a Memory Palace route you

                   know, or to a peg system: Number-Rhyme (1 bun, 2 shoe...),

                   Number-Shape (1 candle, 2 swan...), or Major System pegs.

                5. **Practice** with **Practice these cards**. Each card asks for

                   the next image in the chain, then the digits it encodes. Say the

                   answer out loud, reveal it, and mark whether you knew it.

                6. **Review** on the schedule shown under each story: about 10

                   minutes after learning, then 1 day, 1 week, 1 month, and 3-6

                   months later. The download includes a calendar file with the

                   dates.

                7. **Optionally draw a scene.** Pick one scene under a built story

                   and click **Open in Image tab**. **Whole chain in one picture**

                   is offered for every story (long chains use a compact list of

                   the key pictures, plus parts of four). The Word card has

                   **Draw this card**. Pictures are hints, not a replacement for

                   the story.



                **Numbers:** after a story builds, **Save these words** keeps your

                words in this browser, so your personal 00-99 list grows as you

                use it. **Find other words for a chunk** lists common dictionary

                words for any 1-4 digits. The **00–99 trainer** drills those

                words both ways, times each answer, and remembers which numbers

                you miss most.



                **Names & dates:** for names, pick one face feature and link a

                sound-alike of the name to it; practice runs face to name. For

                dates, the digits become your Major words, linked to the event.



                **Mind Map:** put a topic in the centre and one key word per line

                on branches. Indented lines become details. To review, set

                **Show** to hide the details or every branch, recall each **?**,

                then switch back; or use **Practice these cards** and save the

                map to **My library**.



                The deterministic route is the reliable baseline: curated Major

                words, a linked story, palace or peg anchors, Mind Maps, and

                recall prompts. The models only add optional drafts.



                ## Keep your work



                Each builder has **Download study sheet (.md)**. It writes the

                story, anchors, recall prompt, and review schedule (or the

                assembled word card) to a Markdown file, plus a calendar file

                (.ics) with the review dates. The Mind Map downloads as .svg and

                .md. Drafts are not saved automatically: if you close the page

                without downloading, they are gone. The only things kept are the

                word list, the **My library** items and palace routes you choose

                to save, and the trainer's per-number results, in this browser's

                local storage. The library shows which reviews are due, so you

                can skip the calendar file if you prefer.

                Pictures use the image download button, and only the last eight

                stay in the in-session gallery.



                ## Common questions



                **Do I need to download a model?**

                No. Curated Major-System words, ordered stories, Memory Palace

                routes, study sheets, and practice all work with no model at all.

                Models are opt-in extras.



                **Is anything saved or sent anywhere?**

                {"This online version processes what you type on this Space's servers. The app does not save it, but a hosted page cannot promise on-device privacy: do not paste secrets or private notes. Run the app locally for that." if PUBLIC_DEMO else f"{BIND_NOTE} The app does not intentionally log or save your study material. Inference stays on this computer after any model download."}

                Study-sheet files are temporary display files; download the ones

                you want to keep.



                **Why did a word fail the Major System check?**

                The Major System maps consonant **sounds**. The check looks the

                word up in the CMU Pronouncing Dictionary (American English) and

                shows what it reads, for example "dictionary reads 626" for

                *change*. Words it does not know fall back to an approximate

                spelling check. If your accent differs, say the word aloud and

                choose one that fits your pronunciation.



                **Why does a picture miss part of my cue?**

                Small image models are impressionistic. Shorten the cue,

                change the seed, add steps, or edit the scene. The picture is a

                visual draft, never evidence.



                **Can I use my own associations?**

                Yes, that is the point. Every word, cue, palace stop, and card

                field is editable. Personal images usually work better than

                generic ones.



                ## Major System reference



                {MAJOR_HELP}



                ## Optional text model



                - **Model ID:** `{MODEL_ID}`

                - **License:** {MODEL_LICENSE_NOTE}

                - **First use:** downloads public model weights from Hugging Face;

                  later runs use the {"Space's" if PUBLIC_DEMO else "local"} cache.

                  No token or account is required for these public repositories.

                - **Default size:** SmolLM2-360M-Instruct. The download is roughly

                  0.7 GB; expect higher runtime memory. CPU works but is slower.

                - **Larger option:** set `MEMORY_MODEL` to

                  `HuggingFaceTB/SmolLM2-1.7B-Instruct` for a larger draft model.

                  The download is roughly 3.4 GB; a CUDA or Apple-silicon GPU is

                  helpful and more RAM is needed.

                - **Device:** selected when weights load (CUDA or MPS if available,

                  otherwise CPU). {"Drafts run on this Space's servers, not on your device." if PUBLIC_DEMO else "All inference stays on this computer."}

                - **Dependencies:** {"available in this environment" if dependencies_available() else "not installed; the no-model route is active"}.



                The model files are public, but check the current Hugging Face model

                card for the exact license and usage terms before redistributing

                weights or building a product around them.



                ## Optional image model



                - **Model ID:** `{IMAGE_MODEL_ID}`

                - **License:** {IMAGE_MODEL_LICENSE_NOTE}

                - **Model card:** <{IMAGE_MODEL_CARD_URL}>

                - **First use:** downloads {IMAGE_MODEL_DOWNLOAD_NOTE} of public

                  weights; later runs use the {"Space's" if PUBLIC_DEMO else "local"}

                  cache. No token or account is required.

                - **Speed:** {"The online version runs the model on a shared free GPU; busy periods may queue and a daily quota applies." if PUBLIC_DEMO else f"{DEFAULT_IMAGE_SIZE} × {DEFAULT_IMAGE_SIZE} with {DEFAULT_IMAGE_STEPS} steps is a practical CPU starting point; larger sizes and more steps take longer. A CUDA or Apple-silicon GPU is much faster."}

                - **Limits:** small image models are impressionistic, may omit or

                  distort parts of the cue, and have no bundled safety checker.

                  Treat every picture as an editable visual draft, not a factual

                  illustration.

                - **Dependencies:** {"available in this environment" if image_dependencies_available() else "not installed; the text-only route remains active"}.



                ## Privacy



                {PRIVACY_SECTION}



                ## Accuracy and limits



                - The Major System maps **sounds**, not letters. The checker uses

                  the CMU Pronouncing Dictionary (American English), and an

                  approximate spelling check only for words it does not contain.

                  Read every word aloud in your own accent.

                - A failing candidate is never silently accepted. The number build

                  stops until every chunk has a matching word.

                - Image cues and stories are memory aids, not definitions. This app

                  does not verify technical meanings.

                - AI images are optional visual drafts. They can change or omit

                  details and may reflect model biases; they are not evidence or

                  factual illustrations.

                - The story has one line per row, in order, with each key word in

                  bold, so nothing is dropped. A model-written line is used only if

                  it names its own image; only the bold words carry digits.

                - The review schedule lists dates and a calendar file; the app

                  does not track your reviews or send reminders.

                - Data: CMUdict (BSD-style license) and a common-word frequency list

                  derived from the public-domain 12dicts lists are bundled in

                  `data/` with their notices.



                ## Curated starting words



                These are suggestions to edit, not an official vocabulary. Each

                passes the dictionary check; pronounce each word and replace

                anything that does not fit your accent or personal imagery.

                """,
                )
            )
            with gr.Accordion("Browse the curated 00-99 words", open=False):
                gr.Dataframe(
                    headers=["Chunk", "Word", "Image cue"],
                    datatype=["str", "str", "str"],
                    type="array",
                    value=curated_major_rows(),
                    interactive=False,
                    wrap=True,
                )

    start_numbers.click(
        start_with_numbers,
        inputs=[personal_words, number_chunking],
        outputs=[tabs, number_input, number_use_model, *number_draft_outputs],
    )
    start_list.click(
        start_with_list,
        inputs=None,
        outputs=[tabs, list_input, list_use_model, *list_draft_outputs],
    )
    start_word.click(
        start_with_word,
        inputs=None,
        outputs=[
            tabs,
            word_term,
            word_context,
            word_use_model,
            word_status,
            word_table,
            word_card,
        ],
    )
    word_picture.click(
        word_card_scene,
        inputs=[word_term, word_context, word_table],
        outputs=[tabs, image_cue],
    )
    mind_center.click(
        mind_map_center_cue, inputs=[mind_topic], outputs=[tabs, image_cue]
    )
    start_mind_map.click(
        lambda: (gr.Tabs(selected="mindmap"), *example_mind_map_view()),
        inputs=None,
        outputs=[
            tabs,
            mind_topic,
            mind_outline,
            mind_show,
            mind_status,
            mind_view,
            mind_files,
        ],
    )
    mind_practice.click(
        practice_mind_map,
        inputs=[mind_topic, mind_outline],
        outputs=[tabs, mind_status, practice_kind, practice_text, *practice_outputs],
    )
    mind_library_save.click(
        save_mind_map_to_library,
        inputs=[mind_topic, mind_outline, mind_library_name, library_state],
        outputs=[library_state, mind_status, *library_view_outputs],
    )
    number_save_words.click(
        save_number_words,
        inputs=[number_input, number_table, personal_words, number_chunking],
        outputs=[personal_words, number_status, number_saved_table],
    )
    number_forget.click(
        forget_saved_words,
        inputs=None,
        outputs=[personal_words, number_status, number_saved_table],
    )
    demo.load(
        load_browser_views,
        inputs=[personal_words, library_state, palace_state, trainer_stats],
        outputs=[
            number_saved_table,
            *library_view_outputs,
            number_route_pick,
            list_route_pick,
            trainer_hardest_table,
        ],
    )
    for (
        route_pick,
        route_delete,
        route_stops,
        route_name_box,
        route_save,
        route_note,
        route_anchor,
    ) in (
        (
            number_route_pick,
            number_route_delete,
            number_palace,
            number_route_name,
            number_route_save,
            number_route_note,
            number_anchor,
        ),
        (
            list_route_pick,
            list_route_delete,
            list_palace,
            list_route_name,
            list_route_save,
            list_route_note,
            list_anchor,
        ),
    ):
        # .input fires only when the learner picks, not when the list refreshes.
        route_pick.input(
            use_saved_route,
            inputs=[route_pick, palace_state],
            outputs=[route_anchor, route_stops, route_name_box, route_note],
        )
        route_save.click(
            save_route_handler,
            inputs=[route_name_box, route_stops, palace_state],
            outputs=[palace_state, number_route_pick, list_route_pick, route_note],
        )
        route_name_box.submit(
            save_route_handler,
            inputs=[route_name_box, route_stops, palace_state],
            outputs=[palace_state, number_route_pick, list_route_pick, route_note],
        )
        route_delete.click(
            delete_route_handler,
            inputs=[route_pick, palace_state],
            outputs=[palace_state, number_route_pick, list_route_pick, route_note],
        )
    trainer_start_inputs = [
        trainer_range,
        trainer_direction,
        trainer_count,
        trainer_hardest_first,
        personal_words,
        trainer_stats,
    ]
    trainer_start.click(
        start_trainer, inputs=trainer_start_inputs, outputs=trainer_session_outputs
    )
    trainer_range.submit(
        start_trainer, inputs=trainer_start_inputs, outputs=trainer_session_outputs
    )
    trainer_check_outputs = [
        trainer_state,
        trainer_stats,
        trainer_progress,
        trainer_prompt,
        trainer_feedback,
        trainer_answer,
        trainer_answer_row,
        trainer_summary,
        trainer_retry,
        trainer_hardest_table,
    ]
    for trainer_event in (trainer_check.click, trainer_answer.submit):
        trainer_event(
            check_trainer_answer,
            inputs=[trainer_state, trainer_answer, trainer_stats, personal_words],
            outputs=trainer_check_outputs,
        )
    trainer_skip.click(
        lambda state, stats, saved: check_trainer_answer(state, "", stats, saved),
        inputs=[trainer_state, trainer_stats, personal_words],
        outputs=trainer_check_outputs,
    )
    trainer_retry.click(
        retry_trainer_misses,
        inputs=[trainer_state],
        outputs=trainer_session_outputs,
    )
    trainer_reset.click(
        reset_trainer_stats,
        inputs=None,
        outputs=[trainer_stats, trainer_hardest_table, trainer_reset_status],
    )
    start_trainer_card.click(
        start_with_trainer,
        inputs=[personal_words, trainer_stats],
        outputs=[
            tabs,
            trainer_range,
            trainer_direction,
            trainer_count,
            trainer_hardest_first,
            *trainer_session_outputs,
        ],
    )
    start_names_card.click(
        lambda: (
            gr.Tabs(selected="namesdates"),
            PEOPLE_EXAMPLE,
            *draft_people(PEOPLE_EXAMPLE),
        ),
        inputs=None,
        outputs=[tabs, people_input, people_status, people_table, people_card],
    )
    number_library_save.click(
        save_number_to_library,
        inputs=[
            number_input,
            number_table,
            number_library_name,
            library_state,
            number_chunking,
        ],
        outputs=[library_state, number_status, *library_view_outputs],
    )
    list_library_save.click(
        save_list_to_library,
        inputs=[list_input, list_table, list_library_name, library_state],
        outputs=[library_state, list_status, *library_view_outputs],
    )
    word_library_save.click(
        lambda term, context, table, library: save_word_to_library(
            term, context, table, "", library
        ),
        inputs=[word_term, word_context, word_table, library_state],
        outputs=[library_state, word_status, *library_view_outputs],
    )
    library_review.click(
        review_library_item,
        inputs=[library_pick, library_state],
        outputs=[tabs, library_status, *practice_outputs],
    )
    library_remove.click(
        remove_library_item,
        inputs=[library_pick, library_state],
        outputs=[library_state, library_status, *library_view_outputs],
    )
    start_open_library.click(
        lambda: gr.Tabs(selected="library"), inputs=None, outputs=[tabs]
    )
    number_practice.click(
        practice_number_table,
        inputs=[number_input, number_table, number_chunking],
        outputs=[tabs, number_status, practice_kind, practice_text, *practice_outputs],
    )
    list_practice.click(
        practice_list_table,
        inputs=[list_input, list_table],
        outputs=[tabs, list_status, practice_kind, practice_text, *practice_outputs],
    )
    people_practice.click(
        practice_people,
        inputs=[people_input, people_table],
        outputs=[tabs, people_status, practice_kind, practice_text, *practice_outputs],
    )
    events_practice.click(
        practice_events,
        inputs=[events_input, events_table],
        outputs=[tabs, events_status, practice_kind, practice_text, *practice_outputs],
    )
    people_library_save.click(
        save_people_to_library,
        inputs=[people_input, people_table, people_library_name, library_state],
        outputs=[library_state, people_status, *library_view_outputs],
    )
    events_library_save.click(
        save_events_to_library,
        inputs=[events_input, events_table, events_library_name, library_state],
        outputs=[library_state, events_status, *library_view_outputs],
    )
    start_practice_card.click(
        start_with_practice,
        inputs=None,
        outputs=[
            tabs,
            practice_kind,
            practice_text,
            *practice_outputs,
        ],
    )

    gr.Markdown(
        f"""

        ---

        **No paid API · editable output.**

        **Text model:** `{MODEL_ID}` (optional; no-model mode always available).  

        **Image model:** `{IMAGE_MODEL_ID}` (optional; text-only route always available).  

        {"**Privacy:** online version; submissions are processed on this Space's servers, not on your device." if PUBLIC_DEMO else ("**Privacy:** localhost only; " if LOCAL_ONLY else f"**Privacy:** listening on `{LISTEN_HOST}` (your network); ") + "no sharing link; submitted text and image cues are not intentionally logged or saved."}

        """
    )


# A hosted Space pays the model download during startup, so the first visitor's
# Draw is fast and fits inside one ZeroGPU window. Local runs stay lazy.
if PUBLIC_DEMO:
    # Text generation needs a GPU window on ZeroGPU, like image drawing.
    use_zero_gpu()
    # Out of GPU quota? The backup text model answers on CPU; say so.
    local_llm.on_fallback = lambda: gr.Warning(
        "The free GPU allowance is used up, so the smaller backup model "
        "(SmolLM2-360M, on CPU) wrote this draft. Its lines may be weaker."
    )
    warm_up_text_model()
    warm_up_image_model()


if __name__ == "__main__":
    # Local runs stay private to this computer. A hosted Space must bind 0.0.0.0.
    host = LISTEN_HOST
    port_text = (
        os.getenv("MEMORY_STUDIO_PORT") or os.getenv("PORT") or ""
    ).strip()
    server_port = int(port_text) if port_text.isdigit() else None
    demo.queue(default_concurrency_limit=QUEUE_CONCURRENCY).launch(
        server_name=host,
        server_port=server_port,
        share=False,
        show_error=False,
        theme=APP_THEME,
        css=APP_CSS,
        head=APP_HEAD,
    )