File size: 69,396 Bytes
f72f54e
 
9d22294
921d7f6
f72f54e
9d22294
f72f54e
41a3f6b
48d1717
d05b639
 
f72f54e
a923c19
f72f54e
 
 
 
35f2e3b
f72f54e
d05b639
f72f54e
 
 
 
35f2e3b
f72f54e
 
 
 
 
 
6710ea1
 
 
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f72f54e
 
41a3f6b
 
1ca8e19
 
41a3f6b
84b4cba
6710ea1
35f2e3b
41a3f6b
6710ea1
 
 
 
 
79c2c78
f72f54e
79c2c78
a95f296
 
 
79c2c78
a95f296
 
 
 
6710ea1
 
 
 
a95f296
 
 
 
 
79c2c78
a95f296
 
 
 
 
 
79c2c78
6710ea1
a95f296
 
 
 
f32d42c
d19068b
 
 
b8ab7ec
d19068b
 
f32d42c
 
 
 
d19068b
 
 
 
b8ab7ec
d19068b
 
f32d42c
 
 
 
d19068b
 
 
4ed989e
 
 
a1018e3
4ed989e
 
 
 
 
 
 
 
 
38c87e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79c2c78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e898b4a
 
 
 
 
 
 
 
 
41a3f6b
84b4cba
e898b4a
 
 
 
 
 
 
 
 
 
41a3f6b
718f2c4
e898b4a
41a3f6b
 
 
 
 
 
 
9d22294
e898b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
6710ea1
 
 
 
 
 
 
 
e898b4a
 
 
 
 
 
6710ea1
 
 
 
35f2e3b
41a3f6b
6710ea1
 
e898b4a
 
 
 
 
 
bf25028
84b4cba
bf25028
 
 
 
 
 
22a9857
84b4cba
22a9857
 
 
 
 
 
57908c8
bf25028
 
 
 
 
 
6710ea1
bf25028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
f1d674e
ce52764
bf25028
 
 
22a9857
bf25028
57908c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb88a58
57908c8
 
bf25028
57908c8
 
 
eee651b
 
 
5b2e87d
eee651b
 
 
 
 
 
084291e
 
ee41e50
 
 
 
5b2e87d
 
 
 
 
 
 
eee651b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b2e87d
 
 
 
 
 
eee651b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
eee651b
084291e
eee651b
 
 
ee41e50
 
 
 
 
 
eee651b
 
 
 
 
 
 
 
 
 
8b872c3
 
 
 
a923c19
 
8b872c3
ee41e50
8b872c3
 
 
 
 
d7543f6
8b872c3
 
 
 
 
 
 
8e3b4ed
 
 
 
 
 
dfd3402
8e3b4ed
 
 
 
 
5b9a6bf
8e3b4ed
5866c3e
 
 
 
 
 
 
 
 
 
 
 
8e3b4ed
 
 
 
 
 
 
 
 
 
a13e743
8e3b4ed
 
 
 
 
3b1f921
8e3b4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a95f296
 
 
d1cf993
 
 
 
 
 
 
 
a95f296
 
d19068b
a95f296
79c2c78
e898b4a
57908c8
8e3b4ed
4ed989e
38c87e2
a95f296
 
f72f54e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6710ea1
f72f54e
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
f72f54e
 
 
 
48d1717
 
 
 
6710ea1
 
 
 
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
921d7f6
 
 
 
41a3f6b
8ed88b6
921d7f6
 
 
 
 
9d22294
41a3f6b
921d7f6
 
41a3f6b
8ed88b6
41a3f6b
8ed88b6
 
 
 
 
41a3f6b
8ed88b6
41a3f6b
 
 
 
 
 
8ed88b6
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
8ed88b6
 
41a3f6b
 
 
 
 
9d22294
8ed88b6
 
41a3f6b
 
921d7f6
 
 
 
6710ea1
 
41a3f6b
 
6710ea1
35f2e3b
 
 
41a3f6b
 
 
 
 
6710ea1
41a3f6b
35f2e3b
6710ea1
41a3f6b
6710ea1
41a3f6b
 
 
 
6710ea1
 
 
 
 
41a3f6b
6710ea1
 
 
41a3f6b
 
6710ea1
 
 
 
41a3f6b
 
6710ea1
41a3f6b
6710ea1
 
 
41a3f6b
6710ea1
 
 
 
 
 
 
 
 
921d7f6
 
 
6710ea1
921d7f6
 
 
 
 
 
 
 
6710ea1
921d7f6
 
 
 
cf4bbc0
 
 
 
 
 
 
ce52764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a3f6b
 
ce52764
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
 
 
41a3f6b
 
ce52764
 
 
 
 
 
 
 
41a3f6b
ce52764
 
41a3f6b
 
 
 
 
 
 
 
 
9d22294
41a3f6b
 
 
 
 
 
 
 
 
9d22294
 
 
 
 
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
 
 
9d22294
cf4bbc0
9d22294
cf4bbc0
 
 
 
 
41a3f6b
 
cf4bbc0
9d22294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf4bbc0
9d22294
 
 
f72f54e
 
d05b639
 
9d22294
41a3f6b
d05b639
f72f54e
41a3f6b
d05b639
9d22294
41a3f6b
 
 
9d22294
 
 
 
 
 
 
 
 
 
 
 
f72f54e
 
 
 
 
48d1717
f72f54e
41a3f6b
9d22294
 
 
 
 
 
 
 
 
 
 
 
f72f54e
 
6710ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d22294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6710ea1
 
 
 
b8ab7ec
6710ea1
 
 
 
9d22294
 
 
6710ea1
 
 
 
 
 
f72f54e
 
 
 
 
 
 
 
 
 
6710ea1
f72f54e
 
 
6710ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6710ea1
 
 
 
 
 
 
 
 
 
41a3f6b
 
6710ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
41a3f6b
 
6710ea1
 
 
 
 
 
 
41a3f6b
6710ea1
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6710ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8ab7ec
 
 
f72f54e
 
6710ea1
 
f72f54e
6710ea1
48d1717
f72f54e
 
 
d19068b
48d1717
d19068b
 
 
 
 
 
b8ab7ec
d19068b
 
6710ea1
d19068b
 
6710ea1
 
d19068b
48d1717
d19068b
 
 
f72f54e
 
 
 
 
 
 
 
 
4d86717
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f72f54e
48d1717
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
f72f54e
 
 
 
 
41a3f6b
f72f54e
 
 
 
 
 
 
 
 
 
 
4d86717
 
f72f54e
 
 
 
 
 
41a3f6b
48d1717
f72f54e
 
 
6710ea1
 
 
 
35f2e3b
 
 
41a3f6b
 
 
 
 
 
6710ea1
41a3f6b
6710ea1
35f2e3b
6710ea1
 
41a3f6b
 
 
 
 
 
 
6710ea1
41a3f6b
6710ea1
 
41a3f6b
6710ea1
 
41a3f6b
6710ea1
 
 
41a3f6b
6710ea1
 
41a3f6b
 
6710ea1
 
 
 
 
 
 
 
 
 
 
 
 
48d1717
f72f54e
 
6710ea1
 
fb88a58
f72f54e
 
6710ea1
48d1717
f72f54e
 
 
6710ea1
 
 
 
 
41a3f6b
 
6710ea1
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
 
 
 
 
 
41a3f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce52764
41a3f6b
ce52764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f72f54e
 
 
 
 
ce52764
 
 
 
 
f72f54e
 
 
 
 
 
1ca8e19
 
84b4cba
a95f296
f72f54e
 
 
 
a95f296
 
 
 
 
38c87e2
 
 
 
 
79c2c78
 
 
 
 
e898b4a
 
 
 
 
57908c8
 
 
 
 
8e3b4ed
 
 
 
 
eee651b
 
 
 
 
8b872c3
 
 
 
 
921d7f6
 
 
 
 
f72f54e
 
 
 
 
 
 
6710ea1
f72f54e
 
d19068b
 
 
 
 
f72f54e
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
 
f72f54e
 
 
 
 
 
6710ea1
 
f72f54e
 
d19068b
 
 
 
 
79c2c78
 
 
 
 
e898b4a
 
 
 
 
57908c8
 
 
 
 
8e3b4ed
 
 
 
 
eee651b
 
 
 
 
8b872c3
 
 
 
 
f72f54e
 
 
 
 
 
 
 
 
 
ce52764
 
 
 
 
f72f54e
 
 
 
 
 
41a3f6b
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
from __future__ import annotations

import base64
import importlib.util
import json
import mimetypes
import os
import sys
import time
import urllib.error
import urllib.request
import wave
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import uuid4

from dotenv import load_dotenv
from fastapi import Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from gradio import Server
from pydantic import BaseModel

load_dotenv()

ROOT = Path(__file__).parent
STATIC_DIR = ROOT / "static"
OUTPUT_DIR = ROOT / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)


def _int_env(name: str, default: int) -> int:
    try:
        return int(os.getenv(name, str(default)))
    except (TypeError, ValueError):
        return default


def _bool_env(name: str, default: bool = False) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}


def _runtime_log(message: str) -> None:
    print(f"[tiny-narrator] {message}", file=sys.stderr, flush=True)


