Spaces:
Paused

File size: 128,138 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

models.py β€” Lazy-loaded model backends: embedding model, ChromaDB handle,

text LLM (HuggingFace or GGUF via llama_backend), Vision LLM, and

Speech-to-Text pipeline. Each model type keeps its own module-level cache

and lock, following the lazy-load/lock pattern used throughout the app.

"""

import gc
import os
import threading
import time
from pathlib import Path
from typing import Any, Optional

import torch

from backend import llama_backend
from backend import model_registry as mr
from backend import whisper_cpp_backend
from backend.hardware import DEVICE, TORCH_DTYPE, is_illegal_instruction_error
from backend.live_stream import get_bus
from backend.metadata_hardening import harden_metadata
from ui import i18n
from ui.i18n import LANGUAGES

harden_metadata()


# ──────────────────────────────────────────────────────────────────
# Patch transformers' Gemma-4 RoPE device-mismatch bug:
# In transformers, Gemma4TextRotaryEmbedding.forward does matrix
# multiplication `@` with position_ids on CPU and inv_freq on CUDA when
# device_map="cuda" is used, causing "Expected all tensors to be on the
# same device" RuntimeError.
# ──────────────────────────────────────────────────────────────────
try:
    from transformers.models.gemma4 import modeling_gemma4
    _orig_gemma4_rotary_forward = modeling_gemma4.Gemma4TextRotaryEmbedding.forward

    def _patched_gemma4_rotary_forward(self, x, position_ids, layer_type=None):
        if position_ids is not None and position_ids.device != x.device:
            position_ids = position_ids.to(x.device)
        return _orig_gemma4_rotary_forward(self, x, position_ids, layer_type=layer_type)

    modeling_gemma4.Gemma4TextRotaryEmbedding.forward = _patched_gemma4_rotary_forward
    print("[Gemma4] Applied RoPE device-alignment patch for Gemma4TextRotaryEmbedding.")
except Exception:
    pass


# ──────────────────────────────────────────────────────────────────
# Download size estimation β€” BF16 download sizes in GB for each model
# (from Google's official docs and HuggingFace model cards). Used to
# warn the user before downloading large models they haven't cached yet.
# ──────────────────────────────────────────────────────────────────
_DOWNLOAD_SIZE_GB = mr.DOWNLOAD_SIZE_GB


def _hf_snapshot_has_weights(model_id: str) -> bool:
    """True when the model's local HF cache snapshot contains at least one

    real weight file.



    Metadata alone proves nothing: ``snapshot_download`` fetches the tiny

    config/tokenizer files FIRST, so an interrupted download still caches

    config.json / generation_config.json β€” which made ``is_model_cached``

    report "cached" while the multi-GB safetensors were still downloading

    (the false "Download complete" popup). Weight files are only linked into

    ``snapshots/`` once their blob is complete; an in-progress download lives

    in ``blobs/*.incomplete`` and never appears here."""
    if not model_id:
        return False
    try:
        # huggingface_hub 1.x keeps the constant in .constants (no top-level export)
        from huggingface_hub.constants import HF_HUB_CACHE
        cache_root = HF_HUB_CACHE
    except Exception:
        cache_root = os.environ.get("HF_HUB_CACHE") or os.path.join(
            os.environ.get("HF_HOME") or os.path.join(os.path.expanduser("~"), ".cache"),
            "huggingface", "hub",
        )
    repo_dir = os.path.join(cache_root, "models--" + str(model_id).replace("/", "--"))
    snaps = os.path.join(repo_dir, "snapshots")
    if not os.path.isdir(snaps):
        return False
    weight_exts = (".safetensors", ".bin", ".gguf", ".pt", ".th", ".msgpack", ".h5", ".onnx")
    try:
        for root, _dirs, files in os.walk(snaps):
            for fn in files:
                if fn.lower().endswith(weight_exts):
                    return True
                try:
                    if os.stat(os.path.join(root, fn)).st_size >= 1024 * 1024:
                        return True
                except OSError:
                    continue
    except OSError:
        return False
    return False


def is_model_cached(model_id: str) -> bool:
    """Check if a HuggingFace model or GGUF model is already cached locally."""
    if not model_id:
        return False
    if str(model_id).lower().endswith(".gguf") and os.path.isfile(model_id):
        return True
    # GGUF quant-pinned id form "repo#filename.gguf"
    if "#" in model_id:
        parts = model_id.split("#", 2)
        repo_id = parts[0]
        filename = parts[1] if len(parts) > 1 else None
        if filename:
            try:
                from backend import llama_backend
                # Search EVERY standard model folder β€” the configured GGUF
                # dir, the whisper.cpp dir and the user_data/gguf_models
                # fallback. The old llama-dir-only check never saw a model
                # downloaded into the fallback (no folder configured), so
                # the download popup re-appeared on every pick.
                if llama_backend.find_downloaded_model_file(filename):
                    return True
            except Exception:
                pass
            try:
                from huggingface_hub import try_to_load_from_cache
                res = try_to_load_from_cache(repo_id, filename)
                if res is not None and not isinstance(res, type(None)):
                    return True
            except Exception:
                pass
            return False

    # Check known GGUF repos
    try:
        from backend import llama_backend
        if model_id in llama_backend.KNOWN_GGUF_REPOS:
            info = llama_backend.KNOWN_GGUF_REPOS[model_id]
            fn = info.get("main")
            if fn:
                mdir = Path(llama_backend.LLAMA_CPP_MODEL_DIR)
                if mdir.exists() and llama_backend._find_gguf_in_model_tree(mdir, fn):
                    return True
                from huggingface_hub import try_to_load_from_cache
                res = try_to_load_from_cache(model_id, fn)
                if res is not None and not isinstance(res, type(None)):
                    return True
    except Exception:
        pass

    try:
        # A cached config.json / generation_config.json alone proves NOTHING β€”
        # snapshot_download fetches small metadata first, so an interrupted
        # download still has them and the old check reported "cached" while
        # the multi-GB weights were still downloading (the false "Download
        # complete" popup). Require a real weight file in the snapshot.
        return _hf_snapshot_has_weights(model_id)
    except Exception:
        return False


def get_download_size_gb(model_id: str) -> Optional[float]:
    """Return estimated BF16 download size in GB, or None if unknown."""
    return _DOWNLOAD_SIZE_GB.get(model_id)


def check_model_download(model_id: str) -> Optional[str]:
    """Return a warning message if the model needs downloading, or None

    if it's already cached or is a GGUF/local file."""
    if is_model_cached(model_id):
        return None
    size_gb = get_download_size_gb(model_id)
    if size_gb is None:
        return f"Model '{model_id}' will be downloaded (size unknown)."
    if size_gb >= 20:
        return (
            f"⚠️ '{model_id}' is NOT cached locally and will download "
            f"~{size_gb:.0f} GB. This may take a while depending on your "
            f"internet speed."
        )
    return (
        f"Model '{model_id}' will download ~{size_gb:.0f} GB."
    )

_embed_model         = None
_embed_model_id      = None
_embed_provider      = None
_embed_lock          = threading.Lock()
_chroma_col          = None
_chroma_client       = None
_llm                 = None
_llm_model_id        = mr.DEFAULT_LLM_MODEL
# Context window (n_ctx) the currently-loaded LLM was built with β€” only
# meaningful for the GGUF/llama.cpp backend (see model_registry.py's
# CONTEXT_WINDOW_OPTIONS). None until a GGUF model has actually been
# loaded at least once; HF/transformers models leave this as None too,
# since n_ctx doesn't apply to them.
_llm_n_ctx           = None
# Backend key the currently-loaded LLM was (or was attempted to be) built
# for β€” the (model, provider, backend-mode) discriminator that must match
# for get_llm()'s early-return cache to be valid. Records the REQUESTED
# backend (not necessarily what was actually built: when llama-cpp-python
# is missing, the in-process request auto-falls back to llama-server, and
# recording the request rather than the fallback avoids a rebuild loop on
# every call). See _llm_backend_key_for().
_llm_backend_key     = None

# ──────────────────────────────────────────────────────────────────
# Some newer HuggingFace checkpoints ship architectures that only
# `transformers` releases from a certain version onward know how to
# build (as opposed to older custom-arch models that ship their own
# `trust_remote_code` modeling file and work on any transformers
# version). deepreinforce-ai/Ornith-1.0-9B is one of these: it's a
# Qwen3.5 hybrid linear-/full-attention ("qwen35") architecture that
# requires transformers >= 5.8.1 to even recognize the config class β€”
# on an older install this fails with a confusing
# "Unrecognized configuration class" / KeyError deep inside
# AutoModelForCausalLM.from_pretrained() instead of a clear message.
# Keyed by the model ids in model_registry.ORNITH_IDS so this stays a
# single source of truth if more Ornith-family models are added later.
# ──────────────────────────────────────────────────────────────────
_MIN_TRANSFORMERS_VERSION = {
    "ornith": "5.8.1",
    # Qwen3.6 (dense Qwen3.6-27B, MoE Qwen3.6-35B-A3B) uses the "qwen3_5"
    # architecture β€” confirmed via community reports that transformers
    # <5.2.0 doesn't recognize it (same "config class not found" failure
    # mode as Ornith above). Now wired into BASE_MODEL_OPTIONS (see
    # model_registry.QWEN36_IDS) β€” loading it with an older transformers
    # fails with a clear upgrade message rather than a cryptic AutoModel
    # crash.
    "qwen36": "5.2.0",
    # Gemma 4 (E2B/E4B/12B/26B-A4B/31B) introduced the "gemma4" model type
    # in transformers 5.5.0 β€” confirmed directly via huggingface/transformers
    # issue #45376 and multiple vLLM/llm-compressor compatibility reports.
    # Google's own docs recommend >=5.10.1. Below 5.5.0, AutoConfig can't
    # even parse the checkpoint's config.json (fails with a confusing
    # "'list' object has no attribute 'keys'" deep in tokenizer setup,
    # not a clear version message) β€” this guard replaces that with an
    # actionable error. Applies to google/gemma-4-E2B-it (the app's
    # existing default!) as much as any newly-registered Gemma 4 size.
    "gemma4": "5.10.1",
    # Qwen3-VL (Qwen3VLForConditionalGeneration / Qwen3VLProcessor) only
    # exists in transformers 5.x β€” the Qwen3-VL classes landed with v5.0.0.
    # Below that the AutoModelForImageTextToText fallback in get_vlm() is
    # used, which may not map the Qwen3-VL architecture β€” the guard replaces
    # that gamble with a clear upgrade message.
    "qwen3vl": "5.0.0",
}

# Model-id-set -> (version-guard key, human-readable architecture note).
# Checked in order; first matching set wins. Table-driven so adding a new
# guarded family is one line here instead of another elif branch.
def _version_guard_families():
    return (
        (mr.ORNITH_IDS, "ornith", "Qwen3.5 hybrid linear-/full-attention architecture"),
        (mr.QWEN36_IDS, "qwen36", "Qwen3.6 (qwen3_5) architecture"),
        (mr.GEMMA4_IDS, "gemma4", "Gemma 4 (gemma4) multimodal architecture"),
        (mr.QWEN3_VL_IDS, "qwen3vl", "Qwen3-VL (qwen3_vl) multimodal architecture"),
    )


def _version_tuple(version_str: str) -> tuple:
    """Parse a dotted version string into a comparable tuple of ints,

    ignoring any non-numeric suffix (e.g. 'dev0', 'rc1') per component."""
    parts = []
    for p in str(version_str).split(".")[:3]:
        digits = "".join(ch for ch in p if ch.isdigit())
        parts.append(int(digits) if digits else 0)
    while len(parts) < 3:
        parts.append(0)
    return tuple(parts)


def _check_transformers_version_for(model_id: str) -> None:
    """Raise a clear, actionable RuntimeError if the installed

    `transformers` version is too old to load `model_id`, instead of

    letting a cryptic internal AutoModel error surface first."""
    min_version = None
    arch_note = None
    for id_set, guard_key, note in _version_guard_families():
        if model_id in id_set:
            min_version = _MIN_TRANSFORMERS_VERSION[guard_key]
            arch_note = note
            break
    if min_version is None:
        return
    import transformers as _tf
    installed = getattr(_tf, "__version__", "0")
    if _version_tuple(installed) < _version_tuple(min_version):
        raise RuntimeError(
            f"'{model_id}' needs transformers >= {min_version} β€” it's a "
            f"{arch_note} that older "
            f"transformers releases don't recognize. You have {installed} "
            f"installed.\n\n"
            f"Upgrade with:\n"
            f'  pip install --upgrade "transformers>={min_version}"\n\n'
            f"Then restart the app and try loading the model again."
        )
_vlm_model           = None
_vlm_processor       = None
_vlm_model_id        = None
_vlm_n_ctx           = None
# Backend key the currently-loaded VLM was (or was attempted to be) built
# for β€” the Vision-tab analog of _llm_backend_key (see
# _vlm_backend_key_for()). Same semantics: records the REQUESTED backend so
# get_vlm()'s early-return cache can detect a provider switch that must
# rebuild (releasing a stale server-backed VLM / stopping llama-server).
_vlm_backend_key     = None
_llm_lock            = threading.Lock()
_vlm_lock            = threading.Lock()
_stt_pipeline        = None
_stt_model_id        = None
_stt_lock            = threading.Lock()


def _release_and_clear(global_attr: str):
    """Drop a model-holder module global BEFORE releasing the object, so

    _release_model's `del obj` + gc.collect() + torch.cuda.empty_cache()

    can ACTUALLY collect it.



    The old order (release-then-clear) kept the module global referencing

    the object while _release_model ran: `del obj` only dropped the local

    param reference, gc.collect() found the object still alive, and

    empty_cache() had no freed blocks to reclaim. For a transformers VLM

    the outcome was worse than a no-op β€” `.to("cpu")` is BLOCKED by

    accelerate on device_map-loaded models (Gemma-4 uses device_map="auto",

    Qwen/SmolVLM device_map=DEVICE), so no weight ever left the GPU and

    the whole model stayed resident: the "Free All VRAM still shows ~43%

    after vision chat" leak. Returns the released object (None when the

    global was already empty) so callers that need its id read it first."""
    obj = globals().get(global_attr)
    globals()[global_attr] = None
    if obj is not None:
        _release_model(obj)
    return obj


def _release_model(obj):
    """Explicitly free memory held by a model before dropping the last

    Python reference to it.



    Just setting a global cache variable to None does NOT free GPU/CPU

    memory right away:

      - transformers/torch models: the CUDA caching allocator keeps the

        freed blocks around until torch.cuda.empty_cache() runs (and that

        can only reclaim memory from tensors that have already been

        garbage-collected).

      - llama.cpp (llama-cpp-python) models: the native context / KV-cache

        lives in a C++ object. Its Python wrapper's __del__ will eventually

        close it, but only once the GC actually runs the finalizer β€” which

        is not guaranteed to happen before the next model tries to load,

        causing an OOM when switching models back-to-back.

      - Subprocess-hosted models (LlamaServerModel / LlamaServerVLMModel /

        EmbeddingServerModel via llama-server.exe, WhisperServerModel via

        whisper-server.exe): the real weights live in a SEPARATE process,

        so no Python cleanup helps β€” releasing these objects stops the

        managed subprocess instead (see the branches below).



    Calling this before overwriting/loading a new model avoids the

    "previous model didn't offload, so the next one fails to load" issue.

    """
    if obj is None:
        return

    # llama-server (external process) backend: LlamaServerModel /
    # LlamaServerVLMModel ride the CHAT llama-server subprocess, while
    # EmbeddingServerModel (a GGUF embedding model) has its OWN dedicated
    # embedding subprocess since the port-collision fix (a shared server
    # let a RAG retrieval replace the chat GGUF with an embedding GGUF on
    # the SAME port mid-conversation). None of these wrappers have an
    # in-process model/KV-cache to release β€” the real memory lives in the
    # separate llama-server subprocess. "Releasing" the object means
    # stopping THAT wrapper's own server slot, not any of the
    # torch/llama.cpp cleanup below (which doesn't apply β€” there's no
    # `.llm`/`.model` attribute holding real weights in this Python
    # process). EmbeddingServerModel was previously MISSED by this branch,
    # so "Free All VRAM" dropped its Python wrapper while the
    # llama-server.exe subprocess kept the embedding GGUF loaded in VRAM.
    if isinstance(obj, EmbeddingServerModel):
        # Stop ONLY the dedicated embedding server β€” never the chat/VLM
        # server (independent slots; releasing embeddings must not take
        # the chat model down).
        llama_backend.stop_embed_server()
        del obj
        return

    if isinstance(obj, (
        llama_backend.LlamaServerModel,
        llama_backend.LlamaServerVLMModel,
    )):
        llama_backend.stop_llama_server()
        del obj
        return

    # whisper-server (external process) backend: WhisperServerModel posts to
    # a separate whisper-server subprocess that holds the GGML model in VRAM
    # β€” same story as the llama-server branch above: dropping the wrapper
    # without stopping the subprocess leaves the model resident in GPU
    # memory, so stopping the managed server IS the "release".
    if isinstance(obj, whisper_cpp_backend.WhisperServerModel):
        whisper_cpp_backend.stop_whisper_server()
        del obj
        return

    try:
        # llama.cpp backend: LlamaCppModel wraps the native llama_cpp.Llama
        # instance as `.llm` β€” close it explicitly to free the KV-cache /
        # context right now instead of waiting on GC.
        inner = getattr(obj, "llm", None)
        if inner is not None and hasattr(inner, "close"):
            try:
                inner.close()
            except Exception:
                pass

        # transformers / smolagents TransformersModel: move the module off
        # the GPU so CUDA's allocator can reclaim it. Try the WHOLE module
        # first (moves every submodule incl. a VLM's .visual / .lm_head),
        # then the underlying `.model` β€” accelerate blocks `.to()` on
        # device_map-loaded models, so both attempts can fail; in that case
        # the caller's _release_and_clear() ordering is what actually frees
        # the object (del + gc + empty_cache with no surviving reference).
        moved = False
        for candidate in (obj, getattr(obj, "model", None)):
            if candidate is None or not hasattr(candidate, "to") or isinstance(candidate, str):
                continue
            try:
                candidate.to("cpu")
                moved = True
                break
            except Exception:
                continue
    except Exception:
        pass

    del obj
    gc.collect()
    try:
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            torch.cuda.ipc_collect()
        elif hasattr(torch, "xpu") and torch.xpu.is_available():
            torch.xpu.empty_cache()
            torch.xpu.synchronize()
        elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
            torch.mps.empty_cache()
    except Exception:
        pass


def get_embed_model(model_id: Optional[str] = None, provider: Optional[str] = None):
    """Lazily build (or rebuild, if the model id or provider changed) the shared

    embedding model instance.



    `model_id` lets the "🧩 Embedding Model" control on the Knowledge Base

    tab switch models at runtime, the same way get_llm()/get_vlm() already do

    for their tabs. If not given, falls back to whatever embedding model was

    saved in user_config or hardware-tier recommendation for the active provider.

    """
    global _embed_model, _embed_model_id, _embed_provider
    prov = provider or mr.get_saved_provider("embed")
    target = model_id or mr.get_default_embed_model(prov)

    if _embed_model is not None and target == _embed_model_id and _embed_provider == prov:
        return _embed_model

    with _embed_lock:
        if _embed_model is not None and target == _embed_model_id and _embed_provider == prov:
            return _embed_model

        if _embed_model is not None:
            print(f"[RAG] Unloading previous embedding model '{_embed_model_id}' before loading '{target}' ({prov}) …")
            _release_and_clear("_embed_model")

        # ── HF Inference API ──────────────────────────────────────
        if target == mr.HF_INFERENCE_API_SENTINEL or prov == mr.PROVIDER_HF_API:
            hf_model_id = mr.get_hf_api_model_id_for("embed")
            if not hf_model_id:
                raise ValueError(
                    "Hugging Face Inference API selected for Embedding, but no "
                    "model ID is configured."
                )
            _embed_model = InferenceApiEmbeddingModel(model_id=hf_model_id)
            _embed_model_id = target
            _embed_provider = prov
            return _embed_model

        # ── llama.cpp server embeddings ──────────────────────────
        is_gguf = (
            str(target).lower().endswith(".gguf")
            or target in mr.PRESET_GGUF_EMBED_MODELS
            or target in mr.PRESET_GGUF_EMBED_MODELS.values()
            or prov in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
        )
        if is_gguf:
            print(f"[RAG] Starting dedicated embedding llama-server with '{target}' …")
            base_url = llama_backend.get_or_start_embed_server(
                model_path=target,
                n_ctx=mr.get_saved_context_window(),
                n_gpu_layers=-1,  # external llama-server has its own GPU support
            )
            _embed_model = EmbeddingServerModel(
                model_path=target, base_url=base_url,
                n_ctx=mr.get_saved_context_window(),
            )
            _embed_model_id = target
            _embed_provider = prov
            return _embed_model

        # ── Local HuggingFace SentenceTransformer ────────────────
        print(f"[RAG] Loading embedding model '{target}' on {DEVICE.upper()} …")
        from sentence_transformers import SentenceTransformer
        try:
            _embed_model = SentenceTransformer(target, device=DEVICE, trust_remote_code=True)
        except TypeError:
            _embed_model = SentenceTransformer(target, device=DEVICE)
        _embed_model_id = target
        _embed_provider = prov
        return _embed_model


def force_reload_embed_model(target_model_id: str, provider: Optional[str] = None):
    """Used by the Knowledge Base tab's "🧩 Embedding Model" Load button:

    fully release whatever embedding model is currently loaded (regardless

    of id) and load `target_model_id` fresh β€” mirrors force_reload_llm()/

    force_reload_vlm()/force_reload_stt()."""
    global _embed_model, _embed_model_id, _embed_provider
    _release_and_clear("_embed_model")
    _embed_model_id = None
    _embed_provider = None
    return get_embed_model(target_model_id, provider=provider)


def unload_embed_model_fn(lang_key: str = "kh") -> str:
    """Explicit "force unload from VRAM" action for the embedding model β€”

    mirrors unload_llm_fn()/unload_vlm_fn()/unload_stt_fn()."""
    global _embed_model, _embed_model_id, _embed_provider
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if _embed_model is None:
        return l["btn_unload_none"]
    mid = _embed_model_id
    _release_and_clear("_embed_model")
    _embed_model_id = None
    _embed_provider = None
    return l["msg_unloaded"].format(model=mid)


def encode_texts(texts: list, normalize: bool = True, model_id: Optional[str] = None, provider: Optional[str] = None):
    embed = get_embed_model(model_id=model_id, provider=provider)
    # InferenceApiEmbeddingModel and EmbeddingServerModel have their own
    # encode() with a different signature.
    if hasattr(embed, "encode") and hasattr(embed, "model_id"):
        return embed.encode(texts, normalize=normalize)
    vecs = embed.encode(texts, normalize_embeddings=normalize,
                        show_progress_bar=False)
    return vecs.tolist() if hasattr(vecs, "tolist") else vecs


def get_chroma_collection(name: str = "rag_docs"):
    # NOTE: deliberately no "[RAG] ChromaDB ready β€” N chunks indexed."
    # print here anymore. This function is called from ui.py's
    # demo.load(kb.get_index_stats, ...) right after the UI mounts (see
    # ui.py's comment on why that's deferred rather than eager), so the
    # line used to show up in the terminal on every single app startup β€”
    # it did NOT mean an LLM/embedding model was being preloaded, only
    # that the ChromaDB persistent client had opened. Removed as pure
    # console noise; the same info is already visible in the UI's status
    # bar (kb.get_index_stats()) without needing a terminal print.
    global _chroma_col

    # Use a dimension-aware collection name so that switching to a
    # different embedding model automatically gets its own ChromaDB
    # collection instead of reusing one built with a different vector
    # dimension (which causes the "Collection expecting embedding with
    # dimension of 1024, got 2560" error).
    # When no embedding model is loaded yet, fall back to the hardcoded
    # dimensions table in model_registry.py for the saved/active embed
    # model id.
    _dim_name = None
    if _embed_model is not None:
        mid = getattr(_embed_model, 'model_name', None) or getattr(_embed_model, 'name', None)
        _dim_name = mr.EMBED_MODEL_DIMENSIONS.get(mid)
        if _dim_name is None and hasattr(_embed_model, 'get_sentence_transformer_model'):
            try:
                cfg = _embed_model.get_sentence_transformer_model().config
                _dim_name = getattr(cfg, 'hidden_size', None) or getattr(cfg, 'projection_dim', None)
            except Exception:
                pass
    if _dim_name is None:
        _dim_name = mr.EMBED_MODEL_DIMENSIONS.get(_embed_model_id, None)
    if _dim_name is None:
        _dim_name = mr.EMBED_MODEL_DIMENSIONS.get(mr.get_default_embed_model(), 1024)

    _dim_name = f"rag_docs_{_dim_name}d"

    if _chroma_col is not None:
        old_name = getattr(_chroma_col, 'name', None)
        if old_name is not None and old_name != _dim_name:
            try:
                import chromadb
                chromadb.PersistentClient(
                    path=mr.CHROMA_PERSIST_DIR,
                    settings=chromadb.Settings(anonymized_telemetry=False),
                ).delete_collection(old_name)
            except Exception:
                pass
            print(f"[RAG] Old ChromaDB collection '{old_name}' removed after embedding model switch.")
            _chroma_col = None

    if _chroma_col is None:
        import chromadb
        _chroma_client_new = chromadb.PersistentClient(
            path=mr.CHROMA_PERSIST_DIR,
            settings=chromadb.Settings(anonymized_telemetry=False),
        )
        _chroma_col = _chroma_client_new.get_or_create_collection(
            name=_dim_name, metadata={"hnsw:space": "cosine"})
        global _chroma_client
        _chroma_client = _chroma_client_new
    return _chroma_col


def reset_chroma_collection():
    """Used by clear_index() in knowledge_base.py to drop and recreate the

    collection object after deleting it from disk.



    On Windows, ChromaDB's PersistentClient holds SQLite file locks on the

    chroma_db/ directory β€” closing the client releases those locks so the

    subsequent shutil.rmtree() can actually delete the files."""
    global _chroma_col, _chroma_client
    if _chroma_client is not None:
        try:
            _chroma_client.close()
        except Exception:
            pass
        _chroma_client = None
    _chroma_col = None


def _is_gptq_or_awq(model_id: str) -> bool:
    """Check if a model id is a pre-quantized GPTQ, AWQ, BnB, or MLX checkpoint.

    These models ship with quantized weights and must NOT be re-quantized

    by bitsandbytes β€” doing so breaks loading and wastes time."""
    mid = str(model_id).lower()
    return "gptq" in mid or "awq" in mid or "bnb" in mid or "mlx" in mid or model_id in mr.GPTQ_AWQ_IDS





# ──────────────────────────────────────────────────────────────────────
# HF Inference API tool-schema sanitizer β€” smolagents serializes each
# agent Tool into an OpenAI-style function JSON schema for remote
# providers. Multimodal tool inputs (e.g. the stock SpeechToTextTool's
# {"audio": {"type": "audio"}}) use types that are NOT valid JSON Schema
# for function calling, and strict HF Inference API providers (DeepInfra,
# Novita, …) reject the ENTIRE request with
#   'audio' is not valid under any of the given schemas.
# general_agent.py also ships a fixed local SpeechToTextTool (string
# schema) β€” this sanitizer is the boundary guard so ANY tool with an
# invalid schema type can never break a remote call again.
# ──────────────────────────────────────────────────────────────────────
_JSON_SCHEMA_TYPES = {"string", "number", "integer", "boolean", "array", "object", "null"}


def sanitize_tool_json_schema(tool_dict: dict) -> dict:
    """Deep-copy an OpenAI-style tool/function schema with every property

    `type` outside the JSON-Schema set (e.g. "audio", "image") rewritten to

    "string". Returns a NEW dict; the input is never mutated.



    The tool wrapper's OWN top-level `"type": "function"` marker is

    preserved: it is the OpenAI-compatible API discriminant, NOT a

    JSON-Schema type, and rewriting it ("function" βˆ‰ JSON-Schema) sent

    every tool as `{"type": "string", ...}` β€” strict providers rejected

    the whole request with "Input should be 'function'" per tool."""
    import copy

    out = copy.deepcopy(tool_dict)

    def _walk(node):
        if isinstance(node, dict):
            t = node.get("type")
            # Only rewrite non-JSON-Schema PROPERTY types. The OpenAI tool
            # wrapper's `"type": "function"` marker is exempted so it can
            # never be corrupted to "string" (the regression that broke
            # every remote tool-calling request).
            if isinstance(t, str) and t not in _JSON_SCHEMA_TYPES and t != "function":
                node["type"] = "string"
            for v in node.values():
                _walk(v)
        elif isinstance(node, list):
            for v in node:
                _walk(v)

    _walk(out)
    return out


def install_tool_schema_sanitizer(llm) -> None:
    """Install the tool-schema sanitizer as an instance-level override on a

    remote smolagents LLM (InferenceClientModel / LiteLLMModel β€” both

    inherit `ApiModel._prepare_completion_kwargs`, which serializes the

    agent's tools into the OpenAI-style `tools` array of the request).

    Every tool property `type` outside JSON Schema (e.g. smolagents' stock

    "audio"/"image" inputs) is rewritten to "string" so strict providers

    (DeepInfra, Novita, …) never reject the whole request with

    "'audio' is not valid under any of the given schemas" β€” see

    sanitize_tool_json_schema(). The instance-level override keeps the

    class identity (type name / isinstance checks elsewhere) intact.



    If a future smolagents renames/removes the hook, this SILENTLY NO-OPS

    (the app's own tools already carry valid schemas), rather than crashing

    the remote branch of get_llm() at load time.

    """
    import types

    _orig = getattr(llm, "_prepare_completion_kwargs", None)
    if _orig is None:
        return
    _orig_func = getattr(_orig, "__func__", _orig)

    def _prepare_sanitized(self, *args, **kwargs):
        kw = _orig_func(self, *args, **kwargs)
        if kw.get("tools"):
            kw["tools"] = [sanitize_tool_json_schema(t) for t in kw["tools"]]
        return kw

    llm._prepare_completion_kwargs = types.MethodType(_prepare_sanitized, llm)


def _install_live_streaming(model):
    """Wire a smolagents remote/local model (HF Inference API, LiteLLM,

    transformers) into the live token-streaming bus.



    The GGUF backends already stream their generated tokens to the bus

    (`live` WS events β†’ the growing answer bubble in the web UI). The

    smolagents remote/local models were the gap: their stock `generate()`

    blocks until the whole response arrives, so tabs using the HF API /

    LiteLLM / transformers providers showed NOTHING live β€” the answer just

    popped in at the end. This wraps `generate` so that, while a WS chat

    run owns the bus (`get_bus().running`), it consumes the model's own

    `generate_stream()` and pushes every text delta to the bus β€” the same

    terminal-style live typing the GGUF backends have.



    The streamed result is converted with smolagents' own

    `agglomerate_stream_deltas` (its official stream β†’ ChatMessage

    converter, which merges tool-call deltas correctly), so agentic

    tool-calling runs keep working β€” the returned message is the exact

    shape the non-streaming path would produce. ANY hiccup (a provider

    whose streaming path differs, a version that renames the helper)

    falls back to the original blocking `generate`: live tokens are a

    delivery nicety, never a correctness risk.

    """
    orig_generate = getattr(model, "generate", None)
    stream_gen = getattr(model, "generate_stream", None)
    if not callable(orig_generate) or not callable(stream_gen):
        return model
    try:
        from smolagents.models import agglomerate_stream_deltas
    except Exception:  # noqa: BLE001 β€” a version without the helper: no live streaming
        return model
    from backend.live_stream import get_bus

    def _generate(messages, stop_sequences=None, **kwargs):
        bus = get_bus()
        if not bus.running:
            # Outside a WS chat run (STT analysis, memory compaction, …)
            # keep the original blocking path β€” nothing is listening.
            return orig_generate(messages, stop_sequences=stop_sequences, **kwargs)
        deltas = []
        try:
            bus.begin_generation()
            for delta in stream_gen(messages, stop_sequences=stop_sequences, **kwargs):
                deltas.append(delta)
                frag = (
                    getattr(delta, "content", None)
                    or getattr(delta, "reasoning_content", None)
                    or getattr(delta, "reasoning", None)
                    or getattr(delta, "thought", None)
                    or ""
                )
                if frag:
                    bus.push(frag)
            bus.end_generation()
            return agglomerate_stream_deltas(deltas)
        except Exception as e:  # noqa: BLE001
            try:
                bus.end_generation()
            except Exception:  # noqa: BLE001
                pass
            print(f"[Model] live streaming unavailable for {type(model).__name__} "
                  f"({e}) β€” falling back to blocking generate …")
            return orig_generate(messages, stop_sequences=stop_sequences, **kwargs)

    model.generate = _generate
    return model


def _llm_backend_key_for(target, provider: Optional[str] = None) -> str:
    """The backend key the REQUESTED (model, provider) config implies β€” the

    discriminator that must match the loaded LLM for get_llm()'s

    early-return cache to be valid.



    The cache used to be keyed on (model id, n_ctx) only: switching the

    per-tab provider from 'πŸ–₯️ llama.cpp server' to 'πŸ¦™ llama-cpp-python

    (in-process)' β€” or to a remote backend β€” while keeping the same model

    label returned the STALE server-backed model and, worse, left the

    llama-server.exe subprocess running with its model resident in VRAM.

    Same model id + same n_ctx but a different backend β‡’ different key β‡’

    get_llm() rebuilds, which releases the old model β€” stopping the

    subprocess for a server-backed LLM via _release_model().



    Returns 'gguf:<mode>' (mode 'server' | 'inprocess'), 'hf_api',

    'litellm', or 'transformers'."""
    is_gguf = (
        str(target).lower().endswith(".gguf")
        or target in mr.PRESET_GGUF_MODELS
        or target in mr.PRESET_GGUF_MODELS.values()
        # VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
        # Qwen3-VL GGUF repos) are GGUF models too β€” without this, such an id
        # (which doesn't end in '.gguf' and isn't a text-LLM preset) would
        # fall through to the transformers branch and crash.
        or target in mr.PRESET_GGUF_VLM_MODELS
        or target in mr.PRESET_GGUF_VLM_MODELS.values()
        or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
    )
    if is_gguf:
        backend_mode = mr.get_saved_llm_backend_mode()
        if provider == mr.PROVIDER_SERVER:
            backend_mode = "server"
        elif provider == mr.PROVIDER_LLAMA_CPP_PYTHON:
            backend_mode = "inprocess"
        return f"gguf:{backend_mode}"
    # A curated HF Inference API model id (hf_api_models.csv) under the HF
    # API provider routes to the remote backend just like the sentinel β€” the
    # per-tab model dropdown now lists real remote model ids, not only the
    # single Settings-backed entry.
    if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
        return "hf_api"
    if target == mr.LITELLM_SENTINEL:
        return "litellm"
    return "transformers"


def get_llm(model_id: Optional[str] = None, n_ctx: Optional[int] = None, provider: Optional[str] = None):
    """Lazily build (or rebuild, if the model id, the requested context

    window, OR the requested backend changed) the shared LLM instance.

    """
    global _llm, _llm_model_id, _llm_n_ctx, _llm_backend_key
    target = model_id or _llm_model_id
    is_gguf = (
        str(target).lower().endswith(".gguf")
        or target in mr.PRESET_GGUF_MODELS
        or target in mr.PRESET_GGUF_MODELS.values()
        # VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
        # Qwen3-VL GGUF repos) are GGUF models too β€” without this, such an id
        # (which doesn't end in '.gguf' and isn't a text-LLM preset) would
        # fall through to the transformers branch and crash.
        or target in mr.PRESET_GGUF_VLM_MODELS
        or target in mr.PRESET_GGUF_VLM_MODELS.values()
        or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
    )
    target_ctx = n_ctx if n_ctx is not None else (_llm_n_ctx or mr.get_saved_context_window())
    ctx_changed = is_gguf and target_ctx != _llm_n_ctx
    # Backend (server vs in-process vs remote) the REQUESTED config implies β€”
    # must match the loaded LLM or the cache is stale (e.g. the user switched
    # the provider from llama.cpp server to in-process / HF API / LiteLLM
    # while keeping the same model label: returning the old server-backed
    # model would keep the llama-server subprocess alive in VRAM). A None
    # provider expresses NO preference (the documented _call_llm contract:
    # 'None = use the currently selected/saved provider') β€” such calls (e.g.
    # memory compaction) must reuse whatever is loaded, never force a rebuild
    # that would swap the backend out from under the chat path.
    requested_backend = _llm_backend_key_for(target, provider)
    backend_changed = (
        _llm is not None and provider is not None
        and _llm_backend_key != requested_backend
    )

    if _llm is not None and target == _llm_model_id and not ctx_changed and not backend_changed:
        return _llm

    with _llm_lock:
        if _llm is not None and target == _llm_model_id and not ctx_changed and not backend_changed:
            return _llm

        if _llm is not None:
            if ctx_changed:
                reason = f"context window changed to {target_ctx} tokens"
            elif backend_changed:
                reason = f"backend switched to {requested_backend}"
            else:
                reason = f"loading '{target}'"
            print(f"[Model] Unloading previous LLM '{_llm_model_id}' before {reason} …")
            _release_and_clear("_llm")

        if is_gguf:
            backend_mode = mr.get_saved_llm_backend_mode()
            if provider == mr.PROVIDER_SERVER:
                backend_mode = "server"
            elif provider == mr.PROVIDER_LLAMA_CPP_PYTHON:
                backend_mode = "inprocess"

            if backend_mode == "server":
                print(f"[Model] Starting/reusing llama-server for '{target}' with "
                      f"context window {target_ctx} tokens …")
                base_url = llama_backend.get_or_start_llama_server(
                    model_path=target,
                    n_ctx=target_ctx,
                    n_gpu_layers=-1,  # external llama-server has its own GPU support
                )
                _llm = llama_backend.LlamaServerModel(
                    base_url=base_url,
                    model_path=target,
                    temperature=0.6,
                    top_p=0.95,
                    max_new_tokens=mr.get_saved_max_new_tokens(),
                    # Per-request HTTP timeout (seconds) β€” user-configurable
                    # via the "⏱️ llama-server Request Timeout" dropdown (see
                    # model_registry.get_saved_llm_server_timeout()) instead
                    # of silently using LlamaServerModel's hardcoded 300s
                    # default. A large/slow model with a long agentic prompt
                    # (e.g. Deep Research's manager+sub-agent history) can
                    # easily need more than 300s per generation β€” see that
                    # function's docstring for the full "Error in code
                    # parsing" failure mode this fixes.
                    timeout=mr.get_saved_llm_server_timeout(),
                )
                _llm_n_ctx = target_ctx
                _llm_backend_key = requested_backend
                _llm_model_id = target
                return _llm

            else:
                def _use_llama_server(reason: str):
                    """Start/reuse the external llama-server for `target` and

                    return the wrapped model β€” the shared fallback for both

                    'llama-cpp-python not installed' and 'the installed wheel

                    crashes on this CPU' (AVX-512 wheel on a non-AVX-512 CPU).

                    llama-server release binaries ship per-architecture CPU

                    DLLs, so they work on CPUs the in-process wheel can't."""
                    # Explicit global here β€” nested functions don't inherit
                    # get_llm's `global` declaration, and the module-level
                    # _llm cache + _release_and_clear rely on these globals.
                    global _llm, _llm_n_ctx, _llm_backend_key, _llm_model_id
                    print(f"[Model] {reason} β€” auto-fallbacking to llama-server "
                          f"(external process) for '{target}' …")
                    base_url = llama_backend.get_or_start_llama_server(
                        model_path=target,
                        n_ctx=target_ctx,
                        n_gpu_layers=-1,  # external llama-server has its own GPU support
                    )
                    _llm = llama_backend.LlamaServerModel(
                        base_url=base_url,
                        model_path=target,
                        temperature=0.6,
                        top_p=0.95,
                        max_new_tokens=mr.get_saved_max_new_tokens(),
                        timeout=mr.get_saved_llm_server_timeout(),
                    )
                    _llm_n_ctx = target_ctx
                    _llm_backend_key = requested_backend
                    _llm_model_id = target
                    return _llm

                if not llama_backend.LLAMA_CPP_AVAILABLE:
                    if llama_backend.LLAMA_SERVER_EXE_PATH:
                        return _use_llama_server(
                            "llama-cpp-python not installed")
                    raise RuntimeError(
                        "llama-cpp-python is not installed, and no llama-server "
                        "executable is configured.\n\n"
                        "Option 1: Run SETUP.bat to install llama-cpp-python "
                        "(supports GPU offload).\n"
                        "Option 2: Set the 'πŸ–₯️ llama-server.exe Path' under Model "
                        "Settings to point at a llama-server.exe binary from "
                        "https://github.com/ggml-org/llama.cpp/releases β€” then "
                        "GGUF models run via the external server instead."
                    )
                print(f"[Model] Loading GGUF LLM '{target}' with context window "
                      f"{target_ctx} tokens on {DEVICE.upper()} …")
                try:
                    _llm = llama_backend.LlamaCppModel(
                        model_path=target,
                        n_ctx=target_ctx,
                        n_gpu_layers=-1 if llama_backend.LLAMA_CPP_GPU_AVAILABLE else 0,
                        flash_attn=llama_backend.LLAMA_CPP_GPU_AVAILABLE and mr.get_saved_flash_attn_llama(),
                        temperature=0.6,
                        top_p=0.95,
                        max_new_tokens=mr.get_saved_max_new_tokens(),
                    )
                except Exception as e:
                    if target_ctx > 16384 and ("memory" in str(e).lower() or "alloc" in str(e).lower()):
                        raise RuntimeError(
                            f"Failed to load '{target}' with a {target_ctx}-token context "
                            f"window β€” this likely ran out of VRAM/RAM, since the KV-cache "
                            f"size grows with n_ctx. Try a smaller context window from the "
                            f"'🧠 Context Window' dropdown, or a smaller/more-quantized model.\n\n"
                            f"Original error: {e}"
                        ) from e
                    # The installed llama-cpp-python wheel crashed on this CPU
                    # with an ILLEGAL CPU INSTRUCTION (0xc000001d) β€” the
                    # AVX-512 CUDA wheels cannot run on Intel consumer CPUs
                    # (no AVX-512), where EVERY GGUF load dies this way. The
                    # wheel is unusable here, so route around it via
                    # llama-server instead of surfacing the confusing raw
                    # error (see is_illegal_instruction_error).
                    if is_illegal_instruction_error(e) and llama_backend.LLAMA_SERVER_EXE_PATH:
                        return _use_llama_server(
                            "the installed llama-cpp-python wheel crashed with an "
                            "illegal CPU instruction (0xc000001d β€” AVX-512 build "
                            "on a CPU without AVX-512)")
                    raise
                _llm_n_ctx = target_ctx
                _llm_backend_key = requested_backend
                _llm_model_id = target
                return _llm
        elif target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
            from smolagents import InferenceClientModel
            # A curated catalog id is the model itself; the sentinel (or a
            # custom Settings id) falls back to the per-type remote default.
            hf_model_id = target if target != mr.HF_INFERENCE_API_SENTINEL else mr.get_hf_api_model_id_for("llm")
            hf_token = mr.get_saved_hf_token() or None
            hf_provider = mr.get_saved_hf_provider() or None
            if not hf_model_id:
                raise ValueError(
                    "Hugging Face Inference API selected, but no model ID is configured. "
                    "Enter a model ID in the 'πŸ€— HF Model ID' field under Model Settings."
                )
            if ":" in hf_model_id and not hf_provider:
                hf_model_id, hf_provider = hf_model_id.rsplit(":", 1)
            print(f"[Model] Using Hugging Face Inference API: model={hf_model_id} provider={hf_provider or 'auto'}")
            _llm = InferenceClientModel(
                model_id=hf_model_id,
                token=hf_token,
                provider=hf_provider,
                max_tokens=mr.get_saved_max_new_tokens(),
            )
            # Boundary guard: rewrite any non-JSON-Schema tool property types
            # (smolagents' stock "audio"/"image" tool inputs) to "string"
            # before the payload reaches the provider β€” strict providers
            # reject the whole request otherwise (see
            # install_tool_schema_sanitizer / sanitize_tool_json_schema).
            install_tool_schema_sanitizer(_llm)
            _install_live_streaming(_llm)
            _llm_n_ctx = None
        elif target == mr.LITELLM_SENTINEL:
            try:
                from smolagents import LiteLLMModel
            except ImportError:
                raise RuntimeError(
                    "LiteLLM is not installed. Run: pip install 'smolagents[litellm]'"
                )
            litellm_model_id = mr.get_saved_litellm_model_id()
            litellm_api_key  = mr.get_saved_litellm_api_key() or None
            litellm_api_base = mr.get_saved_litellm_api_base() or None
            if not litellm_model_id:
                raise ValueError(
                    "LiteLLM selected, but no model ID is configured. "
                    "Enter a model ID in the 'πŸ”— LiteLLM Model ID' field "
                    "under Model Settings."
                )
            print(f"[Model] Using LiteLLM: model={litellm_model_id} base={litellm_api_base or 'default'}")
            _llm = LiteLLMModel(
                model_id=litellm_model_id,
                api_key=litellm_api_key,
                api_base=litellm_api_base,
                max_completion_tokens=mr.get_saved_max_new_tokens(),
            )
            # Same tool-schema boundary guard as the HF Inference API branch
            # β€” LiteLLMModel inherits ApiModel._prepare_completion_kwargs, so
            # a strict provider behind LiteLLM (e.g. DeepInfra) would reject
            # an invalid tool schema identically.
            install_tool_schema_sanitizer(_llm)
            _install_live_streaming(_llm)
            _llm_n_ctx = None
        else:
            _check_transformers_version_for(target)
            import inspect
            import importlib.metadata
            from smolagents import TransformersModel
            print(f"[Model] Loading LLM '{target}' on {DEVICE.upper()} …")

            # ── Proactive torch-metadata check ─────────────────────────────
            # In frozen/MSIX builds, torch may be installed but its
            # .dist-info directory is missing (version strings with '+' are
            # illegal in MSIX/OPC filenames).  accelerate.utils.versions
            # calls importlib.metadata.version('torch') at MODULE LEVEL
            # during the TransformersModel.__init__ β†’ transformers β†’
            # accelerate import chain, and a missing .dist-info raises
            # PackageNotFoundError that cascades into a confusing
            # 'Please install transformers extra' error.
            #
            # harden_metadata() should patch this, but in PyInstaller
            # frozen builds the patch may not propagate.  Check NOW β€”
            # before we even create TransformersModel β€” and surface a
            # clear, actionable message if the metadata is broken.
            try:
                importlib.metadata.version("torch")
            except importlib.metadata.PackageNotFoundError:
                # Attempt one more harden_metadata() call in case the
                # runtime hook silently failed (file missing from bundle).
                try:
                    from backend.metadata_hardening import harden_metadata
                    harden_metadata()
                    importlib.metadata.version("torch")  # retry
                except Exception:
                    raise RuntimeError(
                        "Could not read torch package metadata β€” needed by "
                        "the HuggingFace Transformers backend.\n\n"
                        "In a packaged (MSIX/PyInstaller) build, GPU PyTorch "
                        "is NOT bundled.  Please:\n"
                        "  1. Open the βš™οΈ Settings tab\n"
                        '  2. Click "Detect & Install GPU PyTorch"\n\n'
                        "Or switch the provider to 'πŸ€– Local llama.cpp' "
                        "to use GGUF models (no torch needed)."
                    )

            base_kwargs = dict(
                model_id=target,
                device_map=DEVICE,
                max_new_tokens=mr.get_saved_max_new_tokens(),
                temperature=0.6,
                top_p=0.95,
                trust_remote_code=True,
            )
            # smolagents' TransformersModel constructor only recognizes a
            # fixed set of named parameters for MODEL LOADING (model_id,
            # device_map, torch_dtype, trust_remote_code, model_kwargs,
            # max_new_tokens, ...) β€” see
            # https://huggingface.co/docs/smolagents/en/reference/models.
            # Anything passed that ISN'T one of those named parameters
            # does NOT raise a TypeError; it's silently absorbed into
            # TransformersModel's own **kwargs, which it then re-forwards
            # into EVERY subsequent model.generate() call, not just at
            # load time. Passing `dtype=` here (a name TransformersModel's
            # constructor doesn't define) used to slip through this way β€”
            # load succeeded with no error, and the model only blew up the
            # first time an agent actually tried to generate, with
            # "The following `model_kwargs` are not used by the model:
            # ['dtype']" β€” easy to misread as a tool-calling problem
            # rather than a stale kwarg name. Detect the real parameter
            # name instead of guessing, so this fails loudly at load time
            # (a clear, immediate error) if some future smolagents version
            # renames it again.
            ctor_params = inspect.signature(TransformersModel.__init__).parameters
            if "torch_dtype" in ctor_params:
                base_kwargs["torch_dtype"] = _load_dtype()
            elif "dtype" in ctor_params:
                base_kwargs["dtype"] = _load_dtype()
            else:
                print(
                    "[Model] Warning: installed smolagents' TransformersModel exposes "
                    "neither 'torch_dtype' nor 'dtype' as a constructor parameter β€” "
                    "loading without an explicit dtype (will use the model's default)."
                )
            # Pre-quantized GPTQ/AWQ models β€” these ship with quantized
            # weights and must NOT be re-quantized by bitsandbytes. They
            # load via the same AutoModelForCausalLM path but the
            # quantization config is embedded in the model's config.json.
            # transformers auto-detects GPTQ/AWQ from the config and
            # loads the right quantized linear layers.
            model_kw = {}
            if DEVICE == "cuda" and mr.get_saved_flash_attn_pytorch():
                model_kw["attn_implementation"] = "sdpa"
            if _is_gptq_or_awq(target):
                print(
                    f"[Model] Loading pre-quantized GPTQ/AWQ model '{target}' β€” "
                    f"no additional quantization applied."
                )
                base_kwargs["model_kwargs"] = model_kw
            else:
                base_kwargs["model_kwargs"] = model_kw
            try:
                _llm = TransformersModel(**base_kwargs)
            except (ModuleNotFoundError, ImportError) as _e:
                _msg = str(_e)
                # In frozen/MSIX builds where torch is installed but its
                # .dist-info is missing (version strings with '+' are
                # illegal in MSIX/OPC), accelerate's
                # importlib.metadata.version('torch') raises
                # PackageNotFoundError which cascades into a
                # ModuleNotFoundError from smolagents.  Surface a clear
                # message pointing the user to the Settings tab.
                if "torch" in _msg.lower() or "transformers" in _msg.lower():
                    raise RuntimeError(
                        f"{_msg}\n\n"
                        f"In a packaged (MSIX/PyInstaller) build, GPU PyTorch "
                        f"is NOT bundled β€” it must be installed via the "
                        f"βš™οΈ Settings tab (\"Detect & Install GPU PyTorch\").\n\n"
                        f"If you only need GGUF/llama.cpp models, switch the "
                        f"provider to 'πŸ€– Local llama.cpp' instead."
                    ) from _e
                raise
            # Live token streaming for the local transformers backend too
            # (smolagents' TransformersModel has a generate_stream; the
            # wrapper pushes deltas to the live bus while a WS run is
            # active β€” same as the GGUF/remote backends).
            _install_live_streaming(_llm)
            # Opt-in torch.compile on the underlying HF model (CUDA only).
            _inner = getattr(_llm, "model", None)
            if _inner is not None:
                _llm.model = _maybe_torch_compile(_inner)
            # n_ctx doesn't apply to the HF backend β€” clear it so a later
            # switch back to a GGUF model doesn't skip a reload it needs
            # by comparing against a stale value from a previous GGUF load.
            _llm_n_ctx = None
        _llm_backend_key = requested_backend
        _llm_model_id = target
        return _llm


def _estimate_tokens(text: str) -> int:
    """Rough token count from answer text β€” a character-based heuristic

    (β‰ˆ 4 chars per token for English / code, β‰ˆ 2 for Khmer / CJK). Used

    when the model backend did not report usage (smolagents token_usage is

    None). Never returns 0 for non-empty text."""
    if not text:
        return 0
    n = len(text)
    # Heuristic: Khmer/CJK/Devanagari are roughly 2 chars per token;
    # Latin/code is roughly 4. We count non-ASCII chars to guess the mix.
    non_ascii = sum(1 for c in text if ord(c) > 127)
    ascii_chars = n - non_ascii
    return max(1, int(non_ascii / 2 + ascii_chars / 4))


def _call_llm(model_id: str, system: str, user: str, history: Optional[list] = None,

              provider: Optional[str] = None, n_ctx: Optional[int] = None,

              max_tokens: Optional[int] = None) -> tuple[str, float, int]:
    """Direct (non-agentic) single-turn-or-multi-turn LLM call, shared by

    General Chat's and RAG Chat's *direct* paths (chat.py), and by agent

    memory compaction (agent_memory.compact_agent_memory()).



    Built as a plain list of smolagents `ChatMessage`s β€” the same message

    object smolagents' own `CodeAgent`/`TransformersModel`/`LlamaCppModel`

    machinery uses internally β€” so this goes through the exact same

    `model(messages)` call contract as the agentic paths, just without a

    CodeAgent wrapped around it. `role` is passed via smolagents'

    `MessageRole` enum rather than a bare string, matching how smolagents

    documents/constructs `ChatMessage` itself.



    `history` (optional): prior turns as `[{"role": "user"|"assistant",

    "content": str}, ...]`, coming from chat.py's `_recent_memory_messages()`.

    Folded in between the system prompt and the current `user` message so

    follow-up questions can refer back to earlier turns β€” see chat.py's

    "🧠 Conversation Memory" checkbox.



    `provider` (optional): a per-call provider override forwarded to

    get_llm() (None = use the currently selected/saved provider).

    `n_ctx` (optional): a per-call context-window override forwarded to

    get_llm(), for the GGUF backend (None = whatever the loaded model

    was built with, or the saved context window).



    `max_tokens` (optional): a per-call cap on the generated tokens (used

    by memory compaction so its summary call stays short instead of

    inheriting the model's full MAX_NEW_TOKENS budget). Not every backend's

    Model wrapper accepts a `max_tokens` kwarg β€” the TypeError fallback

    re-runs with the model's own default budget.

    """
    from smolagents.models import ChatMessage, MessageRole

    llm = get_llm(model_id, provider=provider, n_ctx=n_ctx)

    messages = [
        ChatMessage(role=MessageRole.SYSTEM, content=[{"type": "text", "text": system}])
    ]
    for turn in (history or []):
        role = turn.get("role")
        content = turn.get("content", "")
        if not content:
            continue
        if role == "user":
            msg_role = MessageRole.USER
        elif role == "assistant":
            msg_role = MessageRole.ASSISTANT
        else:
            continue
        messages.append(ChatMessage(role=msg_role, content=[{"type": "text", "text": content}]))
    messages.append(ChatMessage(role=MessageRole.USER, content=[{"type": "text", "text": user}]))

    t0  = time.time()
    if max_tokens is not None:
        try:
            out = llm(messages, max_tokens=max_tokens)
        except TypeError:
            out = llm(messages)
    else:
        out = llm(messages)
    if hasattr(out, "content"):
        c = out.content
        if isinstance(c, list):
            ans = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in c)
        else:
            ans = str(c)
    else:
        ans = str(out)
    # Extract output token count from the smolagents ChatMessage; fall back
    # to a rough character-based estimate when the backend did not report usage.
    n_tokens = 0
    try:
        tok = getattr(out, "token_usage", None)
        if tok is not None:
            n_tokens = getattr(tok, "output_tokens", 0) or 0
    except Exception:
        pass
    if not n_tokens:
        n_tokens = _estimate_tokens(ans)
    return ans.strip(), time.time() - t0, n_tokens


def _is_local_gguf_file(path: Any) -> bool:
    """True when *path* points at an actual local .gguf file (as opposed to

    a preset GGUF repo ID like 'google/gemma-4-E2B-it-qat-q4_0-gguf' whose

    mmproj is auto-downloaded by llama_backend.resolve_or_download_gguf_model).

    Only genuinely local .gguf files need a registered mmproj from the scan."""
    s = str(path or "")
    if not s.lower().endswith(".gguf"):
        return False
    try:
        return os.path.isfile(s)
    except Exception:
        return False


def _is_quantized_uint8_init_error(exc: Exception) -> bool:
    """True when the failure is transformers trying to torch-init a packed

    uint8 quantized weight β€” the signature of a corrupt/partial Gemma-4 QAT

    checkpoint (missing keys re-initialized with `init.normal_`, which has

    no uint8 kernel). Matches both the CPU RuntimeError and the CUDA

    NotImplementedError variants."""
    msg = str(exc)
    return (
        "expected a floating-point or complex dtype" in msg
        or "not implemented for 'Byte'" in msg
        or "dtype=torch.uint8" in msg
    )


def _clear_hf_model_cache(model_id: str) -> None:
    """Delete every locally cached revision of a HF repo so the next

    `from_pretrained` performs a fresh download. Used to recover from a

    corrupt/partial model.safetensors. Never raises."""
    try:
        from huggingface_hub import scan_cache_dir

        cache_info = scan_cache_dir()
        hashes = [
            revision.commit_hash
            for repo in cache_info.repos
            if repo.repo_id == model_id
            for revision in repo.revisions
        ]
        if not hashes:
            print(f"[VLM] No cached revisions found for '{model_id}' to clear.")
            return
        strategy = cache_info.delete_revisions(*hashes)
        strategy.execute()
        print(
            f"[VLM] Cleared {len(hashes)} cached revision(s) of '{model_id}' "
            f"(freed {strategy.expected_freed_size_str})."
        )
    except Exception as exc:
        print(f"[VLM] Failed to clear HF cache for '{model_id}': {exc}")


def _vlm_backend_key_for(target, provider: Optional[str] = None) -> str:
    """The backend key the REQUESTED (model, provider) config implies for the

    Vision loader β€” the discriminator that must match the loaded VLM for

    get_vlm()'s early-return cache to be valid. Same idea as

    _llm_backend_key_for(): the cache used to be keyed on (model id, n_ctx)

    only, so switching the Vision provider from 'πŸ–₯️ llama.cpp server' to

    'πŸ¦™ llama-cpp-python (in-process)' (or to the HF Inference API) while

    keeping the same model label returned the STALE server-backed VLM and

    left llama-server.exe running with the model resident in VRAM.



    Mirrors get_vlm()'s own routing: a GGUF target under the server provider

    (or with llama-cpp-python unavailable and a server configured) runs via

    the external subprocess ('gguf:server'), otherwise in-process

    ('gguf:inprocess'); the HF Inference API sentinel is 'hf_api'; any local

    transformers VLM is 'transformers'."""
    is_gguf = (
        str(target).lower().endswith(".gguf")
        or target in mr.PRESET_GGUF_MODELS
        or target in mr.PRESET_GGUF_MODELS.values()
        # VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
        # Qwen3-VL GGUF repos) are GGUF models too β€” without this, such an id
        # (which doesn't end in '.gguf' and isn't a text-LLM preset) would
        # fall through to the transformers branch and crash.
        or target in mr.PRESET_GGUF_VLM_MODELS
        or target in mr.PRESET_GGUF_VLM_MODELS.values()
        or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
    )
    if is_gguf:
        use_server = (
            provider == mr.PROVIDER_SERVER
            or (not provider and not llama_backend.LLAMA_CPP_GPU_AVAILABLE
                and bool(llama_backend.LLAMA_SERVER_EXE_PATH))
        )
        return "gguf:server" if use_server else "gguf:inprocess"
    # A curated HF Inference API VLM id under the HF API provider routes to
    # the remote backend just like the sentinel β€” the Vision tab's model
    # dropdown now lists real remote model ids, not only the single
    # Settings-backed entry.
    if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
        return "hf_api"
    return "transformers"


def get_vlm(model_id: Optional[str] = None, mmproj_path: Optional[str] = None, provider: Optional[str] = None, n_ctx: Optional[int] = None):
    global _vlm_model, _vlm_processor, _vlm_model_id, _vlm_n_ctx, _vlm_backend_key

    target = model_id or mr.DEFAULT_VLM_MODEL

    target_ctx = n_ctx if n_ctx is not None else (_vlm_n_ctx or mr.get_saved_context_window())
    ctx_changed = target_ctx != _vlm_n_ctx
    # Backend (server vs in-process vs remote) the REQUESTED config implies β€”
    # must match the loaded VLM or the cache is stale (e.g. the user switched
    # the Vision provider from llama.cpp server to in-process / HF API while
    # keeping the same model label: returning the old server-backed VLM
    # would keep llama-server.exe alive in VRAM). A None provider expresses
    # NO preference (vlm_answer()'s cache-hit call) and must reuse whatever
    # is loaded.
    requested_backend = _vlm_backend_key_for(target, provider)
    backend_changed = (
        _vlm_model is not None and provider is not None
        and _vlm_backend_key != requested_backend
    )

    if _vlm_model is not None and target == _vlm_model_id and not ctx_changed and not backend_changed:
        return _vlm_model, _vlm_processor

    if _vlm_model is not None:
        if ctx_changed:
            reason = f"context window changed to {target_ctx} tokens"
        elif backend_changed:
            reason = f"backend switched to {requested_backend}"
        else:
            reason = f"loading '{target}'"
        print(f"[VLM] Unloading previous VLM '{_vlm_model_id}' before {reason} …")
        _release_and_clear("_vlm_model")
        _vlm_processor = None

    # ── HF Inference API ──────────────────────────────────────────
    if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
        # A curated catalog id is the model itself; the sentinel (or a
        # custom Settings id) falls back to the per-type remote default.
        hf_model_id = target if target != mr.HF_INFERENCE_API_SENTINEL else mr.get_hf_api_model_id_for("vlm")
        if not hf_model_id:
            raise ValueError(
                "Hugging Face Inference API selected for Vision, but no "
                "model ID is configured. Enter a model ID in the "
                "'πŸ€— HF Model ID' field under Model Settings."
            )
        _vlm_model = InferenceApiVLMModel(model_id=hf_model_id)
        _vlm_processor = None
        _vlm_backend_key = requested_backend
        _vlm_model_id = target
        _vlm_n_ctx = None
        return _vlm_model, _vlm_processor

    # ── GGUF vision model (llama.cpp) ─────────────────────────────
    # Treat a model as GGUF when the id is a local .gguf file, a known
    # preset GGUF repo (e.g. 'google/gemma-4-E2B-it-qat-q4_0-gguf' β€” the
    # id itself does NOT end in '.gguf'), or the provider is llama.cpp β€”
    # mirroring get_llm()'s is_gguf detection so the Vision tab routes
    # preset GGUF models to llama.cpp instead of the HuggingFace branch.
    is_gguf = (
        str(target).lower().endswith(".gguf")
        or target in mr.PRESET_GGUF_MODELS
        or target in mr.PRESET_GGUF_MODELS.values()
        # VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
        # Qwen3-VL GGUF repos) are GGUF models too β€” without this, such an id
        # (which doesn't end in '.gguf' and isn't a text-LLM preset) would
        # fall through to the transformers branch and crash.
        or target in mr.PRESET_GGUF_VLM_MODELS
        or target in mr.PRESET_GGUF_VLM_MODELS.values()
        or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
    )
    if is_gguf:
        use_server = (provider == mr.PROVIDER_SERVER) or (not provider and not llama_backend.LLAMA_CPP_GPU_AVAILABLE and bool(llama_backend.LLAMA_SERVER_EXE_PATH))
        if use_server:
            if llama_backend.LLAMA_SERVER_EXE_PATH:
                if not mmproj_path:
                    mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(target)
                if not mmproj_path and _is_local_gguf_file(target):
                    raise RuntimeError(
                        f"No mmproj (vision projector) file is registered for "
                        f"'{target}'. Select one from the mmproj dropdown in the "
                        f"sidebar, or click 'πŸ” Scan' on the GGUF model folder so "
                        f"it can be paired with a matching mmproj .gguf file."
                    )
                print(f"[VLM] llama-cpp-python not available β€” routing GGUF vision "
                      f"through external llama-server …")
                base_url = llama_backend.get_or_start_llama_server(target, n_ctx=target_ctx, mmproj_path=mmproj_path)
                _vlm_model = llama_backend.LlamaServerVLMModel(
                    base_url=base_url,
                    model_path=target,
                    timeout=mr.get_saved_llm_server_timeout(),
                )
                _vlm_processor = None
                _vlm_backend_key = requested_backend
                _vlm_model_id = target
                _vlm_n_ctx = target_ctx
                return _vlm_model, _vlm_processor
            raise RuntimeError(
                "llama-cpp-python is not installed β€” GGUF vision models "
                "unavailable. Run SETUP.bat, or install it manually."
            )
        if not mmproj_path:
            mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(target)
        if not mmproj_path and _is_local_gguf_file(target):
            raise RuntimeError(
                f"No mmproj (vision projector) file is registered for "
                f"'{target}'. Select one from the mmproj dropdown in the "
                f"sidebar, or click 'πŸ” Scan' on the GGUF model folder so "
                f"it can be paired with a matching mmproj .gguf file."
            )
        _vlm_model = llama_backend.LlamaCppVLMModel(
            model_path=target,
            mmproj_path=mmproj_path,
            n_ctx=target_ctx,
            n_gpu_layers=-1 if llama_backend.LLAMA_CPP_GPU_AVAILABLE else 0,
        )
        _vlm_processor = None
        _vlm_backend_key = requested_backend
        _vlm_model_id = target
        _vlm_n_ctx = target_ctx
        return _vlm_model, _vlm_processor

    # ── Local HuggingFace VLM ─────────────────────────────────────
    print(f"[VLM] Loading '{target}' on {DEVICE.upper()} …")
    from transformers import AutoProcessor



    if target in mr.QWEN_VL_IDS:
        from transformers import Qwen2_5_VLForConditionalGeneration

        _vlm_processor = AutoProcessor.from_pretrained(
            target,
            trust_remote_code=True,
            min_pixels=256 * 28 * 28,
            max_pixels=1280 * 28 * 28,
        )

        _vlm_kwargs = dict(
            torch_dtype=_load_dtype(),
            device_map=DEVICE,
            trust_remote_code=True,
            **_vlm_attn_kwargs(),
        )
        _vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
            target, **_vlm_kwargs
        )

        _vlm_model._arch = "qwen_vl"

    elif target in mr.QWEN3_VL_IDS:
        # Qwen3-VL β€” current-gen Qwen vision family (dense 2B/4B/8B).
        # Qwen3VLForConditionalGeneration exists in transformers 5.x (the
        # _MIN_TRANSFORMERS_VERSION["qwen3vl"] guard gives a clear upgrade
        # message below 5.0); AutoModelForImageTextToText is the fallback
        # for the rare 5.x build where the explicit class is missing.
        try:
            from transformers import Qwen3VLForConditionalGeneration
            ModelClass = Qwen3VLForConditionalGeneration
        except ImportError:
            from transformers import AutoModelForImageTextToText
            ModelClass = AutoModelForImageTextToText
            print("[VLM] Qwen3VLForConditionalGeneration unavailable β€” "
                  "using AutoModelForImageTextToText")

        _vlm_processor = AutoProcessor.from_pretrained(
            target,
            trust_remote_code=True,
            min_pixels=256 * 28 * 28,
            max_pixels=1280 * 28 * 28,
        )

        _vlm_kwargs = dict(
            torch_dtype=_load_dtype(),
            device_map=DEVICE,
            trust_remote_code=True,
            **_vlm_attn_kwargs(),
        )
        _vlm_model = ModelClass.from_pretrained(
            target, **_vlm_kwargs
        )

        _vlm_model._arch = "qwen3vl"

    elif target in mr.SMOL_VLM_IDS:
        try:
            from transformers import AutoModelForImageTextToText
            ModelClass = AutoModelForImageTextToText
            print("[VLM] Using AutoModelForImageTextToText")
        except ImportError:
            try:
                from transformers import AutoModelForVision2Seq
                ModelClass = AutoModelForVision2Seq
                print("[VLM] Using AutoModelForVision2Seq")
            except ImportError:
                from transformers import AutoModel
                ModelClass = AutoModel
                print("[VLM] Falling back to AutoModel")

        _vlm_processor = AutoProcessor.from_pretrained(
            target,
            trust_remote_code=True,
        )

        _vlm_kwargs = dict(
            torch_dtype=_load_dtype(),
            device_map=DEVICE,
            trust_remote_code=True,
            **_vlm_attn_kwargs(),
        )
        _vlm_model = ModelClass.from_pretrained(target, **_vlm_kwargs)

        _vlm_model._arch = "smolvlm"

    elif target in mr.GEMMA4_IDS:
        # Gemma 4 (incl. Mobile QAT) is a multimodal family, loaded the
        # same way smolagents' own TransformersModel picks it up β€” the
        # AutoModelForImageTextToText mapping resolves to
        # Gemma4ForConditionalGeneration (verified in the Phase 0 smoke
        # test). AutoModelForMultimodalLM is tried first per the official
        # integration guide; both classes resolve to the same model.
        # NOTE: these pre-quantized (QAT) checkpoints store packed integer
        # weights as uint8/int8 tensors. If a cached model.safetensors is
        # corrupt or partially downloaded, `from_pretrained` loads with
        # MISSING keys; transformers then re-initializes the missing
        # QuantizedLinear/QuantizedEmbedding weight via `init.normal_`,
        # which has no uint8 kernel β€” the exact
        #   RuntimeError: expected a floating-point or complex dtype,
        #   but got dtype=torch.uint8
        # (CPU) / `NotImplementedError: "normal_kernel_cuda" not implemented
        # for 'Byte'` (CUDA) crash. Recover by clearing the bad cache and
        # retrying the load once.
        try:
            from transformers import AutoModelForMultimodalLM
            ModelClass = AutoModelForMultimodalLM
            print("[VLM] Using AutoModelForMultimodalLM")
        except ImportError:
            from transformers import AutoModelForImageTextToText
            ModelClass = AutoModelForImageTextToText
            print("[VLM] Using AutoModelForImageTextToText")

        _vlm_processor = AutoProcessor.from_pretrained(
            target,
            trust_remote_code=True,
        )

        load_kwargs = dict(trust_remote_code=True)
        if DEVICE == "cpu":
            load_kwargs["low_cpu_mem_usage"] = True
        else:
            load_kwargs["torch_dtype"] = "auto"
            load_kwargs["device_map"] = "auto"
        load_kwargs.update(_vlm_attn_kwargs())

        try:
            _vlm_model = ModelClass.from_pretrained(target, **load_kwargs)
        except Exception as e:
            if _is_quantized_uint8_init_error(e):
                print(
                    f"[VLM] '{target}' failed to load from a corrupt/partial "
                    f"HF cache ({type(e).__name__}: {e}). Clearing the cache "
                    f"and retrying the load once …"
                )
                _clear_hf_model_cache(target)
                _vlm_model = ModelClass.from_pretrained(target, **load_kwargs)
            else:
                raise

        _vlm_model._arch = "gemma4"

    else:
        raise ValueError(f"Unknown VLM: {target}")

    _vlm_backend_key = requested_backend
    _vlm_model_id = target
    _vlm_n_ctx = None

    return _maybe_torch_compile(_vlm_model), _vlm_processor


def _vlm_attn_kwargs() -> dict:
    """Attention-implementation kwargs for the local transformers VLM loaders.



    The VLM loaders previously left ``attn_implementation`` unset, so they ran

    EAGER attention on CUDA β€” missing the PyTorch-native FlashAttention (SDPA)

    kernel the text LLM already uses. We now mirror the LLM guard: on CUDA

    with PyTorch FlashAttention enabled, request SDPA (which dispatches to

    PyTorch-native FlashAttention-2 on fp16). On CPU / non-CUDA we leave it

    unset (SDPA gives no benefit and the eager path is the safe fallback)."""
    if DEVICE == "cuda" and mr.get_saved_flash_attn_pytorch():
        return {"attn_implementation": "sdpa"}
    return {}


def _maybe_torch_compile(model):
    """Opt-in ``torch.compile`` for the local transformers backends (CUDA only).



    Fully guarded: any failure silently returns the uncompiled model so the app

    always launches. The first real forward pays the compile cost (one-time);

    subsequent calls are faster. No-op when the setting is off or on non-CUDA.

    The mode (default / reduce-overhead / max-autotune / max-autotune-no-

    cudagraphs) comes from the acceleration Settings toggle."""
    if DEVICE != "cuda" or not mr.get_saved_torch_compile():
        return model
    try:
        import torch

        if not hasattr(torch, "compile"):
            return model
        mode = mr.get_saved_torch_compile_mode() or "default"
        if mode not in mr.TORCH_COMPILE_MODES:
            mode = "default"
        print(f"[Model] Compiling model with torch.compile (one-time cost, mode={mode})…")
        return torch.compile(model, mode=mode, fullgraph=False)
    except Exception as e:
        print(f"[Model] torch.compile skipped ({e}); running uncompiled.")
        return model


def _load_dtype():
    """The torch dtype for local transformers LLM/VLM model loads β€” the

    opt-in bfloat16 fastpath (Ampere+ CUDA GPUs: faster, no fp16 overflow

    risk, best paired with SDPA FlashAttention) when enabled, else the

    hardware default (fp16 on GPU, fp32 on CPU)."""
    if DEVICE == "cuda" and mr.get_saved_torch_bf16():
        try:
            import torch

            if torch.cuda.is_bf16_supported():
                return torch.bfloat16
        except Exception:
            pass
    return TORCH_DTYPE


def _infer_vlm_arch(model_id: Optional[str]) -> Optional[str]:
    """The transformers architecture key for a known multimodal model id

    (the `_arch` value models.get_vlm() stamps on its VLM instances), or

    None when the id isn't a registered multimodal transformers model. Used

    by vlm_answer()'s same-model reuse branch to stamp the shared LLM

    model without loading a second copy."""
    if model_id in mr.QWEN_VL_IDS:
        return "qwen_vl"
    if model_id in mr.QWEN3_VL_IDS:
        return "qwen3vl"
    if model_id in mr.SMOL_VLM_IDS:
        return "smolvlm"
    if model_id in mr.GEMMA4_IDS:
        return "gemma4"
    return None


def vlm_answer(question: str, images: list, context: str = "", model_id: Optional[str] = None, mmproj_path: Optional[str] = None, lang_key: str = "kh", n_ctx: Optional[int] = None, provider: Optional[str] = None) -> str:
    try:
        # ── Same-model reuse (VRAM) ──────────────────────────────────
        # When the requested VLM is the SAME model the text LLM already
        # loaded as a transformers wrapper (e.g. a Gemma-4 / Qwen-VL RAG
        # model on the local-HF provider), reuse its live `.model` +
        # `.processor` instead of loading a SECOND copy into VRAM β€” the
        # RAG chat's visual-grounding pass runs vlm_answer with the RAG
        # chat's OWN model id exactly so no extra model has to fit in
        # memory. The arch is stamped from the id so the transformers
        # dispatch below picks the right branch. Skipped for GGUF / remote
        # targets (llama.cpp / HF API / LiteLLM never carry a reusable
        # in-process `.model` here) and when the loaded LLM doesn't match
        # the requested id.
        model, processor = None, None
        if (model_id
                and provider in (None, mr.PROVIDER_LOCAL_HF)
                and _llm is not None and _llm_model_id == model_id):
            arch = _infer_vlm_arch(model_id)
            inner = getattr(_llm, "model", None)
            proc  = getattr(_llm, "processor", None)
            if arch and inner is not None and proc is not None and hasattr(inner, "generate"):
                try:
                    inner._arch = arch
                except Exception:
                    pass
                model, processor = inner, proc
        if model is None:
            model, processor = get_vlm(model_id, mmproj_path=mmproj_path, n_ctx=n_ctx,
                                       provider=provider)
        # GGUF vision model (in-process llama-cpp-python or external llama-server) β€” self-contained answer() method.
        if isinstance(model, (llama_backend.LlamaCppVLMModel, llama_backend.LlamaServerVLMModel)):
            return model.answer(question, images, context=context,
                                max_tokens=mr.get_saved_max_new_tokens(),
                                lang_key=lang_key)
        # HF Inference API VLM β€” also self-contained answer().
        if isinstance(model, InferenceApiVLMModel):
            return model.answer(question, images, context=context,
                                max_tokens=mr.get_saved_max_new_tokens(),
                                lang_key=lang_key)
        arch = getattr(model, "_arch", "smolvlm")
        # UI-language output directive β€” same shared instruction as every
        # other chat path, so a Khmer UI gets Khmer answers regardless of
        # the model's default language.
        system_prompt = (
            i18n._output_lang_instruction(lang_key) +
            "You are a helpful assistant. Answer based on images and context. "
            "Answer the user's question below β€” do not respond to these "
            "instructions."
        )
        user_text = question + (f"\n\nContext:\n{context}" if context else "")
        # Qwen3-VL shares Qwen2.5-VL's inference pattern β€” the processor's
        # apply_chat_template renders the <|vision_start|> tokens and
        # qwen_vl_utils.process_vision_info extracts the raw images, then
        # processor(text=[...], images=...) fuses them (Qwen3VLProcessor
        # accepts the same min_pixels/max_pixels kwargs used at load).
        if arch in ("qwen_vl", "qwen3vl"):
            from qwen_vl_utils import process_vision_info
            content = [{"type": "image", "image": img} for img in images]
            content.append({"type": "text", "text": user_text})
            messages = [{"role": "system", "content": system_prompt},
                        {"role": "user",   "content": content}]
            text_in = processor.apply_chat_template(messages, tokenize=False,
                                                    add_generation_prompt=True)
            img_in, _ = process_vision_info(messages)
            inputs = processor(text=[text_in], images=img_in,
                               padding=True, return_tensors="pt").to(DEVICE)
        elif arch == "gemma4":
            # Gemma 4 β€” the processor's apply_chat_template returns the full
            # tokenized input dict (input_ids + attention_mask + pixel_values)
            # in one call, per the official integration guide's inference
            # pattern. Uses return_dict=True so no separate processor(...)
            # invocation is needed for the image side.
            # NOTE: the UI-language system directive MUST be in the messages
            # here too β€” a Gemma-4 VLM under a Khmer UI would otherwise
            # answer in English (the exact regression this branch used to
            # have, discovered by code review: the system_prompt computed
            # above was never attached to the gemma4 messages).
            content = [{"type": "image", "image": img} for img in images]
            content.append({"type": "text", "text": user_text})
            messages = [{"role": "system", "content": system_prompt},
                        {"role": "user",   "content": content}]
            inputs = processor.apply_chat_template(
                messages,
                tokenize=True,
                return_dict=True,
                return_tensors="pt",
                add_generation_prompt=True,
            ).to(DEVICE)
        else:
            content = [{"type": "image"} for _ in images]
            content.append({"type": "text", "text": user_text})
            messages = [{"role": "system", "content": system_prompt},
                        {"role": "user",   "content": content}]
            text_in = processor.apply_chat_template(messages, add_generation_prompt=True)
            inputs  = processor(text=text_in, images=images or None, return_tensors="pt").to(DEVICE)
        max_new = mr.get_saved_max_new_tokens()
        bus = get_bus()
        if bus.running:
            # Live token streaming for the local transformers VLM: run the
            # generation in a background thread feeding a TextIteratorStreamer,
            # pushing each decoded text delta to the live bus β€” the Vision
            # answer grows from REAL tokens like the GGUF VLM backends. Any
            # hiccup (no tokenizer, unsupported streamer) falls back to the
            # plain blocking generate below.
            try:
                from transformers import TextIteratorStreamer
                import threading

                tok = getattr(processor, "tokenizer", None) or getattr(processor, "chat_template", None) or processor
                streamer = TextIteratorStreamer(
                    tok, skip_prompt=True, skip_special_tokens=True)
                gen_kwargs = dict(inputs)
                gen_kwargs["max_new_tokens"] = max_new
                gen_kwargs["streamer"] = streamer
                thread = threading.Thread(
                    target=model.generate, kwargs=gen_kwargs, daemon=True)
                thread.start()
                bus.begin_generation()
                pieces = []
                with torch.no_grad():
                    for piece in streamer:
                        if piece:
                            pieces.append(piece)
                            bus.push(piece)
                thread.join()
                bus.end_generation()
                return "".join(pieces)
            except Exception as e:
                try:
                    bus.end_generation()
                except Exception:  # noqa: BLE001
                    pass
                print(f"[VLM] transformers live streaming unavailable ({e}) β€” "
                      "using blocking generate …")
        with torch.no_grad():
            out = model.generate(**inputs, max_new_tokens=max_new)
        trimmed = out[0][inputs["input_ids"].shape[-1]:]
        return processor.decode(trimmed, skip_special_tokens=True)
    except Exception as e:
        import traceback
        return f"❌ Error during VLM generation: {str(e)}\n\n{traceback.format_exc()}"


def get_stt_pipeline(model_id: Optional[str] = None):
    global _stt_pipeline, _stt_model_id
    target = model_id or mr.DEFAULT_STT_MODEL

    if _stt_pipeline is not None and target == _stt_model_id:
        return _stt_pipeline

    with _stt_lock:
        if _stt_pipeline is not None and target == _stt_model_id:
            return _stt_pipeline

        if _stt_pipeline is not None:
            print(f"[STT] Unloading previous STT model '{_stt_model_id}' before loading '{target}' …")
            _release_and_clear("_stt_pipeline")

        # ── HF Inference API ──────────────────────────────────────
        if target == mr.HF_INFERENCE_API_SENTINEL:
            hf_model_id = mr.get_hf_api_model_id_for("stt")
            if not hf_model_id:
                raise ValueError(
                    "Hugging Face Inference API selected for Speech, but no "
                    "model ID is configured."
                )
            _stt_pipeline = InferenceApiSTTModel(model_id=hf_model_id)
            _stt_model_id = target
            return _stt_pipeline

        # ── whisper.cpp server ────────────────────────────────────
        suffix = str(target).lower()
        if suffix.endswith(".ggml") or suffix.endswith(".bin"):
            base_url = whisper_cpp_backend.get_or_start_whisper_server(target)
            _stt_pipeline = whisper_cpp_backend.WhisperServerModel(
                base_url=base_url, model_path=target,
            )
            _stt_model_id = target
            return _stt_pipeline

        # ── Local HuggingFace Whisper pipeline ────────────────────
        print(f"[STT] Loading '{target}' on {DEVICE.upper()} …")
        # Stub `av` (PyAV) if its native DLLs are missing (frozen/MSIX
        # builds). transformers.pipelines.__init__ unconditionally imports
        # VideoClassificationPipeline β†’ `av`, but we only need ASR.
        import sys as _sys
        if "av" not in _sys.modules:
            try:
                import av as _av_probe  # noqa: F401
            except Exception:
                import types as _types
                import importlib.machinery as _machinery
                _av_stub = _types.ModuleType("av")
                _av_stub.__path__ = []
                _av_stub.__spec__ = _machinery.ModuleSpec("av", None, is_package=True)
                _av_stub.__spec__.submodule_search_locations = []
                _sys.modules["av"] = _av_stub
                print("[STT] Stubbed missing 'av' (PyAV) β€” video classification disabled, ASR unaffected.")
        from transformers import pipeline as hf_pipeline

        if DEVICE == "cuda":
            device_arg = 0
        elif DEVICE == "xpu":
            device_arg = "xpu"
        elif DEVICE == "mps":
            device_arg = "mps"
        else:
            device_arg = -1

        _stt_pipeline = hf_pipeline(
            "automatic-speech-recognition",
            model=target,
            dtype=TORCH_DTYPE,
            device=device_arg,
        )
        # NOTE: the pipeline is built WITHOUT chunk_length_s/stride_length_s:
        # transformers flags that experimental seq2seq windowing as
        # inaccurate, and the app no longer feeds 30s manual chunks through
        # it β€” transcribe_audio_stream drives the model's NATIVE long-form
        # generate() instead (the path the transformers warning recommends).
        if hasattr(_stt_pipeline, "model") and hasattr(_stt_pipeline.model, "generation_config"):
            gen_cfg = _stt_pipeline.model.generation_config
            gen_cfg.forced_decoder_ids = None

            # Some community Whisper fine-tunes (e.g. the Khmer-tuned
            # checkpoints in STT_OPTIONS) ship a generation_config.json
            # predating transformers' current language-forcing mechanism β€”
            # it's missing lang_to_id/task_to_id, which makes
            # generate(language=...) raise "generation config is outdated"
            # the moment a specific language (not auto-detect) is picked.
            # Patch the missing multilingual mapping in from the matching
            # stock openai/whisper checkpoint of the same size β€” same
            # tokenizer/architecture, so the mapping is valid β€” instead of
            # only discovering this the first time someone picks a language.
            if getattr(gen_cfg, "lang_to_id", None) is None:
                try:
                    from transformers import GenerationConfig
                    size_hint = next(
                        (s for s in ("large-v3", "large-v2", "large", "medium", "small", "base", "tiny")
                         if s in target.lower()),
                        "small",
                    )
                    base_id  = f"openai/whisper-{size_hint}"
                    base_cfg = GenerationConfig.from_pretrained(base_id)
                    for attr in ("lang_to_id", "task_to_id", "is_multilingual"):
                        if hasattr(base_cfg, attr):
                            setattr(gen_cfg, attr, getattr(base_cfg, attr))
                    gen_cfg.forced_decoder_ids = None
                    print(f"[STT] '{target}' had an outdated generation_config β€” "
                          f"patched language mapping from '{base_id}'.")
                except Exception as e:
                    print(f"[STT] Could not patch outdated generation_config for '{target}': {e}")
        _stt_model_id = target
        return _stt_pipeline


def _is_khmer_asr_target(language: Optional[str], model_id: Optional[str]) -> bool:
    """Identify if the target audio transcription is Khmer (by language selection or Khmer fine-tuned model)."""
    lang = str(language or "").strip().lower()
    mid = str(model_id or "").strip().lower()
    if lang in ("khmer", "km"):
        return True
    if any(k in mid for k in ("khmer", "metythorn", "seanghay")):
        return True
    return False


def _transcribe_khmer_whisper(

    model, feature_extractor, tokenizer, audio_array, target_sr: int,

    total_samples: int, language: Optional[str] = None, model_id: Optional[str] = None

):
    """Dedicated transcription pipeline for Khmer language and Khmer fine-tuned checkpoints.

    

    Khmer is a multi-byte unspaced abugida script with frequent subword overlap. It must NOT

    use n-gram repetition bans or repetition penalties during generation, as those penalize

    legitimate Khmer syllables and trigger random multilingual token swaps.

    """
    import re
    import threading
    from transformers import TextIteratorStreamer

    # Khmer generation setup
    gen_kwargs = {"task": "transcribe"}
    # Force "km" if not auto or if explicit
    if language and language != "auto":
        gen_kwargs["language"] = "km" if language.lower() in ("khmer", "km") else language

    inputs = feature_extractor(
        audio_array, sampling_rate=target_sr,
        return_tensors="pt", return_attention_mask=True,
    )
    try:
        inputs = {k: v.to(model.device) for k, v in inputs.items()}
        inputs = {
            k: (v.to(model.dtype) if v.is_floating_point() else v)
            for k, v in inputs.items()
        }
    except Exception:
        pass

    def _clean_khmer_output(t_str: str) -> str:
        if not t_str:
            return ""
        # Deduplicate consecutive repeated Khmer words
        t_str = re.sub(r'(\b[\u1780-\u17FF\w]+\b)(?:\s+\1){2,}', r'\1', t_str)
        t_str = re.sub(r'\s{2,}', ' ', t_str)
        return t_str.strip()

    # 1. Try real-time token streaming
    try:
        streamer = TextIteratorStreamer(
            tokenizer, skip_prompt=True, skip_special_tokens=True
        )
        gen_dict = dict(inputs, **gen_kwargs, streamer=streamer)
        if total_samples > 30 * target_sr:
            gen_dict["return_segments"] = True
            gen_dict["condition_on_prev_tokens"] = True

        # The generation thread MUST always signal streamer.end() β€” if
        # model.generate raises inside the thread (OOM, unsupported kwarg,
        # outdated generation config …), an un-signalled streamer leaves the
        # `for piece in streamer` loop below blocked on its queue FOREVER
        # (a frozen STT tab). On failure we fall through to the batch path.
        gen_error = []

        def _streaming_generate():
            try:
                model.generate(**gen_dict)
            except Exception as e:
                gen_error.append(e)
                print(f"[STT-Khmer] Streaming generate failed ({e})")
            finally:
                streamer.end()

        thread = threading.Thread(target=_streaming_generate, daemon=True)
        thread.start()

        acc = []
        for piece in streamer:
            if piece:
                acc.append(piece)
                yield "".join(acc).strip()
        thread.join()
        final_res = _clean_khmer_output("".join(acc))
        if not gen_error:
            yield final_res if final_res else "(No speech detected)"
            return
        print("[STT-Khmer] Streaming fallback β€” running batch generate …")
        if "generation config is outdated" in str(gen_error[0]):
            # Don't replay the poisoned kwargs into the batch path β€” go
            # straight to the plain auto-detect generate (the known-good
            # recovery for an outdated generation config).
            outputs = model.generate(**inputs)
            seqs = outputs["sequences"] if isinstance(outputs, dict) else outputs
            text = _clean_khmer_output(" ".join(
                t.strip() for t in tokenizer.batch_decode(
                    seqs, skip_special_tokens=True)
                if t.strip()))
            yield text if text else "(No speech detected)"
            return
    except Exception as e:
        print(f"[STT-Khmer] Streaming fallback ({e}) β€” running batch generate …")

    # 2. Batch generate fallback
    try:
        if total_samples > 30 * target_sr:
            outputs = model.generate(
                **inputs, return_segments=True,
                condition_on_prev_tokens=True, **gen_kwargs,
            )
        else:
            outputs = model.generate(**inputs, **gen_kwargs)
    except ValueError as e:
        if "generation config is outdated" in str(e):
            outputs = model.generate(**inputs)
        else:
            raise

    sequences = outputs["sequences"] if isinstance(outputs, dict) else outputs
    text = " ".join(
        t.strip()
        for t in tokenizer.batch_decode(sequences, skip_special_tokens=True)
        if t.strip()
    )
    text = _clean_khmer_output(text)
    yield text if text else "(No speech detected)"


def _transcribe_english_and_multilingual_whisper(

    model, feature_extractor, tokenizer, audio_array, target_sr: int,

    total_samples: int, language: Optional[str] = None, model_id: Optional[str] = None

):
    """Dedicated transcription pipeline for English and standard international languages."""
    import re
    import threading
    from transformers import TextIteratorStreamer

    gen_kwargs = {}
    if language and language != "auto":
        gen_kwargs["language"] = language
        gen_kwargs["task"] = "transcribe"

    inputs = feature_extractor(
        audio_array, sampling_rate=target_sr,
        return_tensors="pt", return_attention_mask=True,
    )
    try:
        inputs = {k: v.to(model.device) for k, v in inputs.items()}
        inputs = {
            k: (v.to(model.dtype) if v.is_floating_point() else v)
            for k, v in inputs.items()
        }
    except Exception:
        pass

    def _clean_standard_output(t_str: str) -> str:
        if not t_str:
            return ""
        t_str = re.sub(r'(\b\S+\b)(?:\s+\1){3,}', r'\1', t_str)
        return t_str.strip()

    # 1. Try real-time token streaming
    try:
        streamer = TextIteratorStreamer(
            tokenizer, skip_prompt=True, skip_special_tokens=True
        )
        gen_dict = dict(inputs, **gen_kwargs, streamer=streamer)
        if total_samples > 30 * target_sr:
            gen_dict["return_segments"] = True
            gen_dict["condition_on_prev_tokens"] = True

        # Same end-signal guarantee as _transcribe_khmer_whisper: a generate
        # that raises inside its thread must never leave the streamer loop
        # below blocked forever β€” fall through to the batch path instead.
        gen_error = []

        def _streaming_generate():
            try:
                model.generate(**gen_dict)
            except Exception as e:
                gen_error.append(e)
                print(f"[STT-Multilingual] Streaming generate failed ({e})")
            finally:
                streamer.end()

        thread = threading.Thread(target=_streaming_generate, daemon=True)
        thread.start()

        acc = []
        for piece in streamer:
            if piece:
                acc.append(piece)
                yield "".join(acc).strip()
        thread.join()
        final_res = _clean_standard_output("".join(acc))
        if not gen_error:
            yield final_res if final_res else "(No speech detected)"
            return
        print("[STT-Multilingual] Streaming fallback β€” running batch generate …")
        if "generation config is outdated" in str(gen_error[0]):
            # Same poisoned-kwargs rule as the Khmer path: an outdated
            # generation config recovers via the plain auto-detect generate.
            outputs = model.generate(**inputs)
            seqs = outputs["sequences"] if isinstance(outputs, dict) else outputs
            text = _clean_standard_output(" ".join(
                t.strip() for t in tokenizer.batch_decode(
                    seqs, skip_special_tokens=True)
                if t.strip()))
            yield text if text else "(No speech detected)"
            return
    except Exception as e:
        print(f"[STT-Multilingual] Streaming fallback ({e}) β€” running batch generate …")

    # 2. Batch generate fallback
    try:
        if total_samples > 30 * target_sr:
            outputs = model.generate(
                **inputs, return_segments=True,
                condition_on_prev_tokens=True, **gen_kwargs,
            )
        else:
            outputs = model.generate(**inputs, **gen_kwargs)
    except ValueError as e:
        if gen_kwargs and "generation config is outdated" in str(e):
            outputs = model.generate(**inputs)
        else:
            raise

    sequences = outputs["sequences"] if isinstance(outputs, dict) else outputs
    text = " ".join(
        t.strip()
        for t in tokenizer.batch_decode(sequences, skip_special_tokens=True)
        if t.strip()
    )
    text = _clean_standard_output(text)
    yield text if text else "(No speech detected)"


def transcribe_audio_stream(audio_path: Optional[str], language: Optional[str] = None,

                            model_id: Optional[str] = None):
    """Generator version of transcribe_audio β€” yields intermediate status and chunked

    transcription text in real-time for live UI streaming."""
    if not audio_path:
        return

    yield "⏳ Preparing speech-to-text model..."

    try:
        asr = get_stt_pipeline(model_id)

        if hasattr(asr, "transcribe") and callable(asr.transcribe):
            yield "🌐 Transcribing via server/remote API..."
            res = asr.transcribe(audio_path, language=language)
            yield res
            return

        gen_kwargs = {}
        if language and language != "auto":
            gen_kwargs["language"] = language
            gen_kwargs["task"] = "transcribe"

        yield "🎡 Loading and decoding audio file..."

        import numpy as np
        target_sr = getattr(getattr(asr, "feature_extractor", None), "sampling_rate", 16000)

        try:
            import soundfile as sf
            audio_array, src_sr = sf.read(audio_path, dtype="float32", always_2d=False)
        except Exception:
            import librosa
            audio_array, src_sr = librosa.load(audio_path, sr=None, mono=False)

        audio_array = np.asarray(audio_array, dtype="float32")
        if audio_array.ndim == 2:
            channel_axis = 0 if audio_array.shape[0] < audio_array.shape[1] else 1
            audio_array = audio_array.mean(axis=channel_axis).astype("float32")

        if src_sr != target_sr:
            import librosa
            audio_array = librosa.resample(audio_array, orig_sr=src_sr, target_sr=target_sr)

        total_samples = len(audio_array)

        # ── Native Whisper long-form transcription (model.generate) ──────
        from transformers import WhisperForConditionalGeneration

        model = getattr(asr, "model", None)
        feature_extractor = getattr(asr, "feature_extractor", None)
        tokenizer = getattr(asr, "tokenizer", None)
        if (isinstance(model, WhisperForConditionalGeneration)
                and feature_extractor is not None and tokenizer is not None):
            yield "πŸŽ™οΈ Transcribing audio..."

            if _is_khmer_asr_target(language, model_id):
                yield from _transcribe_khmer_whisper(
                    model, feature_extractor, tokenizer, audio_array,
                    target_sr, total_samples, language, model_id
                )
            else:
                yield from _transcribe_english_and_multilingual_whisper(
                    model, feature_extractor, tokenizer, audio_array,
                    target_sr, total_samples, language, model_id
                )
            return

        # ── Fallback (non-Whisper HF ASR models) β€” the old per-chunk path ──
        gen_kwargs = {}
        if language and language != "auto":
            gen_kwargs["language"] = language
            gen_kwargs["task"] = "transcribe"

        chunk_samples = 30 * target_sr  # 30-second audio chunks

        if total_samples > chunk_samples:
            transcripts = []
            num_chunks = int(np.ceil(total_samples / chunk_samples))
            for i in range(num_chunks):
                start = i * chunk_samples
                end = min((i + 1) * chunk_samples, total_samples)
                chunk_data = audio_array[start:end]

                yield f"πŸŽ™οΈ Transcribing chunk {i+1}/{num_chunks} ({len(chunk_data)/target_sr:.1f}s)..."

                try:
                    res = asr({"array": chunk_data, "sampling_rate": target_sr}, generate_kwargs=gen_kwargs)
                except ValueError as e:
                    if gen_kwargs and "generation config is outdated" in str(e):
                        res = asr({"array": chunk_data, "sampling_rate": target_sr})
                    else:
                        raise
                chunk_text = (res.get("text", "") if isinstance(res, dict) else str(res)).strip()
                if chunk_text:
                    transcripts.append(chunk_text)
                    yield "\n".join(transcripts)

            final_text = "\n".join(transcripts).strip()
            yield final_text if final_text else "(No speech detected)"
        else:
            yield "πŸŽ™οΈ Transcribing audio..."
            try:
                result = asr({"array": audio_array, "sampling_rate": target_sr}, generate_kwargs=gen_kwargs)
            except ValueError as e:
                if gen_kwargs and "generation config is outdated" in str(e):
                    result = asr({"array": audio_array, "sampling_rate": target_sr})
                else:
                    raise
            text = (result.get("text", "") if isinstance(result, dict) else str(result)).strip()
            yield text if text else "(No speech detected)"

    except Exception as e:
        import traceback
        yield f"❌ {e}\n\n{traceback.format_exc()}"


def transcribe_audio(audio_path: Optional[str], language: Optional[str] = None,

                     model_id: Optional[str] = None) -> str:
    if not audio_path:
        return ""
    last_text = ""
    for chunk in transcribe_audio_stream(audio_path, language=language, model_id=model_id):
        last_text = chunk
    return last_text


# ──────────────────────────────────────────────────────────────────
# HF Inference API model proxies β€” thin wrappers that call
# huggingface_hub.InferenceClient for model types that don't have a
# smolagents built-in equivalent (InferenceClientModel only covers
# text-generation).  Each shares the HF token / model ID configured
# in the shared provider settings below.
# ──────────────────────────────────────────────────────────────────

class InferenceApiVLMModel:
    """Vision‑language model via HF Inference API β€” sends image + text

    to the remote endpoint instead of loading weights locally."""

    def __init__(self, model_id: str):
        self.model_id = model_id
        self._client = None

    def _get_client(self):
        if self._client is None:
            from huggingface_hub import InferenceClient
            token = mr.get_saved_hf_token() or None
            self._client = InferenceClient(token=token)
        return self._client

    def _stream_chat(self, messages: list, max_tokens: int) -> str:
        """Run one HF Inference API chat completion in STREAMING mode,

        pushing each generated text delta to the live bus (so the Vision

        tab / RAG grounding answer grows from real tokens, like the GGUF

        VLM backends). Returns the accumulated text; falls back to the

        non-streaming call if the endpoint rejects streaming."""
        client = self._get_client()
        bus = get_bus()
        if not bus.running:
            resp = client.chat_completion(
                messages=messages, model=self.model_id, max_tokens=max_tokens,
            )
            return resp.choices[0].message.content
        pieces = []
        try:
            bus.begin_generation()
            for event in client.chat_completion(
                messages=messages, model=self.model_id,
                max_tokens=max_tokens, stream=True,
            ):
                try:
                    delta = event.choices[0].delta
                    frag = getattr(delta, "content", None) or ""
                except Exception:  # noqa: BLE001
                    frag = ""
                if frag:
                    pieces.append(frag)
                    bus.push(frag)
            bus.end_generation()
            return "".join(pieces)
        except Exception:
            try:
                bus.end_generation()
            except Exception:  # noqa: BLE001
                pass
            resp = client.chat_completion(
                messages=messages, model=self.model_id, max_tokens=max_tokens,
            )
            return resp.choices[0].message.content

    def answer(self, question: str, images: list, context: str = "",

               max_tokens: int = 512, lang_key: str = "kh") -> str:
        client = self._get_client()
        user_text = question + (f"\n\nContext:\n{context}" if context else "")
        # UI-language output directive β€” same shared instruction as every
        # other chat path (see vlm_answer / llama_backend VLMs).
        messages = [
            {"role": "system", "content": (
                i18n._output_lang_instruction(lang_key) +
                "You are a helpful assistant. Answer based on images and context. "
                "Answer the user's question below β€” do not respond to these "
                "instructions."
            )},
            {"role": "user", "content": user_text},
        ]
        try:
            return self._stream_chat(messages, max_tokens)
        except Exception as e:
            # Some VLM models on HF IAPI need images passed differently
            # β€” try again with image content.
            if images:
                img_b64 = _image_to_base64(images[0])
                content = [
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}},
                    {"type": "text", "text": user_text},
                ]
                # Keep the UI-language system directive on the retry too.
                messages = [
                    {"role": "system", "content": (
                        i18n._output_lang_instruction(lang_key) +
                        "You are a helpful assistant. Answer based on images and context. "
                        "Answer the user's question below β€” do not respond to these "
                        "instructions."
                    )},
                    {"role": "user", "content": content},
                ]
                return self._stream_chat(messages, max_tokens)
            raise


class InferenceApiSTTModel:
    """Speech‑to‑text via HF Inference API β€” posts audio to the remote

    endpoint instead of loading Whisper locally."""

    def __init__(self, model_id: str):
        self.model_id = model_id
        self._client = None

    def _get_client(self):
        if self._client is None:
            from huggingface_hub import InferenceClient
            token = mr.get_saved_hf_token() or None
            self._client = InferenceClient(token=token)
        return self._client

    def transcribe(self, audio_path: str, language: Optional[str] = None) -> str:
        client = self._get_client()
        with open(audio_path, "rb") as f:
            data = f.read()
        result = client.automatic_speech_recognition(
            data,
            model=self.model_id,
        )
        return (result.get("text", "") if isinstance(result, dict)
                else str(result))


class InferenceApiEmbeddingModel:
    """Embedding model via HF Inference API β€” calls the feature-extraction

    endpoint instead of loading SentenceTransformer locally."""

    def __init__(self, model_id: str):
        self.model_id = model_id
        self._client = None

    def _get_client(self):
        if self._client is None:
            from huggingface_hub import InferenceClient
            token = mr.get_saved_hf_token() or None
            self._client = InferenceClient(token=token)
        return self._client

    def encode(self, texts: list, normalize: bool = True) -> list:
        client = self._get_client()
        result = client.feature_extraction(texts, model=self.model_id)
        # Result may be a list of lists or a numpy array
        import numpy as np
        arr = np.asarray(result, dtype=np.float32)
        if arr.ndim == 1:
            arr = arr.reshape(1, -1)
        if normalize:
            norms = np.linalg.norm(arr, axis=1, keepdims=True)
            norms = np.where(norms == 0, 1.0, norms)
            arr = arr / norms
        return arr.tolist()


class EmbeddingServerModel:
    """Embedding model via llama.cpp server's /v1/embeddings endpoint

    (OpenAI-compatible).  Spawns/reuses the DEDICATED embedding llama-server

    process managed by llama_backend.get_or_start_embed_server() β€” its own

    subprocess on its own port, fully independent of the chat/VLM server."""

    def __init__(self, model_path: str, base_url: str, n_ctx: int = 16384):
        self.model_id = model_path
        self.model_path = model_path
        self.base_url = base_url.rstrip("/")
        # Remembered so a dead-server restart re-requests the SAME config
        # (a different n_ctx would needlessly relaunch the server).
        self.n_ctx = int(n_ctx or 16384)

    def encode(self, texts: list, normalize: bool = True) -> list:
        import requests
        import numpy as np

        # For a single string, wrap it
        if isinstance(texts, str):
            texts = [texts]

        payload = {
            "input": texts,
            "model": self.model_path,
        }

        try:
            resp = requests.post(
                f"{self.base_url}/v1/embeddings",
                json=payload,
                timeout=120,
            )
            resp.raise_for_status()
        except requests.exceptions.ConnectionError:
            # The dedicated embedding server died or was stopped (Free All
            # VRAM, an exe-path change, a crash) while this cached wrapper
            # survived. Restart it ONCE on its own slot and retry β€” the
            # chat/VLM server is never touched.
            print(f"[RAG] Embedding server unreachable at {self.base_url} β€” "
                  f"restarting the dedicated embedding llama-server …")
            base_url = llama_backend.get_or_start_embed_server(
                model_path=self.model_path,
                n_ctx=self.n_ctx,
            )
            self.base_url = base_url.rstrip("/")
            resp = requests.post(
                f"{self.base_url}/v1/embeddings",
                json=payload,
                timeout=120,
            )
            resp.raise_for_status()
        data = resp.json()

        # Extract embeddings in order of the input indices
        embeddings = [d["embedding"] for d in sorted(data["data"], key=lambda x: x["index"])]

        arr = np.asarray(embeddings, dtype=np.float32)
        if normalize:
            norms = np.linalg.norm(arr, axis=1, keepdims=True)
            norms = np.where(norms == 0, 1.0, norms)
            arr = arr / norms
        return arr.tolist()


def _image_to_base64(img) -> str:
    """Convert a PIL image to a base64-encoded JPEG string."""
    import base64
    from io import BytesIO
    buf = BytesIO()
    img.convert("RGB").save(buf, format="JPEG", quality=85)
    return base64.b64encode(buf.getvalue()).decode("utf-8")


# ──────────────────────────────────────────────────────────────────
# Explicit "force unload / offload from VRAM" actions β€” wired to an
# "Unload from VRAM" button on each relevant tab. These free memory
# immediately via _release_model() without loading any replacement,
# unlike get_llm()/get_vlm()/get_stt_pipeline() which only release the
# *previous* model right before loading a new one.
# ──────────────────────────────────────────────────────────────────
def unload_llm_fn(lang_key: str = "kh") -> str:
    global _llm, _llm_model_id, _llm_backend_key
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if _llm is None:
        return l["btn_unload_none"]
    mid = _llm_model_id
    _release_and_clear("_llm")
    _llm_backend_key = None
    return l["msg_unloaded"].format(model=mid)


def unload_vlm_fn(lang_key: str = "kh") -> str:
    global _vlm_model, _vlm_processor, _vlm_model_id, _vlm_n_ctx, _vlm_backend_key
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if _vlm_model is None:
        return l["btn_unload_none"]
    mid = _vlm_model_id
    _release_and_clear("_vlm_model")
    _vlm_processor = None
    _vlm_model_id = None
    _vlm_n_ctx = None
    _vlm_backend_key = None
    return l["msg_unloaded"].format(model=mid)


def unload_stt_fn(lang_key: str = "kh") -> str:
    global _stt_pipeline, _stt_model_id
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if _stt_pipeline is None:
        return l["btn_unload_none"]
    mid = _stt_model_id
    _release_and_clear("_stt_pipeline")
    _stt_model_id = None
    return l["msg_unloaded"].format(model=mid)


def force_reload_llm(target_model_id: str, n_ctx: Optional[int] = None, provider: Optional[str] = None):
    """Used by the tab-level 'Load' buttons and the global '🧠 Context

    Window' control: fully release whatever LLM is currently loaded

    (regardless of id) and load `target_model_id` fresh β€” optionally with

    a specific context window (GGUF backend only; ignored for HF models)."""
    global _llm
    _release_and_clear("_llm")
    return get_llm(target_model_id, n_ctx=n_ctx, provider=provider)


def force_reload_vlm(target_model_id: str, mmproj_path: Optional[str] = None, provider: Optional[str] = None, n_ctx: Optional[int] = None):
    global _vlm_model, _vlm_processor
    _release_and_clear("_vlm_model")
    _vlm_processor = None
    return get_vlm(target_model_id, mmproj_path=mmproj_path, provider=provider, n_ctx=n_ctx)


def force_reload_stt(target_model_id: str):
    global _stt_pipeline, _stt_model_id
    _release_and_clear("_stt_pipeline")
    _stt_model_id = None
    return get_stt_pipeline(target_model_id)