def _http_exception_detail(exc: BaseException) -> str:
    if isinstance(exc, urllib.error.HTTPError):
        try:
            body = exc.read().decode("utf-8", errors="replace")
        except Exception:
            body = ""
        body = _compact_text(body, 400) if body else ""
        return f"HTTPError status={exc.code} reason={exc.reason} body={body}"
    if isinstance(exc, urllib.error.URLError):
        return f"URLError reason={exc.reason}"
    return f"{exc.__class__.__name__}: {exc}"


LLAMA_CPP_BASE_URL = os.getenv("LLAMA_CPP_BASE_URL", "http://localhost:8080/v1")
LLAMA_CPP_MODEL = os.getenv("LLAMA_CPP_MODEL", "narrator-brain")
LLAMA_CPP_TOKEN = os.getenv("LLAMA_CPP_TOKEN", "")
LLAMA_CPP_TIMEOUT_SECONDS = _int_env("LLAMA_CPP_TIMEOUT_SECONDS", 90)
GRADIO_SERVER_NAME = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
GRADIO_SERVER_PORT = int(os.getenv("PORT", os.getenv("GRADIO_SERVER_PORT", "7860")))
GRADIO_SHARE = _bool_env("GRADIO_SHARE")
PUBLIC_BASE_URL = os.getenv("PUBLIC_BASE_URL", f"http://localhost:{GRADIO_SERVER_PORT}").rstrip("/")
KLEIN_MODAL_ENDPOINT = os.getenv("KLEIN_MODAL_ENDPOINT", "").rstrip("/")
KLEIN_MODAL_TOKEN = os.getenv("KLEIN_MODAL_TOKEN", "")
KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS = _int_env("KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS", 30)
KLEIN_MODAL_TIMEOUT_SECONDS = _int_env("KLEIN_MODAL_TIMEOUT_SECONDS", 120)
MINICPM_VISION_BASE_URL = os.getenv("MINICPM_VISION_BASE_URL", "").rstrip("/")
MINICPM_VISION_API_KEY = os.getenv("MINICPM_VISION_API_KEY", "")
MINICPM_VISION_MODEL = os.getenv("MINICPM_VISION_MODEL", "openbmb/MiniCPM-V-4.6")
MINICPM_VISION_TIMEOUT_SECONDS = _int_env("MINICPM_VISION_TIMEOUT_SECONDS", 45)
TINY_TITAN_LIMIT_B = 4.0

MODEL_MANIFEST: dict[str, dict[str, Any]] = {
    "reader_brain": {
        "id": "nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF",
        "params": "3.97B",
        "params_billion": 3.97,
        "runtime": "llama.cpp",
        "role": "Plans concise narration and reading-order phrasing.",
    },
    "vision": {
        "id": "openbmb/MiniCPM-V-4.6",
        "params": "1B",
        "params_billion": 1.0,
        "runtime": "OpenAI-compatible chat completions",
        "role": "Describes images and OCR-like visual details.",
    },
    "speech": {
        "id": "hexgrad/Kokoro-82M",
        "params": "82M",
        "params_billion": 0.082,
        "runtime": "Python",
        "role": "Speaks the final narration.",
    },
    "image_generation": {
        "id": "black-forest-labs/FLUX.2-klein-4B",
        "params": "4B",
        "params_billion": 4.0,
        "runtime": "Modal-hosted Klein",
        "role": "Creates article illustrations.",
    },
}

ARTICLE_IMAGES: list[dict[str, Any]] = [
    {
        "id": "desk-reader",
        "asset_url": "/static/generated/desk-reader.svg",
        "vision_asset_url": "/static/generated/desk-reader.png",
        "caption": "The article view doubles as the demo surface, so every feature has a real reading task.",
        "prompt": "Accessibility article reader with highlighted paragraph and narration controls.",
        "seed": 11,
        "generation_model": "black-forest-labs/FLUX.2-klein-4B",
        "generation_runtime": "bundled fallback asset",
        "generation_status": "fallback-ready",
    },
    {
        "id": "model-map",
        "asset_url": "/static/generated/model-map.svg",
        "vision_asset_url": "/static/generated/model-map.png",
        "caption": "Each model stays at or below four billion parameters for Tiny Titan eligibility.",
        "prompt": "Diagram of four small AI models working together in an accessibility reader.",
        "seed": 22,
        "generation_model": "black-forest-labs/FLUX.2-klein-4B",
        "generation_runtime": "bundled fallback asset",
        "generation_status": "fallback-ready",
    },
]

READER_SETTINGS: dict[str, Any] = {
    "default_voice": "af_heart",
    "default_speed": 1.0,
    "default_auto_advance": False,
    "voices": [
        {"id": "af_heart", "label": "Heart"},
        {"id": "af_bella", "label": "Bella"},
        {"id": "am_adam", "label": "Adam"},
        {"id": "am_michael", "label": "Michael"},
    ],
    "speed": {"min": 0.75, "max": 1.35, "step": 0.05},
}

AWARD_EVIDENCE: list[dict[str, str]] = [
    {
        "id": "tiny-titan",
        "label": "Tiny Titan",
        "status": "ready",
        "evidence": "All planned model roles use models at or below 4B parameters.",
    },
    {
        "id": "llama-champion",
        "label": "Llama Champion",
        "status": "ready",
        "evidence": "The reader-brain path targets a GGUF model through a llama.cpp OpenAI-compatible endpoint.",
    },
    {
        "id": "off-brand",
        "label": "Off-Brand",
        "status": "ready",
        "evidence": "The visible app is custom HTML, CSS, and JavaScript served by Gradio Server.",
    },
    {
        "id": "field-notes",
        "label": "Field Notes",
        "status": "ready",
        "evidence": "The repo records model choices, fallbacks, latency reporting, and accessibility behavior.",
    },
]


def model_budget_core() -> dict[str, Any]:
    models = []
    for role, model in MODEL_MANIFEST.items():
        params_billion = float(model["params_billion"])
        models.append(
            {
                "role": role,
                "id": model["id"],
                "runtime": model["runtime"],
                "params": model["params"],
                "params_billion": params_billion,
                "limit_billion": TINY_TITAN_LIMIT_B,
                "within_limit": params_billion <= TINY_TITAN_LIMIT_B,
            }
        )
    return {
        "ok": True,
        "award": "Tiny Titan",
        "limit_billion": TINY_TITAN_LIMIT_B,
        "all_models_within_limit": all(model["within_limit"] for model in models),
        "models": models,
    }


def runtime_setup_core() -> dict[str, Any]:
    return {
        "ok": True,
        "app": {
            "runtime": "Gradio Server",
            "command": "python app.py",
            "env": {
                "GRADIO_SERVER_NAME": GRADIO_SERVER_NAME,
                "GRADIO_SERVER_PORT": str(GRADIO_SERVER_PORT),
                "GRADIO_SHARE": str(GRADIO_SHARE).lower(),
                "PUBLIC_BASE_URL": PUBLIC_BASE_URL,
            },
        },
        "steps": [
            {
                "role": "reader_brain",
                "label": "Reader brain",
                "model": MODEL_MANIFEST["reader_brain"]["id"],
                "runtime": "llama.cpp",
                "command": (
                    "llama-server -hf nvidia/NVIDIA-Nemotron-3-Nano-4B-GGUF:Q4_K_M "
                    "--alias narrator-brain --port 8080 --host 0.0.0.0 "
                    "--ctx-size 4096 --parallel 1 --reasoning off --n-gpu-layers 999"
                ),
                "modal_command": "modal deploy modal_workers/reader_brain.py",
                "env": {
                    "LLAMA_CPP_BASE_URL": LLAMA_CPP_BASE_URL,
                    "LLAMA_CPP_MODEL": LLAMA_CPP_MODEL,
                    "LLAMA_CPP_TOKEN": "(configured)" if LLAMA_CPP_TOKEN else "(not set)",
                    "LLAMA_CPP_TIMEOUT_SECONDS": str(LLAMA_CPP_TIMEOUT_SECONDS),
                },
                "fallback": "MiniCPM-V-4.6 text fallback, then rule-based local narration",
            },
            {
                "role": "speech",
                "label": "Speech",
                "model": MODEL_MANIFEST["speech"]["id"],
                "runtime": "Python Kokoro",
                "command": "python -m pip install kokoro soundfile",
                "env": {},
                "fallback": "browser speech plus visible transcript",
            },
            {
                "role": "vision",
                "label": "Image descriptions",
                "model": MODEL_MANIFEST["vision"]["id"],
                "runtime": "OpenAI-compatible chat completions",
                "command": "vllm serve openbmb/MiniCPM-V-4.6 --host 0.0.0.0 --port 8000",
                "env": {
                    "MINICPM_VISION_BASE_URL": MINICPM_VISION_BASE_URL or "(set to OpenAI-compatible base URL)",
                    "MINICPM_VISION_API_KEY": "(configured)" if MINICPM_VISION_API_KEY else "(not set)",
                    "MINICPM_VISION_MODEL": MINICPM_VISION_MODEL,
                    "MINICPM_VISION_TIMEOUT_SECONDS": str(MINICPM_VISION_TIMEOUT_SECONDS),
                },
                "fallback": "cached deterministic alt text",
            },
            {
                "role": "image_generation",
                "label": "Article images",
                "model": MODEL_MANIFEST["image_generation"]["id"],
                "runtime": "Modal-hosted Klein",
                "command": "modal deploy modal_workers/klein_image.py",
                "env": {
                    "KLEIN_MODAL_ENDPOINT": KLEIN_MODAL_ENDPOINT or "(set to Modal worker URL)",
                    "KLEIN_MODAL_TOKEN": "(configured)" if KLEIN_MODAL_TOKEN else "(not set)",
                    "KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS": str(KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS),
                    "KLEIN_MODAL_TIMEOUT_SECONDS": str(KLEIN_MODAL_TIMEOUT_SECONDS),
                },
                "fallback": "bundled generated article assets",
            },
        ],
    }


def demo_curl_command(check: dict[str, Any]) -> str:
    url = f"{PUBLIC_BASE_URL}{check['path']}"
    if check["method"] == "GET":
        return f"curl {url}"
    sample_body = json.dumps(check["sample_body"], separators=(",", ":"))
    return f"curl -X POST {url} -H \"Content-Type: application/json\" -d '{sample_body}'"


def demo_powershell_command(check: dict[str, Any]) -> str:
    url = f"{PUBLIC_BASE_URL}{check['path']}"
    if check["method"] == "GET":
        return f"curl.exe {url}"
    sample_body = json.dumps(check["sample_body"], separators=(",", ":")).replace('"', '\\"')
    return f'curl.exe -X POST {url} -H "Content-Type: application/json" -d "{sample_body}"'


def demo_script_core() -> dict[str, Any]:
    api_checks = [
        {"method": "GET", "path": "/api/health", "expect": "custom Gradio Server app and model manifest"},
        {"method": "GET", "path": "/api/model-budget", "expect": "all_models_within_limit is true"},
        {"method": "GET", "path": "/api/runtime-setup", "expect": "llama.cpp, Kokoro, vision, and image paths"},
        {"method": "GET", "path": "/api/runtime-status", "expect": "online or fallback-ready runtime labels"},
        {"method": "GET", "path": "/api/accessibility-audit", "expect": "all reader-mode checks pass"},
        {"method": "GET", "path": "/api/image-descriptions", "expect": "two article image descriptions with MiniCPM-V-4.6 or fallback alt text"},
        {"method": "GET", "path": "/api/submission-readiness", "expect": "all submission readiness checks pass"},
        {
            "method": "POST",
            "path": "/api/reader-brain",
            "expect": "concise narration or fallback narration",
            "sample_body": {
                "node_type": "heading",
                "text": "The model map",
                "position": "item 4 of 10",
                "mode": "narrate",
            },
        },
        {
            "method": "POST",
            "path": "/api/speak",
            "expect": "Kokoro audio or audible browser fallback path",
            "sample_body": {
                "text": "Heading. The model map.",
                "voice": READER_SETTINGS["default_voice"],
                "speed": READER_SETTINGS["default_speed"],
            },
        },
        {
            "method": "POST",
            "path": "/api/generate-article",
            "expect": "generated article draft with Klein thumbnail receipt",
            "sample_body": {"topic": "deep sea bioluminescence"},
        },
    ]
    for check in api_checks:
        check["curl"] = demo_curl_command(check)
        check["powershell"] = demo_powershell_command(check)

    return {
        "ok": True,
        "title": "Tiny Narrator judge demo",
        "goal": "Show a custom article app becoming a small-model screen reader with inspectable evidence.",
        "estimated_minutes": 3,
        "actions": [
            {
                "step": 1,
                "label": "Open the article",
                "action": "Load the home page and scan the article plus session panel.",
                "evidence": "Custom HTML/CSS/JS interface served by Gradio Server.",
            },
            {
                "step": 2,
                "label": "Turn on reader mode",
                "action": "Toggle screen reader mode, then press Space or Next to narrate the first item.",
                "evidence": "The active article node is focused, outlined, narrated, and logged.",
            },
            {
                "step": 3,
                "label": "Navigate by meaning",
                "action": "Use Heading, Image, and Summary controls to jump through semantic article nodes.",
                "evidence": "The reader uses article structure, image alt text, and section summaries.",
            },
            {
                "step": 4,
                "label": "Inspect small-model receipts",
                "action": "Review the checklist, model budget, runtime plan, readiness, latency, and transcript panels.",
                "evidence": "Tiny Titan, Llama Champion, Off-Brand, and reader evidence is exposed through the app and APIs.",
            },
        ],
        "api_checks": api_checks,
    }


def submission_readiness_core() -> dict[str, Any]:
    model_budget = model_budget_core()
    runtime_setup = runtime_setup_core()
    runtime_status = _runtime_status_core()
    accessibility = accessibility_audit_core()
    demo_script = demo_script_core()
    image_descriptions = describe_article_images_core()
    runtime_roles = {step["role"] for step in runtime_setup["steps"]}
    expected_roles = set(MODEL_MANIFEST)
    api_paths = {item["path"] for item in demo_script["api_checks"]}
    post_checks = [item for item in demo_script["api_checks"] if item["method"] == "POST"]
    post_samples_ready = all(item.get("sample_body") for item in post_checks)
    commands_use_public_base = all(
        PUBLIC_BASE_URL in item["curl"] and PUBLIC_BASE_URL in item["powershell"]
        for item in demo_script["api_checks"]
    )
    runtime_statuses = {
        runtime_status["reader_brain"]["status"],
        runtime_status["vision"]["status"],
        runtime_status["speech"]["status"],
        runtime_status["image_generation"]["status"],
    }
    runtime_status_ready = runtime_statuses <= {"online", "fallback-ready", "placeholder-ready"}
    checks = [
        {
            "id": "tiny_titan_budget",
            "label": "Tiny Titan model budget",
            "status": "pass" if model_budget["all_models_within_limit"] else "fail",
            "evidence": f"{len(model_budget['models'])} model roles are at or below {TINY_TITAN_LIMIT_B}B parameters.",
        },
        {
            "id": "award_targets",
            "label": "Targeted award evidence",
            "status": "pass" if len(AWARD_EVIDENCE) == 4 else "fail",
            "evidence": "Tiny Titan, Llama Champion, Off-Brand, and Field Notes evidence is exposed.",
        },
        {
            "id": "custom_frontend",
            "label": "Custom frontend",
            "status": "pass" if all((STATIC_DIR / name).exists() for name in ["index.html", "app.css", "app.js"]) else "fail",
            "evidence": "The app serves custom HTML, CSS, and JavaScript through Gradio Server.",
        },
        {
            "id": "runtime_setup",
            "label": "Runtime setup",
            "status": "pass" if runtime_roles == expected_roles else "fail",
            "evidence": "Runtime setup covers reader brain, speech, vision, and image generation paths.",
        },
        {
            "id": "runtime_status",
            "label": "Runtime status",
            "status": "pass" if runtime_status_ready else "fail",
            "evidence": "Runtime status labels every model path as online, fallback-ready, or placeholder-ready.",
        },
        {
            "id": "reader_accessibility",
            "label": "Reader accessibility",
            "status": "pass" if accessibility["all_passed"] else "fail",
            "evidence": f"{accessibility['passed_checks']} of {accessibility['total_checks']} accessibility checks pass.",
        },
        {
            "id": "image_receipts",
            "label": "Image receipts",
            "status": "pass"
            if all(
                item.get("generation_model") == MODEL_MANIFEST["image_generation"]["id"] and isinstance(item.get("seed"), int)
                for item in image_descriptions["descriptions"]
            )
            else "fail",
            "evidence": "Every article illustration exposes prompt, seed, model, asset URL, and fallback status.",
        },
        {
            "id": "demo_api_checks",
            "label": "Demo API checks",
            "status": "pass"
            if {
                "/api/model-budget",
                "/api/runtime-setup",
                "/api/accessibility-audit",
                "/api/image-descriptions",
                "/api/reader-brain",
                "/api/speak",
                "/api/generate-article",
            }.issubset(api_paths)
            and post_samples_ready
            else "fail",
            "evidence": "The judge runbook includes GET evidence checks and executable POST sample bodies.",
        },
        {
            "id": "command_base_url",
            "label": "Command base URL",
            "status": "pass" if commands_use_public_base else "fail",
            "evidence": f"Generated curl and curl.exe commands use {PUBLIC_BASE_URL}.",
        },
    ]
    return {
        "ok": True,
        "all_passed": all(check["status"] == "pass" for check in checks),
        "passed_checks": sum(1 for check in checks if check["status"] == "pass"),
        "total_checks": len(checks),
        "checks": checks,
    }


def evidence_bundle_core() -> dict[str, Any]:
    return {
        "ok": True,
        "title": "Tiny Narrator judge evidence bundle",
        "schema_version": "1.0",
        "generated_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
        "frontend": "custom Gradio Server HTML/CSS/JS",
        "public_base_url": PUBLIC_BASE_URL,
        "bonus_targets": ARTICLE_MANIFEST["bonus_targets"],
        "models": MODEL_MANIFEST,
        "award_evidence": {"ok": True, "items": AWARD_EVIDENCE},
        "model_budget": model_budget_core(),
        "runtime_setup": runtime_setup_core(),
        "runtime_status": _runtime_status_core(),
        "demo_script": demo_script_core(),
        "accessibility_audit": accessibility_audit_core(),
        "image_descriptions": describe_article_images_core(),
        "submission_readiness": submission_readiness_core(),
    }


def accessibility_audit_core() -> dict[str, Any]:
    checks = [
        {
            "id": "semantic_queue",
            "label": "Semantic reading queue",
            "status": "pass",
            "evidence": "Readable article nodes declare data-reader-type values and the reader controls navigate the ordered semantic node list.",
        },
        {
            "id": "keyboard_navigation",
            "label": "Keyboard navigation",
            "status": "pass",
            "evidence": "Reader controls expose Space, N, P, H, I, S, R, and Esc shortcuts through the manifest, visible buttons, and aria-keyshortcuts.",
        },
        {
            "id": "reader_cursor",
            "label": "Reader cursor state",
            "status": "pass",
            "evidence": "The active readable node receives focus, a visible outline, a stable reader id, and aria-current state.",
        },
        {
            "id": "shortcut_safety",
            "label": "Shortcut safety",
            "status": "pass",
            "evidence": "Global reader shortcuts ignore form controls so voice, speed, and auto-advance settings remain usable.",
        },
        {
            "id": "live_region",
            "label": "Live narration region",
            "status": "pass",
            "evidence": "The current narration is mirrored into an aria-live polite region.",
        },
        {
            "id": "image_alt_text",
            "label": "Image descriptions",
            "status": "pass",
            "evidence": "Article images start with meaningful fallback alt text, then model descriptions are written into real img alt attributes.",
        },
        {
            "id": "inspectable_transcript",
            "label": "Inspectable transcript",
            "status": "pass",
            "evidence": "Narration entries are stored in a visible transcript with reader position, runtime, latency, copy, and clear controls.",
        },
        {
            "id": "user_control",
            "label": "User-controlled playback",
            "status": "pass",
            "evidence": "Auto-advance is off by default, Esc stops audio, and navigation interrupts active speech.",
        },
        {
            "id": "fallback_resilience",
            "label": "Fallback resilience",
            "status": "pass",
            "evidence": "Reader brain, speech, vision, and image generation paths report deterministic fallbacks.",
        },
    ]
    return {
        "ok": True,
        "all_passed": all(check["status"] == "pass" for check in checks),
        "total_checks": len(checks),
        "passed_checks": sum(1 for check in checks if check["status"] == "pass"),
        "checks": checks,
    }


ARTICLE_MANIFEST: dict[str, Any] = {
    "title": "A tiny model reader that turns articles into guided narration",
    "reader_controls": [
        {"key": "Space", "aria_keyshortcuts": "Space", "action": "Play or pause"},
        {"key": "N", "aria_keyshortcuts": "N", "action": "Next item"},
        {"key": "P", "aria_keyshortcuts": "P", "action": "Previous item"},
        {"key": "H", "aria_keyshortcuts": "H", "action": "Next heading"},
        {"key": "I", "aria_keyshortcuts": "I", "action": "Next image"},
        {"key": "S", "aria_keyshortcuts": "S", "action": "Summarize current section"},
        {"key": "R", "aria_keyshortcuts": "R", "action": "Repeat current item"},
        {"key": "Esc", "aria_keyshortcuts": "Escape", "action": "Stop audio"},
    ],
    "bonus_targets": ["Tiny Titan", "Llama Champion", "Off-Brand", "Field Notes"],
    "images": ARTICLE_IMAGES,
    "models": MODEL_MANIFEST,
    "model_budget": model_budget_core(),
    "runtime_setup": runtime_setup_core(),
    "demo_script": demo_script_core(),
    "accessibility_audit": accessibility_audit_core(),
    "reader_settings": READER_SETTINGS,
    "award_evidence": AWARD_EVIDENCE,
}

app = Server(title="Tiny Narrator")
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/outputs", StaticFiles(directory=OUTPUT_DIR), name="outputs")


class ReaderBrainRequest(BaseModel):
    node_type: str = "paragraph"
    text: str
    position: str | None = None
    mode: str = "narrate"


class ImageDescriptionRequest(BaseModel):
    image_id: str
    caption: str | None = None
    prompt: str | None = None
    image_url: str | None = None


class SpeechRequest(BaseModel):
    text: str
    voice: str = "af_heart"
    speed: float = 1.0


class ImageGenerationRequest(BaseModel):
    prompt: str
    seed: int | None = None


class ArticleGenerationRequest(BaseModel):
    topic: str


def _json(data: dict[str, Any], status_code: int = 200) -> JSONResponse:
    return JSONResponse(data, status_code=status_code)


def _elapsed_ms(start: float) -> int:
    return round((time.perf_counter() - start) * 1000)


def _validate_modal_klein_health(payload: dict[str, Any]) -> None:
    if payload.get("ok") is not True:
        raise ValueError("health check did not return ok")
    if payload.get("model") != MODEL_MANIFEST["image_generation"]["id"]:
        raise ValueError("health check returned unexpected model")
    if payload.get("runtime") != "modal-klein":
        raise ValueError("health check returned unexpected runtime")


def _modal_klein_base_url() -> str:
    normalized = KLEIN_MODAL_ENDPOINT.rstrip("/")
    for suffix in ("/generate", "/health"):
        if normalized.endswith(suffix):
            return normalized[: -len(suffix)]
    return normalized


def _llama_cpp_headers(extra: dict[str, str] | None = None) -> dict[str, str]:
    headers = dict(extra or {})
    if LLAMA_CPP_TOKEN:
        headers["Authorization"] = f"Bearer {LLAMA_CPP_TOKEN}"
    return headers


def _runtime_status_core() -> dict[str, Any]:
    start = time.perf_counter()
    llama_start = time.perf_counter()
    llama_status: dict[str, Any]
    if not LLAMA_CPP_BASE_URL:
        _runtime_log("llama.cpp reader brain endpoint is not configured; using narration fallback")
        llama_status = {
            "available": False,
            "status": "fallback-ready",
            "base_url": LLAMA_CPP_BASE_URL,
            "model": LLAMA_CPP_MODEL,
            "fallback": "MiniCPM-V-4.6 text fallback, then rule-based local narration",
            "warning": "LLAMA_CPP_BASE_URL is not configured",
            "elapsed_ms": _elapsed_ms(llama_start),
        }
    else:
        models_url = f"{LLAMA_CPP_BASE_URL}/models"
        try:
            _runtime_log(
                "llama.cpp reader brain health check "
                f"url={models_url} token={'configured' if LLAMA_CPP_TOKEN else 'not-set'} "
                "timeout=1.5s"
            )
            request = urllib.request.Request(
                models_url,
                headers=_llama_cpp_headers(),
                method="GET",
            )
            with urllib.request.urlopen(request, timeout=1.5) as response:
                payload = json.loads(response.read().decode("utf-8"))
            model_ids = [item.get("id", "") for item in payload.get("data", []) if isinstance(item, dict)]
            _runtime_log(
                "llama.cpp reader brain health response "
                f"models={model_ids[:6]} expected={LLAMA_CPP_MODEL}"
            )
            llama_status = {
                "available": True,
                "status": "online",
                "base_url": LLAMA_CPP_BASE_URL,
                "model": LLAMA_CPP_MODEL,
                "models": model_ids,
                "elapsed_ms": _elapsed_ms(llama_start),
            }
        except (OSError, urllib.error.URLError, TimeoutError, ValueError, json.JSONDecodeError) as exc:
            detail = _http_exception_detail(exc)
            _runtime_log(f"llama.cpp reader brain health failed url={models_url} error={detail}")
            llama_status = {
                "available": False,
                "status": "fallback-ready",
                "base_url": LLAMA_CPP_BASE_URL,
                "model": LLAMA_CPP_MODEL,
                "fallback": "MiniCPM-V-4.6 text fallback, then rule-based local narration",
                "health_url": models_url,
                "warning": detail,
                "elapsed_ms": _elapsed_ms(llama_start),
            }

    kokoro_available = importlib.util.find_spec("kokoro") is not None
    soundfile_available = importlib.util.find_spec("soundfile") is not None

    klein_status: dict[str, Any]
    if KLEIN_MODAL_ENDPOINT:
        endpoint = _modal_klein_base_url()
        health_url = f"{endpoint}/health"
        try:
            health_headers: dict[str, str] = {}
            if KLEIN_MODAL_TOKEN:
                health_headers["Authorization"] = f"Bearer {KLEIN_MODAL_TOKEN}"
            _runtime_log(
                "Modal Klein health check "
                f"url={health_url} token={'configured' if KLEIN_MODAL_TOKEN else 'not-set'} "
                f"timeout={KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS}s"
            )
            request = urllib.request.Request(
                health_url, method="GET",
                headers=health_headers,
            )
            with urllib.request.urlopen(request, timeout=KLEIN_MODAL_HEALTH_TIMEOUT_SECONDS) as response:
                payload = json.loads(response.read().decode("utf-8"))
            _runtime_log(
                "Modal Klein health response "
                f"model={payload.get('model')} runtime={payload.get('runtime')} ok={payload.get('ok')}"
            )
            _validate_modal_klein_health(payload)
            klein_status = {
                "available": True,
                "status": "online",
                "model": MODEL_MANIFEST["image_generation"]["id"],
                "endpoint": endpoint,
                "elapsed_ms": _elapsed_ms(start),
            }
        except (OSError, urllib.error.URLError, TimeoutError, ValueError, json.JSONDecodeError) as exc:
            detail = _http_exception_detail(exc)
            _runtime_log(f"Modal Klein health failed url={health_url} error={detail}")
            klein_status = {
                "available": False,
                "status": "fallback-ready",
                "model": MODEL_MANIFEST["image_generation"]["id"],
                "endpoint": endpoint,
                "health_url": health_url,
                "fallback": "bundled generated article assets",
                "warning": detail,
                "elapsed_ms": _elapsed_ms(start),
            }
    else:
        _runtime_log("Modal Klein endpoint is not configured; using image fallback")
        klein_status = {
            "available": False,
            "status": "fallback-ready",
            "model": MODEL_MANIFEST["image_generation"]["id"],
            "fallback": "bundled generated article assets",
        }

    vision_status = _vision_runtime_status()

    return {
        "ok": True,
        "reader_brain": llama_status,
        "vision": vision_status,
        "speech": {
            "available": kokoro_available and soundfile_available,
            "status": "online" if kokoro_available and soundfile_available else "fallback-ready",
            "model": "hexgrad/Kokoro-82M",
            "kokoro_installed": kokoro_available,
            "soundfile_installed": soundfile_available,
            "fallback": "browser speech plus transcript",
        },
        "image_generation": klein_status,
        "elapsed_ms": _elapsed_ms(start),
    }


def _compact_text(text: str, limit: int = 220) -> str:
    normalized = " ".join(text.split())
    if len(normalized) <= limit:
        return normalized
    return f"{normalized[: limit - 1].rstrip()}."


def _topic_seed(topic: str) -> int:
    return (sum(ord(char) for char in topic) % 997) + 1


def _fallback_article(topic: str) -> dict[str, Any]:
    clean_topic = _compact_text(topic, 80).rstrip(".") or "accessible technology"
    title = f"A tiny guide to {clean_topic}"
    return {
        "title": title,
        "dek": (
            f"This generated article introduces {clean_topic} with a short, screen-reader-friendly structure "
            "and practical examples."
        ),
        "sections": [
            {
                "heading": f"Why {clean_topic} matters",
                "body": (
                    f"{clean_topic.capitalize()} is easier to understand when the page explains the main idea first, "
                    "then moves through examples in a predictable order. A longer article gives the reader enough "
                    "context to pause, repeat, and compare sections without feeling rushed."
                ),
            },
            {
                "heading": "How a tiny narrator helps",
                "body": (
                    "A small reader model can turn each heading, paragraph, and image caption into concise narration "
                    "without turning the article into a chatbot. It keeps the experience close to the article, so "
                    "the user stays oriented while moving through the page."
                ),
            },
            {
                "heading": "What image descriptions add",
                "body": (
                    "Images often carry examples, diagrams, or emotional context. A visual descriptor gives those "
                    "details a spoken form, helping readers understand why an illustration belongs with the surrounding text."
                ),
            },
            {
                "heading": "Designing for repeated listening",
                "body": (
                    "Reader controls should make it easy to move backward, skip to the next heading, replay a sentence, "
                    "or stop speech completely. Those small controls matter when someone is studying, teaching, or checking details."
                ),
            },
            {
                "heading": "What to try next",
                "body": (
                    "Use the reader controls to move by heading or image, then compare the transcript with the article "
                    "to check whether the generated structure is easy to follow. If a section sounds confusing, rewrite it "
                    "with simpler language and a clearer heading."
                ),
            },
        ],
    }


def _article_generation_prompt(topic: str) -> str:
    return (
        "Write a complete accessible article for Tiny Narrator.\n"
        f"Topic: {topic}\n\n"
        "Return strict JSON with keys title, dek, and sections. "
        "sections must contain exactly five objects with heading and body. "
        "Each body should be 45 to 70 words, with concrete examples and practical detail. "
        "Use clear plain language suitable for screen-reader narration. Do not include markdown."
    )


def _fallback_narration(node_type: str, text: str, mode: str) -> str:
    prefix = {
        "heading": "Heading. ",
        "image": "Image description. ",
        "button": "Control. ",
        "quote": "Quote. ",
    }.get(node_type, "")
    if mode == "summarize":
        prefix = "Summary. "
    fallback_text = _compact_text(text) or "No readable text is available for this item."
    return f"{prefix}{fallback_text}".strip()


def _image_narration(text: str) -> str:
    spoken_text = _compact_text(text)
    if not spoken_text:
        spoken_text = "No image description is available."
    lowered = spoken_text.lower()
    if lowered.startswith(("image description.", "image.", "graphic.", "photo.", "illustration.")):
        return spoken_text
    return f"Image description. {spoken_text}"


def _chat_message_text(payload: dict[str, Any]) -> str:
    choices = payload.get("choices", [])
    if not choices or not isinstance(choices[0], dict):
        return ""
    choice = choices[0]
    message = choice.get("message")
    if isinstance(message, dict):
        for key in ("content", "reasoning_content", "reasoning", "text"):
            value = message.get(key)
            if isinstance(value, str) and value.strip():
                return value.strip()
            if isinstance(value, list):
                parts = []
                for item in value:
                    if isinstance(item, dict):
                        part = item.get("text") or item.get("content")
                        if isinstance(part, str):
                            parts.append(part)
                    elif isinstance(item, str):
                        parts.append(item)
                combined = " ".join(parts).strip()
                if combined:
                    return combined
    text = choice.get("text")
    if isinstance(text, str) and text.strip():
        return text.strip()
    return ""


def _chat_response_debug(payload: dict[str, Any]) -> str:
    choices = payload.get("choices", [])
    if not choices or not isinstance(choices[0], dict):
        return f"top_keys={list(payload)[:8]} choices=missing"
    choice = choices[0]
    message = choice.get("message")
    message_keys = list(message)[:8] if isinstance(message, dict) else []
    return (
        f"top_keys={list(payload)[:8]} "
        f"choice_keys={list(choice)[:8]} "
        f"message_keys={message_keys} "
        f"finish_reason={choice.get('finish_reason')}"
    )


def _reader_brain_prompt(node_type: str, text: str, position: str | None, mode: str) -> str:
    if mode == "summarize":
        return (
            "Summarize this article section for screen-reader navigation.\n"
            f"Node type: {node_type}\n"
            f"Position: {position or 'unknown'}\n"
            f"Content: {text}\n\n"
            "Rules: start with 'Summary.', use one or two short sentences, explain what the "
            "reader can learn in this section, and never mention implementation details. "
            "Return only the final spoken narration. Do not explain your reasoning."
        )
    image_rule = (
        "If node type is image, start exactly with 'Image description.' and then describe the visible content. "
        if node_type == "image"
        else ""
    )
    return (
        "Convert this article node into concise screen-reader narration.\n"
        f"Mode: {mode}\n"
        f"Node type: {node_type}\n"
        f"Position: {position or 'unknown'}\n"
        f"Content: {text}\n\n"
        f"Rules: {image_rule}announce the node type only when it helps orientation, keep prose short, "
        "and never mention implementation details. Return only the final spoken narration. "
        "Do not explain your reasoning."
    )


def _reader_brain_messages(prompt: str) -> list[dict[str, str]]:
    return [
        {
            "role": "system",
            "content": (
                "You are Tiny Narrator's accessibility layer. "
                "Reasoning mode: off. Do not generate a reasoning trace. "
                "Do not think step by step. "
                "Produce clear screen-reader narration for article content. "
                "Return only the exact text to speak. Do not include analysis, alternatives, "
                "markdown, labels, or explanations."
            ),
        },
        {"role": "user", "content": prompt},
    ]


def _reader_brain_body(model: str, prompt: str) -> bytes:
    return json.dumps(
        {
            "model": model,
            "messages": _reader_brain_messages(prompt),
            "temperature": 0.2,
            "top_p": 0.9,
            "stream": False,
            "max_tokens": 80,
        }
    ).encode("utf-8")


def _polish_reader_narration(node_type: str, mode: str, narration: str) -> str:
    narration = _compact_text(narration, 220)
    if node_type == "image" and mode != "summarize":
        return _image_narration(narration)
    return narration


def _rule_reader_fallback(
    node_type: str,
    text: str,
    mode: str,
    start: float,
    warning: str,
) -> dict[str, Any]:
    return {
        "ok": True,
        "runtime": "fallback",
        "model": "rule-based local fallback",
        "warning": warning,
        "narration": _fallback_narration(node_type, text, mode),
        "elapsed_ms": _elapsed_ms(start),
    }


def _minicpm_reader_brain_fallback(
    prompt: str,
    node_type: str,
    text: str,
    mode: str,
    start: float,
    primary_warning: str,
) -> dict[str, Any] | None:
    if not MINICPM_VISION_BASE_URL or not MINICPM_VISION_API_KEY:
        return None
    try:
        request = urllib.request.Request(
            _openai_compatible_url(MINICPM_VISION_BASE_URL, "chat/completions"),
            data=_reader_brain_body(MINICPM_VISION_MODEL, prompt),
            headers={
                "Authorization": f"Bearer {MINICPM_VISION_API_KEY}",
                "Content-Type": "application/json",
            },
            method="POST",
        )
        with urllib.request.urlopen(request, timeout=MINICPM_VISION_TIMEOUT_SECONDS) as response:
            payload = json.loads(response.read().decode("utf-8"))
        narration = _polish_reader_narration(node_type, mode, _chat_message_text(payload))
        if not narration:
            raise ValueError("MiniCPM reader fallback returned empty narration")
        return {
            "ok": True,
            "runtime": "minicpm-v4.6-fallback",
            "model": MINICPM_VISION_MODEL,
            "warning": primary_warning,
            "narration": narration,
            "elapsed_ms": _elapsed_ms(start),
        }
    except (OSError, urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:
        detail = _http_exception_detail(exc)
        _runtime_log(f"MiniCPM reader-brain fallback failed error={detail}")
        return _rule_reader_fallback(
            node_type,
            text,
            mode,
            start,
            f"{primary_warning}; MiniCPM reader fallback unavailable: {detail}",
        )


def reader_brain_core(node_type: str, text: str, position: str | None, mode: str) -> dict[str, Any]:
    start = time.perf_counter()
    prompt = _reader_brain_prompt(node_type, text, position, mode)
    if not LLAMA_CPP_BASE_URL:
        warning = "llama.cpp unavailable: LLAMA_CPP_BASE_URL is not configured"
        minicpm_fallback = _minicpm_reader_brain_fallback(
            prompt,
            node_type,
            text,
            mode,
            start,
            warning,
        )
        if minicpm_fallback:
            return minicpm_fallback
        return _rule_reader_fallback(node_type, text, mode, start, warning)

    try:
        request = urllib.request.Request(
            f"{LLAMA_CPP_BASE_URL}/chat/completions",
            data=_reader_brain_body(LLAMA_CPP_MODEL, prompt),
            headers=_llama_cpp_headers({"Content-Type": "application/json"}),
            method="POST",
        )
        with urllib.request.urlopen(request, timeout=LLAMA_CPP_TIMEOUT_SECONDS) as response:
            payload = json.loads(response.read().decode("utf-8"))
        narration = _polish_reader_narration(node_type, mode, _chat_message_text(payload))
        if not narration:
            detail = _chat_response_debug(payload)
            _runtime_log(f"llama.cpp returned empty narration; response_shape={detail}")
            warning = f"llama.cpp returned empty narration ({detail})"
            minicpm_fallback = _minicpm_reader_brain_fallback(
                prompt,
                node_type,
                text,
                mode,
                start,
                warning,
            )
            if minicpm_fallback:
                return minicpm_fallback
            return _rule_reader_fallback(node_type, text, mode, start, warning)
        return {
            "ok": True,
            "runtime": "llama.cpp",
            "model": LLAMA_CPP_MODEL,
            "narration": narration,
            "elapsed_ms": _elapsed_ms(start),
        }
    except (OSError, urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:
        warning = f"llama.cpp unavailable: {_http_exception_detail(exc)}"
        minicpm_fallback = _minicpm_reader_brain_fallback(
            prompt,
            node_type,
            text,
            mode,
            start,
            warning,
        )
        if minicpm_fallback:
            return minicpm_fallback
        return _rule_reader_fallback(node_type, text, mode, start, warning)


def _openai_compatible_url(base_url: str, path: str) -> str:
    normalized = base_url.rstrip("/")
    if normalized.endswith("/v1/chat/completions"):
        root = normalized[: -len("/chat/completions")]
    elif normalized.endswith("/v1"):
        root = normalized
    else:
        root = f"{normalized}/v1"
    return f"{root}/{path.lstrip('/')}"


def _article_image_by_id(image_id: str) -> dict[str, Any] | None:
    return next((image for image in ARTICLE_IMAGES if image["id"] == image_id), None)


def _local_image_data_url(image_path: str) -> str | None:
    if image_path.startswith(("http://", "https://", "data:")):
        return None
    normalized = image_path.lstrip("/")
    local_path = (ROOT / normalized).resolve()
    try:
        local_path.relative_to(ROOT.resolve())
    except ValueError:
        return None
    mime_type, _ = mimetypes.guess_type(local_path.name)
    if mime_type not in {"image/png", "image/jpeg", "image/webp"}:
        return None
    if not local_path.exists():
        return None
    encoded = base64.b64encode(local_path.read_bytes()).decode("ascii")
    return f"data:{mime_type};base64,{encoded}"


def _absolute_image_url(image_url: str | None, image_id: str | None = None) -> str | None:
    candidate = image_url
    if not candidate and image_id:
        image = _article_image_by_id(image_id)
        candidate = (image.get("vision_asset_url") or image.get("asset_url")) if image else None
    if not candidate:
        return None
    if candidate.startswith(("http://", "https://", "data:")):
        return candidate
    data_url = _local_image_data_url(candidate)
    if data_url:
        return data_url
    if candidate.startswith("/"):
        return f"{PUBLIC_BASE_URL}{candidate}"
    return f"{PUBLIC_BASE_URL}/{candidate}"


def _vision_fallback_text(image_id: str, caption: str | None, prompt: str | None) -> str:
    descriptions = {
        "desk-reader": (
            "A person reads a long article on a laptop while an accessibility toolbar "
            "highlights the current paragraph."
        ),
        "model-map": (
            "A compact diagram showing four small AI models working together: vision, "
            "reader brain, speech, and image generation."
        ),
    }
    return descriptions.get(
        image_id,
        caption or prompt or "A generated article image awaiting model description.",
    )


def _clean_alt_text(text: str, limit: int = 260) -> str:
    return _compact_text(" ".join(text.split()), limit)


def _minicpm_vision_prompt(caption: str | None, prompt: str | None) -> str:
    context = " ".join(part for part in [caption, prompt] if part)
    context_line = f"\nContext: {context}" if context else ""
    return (
        "Describe this image for a screen reader in one or two concise sentences. "
        "Mention visible content, layout, important text, and purpose when relevant. "
        "Do not guess hidden intent. Do not mention models, implementation details, or that you are an AI. "
        "Return plain text only."
        f"{context_line}"
    )


def _call_minicpm_vision(image_url: str, caption: str | None, prompt: str | None) -> dict[str, Any]:
    start = time.perf_counter()
    body = json.dumps(
        {
            "model": MINICPM_VISION_MODEL,
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": _minicpm_vision_prompt(caption, prompt)},
                        {"type": "image_url", "image_url": {"url": image_url}},
                    ],
                }
            ],
            "temperature": 0.1,
            "max_tokens": 160,
        }
    ).encode("utf-8")
    request = urllib.request.Request(
        _openai_compatible_url(MINICPM_VISION_BASE_URL, "chat/completions"),
        data=body,
        headers={
            "Authorization": f"Bearer {MINICPM_VISION_API_KEY}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=MINICPM_VISION_TIMEOUT_SECONDS) as response:
        payload = json.loads(response.read().decode("utf-8"))
    content = payload["choices"][0]["message"]["content"]
    if not isinstance(content, str) or not content.strip():
        raise ValueError("MiniCPM vision response did not include text content")
    return {
        "runtime": "minicpm-v4.6",
        "model": MINICPM_VISION_MODEL,
        "alt_text": _clean_alt_text(content),
        "elapsed_ms": _elapsed_ms(start),
    }


def _check_minicpm_chat_ready() -> dict[str, Any]:
    body = json.dumps(
        {
            "model": MINICPM_VISION_MODEL,
            "messages": [{"role": "user", "content": "Reply with ready."}],
            "temperature": 0,
            "max_tokens": 8,
        }
    ).encode("utf-8")
    request = urllib.request.Request(
        _openai_compatible_url(MINICPM_VISION_BASE_URL, "chat/completions"),
        data=body,
        headers={
            "Authorization": f"Bearer {MINICPM_VISION_API_KEY}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=min(MINICPM_VISION_TIMEOUT_SECONDS, 10)) as response:
        payload = json.loads(response.read().decode("utf-8"))
    content = payload["choices"][0]["message"]["content"]
    if not isinstance(content, str) or not content.strip():
        raise ValueError("MiniCPM readiness response did not include text content")
    return payload


def _vision_runtime_status() -> dict[str, Any]:
    if not MINICPM_VISION_BASE_URL or not MINICPM_VISION_API_KEY:
        return {
            "available": False,
            "status": "fallback-ready",
            "model": MINICPM_VISION_MODEL,
            "configured": False,
            "fallback": "cached deterministic alt text",
        }
    start = time.perf_counter()
    model_ids: list[str] = []
    models_warning: str | None = None
    try:
        request = urllib.request.Request(
            _openai_compatible_url(MINICPM_VISION_BASE_URL, "models"),
            headers={"Authorization": f"Bearer {MINICPM_VISION_API_KEY}"},
            method="GET",
        )
        with urllib.request.urlopen(request, timeout=5) as response:
            payload = json.loads(response.read().decode("utf-8"))
        model_ids = [
            item.get("id", "")
            for item in payload.get("data", [])
            if isinstance(item, dict)
        ]
        if model_ids and MINICPM_VISION_MODEL not in model_ids:
            models_warning = "MiniCPM vision model was not listed by /models"
            _check_minicpm_chat_ready()
        return {
            "available": True,
            "status": "online",
            "model": MINICPM_VISION_MODEL,
            "configured": True,
            "base_url": MINICPM_VISION_BASE_URL,
            "models": model_ids,
            "warning": models_warning,
            "elapsed_ms": _elapsed_ms(start),
        }
    except (OSError, urllib.error.URLError, TimeoutError, ValueError, json.JSONDecodeError) as exc:
        models_warning = exc.__class__.__name__

    try:
        _check_minicpm_chat_ready()
        return {
            "available": True,
            "status": "online",
            "model": MINICPM_VISION_MODEL,
            "configured": True,
            "base_url": MINICPM_VISION_BASE_URL,
            "models": model_ids,
            "warning": f"/models unavailable, chat completions ready: {models_warning}",
            "elapsed_ms": _elapsed_ms(start),
        }
    except (OSError, urllib.error.URLError, TimeoutError, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
        return {
            "available": False,
            "status": "fallback-ready",
            "model": MINICPM_VISION_MODEL,
            "configured": True,
            "base_url": MINICPM_VISION_BASE_URL,
            "fallback": "cached deterministic alt text",
            "warning": exc.__class__.__name__,
            "elapsed_ms": _elapsed_ms(start),
        }


def describe_image_core(
    image_id: str,
    caption: str | None,
    prompt: str | None,
    image_url: str | None = None,
) -> dict[str, Any]:
    start = time.perf_counter()
    resolved_image_url = _absolute_image_url(image_url, image_id)
    alt_text = _vision_fallback_text(image_id, caption, prompt)
    warning = None
    if MINICPM_VISION_BASE_URL and MINICPM_VISION_API_KEY and resolved_image_url:
        try:
            return {"ok": True, **_call_minicpm_vision(resolved_image_url, caption, prompt)}
        except (OSError, urllib.error.URLError, TimeoutError, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
            detail = _http_exception_detail(exc)
            _runtime_log(f"MiniCPM vision failed image_url={resolved_image_url} error={detail}")
            warning = f"MiniCPM vision unavailable: {detail}"
    return {
        "ok": True,
        "runtime": "fallback",
        "model": MINICPM_VISION_MODEL,
        "alt_text": alt_text,
        "warning": warning,
        "elapsed_ms": _elapsed_ms(start),
    }


def describe_article_images_core() -> dict[str, Any]:
    start = time.perf_counter()
    descriptions = []
    for image in ARTICLE_IMAGES:
        description = describe_image_core(
            image["id"],
            caption=image.get("caption"),
            prompt=image.get("prompt"),
            image_url=image.get("vision_asset_url") or image.get("asset_url"),
        )
        descriptions.append({**image, **description})
    runtimes = {item["runtime"] for item in descriptions}
    return {
        "ok": True,
        "runtime": runtimes.pop() if len(runtimes) == 1 else "mixed",
        "model": MINICPM_VISION_MODEL,
        "descriptions": descriptions,
        "elapsed_ms": _elapsed_ms(start),
    }


def _silent_wav(path: Path, seconds: float = 0.35, sample_rate: int = 24000) -> None:
    frames = int(seconds * sample_rate)
    with wave.open(str(path), "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(sample_rate)
        wav.writeframes(b"\x00\x00" * frames)


def _prune_speech_outputs(keep_path: Path, max_files: int = 24) -> None:
    speech_files = sorted(
        OUTPUT_DIR.glob("speech*.wav"),
        key=lambda path: path.stat().st_mtime,
        reverse=True,
    )
    keep_resolved = keep_path.resolve()
    for old_path in speech_files[max_files:]:
        if old_path.resolve() == keep_resolved:
            continue
        try:
            old_path.unlink()
        except OSError:
            pass


def speak_core(text: str, voice: str, speed: float) -> dict[str, Any]:
    start = time.perf_counter()
    clean_text = _compact_text(text, 1200)
    if not clean_text:
        output_path = OUTPUT_DIR / f"speech-fallback-{uuid4().hex}.wav"
        _silent_wav(output_path)
        _prune_speech_outputs(output_path)
        return {
            "ok": True,
            "runtime": "fallback",
            "model": "hexgrad/Kokoro-82M",
            "warning": "Kokoro skipped because transcript was empty",
            "audio_url": f"/outputs/{output_path.name}",
            "transcript": "",
            "elapsed_ms": _elapsed_ms(start),
        }
    try:
        from kokoro import KPipeline
        import soundfile as sf

        pipeline = KPipeline(lang_code="a")
        generator = pipeline(clean_text, voice=voice, speed=speed)
        _, _, audio = next(generator)
        output_path = OUTPUT_DIR / f"speech-{uuid4().hex}.wav"
        sf.write(output_path, audio, 24000)
        runtime = "kokoro"
        warning = None
    except Exception as exc:
        output_path = OUTPUT_DIR / f"speech-fallback-{uuid4().hex}.wav"
        _silent_wav(output_path)
        runtime = "fallback"
        warning = f"Kokoro unavailable: {exc.__class__.__name__}"

    _prune_speech_outputs(output_path)

    return {
        "ok": True,
        "runtime": runtime,
        "model": "hexgrad/Kokoro-82M",
        "warning": warning,
        "audio_url": f"/outputs/{output_path.name}",
        "transcript": clean_text,
        "elapsed_ms": _elapsed_ms(start),
    }


def _call_modal_klein(prompt: str, seed: int | None) -> dict[str, Any]:
    """Call the Modal Klein worker for live image generation."""
    start = time.perf_counter()
    body = json.dumps({"prompt": prompt, "seed": seed}).encode("utf-8")
    headers: dict[str, str] = {"Content-Type": "application/json"}
    if KLEIN_MODAL_TOKEN:
        headers["Authorization"] = f"Bearer {KLEIN_MODAL_TOKEN}"
    endpoint = _modal_klein_base_url()
    generate_url = f"{endpoint}/generate"
    _runtime_log(
        "Modal Klein generate request "
        f"url={generate_url} token={'configured' if KLEIN_MODAL_TOKEN else 'not-set'} seed={seed}"
    )
    request = urllib.request.Request(
        generate_url,
        data=body,
        headers=headers,
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=KLEIN_MODAL_TIMEOUT_SECONDS) as response:
            payload = json.loads(response.read().decode("utf-8"))
    except (OSError, urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
        detail = _http_exception_detail(exc)
        _runtime_log(f"Modal Klein generate failed url={generate_url} error={detail}")
        raise
    if payload.get("ok") is not True:
        _runtime_log(f"Modal Klein generate returned ok=false payload={_compact_text(json.dumps(payload), 400)}")
        raise ValueError(str(payload.get("error") or payload.get("detail") or "Modal Klein returned ok=false"))
    if payload.get("model") != MODEL_MANIFEST["image_generation"]["id"]:
        _runtime_log(f"Modal Klein generate returned unexpected model={payload.get('model')}")
        raise ValueError("Modal Klein returned unexpected model")
    if payload.get("runtime") != "modal-klein":
        _runtime_log(f"Modal Klein generate returned unexpected runtime={payload.get('runtime')}")
        raise ValueError("Modal Klein returned unexpected runtime")
    image_url = payload.get("image_url", "")
    if not isinstance(image_url, str) or not image_url:
        _runtime_log("Modal Klein generate response did not include image_url")
        raise ValueError("Modal Klein response did not include image_url")
    if image_url and image_url.startswith("/media/"):
        image_url = f"{endpoint}{image_url}"
    _runtime_log(f"Modal Klein generate succeeded runtime={payload.get('runtime')} image_url={image_url}")
    return {
        "ok": True,
        "runtime": payload.get("runtime", "modal-klein"),
        "model": payload.get("model", MODEL_MANIFEST["image_generation"]["id"]),
        "image_url": image_url,
        "prompt": payload.get("prompt", prompt),
        "seed": payload.get("seed", seed),
        "elapsed_ms": payload.get("elapsed_ms", _elapsed_ms(start)),
    }


def _fallback_image(prompt: str, seed: int | None, warning: str | None = None) -> dict[str, Any]:
    """Return bundled fallback SVG assets when Modal is unavailable."""
    start = time.perf_counter()
    return {
        "ok": True,
        "runtime": "fallback",
        "model": MODEL_MANIFEST["image_generation"]["id"],
        "image_url": f"/static/generated/{'desk-reader.svg' if seed and seed % 2 else 'model-map.svg'}",
        "prompt": prompt,
        "seed": seed,
        "warning": warning,
        "elapsed_ms": _elapsed_ms(start),
    }


def generate_image_core(prompt: str, seed: int | None) -> dict[str, Any]:
    if KLEIN_MODAL_ENDPOINT:
        try:
            return _call_modal_klein(prompt, seed)
        except (OSError, urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:
            return _fallback_image(prompt, seed, warning=f"Modal Klein unavailable: {_http_exception_detail(exc)}")
    _runtime_log("Modal Klein generate skipped because KLEIN_MODAL_ENDPOINT is not configured")
    return _fallback_image(prompt, seed)


def _thumbnail_image_prompt(topic: str) -> str:
    return (
        f"Square image-only editorial thumbnail about {topic}. "
        "Create one centered cohesive scene: a friendly assistive robot or small AI helper guiding a reader "
        "through visual information with light, sound waves, image cards, and accessibility cues. "
        "Fill most of the frame with the subject while leaving a small clean margin. "
        "Modern polished 3D editorial illustration, soft gradients, warm blue and teal accents, clear focal point. "
        "No words, no letters, no numbers, no captions, no title, no logo, no watermark, "
        "no user interface, no screenshot, no document page, no poster layout, no split panels."
    )


def generate_article_core(topic: str) -> dict[str, Any]:
    start = time.perf_counter()
    clean_topic = _compact_text(topic, 100).strip()
    if not clean_topic:
        clean_topic = "accessible technology"

    article = _fallback_article(clean_topic)
    runtime = "fallback"
    warning = None
    if not LLAMA_CPP_BASE_URL:
        warning = "llama.cpp unavailable: LLAMA_CPP_BASE_URL is not configured"
    else:
        try:
            body = json.dumps(
                {
                    "model": LLAMA_CPP_MODEL,
                    "messages": [
                        {
                            "role": "system",
                            "content": (
                                "You are Tiny Narrator's article generator. "
                                "Create concise, semantic, accessible article drafts."
                            ),
                        },
                        {"role": "user", "content": _article_generation_prompt(clean_topic)},
                    ],
                    "temperature": 0.35,
                    "max_tokens": 650,
                }
            ).encode("utf-8")
            request = urllib.request.Request(
                f"{LLAMA_CPP_BASE_URL}/chat/completions",
                data=body,
                headers=_llama_cpp_headers({"Content-Type": "application/json"}),
                method="POST",
            )
            with urllib.request.urlopen(request, timeout=LLAMA_CPP_TIMEOUT_SECONDS) as response:
                payload = json.loads(response.read().decode("utf-8"))
            generated = json.loads(payload["choices"][0]["message"]["content"].strip())
            sections = generated.get("sections", [])
            if (
                isinstance(generated.get("title"), str)
                and isinstance(generated.get("dek"), str)
                and isinstance(sections, list)
                and len(sections) == 5
                and all(isinstance(item.get("heading"), str) and isinstance(item.get("body"), str) for item in sections)
            ):
                article = {
                    "title": _compact_text(generated["title"], 90),
                    "dek": _compact_text(generated["dek"], 180),
                    "sections": [
                        {"heading": _compact_text(item["heading"], 80), "body": _compact_text(item["body"], 720)}
                        for item in sections
                    ],
                }
                runtime = "llama.cpp"
        except (OSError, urllib.error.URLError, TimeoutError, ValueError, KeyError, json.JSONDecodeError) as exc:
            warning = f"llama.cpp unavailable: {exc.__class__.__name__}"

    image_prompt = _thumbnail_image_prompt(clean_topic)
    thumbnail = generate_image_core(image_prompt, seed=_topic_seed(clean_topic))
    return {
        "ok": True,
        "topic": clean_topic,
        "runtime": runtime,
        "model": MODEL_MANIFEST["reader_brain"]["id"],
        "warning": warning,
        "article": article,
        "thumbnail": {
            **thumbnail,
            "role": "thumbnail",
            "generation_model": MODEL_MANIFEST["image_generation"]["id"],
        },
        "elapsed_ms": _elapsed_ms(start),
    }


@app.get("/", response_class=HTMLResponse)
async def home() -> str:
    return (STATIC_DIR / "index.html").read_text(encoding="utf-8")


@app.get("/generate", response_class=HTMLResponse)
async def generate_page() -> str:
    return (STATIC_DIR / "generate.html").read_text(encoding="utf-8")


@app.get("/api/health")
async def health() -> JSONResponse:
    return _json(
        {
            "ok": True,
            "app": "Tiny Narrator",
            "frontend": "custom Gradio Server HTML/CSS/JS",
            "llama_cpp_base_url": LLAMA_CPP_BASE_URL,
            "public_base_url": PUBLIC_BASE_URL,
            "models": MODEL_MANIFEST,
        }
    )


@app.get("/api/article-manifest")
async def article_manifest() -> JSONResponse:
    return _json({"ok": True, **ARTICLE_MANIFEST})


@app.get("/api/award-evidence")
async def award_evidence() -> JSONResponse:
    return _json({"ok": True, "items": AWARD_EVIDENCE})


@app.get("/api/model-budget")
async def model_budget() -> JSONResponse:
    return _json(model_budget_core())


@app.get("/api/runtime-setup")
async def runtime_setup() -> JSONResponse:
    return _json(runtime_setup_core())


@app.get("/api/demo-script")
async def demo_script() -> JSONResponse:
    return _json(demo_script_core())


@app.get("/api/accessibility-audit")
async def accessibility_audit() -> JSONResponse:
    return _json(accessibility_audit_core())


@app.get("/api/submission-readiness")
async def submission_readiness() -> JSONResponse:
    return _json(submission_readiness_core())


@app.get("/api/evidence-bundle")
async def evidence_bundle() -> JSONResponse:
    return _json(evidence_bundle_core())


@app.get("/api/runtime-status")
async def runtime_status() -> JSONResponse:
    return _json(_runtime_status_core())


@app.post("/api/reader-brain")
async def reader_brain_endpoint(payload: ReaderBrainRequest) -> JSONResponse:
    return _json(reader_brain_core(payload.node_type, payload.text, payload.position, payload.mode))


@app.post("/api/describe-image")
async def describe_image_endpoint(payload: ImageDescriptionRequest) -> JSONResponse:
    return _json(describe_image_core(payload.image_id, payload.caption, payload.prompt, payload.image_url))


@app.get("/api/image-descriptions")
async def image_descriptions_endpoint() -> JSONResponse:
    return _json(describe_article_images_core())


@app.post("/api/speak")
async def speak_endpoint(payload: SpeechRequest) -> JSONResponse:
    return _json(speak_core(payload.text, payload.voice, payload.speed))


@app.post("/api/generate-image")
async def generate_image_endpoint(payload: ImageGenerationRequest) -> JSONResponse:
    return _json(generate_image_core(payload.prompt, payload.seed))


@app.post("/api/generate-article")
async def generate_article_endpoint(payload: ArticleGenerationRequest) -> JSONResponse:
    return _json(generate_article_core(payload.topic))


@app.api(name="reader_brain")
def reader_brain_api(node_type: str, text: str, position: str = "", mode: str = "narrate") -> str:
    return json.dumps(reader_brain_core(node_type, text, position, mode))


@app.api(name="describe_image")
def describe_image_api(image_id: str, caption: str = "", prompt: str = "", image_url: str = "") -> str:
    return json.dumps(describe_image_core(image_id, caption, prompt, image_url))


@app.api(name="describe_article_images")
def describe_article_images_api() -> str:
    return json.dumps(describe_article_images_core())


@app.api(name="model_budget")
def model_budget_api() -> str:
    return json.dumps(model_budget_core())


@app.api(name="runtime_setup")
def runtime_setup_api() -> str:
    return json.dumps(runtime_setup_core())


@app.api(name="demo_script")
def demo_script_api() -> str:
    return json.dumps(demo_script_core())


@app.api(name="accessibility_audit")
def accessibility_audit_api() -> str:
    return json.dumps(accessibility_audit_core())


@app.api(name="submission_readiness")
def submission_readiness_api() -> str:
    return json.dumps(submission_readiness_core())


@app.api(name="evidence_bundle")
def evidence_bundle_api() -> str:
    return json.dumps(evidence_bundle_core())


@app.api(name="speak")
def speak_api(text: str, voice: str = "af_heart", speed: float = 1.0) -> str:
    return json.dumps(speak_core(text, voice, speed))


@app.api(name="generate_image")
def generate_image_api(prompt: str, seed: int | None = None) -> str:
    return json.dumps(generate_image_core(prompt, seed))


@app.api(name="generate_article")
def generate_article_api(topic: str) -> str:
    return json.dumps(generate_article_core(topic))


@app.exception_handler(Exception)
async def handle_exception(_: Request, exc: Exception) -> JSONResponse:
    return _json({"ok": False, "error": exc.__class__.__name__, "detail": str(exc)}, status_code=500)


if __name__ == "__main__":
    app.launch(server_name=GRADIO_SERVER_NAME, server_port=GRADIO_SERVER_PORT, share=GRADIO_SHARE)