Spaces:
Paused

File size: 100,727 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
"""

knowledge_base.py β€” Document indexing (PDF/TXT/MD/DOCX + HuggingFace

datasets) into ChromaDB, the optional visual (image-based PDF) index via

byaldi, and retrieval helpers used by the chat tabs.

"""

import base64
import hashlib
import json
import re
import time
from collections import defaultdict
from difflib import SequenceMatcher
from collections import Counter
from io import BytesIO
from pathlib import Path
from typing import Optional

from PIL import Image

from smolagents import Tool

from backend import model_registry as mr
from backend import models
from backend.hardware import DEVICE
from backend.paths import third_party_dir
from ui.i18n import LANGUAGES

import os
import sys

_visual_retriever    = None
_visual_retriever_id = None


def _add_poppler_to_path():
    if sys.platform != "win32":
        return
    for poppler_dir in [third_party_dir() / "poppler",
                        Path.cwd() / "third_party" / "poppler", Path.cwd() / "poppler"]:
        if poppler_dir.exists():
            for pdfinfo_file in poppler_dir.rglob("pdfinfo.exe"):
                bin_dir = pdfinfo_file.parent
                bin_str = str(bin_dir)
                if bin_str not in os.environ["PATH"]:
                    os.environ["PATH"] = bin_str + os.pathsep + os.environ["PATH"]
                    print(f"[Poppler] Found local Poppler at: {bin_str}")
                return

    possible_paths = [
        Path(sys.prefix) / "Library" / "bin",
        Path(sys.prefix) / "bin",
        Path(os.environ.get("LOCALAPPDATA", "")) / "scoop" / "apps" / "poppler" / "current" / "bin",
        Path(os.environ.get("USERPROFILE", "")) / "scoop" / "apps" / "poppler" / "current" / "bin",
        Path(r"C:\poppler\Library\bin"),
        Path(r"C:\poppler\bin"),
        Path(r"C:\Program Files\poppler\Library\bin"),
        Path(r"C:\Program Files\poppler\bin"),
    ]
    for p in possible_paths:
        if p.exists() and (p / "pdfinfo.exe").exists():
            p_str = str(p)
            if p_str not in os.environ["PATH"]:
                os.environ["PATH"] = p_str + os.pathsep + os.environ["PATH"]
                print(f"[Poppler] Auto-detected Poppler at: {p_str}")
            break

_add_poppler_to_path()


def get_file_path(f) -> Optional[str]:
    if f is None:          return None
    if isinstance(f, str): return f
    if isinstance(f, dict):return f.get("path") or f.get("name") or f.get("tmp_path")
    if hasattr(f, "path"): return f.path
    if hasattr(f, "name"): return f.name
    return None


def _chunk_text(text: str):
    chunks, start = [], 0
    while start < len(text):
        chunks.append(text[start: start + mr.CHUNK_SIZE])
        start += mr.CHUNK_SIZE - mr.CHUNK_OVERLAP
    return chunks


def _safe_meta(meta: dict, chunk_index: int) -> dict:
    safe = {k: v if isinstance(v, (str, int, float, bool)) else str(v)
            for k, v in meta.items()}
    safe["chunk_index"] = chunk_index
    return safe


_DIMENSION_MISMATCH_HINT = (
    "The current embedding model doesn't match the one this knowledge "
    "base was indexed with (vector dimension mismatch). Switch back to "
    "the original embedding model in the πŸ“‚ Knowledge Base tab's "
    "'🧩 Embedding Model' control, or clear the index (πŸ’₯ Clear ALL) and "
    "re-index your documents with the new embedding model."
)


def get_collection_embedding_dim() -> Optional[int]:
    """Best-effort: return the vector dimension the CURRENT ChromaDB

    collection was actually built with, by peeking at one stored

    embedding. Returns None if the collection is empty β€” nothing to

    compare against yet, so any embedding model is safe to switch to.



    Used by the Knowledge Base tab's "🧩 Embedding Model" Load button to

    warn the user BEFORE they switch, rather than only finding out the

    hard way on the next query/index call.

    """
    col = models.get_chroma_collection()
    if col.count() == 0:
        return None
    try:
        peek = col.peek(limit=1)
        vecs = peek.get("embeddings")
        if vecs is not None and len(vecs) > 0:
            return len(vecs[0])
    except Exception:
        pass
    return None


def _tag_pairs(theme="", subtheme="") -> list[tuple[str, str]]:
    """Expand the (possibly multi-select) theme/subtheme tags into a list

    of SCALAR (theme, subtheme) pairs to index.



    ChromaDB's where-filters (`$eq` / `$in`) only match SCALAR metadata

    values, so a file tagged with several themes/subthemes is indexed once

    per selected combination β€” each copy carries ONE scalar pair and is

    therefore retrievable under every tag the user picked. Empty selections

    produce the single ('', '') pass (untagged indexing, as before).



    E.g. themes=[Law, Health], subthemes=[Criminal] β†’

    [(Law, Criminal), (Health, Criminal)].

    """
    themes = _as_scope_list(theme) or [""]
    subs = _as_scope_list(subtheme) or [""]
    return [(t, s) for t in themes for s in subs]


def index_texts(texts: list, metadatas: list) -> int:
    invalidate_doc_table_cache()
    col = models.get_chroma_collection()
    all_chunks, all_metas, all_ids = [], [], []
    for text, meta in zip(texts, metadatas):
        for j, chunk in enumerate(_chunk_text(text)):
            # The id must be unique per (source, metadata) AND stable across
            # re-indexing the same file with the same tags (so upsert
            # replaces rather than duplicates). The metadata hash makes a
            # multi-tagged file's copies β€” identical chunk text under
            # different theme/subtheme tags β€” get DIFFERENT ids instead of
            # colliding on a local counter (the second tag pass used to
            # upsert over the first).
            meta_key = hashlib.md5(
                json.dumps(meta, sort_keys=True, ensure_ascii=False).encode("utf-8")
            ).hexdigest()[:10]
            uid = f"{meta.get('source','doc')}__{meta_key}__{len(all_chunks)}"
            all_chunks.append(chunk)
            all_metas.append(_safe_meta(meta, j))
            all_ids.append(uid)
    if not all_chunks:
        return 0
    for i in range(0, len(all_chunks), 64):
        vecs = models.encode_texts(all_chunks[i:i+64])
        try:
            col.upsert(embeddings=vecs, documents=all_chunks[i:i+64],
                       metadatas=all_metas[i:i+64], ids=all_ids[i:i+64])
        except Exception as e:
            if "dimension" in str(e).lower():
                raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e
            raise
    return len(all_chunks)


# ──────────────────────────────────────────────────────────────────
# byaldi (visual PDF RAG) is a heavy native-binary dependency chain:
# byaldi -> colpali_engine -> transformers -> torchaudio. On machines
# with a broken or mismatched native wheel (e.g. a CUDA torchaudio build
# sitting on top of a CPU-only torch install β€” the same family of
# failure as llama-cpp-python), importing it at module level killed app
# startup with an OSError/RuntimeError. Per AGENTS.md ("the app MUST
# always launch"), byaldi is imported lazily and its failure is cached
# so visual RAG degrades to a clear message instead of a crash.
# ──────────────────────────────────────────────────────────────────
_BYALDI_AVAILABLE    = None      # None = untested, False = broken, class = OK
_BYALDI_IMPORT_ERROR = ""


def _get_byaldi():
    """Lazily import and return byaldi's RAGMultiModalModel class, or

    None if it can't load on this machine (broken native/CUDA wheel).

    Never raises β€” the app must always launch (AGENTS.md)."""
    global _BYALDI_AVAILABLE, _BYALDI_IMPORT_ERROR
    if _BYALDI_AVAILABLE is None:
        try:
            from byaldi import RAGMultiModalModel
            _BYALDI_AVAILABLE = RAGMultiModalModel
        except Exception as e:  # ImportError, OSError, RuntimeError, ...
            _BYALDI_AVAILABLE = False
            _BYALDI_IMPORT_ERROR = str(e)
            print("[Vision] byaldi unavailable β€” visual PDF RAG disabled. "
                  f"({type(e).__name__}: {str(e)[:200]})")
    return _BYALDI_AVAILABLE if _BYALDI_AVAILABLE else None


_VISUAL_UNAVAILABLE_MSG = (
    "⚠️ Visual PDF indexing is unavailable on this PC β€” the visual-RAG "
    "engine (byaldi/torchaudio) can't load its native libraries here "
    "(typically a CUDA build installed on a machine without the matching "
    "CUDA runtime, or an old GPU). Text indexing works fine. To enable it, "
    "install the CPU build of torchaudio matching your torch version: "
    'pip install "torchaudio==<your torch version>+cpu" '
    "--index-url https://download.pytorch.org/whl/cpu"
    "\n\nActual error: {detail}"
)


def _load_byaldi_model(retriever_id: str):
    global _visual_retriever, _visual_retriever_id
    if _visual_retriever is not None and _visual_retriever_id == retriever_id:
        return _visual_retriever

    byaldi_cls = _get_byaldi()
    if byaldi_cls is None:
        raise RuntimeError(_VISUAL_UNAVAILABLE_MSG.format(
            detail=_BYALDI_IMPORT_ERROR or "unknown"))

    target = retriever_id or mr.DEFAULT_VISUAL_RETRIEVER
    index_path = Path(mr.VISUAL_INDEX_DIR) / "main"
    try:
        if index_path.exists():
            # Load the EXISTING index via from_index β€” it populates the
            # embeddings / mappings / collection. from_pretrained alone
            # leaves indexed_embeddings EMPTY, so search() fails with
            # "No passages provided" and the visual retrieval can never see
            # the indexed pages (the exact failure in the RAG logs: the
            # retriever loads but returns nothing). The persisted index
            # dictates its own model (index_config.model_name), so the
            # requested retriever id is advisory once an index exists.
            _visual_retriever = byaldi_cls.from_index(str(index_path))
            try:
                cfg = _read_gzip_json(index_path / "index_config.json.gz")
                _visual_retriever_id = cfg.get("model_name") or target
            except Exception:
                _visual_retriever_id = target
        else:
            _visual_retriever = byaldi_cls.from_pretrained(
                target, index_root=mr.VISUAL_INDEX_DIR, verbose=0,
            )
            _visual_retriever_id = target
    except ValueError as e:
        if "only supports ColPali and ColQwen2" in str(e):
            fallback = "vidore/colqwen2-v1.0"
            print(f"[Vision] '{target}' not supported by this version of Byaldi. Falling back to: {fallback}")
            _visual_retriever = byaldi_cls.from_pretrained(
                fallback, index_root=mr.VISUAL_INDEX_DIR, verbose=0,
            )
            _visual_retriever_id = fallback
        else:
            raise
    return _visual_retriever


def get_visual_retriever():
    try:
        return _load_byaldi_model(_visual_retriever_id or mr.DEFAULT_VISUAL_RETRIEVER)
    except Exception as e:
        print(f"[Vision] Visual retriever unavailable: {e}")
        return None


def visual_retriever_needs_load() -> bool:
    """True when the visual index exists but the retriever model is NOT yet

    loaded in memory β€” i.e. the next visual_retrieve() will pay the cold

    2-8 GB model load. chat.py's direct RAG path uses this to show a

    'πŸ–ΌοΈ Loading visual index…' status line ONLY when the load is actually

    about to happen (warm calls stay snappy β€” no flicker)."""
    return ((Path(mr.VISUAL_INDEX_DIR) / "main").exists()
            and _visual_retriever is None)


def index_pdf_visual(filepath: str, retriever_id: str, lang_key: str = "kh",

                     source_name: str = "", theme: str = "", subtheme: str = "") -> str:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    try:
        byaldi_cls = _get_byaldi()
        if byaldi_cls is None:
            return _VISUAL_UNAVAILABLE_MSG.format(
                detail=_BYALDI_IMPORT_ERROR or "unknown")

        global _visual_retriever, _visual_retriever_id
        index_path = Path(mr.VISUAL_INDEX_DIR) / "main"
        index_path.parent.mkdir(parents=True, exist_ok=True)
        
        _load_byaldi_model(retriever_id)

        meta = {"source": source_name or Path(filepath).name,
                "theme": _meta_tags(theme), "subtheme": _meta_tags(subtheme)}

        # _load_byaldi_model already loaded the index (when present) β€” reuse
        # it for add_to_index instead of from_index again (a second call
        # would re-create the whole 2-8 GB model).
        if index_path.exists():
            try:
                _visual_retriever.add_to_index(input_item=filepath,
                                               store_collection_with_index=True,
                                               doc_id=int(time.time()),
                                               metadata=meta)
            except Exception:
                _visual_retriever.index(input_path=filepath, index_name="main",
                                        store_collection_with_index=True, overwrite=True)
        else:
            _visual_retriever.index(input_path=filepath, index_name="main",
                                    store_collection_with_index=True, overwrite=False,
                                    metadata=[meta])
        return l["kb_msg_visual_updated"].format(name=source_name or Path(filepath).name)
    except ImportError:
        return l["kb_msg_byaldi_missing"]
    except Exception as e:
        err_str = str(e)
        if "poppler" in err_str.lower() or "page count" in err_str.lower():
            return l["kb_msg_poppler_missing"]
        return f"❌ {e}"


def index_image_visual(filepath: str, retriever_id: str, lang_key: str = "kh",

                       source_name: str = "", theme: str = "", subtheme: str = "") -> str:
    """Add a STANDALONE image file to the byaldi visual index (image chunks

    via ColPali β€” the same index the PDF visual pipeline uses). Only the

    extensions byaldi's _process_and_add_to_index handles (jpg/jpeg/png/bmp)

    are accepted; webp/gif/tiff get the text index only and report a clear

    skip here. Unlike PDFs, an existing index is NEVER rebuilt from a single

    image (that would wipe every other visual doc) β€” add_to_index only."""
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    ext = Path(filepath).suffix.lower()
    if ext not in (".jpg", ".jpeg", ".png", ".bmp"):
        return l["kb_msg_image_visual_skipped"].format(ext=ext or "?")
    try:
        byaldi_cls = _get_byaldi()
        if byaldi_cls is None:
            return _VISUAL_UNAVAILABLE_MSG.format(
                detail=_BYALDI_IMPORT_ERROR or "unknown")

        global _visual_retriever, _visual_retriever_id
        index_path = Path(mr.VISUAL_INDEX_DIR) / "main"
        index_path.parent.mkdir(parents=True, exist_ok=True)

        _load_byaldi_model(retriever_id)

        meta = {"source": source_name or Path(filepath).name,
                "theme": _meta_tags(theme), "subtheme": _meta_tags(subtheme)}

        # Reuse the index loaded by _load_byaldi_model (never from_index
        # again β€” that would re-create the whole 2-8 GB model).
        if index_path.exists():
            _visual_retriever.add_to_index(input_item=filepath,
                                           store_collection_with_index=True,
                                           doc_id=int(time.time()),
                                           metadata=meta)
        else:
            _visual_retriever.index(input_path=filepath, index_name="main",
                                    store_collection_with_index=True, overwrite=False,
                                    metadata=[meta])
        return l["kb_msg_visual_updated"].format(name=source_name or Path(filepath).name)
    except ImportError:
        return l["kb_msg_byaldi_missing"]
    except Exception as e:
        return f"❌ {e}"


def _visual_search_results(query: str, top_k: int = 3) -> list:
    """Raw byaldi search results for `query` against the visual index, or

    [] when there is no index / the retriever can't load / search fails.

    Shared by visual_retrieve() (page images for the RAG grounding pass)

    and VisualRetrieverTool (page images + per-page source metadata for the

    agentic RAG path) so both go through ONE search implementation. The

    cheap directory check runs first β€” the ~2-8 GB retriever model is only

    loaded when an index actually exists."""
    # Nothing has been indexed into the visual (image-based PDF) index yet β€”
    # skip entirely instead of loading the ~2-8 GB retriever model just to
    # search an empty index. This is the normal state until the user
    # indexes at least one PDF / image from the Knowledge Base tab.
    if not (Path(mr.VISUAL_INDEX_DIR) / "main").exists():
        return []
    retriever = get_visual_retriever()
    if retriever is None:
        return []
    try:
        return retriever.search(query, k=top_k)
    except Exception as e:
        print(f"[VIS] {e}")
        return []


def visual_retrieve(query: str, top_k: int = 3) -> list:
    """Page images (PIL, RGB) from the visual index most relevant to

    `query`, or [] when the index is empty / unavailable. The 2-8 GB

    retriever model is only loaded when an index actually exists."""
    images = []
    for r in _visual_search_results(query, top_k):
        if hasattr(r, "base64") and r.base64:
            images.append(Image.open(BytesIO(base64.b64decode(r.base64))).convert("RGB"))
    return images


# ──────────────────────────────────────────────────────────────────────
# Visual-tool hits cache β€” the page images a VisualRetrieverTool call
# retrieved during an AGENTIC RAG run. The tool returns only a TEXT report
# to the model (a text-only LLM can't see images), but the multimodal
# grounding pass in chat.py needs the ACTUAL images; the tool stashes them
# here so the grounding pass reuses them instead of loading the 2-8 GB
# retriever model a second time to re-retrieve by query. Reset before each
# run (rag_agent.reset_retriever_stats), consumed + cleared after.
# ──────────────────────────────────────────────────────────────────────
_visual_tool_hits: list = []


def reset_visual_tool_hits() -> None:
    """Clear the cached page images from a previous run (called right

    before agent.run(), mirroring reset_retriever_stats)."""
    global _visual_tool_hits
    _visual_tool_hits = []


def consume_visual_tool_hits() -> list:
    """Return and clear the page images the agent's visual_retriever tool

    retrieved this run β€” the grounding pass feeds them (with the retrieved

    text context) to the same-model VLM. [] when the tool never ran or

    found nothing."""
    global _visual_tool_hits
    hits = _visual_tool_hits
    _visual_tool_hits = []
    return hits


def unload_visual_retriever_fn(lang_key: str = "kh") -> str:
    global _visual_retriever, _visual_retriever_id
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if _visual_retriever is None:
        return l["btn_unload_none"]
    mid = _visual_retriever_id or mr.DEFAULT_VISUAL_RETRIEVER
    obj = _visual_retriever
    _visual_retriever = None
    _visual_retriever_id = None
    models._release_model(obj)
    return l["msg_unloaded"].format(model=mid)


# ──────────────────────────────────────────────────────────────────────
# Visual index table / delete / clear β€” pure file surgery on byaldi's
# persisted files. byaldi 0.0.7 has NO per-doc delete API (remove_from_index
# is NotImplementedError), so rows are removed by rewriting the persisted
# index directly: embeddings chunks (flat list β†’ position = embed_id),
# embed_id_to_doc_id mapping, doc_ids_to_file_names, collection chunks,
# metadata and index_config. Embed ids are renumbered sequentially (search
# indexes indexed_embeddings positionally and maps back through
# embed_id_to_doc_id, so gaps would break it). The 2-8 GB retriever model
# is NEVER loaded for listing/deleting.
# ──────────────────────────────────────────────────────────────────────


def _meta_tags(value) -> str:
    """Join multi-select theme/subtheme tags into the single metadata

    string stored on visual docs (", ".join, sorted β€” the same display as

    the docs table). Empty selection β†’ ""."""
    vals = _as_scope_list(value)
    return ", ".join(sorted(v for v in vals if v))


def _visual_index_dir() -> Path:
    return Path(mr.VISUAL_INDEX_DIR) / "main"


def _read_gzip_json(p: Path):
    import gzip
    with gzip.open(p, "rt", encoding="utf-8") as fh:
        return json.load(fh)


def _write_gzip_json(p: Path, data):
    import gzip
    with gzip.open(p, "wt", encoding="utf-8") as fh:
        json.dump(data, fh, ensure_ascii=False)


def _visual_display_name(doc_id, file_names, metadata) -> str:
    """Display name for a visual doc: prefer the original filename stored in

    byaldi metadata (added on ingest), else the basename of the stored path

    (older indexes record the upload temp path)."""
    meta = metadata.get(str(doc_id)) or metadata.get(doc_id) or {}
    src = meta.get("source") or file_names.get(str(doc_id)) or file_names.get(doc_id) or ""
    if src and src != "In-memory Image":
        return Path(str(src)).name
    return src or f"doc-{doc_id}"


def _visual_sources_set() -> set:
    """The set of source filenames that have page images in the visual

    index, read straight from the persisted metadata gz β€” NO retriever

    model load (the same cheap file read `_visual_doc_id_for_source`

    uses, but for all sources at once). Empty set when no visual index

    exists. Used by the RAG summary tools to signal "this document also

    has page images β€” delegate to `knowledge_searcher` for a visual

    pass" (the scanned-PDF case: text chunks are OCR garbage but the

    page images carry the real content)."""
    index_path = _visual_index_dir()
    if not index_path.exists():
        return set()
    try:
        metadata = _read_gzip_json(index_path / "metadata.json.gz")
    except FileNotFoundError:
        return set()
    except Exception:
        return set()
    out = set()
    for meta in metadata.values():
        src = str((meta or {}).get("source", "") or "")
        if src and src != "In-memory Image":
            out.add(src)
    return out


def _looks_like_ocr_garbage(text: str) -> bool:
    """True when extracted TEXT looks like failed OCR β€” the telltale

    `(cid:N)` glyph-id fragments, `cid:N` markers, or U+FFFD replacement

    chars that scanned-PDF text extraction leaves behind when the font

    has no Unicode mapping. The RAG searcher / manager use this signal to

    route image-heavy scanned documents to `visual_retriever` instead of

    concluding the knowledge base "has nothing" or summarizing garbage.

    """
    sample = str(text or "")[:20000]
    if re.search(r"\(cid:\s*\d+\)", sample, re.IGNORECASE):
        return True
    if re.search(r"\bcid\s*\d+\b", sample, re.IGNORECASE):
        return True
    return "\ufffd" in sample


def _visual_doc_id_for_source(source: str):
    """The visual-index doc id whose ingest metadata carries `source` (the

    original filename), or None β€” used to link a docs-table image row to its

    visual page thumbnail. Reads the persisted metadata gz, no model load."""
    index_path = _visual_index_dir()
    if not index_path.exists() or not source:
        return None
    try:
        metadata = _read_gzip_json(index_path / "metadata.json.gz")
    except FileNotFoundError:
        metadata = {}
    except Exception:
        return None
    for doc_id, meta in metadata.items():
        if str(meta.get("source", "")) == source:
            return str(doc_id)
    return None


def get_visual_index_table() -> list:
    """List every visual document WITHOUT loading the retriever model:

    rows of [source file, doc id, pages/images, theme, subtheme] read

    straight from the index's persisted gz mappings (theme/subtheme come

    from the byaldi metadata stored on ingest; older rows show "").

    Empty when no visual index exists."""
    index_path = _visual_index_dir()
    if not index_path.exists():
        return []
    try:
        file_names = _read_gzip_json(index_path / "doc_ids_to_file_names.json.gz")
        embed_map  = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz")
        try:
            metadata = _read_gzip_json(index_path / "metadata.json.gz")
        except FileNotFoundError:
            metadata = {}
        counts = {}
        for entry in embed_map.values():
            try:
                doc_id = int(entry.get("doc_id"))
            except (TypeError, ValueError):
                continue
            counts[doc_id] = counts.get(doc_id, 0) + 1
        rows = []
        for doc_id in sorted(counts):
            meta = metadata.get(str(doc_id)) or metadata.get(doc_id) or {}
            rows.append([_visual_display_name(doc_id, file_names, metadata),
                         str(doc_id), str(counts[doc_id]),
                         str(meta.get("theme", "") or ""),
                         str(meta.get("subtheme", "") or "")])
        return rows
    except Exception as e:
        print(f"[Vision] visual index table read failed: {e}")
        return []


def get_visual_thumb_bytes(doc_id: int, page_id: int = 1):
    """The stored PNG bytes for a visual document's page, read straight

    from the persisted collection (base64 per embed id) β€” NO retriever

    model load, so thumbnails render instantly in the KB tab. Returns None

    when the visual index / collection is missing, the (doc, page) doesn't

    exist, or the read fails."""
    index_path = _visual_index_dir()
    coll_dir = index_path / "collection"
    if not index_path.exists() or not coll_dir.exists():
        return None
    try:
        embed_map = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz")
        target = None
        for eid, entry in embed_map.items():
            try:
                if (int(entry.get("doc_id", -1)) == int(doc_id)
                        and int(entry.get("page_id", -1)) == int(page_id)):
                    target = int(eid)
                    break
            except (TypeError, ValueError):
                continue
        if target is None:
            return None
        for f in sorted(coll_dir.glob("*.json.gz"),
                        key=lambda x: int(x.stem.split(".")[0])):
            chunk = _read_gzip_json(f)
            b64 = chunk.get(str(target))
            if b64:
                return base64.b64decode(b64)
        return None
    except Exception as e:
        print(f"[Vision] visual thumb read failed: {e}")
        return None


def _load_visual_embedding_files(index_path: Path) -> list:
    """Flatten the persisted embeddings_*.pt chunks into one list whose

    position is the embed id (byaldi's on-disk layout)."""
    import torch
    embeddings_path = index_path / "embeddings"
    files = sorted(embeddings_path.glob("embeddings_*.pt"),
                   key=lambda x: int(x.stem.split("_")[1]))
    out = []
    for f in files:
        try:
            out.extend(torch.load(f))
        except Exception:
            out.extend(torch.load(f, weights_only=False))
    return out


def _drop_rows(seq, drop_positions):
    return [x for i, x in enumerate(seq) if i not in drop_positions]


def delete_visual_docs(selected_rows: list, rows: list = None, lang_key: str = "kh") -> tuple:
    """Delete selected visual documents by doc id. `selected_rows` are row

    indexes into the visual table (row[1] = doc id). Rewrites the persisted

    byaldi files so search keeps working without a rebuild; when the last

    doc goes, the whole index dir is removed. Returns (new table, message)."""
    global _visual_retriever, _visual_retriever_id
    import shutil
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    index_path = _visual_index_dir()
    table = get_visual_index_table()
    if not index_path.exists():
        return table, l["err_nothing_deleted"]

    rows_to_use = rows if (rows and len(rows) > 0) else table
    doc_ids, names = [], []
    for idx in selected_rows or []:
        if 0 <= idx < len(rows_to_use):
            try:
                doc_ids.append(int(rows_to_use[idx][1]))
                names.append(str(rows_to_use[idx][0]))
            except (TypeError, ValueError):
                continue
    if not doc_ids:
        return table, l["err_nothing_deleted"]
    deleted = set(doc_ids)

    try:
        embed_map_raw  = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz")
        file_names_raw = _read_gzip_json(index_path / "doc_ids_to_file_names.json.gz")
        config         = _read_gzip_json(index_path / "index_config.json.gz")
        try:
            metadata = _read_gzip_json(index_path / "metadata.json.gz")
        except FileNotFoundError:
            metadata = {}

        # embed id -> entry, keeping only non-deleted docs (order preserved)
        kept = [(int(eid), entry) for eid, entry in embed_map_raw.items()
                if int(entry.get("doc_id", -1)) not in deleted]

        if not kept:
            # nothing left β€” wipe the whole visual index
            shutil.rmtree(index_path, ignore_errors=True)
            _visual_retriever = None
            _visual_retriever_id = None
            joined = ", ".join(names) or l["err_nothing_deleted"]
            return [], l["kb_visual_deleted"].format(n=len(deleted), names=joined)

        drop_positions = {int(eid) for eid, entry in embed_map_raw.items()
                          if int(entry.get("doc_id", -1)) in deleted}

        # 1. embeddings β€” drop rows, keep relative order, re-chunk by 500
        embeddings = _drop_rows(_load_visual_embedding_files(index_path), drop_positions)
        emb_dir = index_path / "embeddings"
        for f in emb_dir.glob("embeddings_*.pt"):
            f.unlink(missing_ok=True)
        import torch
        for i in range(0, len(embeddings), 500):
            torch.save(embeddings[i:i + 500], emb_dir / f"embeddings_{i}.pt")

        # 2. embed_id_to_doc_id β€” renumber sequentially
        new_embed_map = {str(i): entry for i, (_, entry) in enumerate(kept)}
        _write_gzip_json(index_path / "embed_id_to_doc_id.json.gz", new_embed_map)

        # 3. doc_ids_to_file_names / metadata β€” drop deleted docs
        new_file_names = {k: v for k, v in file_names_raw.items()
                          if int(k) not in deleted}
        _write_gzip_json(index_path / "doc_ids_to_file_names.json.gz", new_file_names)
        new_metadata = {k: v for k, v in metadata.items() if int(k) not in deleted}
        _write_gzip_json(index_path / "metadata.json.gz", new_metadata)

        # 4. collection chunks (only when full_document_collection) β€” drop +
        #    renumber, re-chunk by 500
        if config.get("full_document_collection"):
            coll_dir = index_path / "collection"
            collection = {}
            for f in sorted(coll_dir.glob("*.json.gz"),
                            key=lambda x: int(x.stem.split(".")[0])):
                collection.update(_read_gzip_json(f))
            collection = {str(i): v for i, (old, v) in enumerate(
                (k, v) for k, v in collection.items() if int(k) not in drop_positions)}
            for f in coll_dir.glob("*.json.gz"):
                f.unlink(missing_ok=True)
            for i in range(0, len(collection), 500):
                chunk = dict(list(collection.items())[i:i + 500])
                _write_gzip_json(coll_dir / f"{i}.json.gz", chunk)

        # 5. index_config β€” keep everything, refresh highest_doc_id
        config["highest_doc_id"] = max(
            (int(e.get("doc_id", -1)) for e in new_embed_map.values()), default=-1)
        _write_gzip_json(index_path / "index_config.json.gz", config)

        # 6. any in-memory retriever is stale now β€” reload from disk next time
        _visual_retriever = None
        _visual_retriever_id = None

        joined = ", ".join(names)
        return get_visual_index_table(), l["kb_visual_deleted"].format(n=len(deleted), names=joined)
    except Exception as e:
        return table, f"❌ {e}"


def clear_visual_index(lang_key: str = "kh") -> tuple:
    """Delete the ENTIRE visual index (all visual docs). Returns the empty

    table and a bilingual message β€” never raises."""
    import shutil
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    global _visual_retriever, _visual_retriever_id
    _visual_retriever = None
    _visual_retriever_id = None
    if Path(mr.VISUAL_INDEX_DIR).exists():
        shutil.rmtree(mr.VISUAL_INDEX_DIR, ignore_errors=True)
    return [], l["kb_visual_cleared"]


def _delete_source_chunks(source: str):
    """Drop every previously-indexed chunk for a source before re-indexing

    it, so re-tagging a file REPLACES its old index instead of stacking new

    tag copies on top of the old ones (the pre-multi-tag behavior)."""
    if not source:
        return
    try:
        col = models.get_chroma_collection()
        col.delete(where={"source": {"$eq": source}})
    except Exception:
        pass


def index_pdf_file(filepath: str, visual_retriever_id: str = mr.DEFAULT_VISUAL_RETRIEVER,

                   theme: str = "", subtheme: str = "", lang_key: str = "kh",

                   source_name: str = "") -> str:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    display = source_name or Path(filepath).name
    msgs = []
    _delete_source_chunks(display)
    try:
        import pdfplumber  # MIT β€” replaced PyMuPDF (AGPL) for Store distribution
        texts = []
        with pdfplumber.open(filepath) as pdf:
            for n, page in enumerate(pdf.pages):
                t = page.extract_text() or ""
                if t.strip():
                    texts.append((t, n + 1))
        total = 0
        for tag_theme, tag_sub in _tag_pairs(theme, subtheme):
            metas = [{"source": display, "page": n, "type": "pdf",
                      "theme": tag_theme, "subtheme": tag_sub}
                     for _, n in texts]
            total += index_texts([t for t, _ in texts], metas)
        msgs.append(l["kb_msg_text_chunks"].format(n=total))
    except Exception as e:
        msgs.append(l["kb_msg_text_failed"].format(err=e))
    msgs.append(f"πŸ–ΌοΈ {index_pdf_visual(filepath, visual_retriever_id, lang_key=lang_key, source_name=display, theme=theme, subtheme=subtheme)}")
    return "\n".join(msgs)


def index_txt_file(filepath: str, theme: str = "", subtheme: str = "", lang_key: str = "kh",

                   source_name: str = "") -> str:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    display = source_name or Path(filepath).name
    _delete_source_chunks(display)
    try:
        text = Path(filepath).read_text(encoding="utf-8", errors="replace")
        k = 0
        for tag_theme, tag_sub in _tag_pairs(theme, subtheme):
            k += index_texts([text], [{"source": display, "type": "txt",
                                       "theme": tag_theme, "subtheme": tag_sub}])
        return l["kb_msg_chunks_from"].format(k=k, name=display)
    except Exception as e:
        return f"❌ {e}"


def index_docx_file(filepath: str, theme: str = "", subtheme: str = "", lang_key: str = "kh",

                    source_name: str = "") -> str:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    display = source_name or Path(filepath).name
    _delete_source_chunks(display)
    try:
        import docx  # python-docx
        document = docx.Document(filepath)

        parts = []
        for para in document.paragraphs:
            if para.text.strip():
                parts.append(para.text)

        for table in document.tables:
            for row in table.rows:
                cells = [c.text.strip() for c in row.cells if c.text.strip()]
                if cells:
                    parts.append(" | ".join(cells))

        text = "\n".join(parts)
        if not text.strip():
            return l["kb_msg_no_text"].format(name=display)

        k = 0
        for tag_theme, tag_sub in _tag_pairs(theme, subtheme):
            k += index_texts([text], [{"source": display, "type": "docx",
                                       "theme": tag_theme, "subtheme": tag_sub}])
        return l["kb_msg_chunks_from"].format(k=k, name=display)
    except ImportError:
        return l["kb_msg_docx_missing"]
    except Exception as e:
        return f"❌ {e}"


def index_image_file(filepath: str, visual_retriever_id: str = mr.DEFAULT_VISUAL_RETRIEVER,

                     theme: str = "", subtheme: str = "", lang_key: str = "kh",

                     source_name: str = "") -> str:
    """Index a STANDALONE image file. Two parts, mirroring how PDFs are

    handled:



    1. A small text chunk ("πŸ–ΌοΈ Image: <name> (WΓ—Hpx)") into ChromaDB so the

       image appears in the Knowledge Base docs table as an ingested file

       (type "image"), carries its theme/subtheme tags (multi-select, one

       copy per tag combination like every other file type), is deletable,

       and is discoverable by filename in RAG.

    2. The image itself into the byaldi VISUAL index (ColPali image chunks)

       when the visual engine is available β€” the content-level retrieval

       path. jpg/jpeg/png/bmp are supported; other image formats degrade to

       the text index only with a clear note."""
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    display = source_name or Path(filepath).name
    _delete_source_chunks(display)
    msgs = []
    # Filename/dimension stub so the image shows in the KB docs table and
    # joins the theme/subtheme filters (no OCR/VLM caption is available).
    dims = ""
    try:
        with Image.open(filepath) as im:
            dims = f" ({im.width}Γ—{im.height}px)"
    except Exception:
        pass
    text = f"πŸ–ΌοΈ Image: {display}{dims}"
    k = 0
    for tag_theme, tag_sub in _tag_pairs(theme, subtheme):
        k += index_texts([text], [{"source": display, "type": "image",
                                   "theme": tag_theme, "subtheme": tag_sub}])
    msgs.append(l["kb_msg_image_chunks"].format(k=k, name=display))
    msgs.append(f"πŸ–ΌοΈ {index_image_visual(filepath, visual_retriever_id, lang_key=lang_key, source_name=display, theme=theme, subtheme=subtheme)}")
    return "\n".join(msgs)


def index_uploaded_files(files, visual_retriever_label: str,

                        theme: str = "", subtheme: str = "", lang_key: str = "kh",

                        source_names: dict = None) -> str:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    if not files:
        return l["err_no_files"]
    retriever_id = mr.VISUAL_RETRIEVER_OPTIONS.get(visual_retriever_label, mr.DEFAULT_VISUAL_RETRIEVER)
    if not isinstance(files, list):
        files = [files]
    flat = []
    for item in files:
        flat.extend(item) if isinstance(item, list) else flat.append(item)
    msgs = []
    for f in flat:
        path = get_file_path(f)
        if not path:
            msgs.append(l["err_upload"] + repr(f))
            continue
        # The uploaded temp file carries a <uuid>-<name> prefix β€” index under
        # the user's ORIGINAL file name (source_names maps path β†’ real name).
        original = (source_names or {}).get(path) or ""
        ext = Path(path).suffix.lower()
        if ext == ".pdf":
            msgs.append(index_pdf_file(path, retriever_id, theme, subtheme, lang_key=lang_key,
                                       source_name=original))
        elif ext in (".txt", ".md"):
            msgs.append(index_txt_file(path, theme, subtheme, lang_key=lang_key, source_name=original))
        elif ext == ".docx":
            msgs.append(index_docx_file(path, theme, subtheme, lang_key=lang_key, source_name=original))
        elif ext in (".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".tiff", ".tif"):
            msgs.append(index_image_file(path, retriever_id, theme, subtheme, lang_key=lang_key,
                                         source_name=original))
        else:
            msgs.append(l["err_unsupported"] + ext)
    return "\n".join(msgs) or l["err_nothing_indexed"]


def index_hf_dataset(dataset_name: str, text_col: str, source_col: str = "",

                     theme: str = "", subtheme: str = ""):
    try:
        import datasets as ds
        dataset = ds.load_dataset(dataset_name, split="train")
        texts, metas = [], []
        for row in dataset:
            t = row.get(text_col, "")
            if not t:
                continue
            src = row.get(source_col, dataset_name) if source_col else dataset_name
            texts.append(str(t))
            metas.append({"source": str(src), "type": "hf_dataset",
                          "theme": theme, "subtheme": subtheme})
        k = index_texts(texts, metas)
        return f"βœ… {k} chunks from '{dataset_name}'", get_doc_table()
    except Exception as e:
        return f"❌ {e}", get_doc_table()


_DOC_TABLE_CACHE = None
_DOC_TABLE_CACHE_COUNT = -1


def invalidate_doc_table_cache():
    global _DOC_TABLE_CACHE, _DOC_TABLE_CACHE_COUNT
    _DOC_TABLE_CACHE = None
    _DOC_TABLE_CACHE_COUNT = -1


def get_doc_table(force_refresh: bool = False) -> list:
    global _DOC_TABLE_CACHE, _DOC_TABLE_CACHE_COUNT
    try:
        col = models.get_chroma_collection()
        count = col.count()
    except Exception:
        return []

    if count == 0:
        _DOC_TABLE_CACHE = []
        _DOC_TABLE_CACHE_COUNT = 0
        return []

    if not force_refresh and _DOC_TABLE_CACHE is not None and _DOC_TABLE_CACHE_COUNT == count:
        return _DOC_TABLE_CACHE

    result = col.get(include=["metadatas"])
    # A multi-tagged file stores one COPY of each chunk per tag combination
    # (scalar metadata is required for Chroma's where-filters), so the
    # per-source aggregation must dedupe those copies: chunks are counted by
    # their (page, chunk_index) position β€” identical across copies β€” and the
    # theme/subtheme columns join the file's unique tag values.
    agg = defaultdict(lambda: {"type": "", "pages": set(), "chunks": set(),
                               "themes": set(), "subthemes": set()})
    for m in result["metadatas"]:
        src = m.get("source", "unknown")
        agg[src]["type"]  = m.get("type", "unknown")
        agg[src]["chunks"].add((m.get("page") or 0, m.get("chunk_index") or 0))
        agg[src]["pages"].add(m.get("page")) if m.get("page") else None
        if m.get("theme"):
            agg[src]["themes"].add(str(m["theme"]).strip())
        if m.get("subtheme"):
            agg[src]["subthemes"].add(str(m["subtheme"]).strip())

    def _join(vals):
        return ", ".join(sorted(v for v in vals if v)) if vals else ""

    table = []
    for src, info in sorted(agg.items()):
        # Image rows can carry a thumbnail from the visual index (byaldi
        # metadata links the original filename to its doc id) β€” the docs
        # table's 7th column; empty for text rows or images without a
        # visual entry (e.g. indexed when byaldi was unavailable).
        thumb = ""
        if info["type"] == "image":
            did = _visual_doc_id_for_source(src)
            if did is not None:
                thumb = did
        table.append([src, info["type"],
                      str(len(info["pages"])) if info["pages"] else "β€”",
                      len(info["chunks"]),
                      _join(info["themes"]),
                      _join(info["subthemes"]),
                      thumb])

    _DOC_TABLE_CACHE = table
    _DOC_TABLE_CACHE_COUNT = count
    return table


def delete_selected_sources(selected_rows: list, doc_table_data: list,

                            lang_key: str = "kh") -> tuple:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    invalidate_doc_table_cache()
    if not selected_rows:
        return get_doc_table(force_refresh=True), l["err_no_rows"]
    
    current_table = get_doc_table(force_refresh=True)
    rows_to_use = doc_table_data if (doc_table_data and len(doc_table_data) > 0) else current_table

    col, deleted = models.get_chroma_collection(), []
    for row_idx in selected_rows:
        if row_idx >= len(rows_to_use):
            continue
        src = rows_to_use[row_idx][0]
        result = col.get(where={"source": src}, include=["metadatas"])
        if result["ids"]:
            col.delete(ids=result["ids"])
            deleted.append(f"'{src}' ({len(result['ids'])} chunks)")

    invalidate_doc_table_cache()
    msg = (l["err_deleted"] + ", ".join(deleted)) if deleted else l["err_nothing_deleted"]
    return get_doc_table(force_refresh=True), msg


def clear_index(lang_key: str = "kh") -> tuple:
    l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
    import shutil
    global _visual_retriever, _visual_retriever_id
    invalidate_doc_table_cache()

    # 1. Close the ChromaDB PersistentClient FIRST so it releases its
    #    SQLite file locks β€” on Windows, shutil.rmtree silently fails to
    #    delete locked files and the old chunks reappear on the next
    #    get_or_create_collection() call.
    models.reset_chroma_collection()

    # 2. Nuke the ENTIRE chroma_db directory β€” this is the only
    #    reliable way to guarantee all chunks are gone.
    chroma_path = Path(mr.CHROMA_PERSIST_DIR)
    if chroma_path.exists():
        try:
            shutil.rmtree(str(chroma_path))
        except Exception:
            pass

    # Recreate a fresh (empty) collection so the app doesn't crash
    # on the next retrieval attempt.
    models.get_chroma_collection()

    # 3. Delete visual index and unload the retriever model
    _visual_retriever = None
    _visual_retriever_id = None
    if Path(mr.VISUAL_INDEX_DIR).exists():
        try:
            shutil.rmtree(mr.VISUAL_INDEX_DIR)
        except Exception:
            pass

    return [], l["err_clear_msg"]


def get_index_stats(lang_key: str = "en") -> tuple[str, str]:
    l = LANGUAGES[lang_key]
    n       = models.get_chroma_collection().count()
    vis_str = l["err_visual_ready"] if (Path(mr.VISUAL_INDEX_DIR) / "main").exists() else l["err_empty_visual"]
    msg = l["err_status_bar"].format(n=n, vis=vis_str, dev=DEVICE.upper())
    return msg, msg


def _as_scope_list(value) -> list[str]:
    """Normalize a metadata scope value into a list of non-empty strings.

    A single string becomes a one-element list; None / "" / [] mean "no

    filter". Lists are kept as-is (stripped, empties dropped) β€” the RAG

    tab's multi-select Theme/Subtheme/File filters send arrays."""
    if value is None:
        return []
    if isinstance(value, str):
        return [value.strip()] if value.strip() else []
    return [str(v).strip() for v in value if v is not None and str(v).strip()]


def retrieve_context(query: str, theme="", subtheme: str = "", sources=None) -> tuple[str, list[str]]:
    """Semantic retrieval over the indexed knowledge base, optionally scoped

    to a set of themes / subthemes / source filenames.



    `theme` / `subtheme` accept EITHER a single value (backward-compatible

    string) OR a list of values β€” the RAG tab's multi-select filters β€” and

    build Chroma `$in` filters so chunks matching ANY selected value are

    returned. `sources` is a list of source filenames (the RAG tab's file

    picker); empty/None means no filter on that dimension."""
    col = models.get_chroma_collection()
    if col.count() == 0:
        return "", []
    clauses = []
    themes = _as_scope_list(theme)
    if themes:
        clauses.append({"theme": {"$in": themes}})
    subthemes = _as_scope_list(subtheme)
    if subthemes:
        clauses.append({"subtheme": {"$in": subthemes}})
    srcs = _as_scope_list(sources)
    if srcs:
        clauses.append({"source": {"$in": srcs}})
    where_filter = {}
    if len(clauses) == 1:
        where_filter = clauses[0]
    elif len(clauses) > 1:
        where_filter = {"$and": clauses}
    try:
        results = col.query(query_embeddings=models.encode_texts([query]),
                            n_results=min(mr.TOP_K, col.count()),
                            where=where_filter or None)
    except Exception as e:
        if "dimension" in str(e).lower():
            raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e
        raise
    docs  = results["documents"][0]
    metas = results["metadatas"][0]
    if not docs:
        return "", []
    # A file indexed under several theme/subtheme tags has one copy of each
    # chunk per tag combination (Chroma's filters only match scalar
    # metadata); dedupe by chunk TEXT so a multi-tag retrieval (e.g. theme
    # $in [A, B]) never shows the same chunk twice.
    seen, uniq_docs, uniq_metas = set(), [], []
    for d, m in zip(docs, metas):
        if d in seen:
            continue
        seen.add(d)
        uniq_docs.append(d)
        uniq_metas.append(m)
    context = "\n\n".join(f"[{m.get('source','?')}]\n{d}"
                          for d, m in zip(uniq_docs, uniq_metas))
    sources = list({m.get("source", "?") for m in uniq_metas})
    return context, sources


_SUMMARY_STOPWORDS = {
    "the", "and", "for", "with", "that", "this", "from", "are", "was", "were",
    "have", "has", "had", "not", "but", "you", "your", "our", "their", "they",
    "them", "his", "her", "its", "can", "may", "will", "shall", "should",
    "would", "could", "about", "into", "over", "under", "than", "then", "when",
    "what", "which", "who", "whom", "why", "how", "all", "any", "each", "more",
    "most", "some", "such", "also", "there", "here", "been", "being", "because",
    "very", "much", "many", "less", "few", "just", "only", "off", "out", "up",
    "down", "in", "on", "at", "by", "to", "of", "as", "is", "it", "a", "an",
}


def _build_scope_filter(theme: str = "", subtheme: str = "", source: str = "") -> dict:
    clauses = []
    if theme:
        clauses.append({"theme": {"$eq": theme}})
    if subtheme:
        clauses.append({"subtheme": {"$eq": subtheme}})
    if source:
        clauses.append({"source": {"$eq": source}})
    if not clauses:
        return {}
    if len(clauses) == 1:
        return clauses[0]
    return {"$and": clauses}


def _safe_int(value, default: int = 0) -> int:
    try:
        return int(value)
    except Exception:
        return default


def _scope_value_key(value) -> str:
    """Normalize a metadata value for case-insensitive comparison."""
    return re.sub(r"\s+", " ", str(value or "")).strip().casefold()


def _best_matching_scope_value(want, candidates) -> Optional[str]:
    """Return the closest STORED metadata value to `want` (the value a small

    agent paraphrased), or None when nothing is close enough.



    Ladder: case-insensitive exact -> containment (either direction) ->

    token overlap / prefix (stem-ish) -> difflib ratio. Only ever returns an

    exact stored value, so a retry with the result stays an exact `$eq`

    filter β€” never a loose scan that could dump unrelated documents."""
    want_text = str(want or "").strip()
    if not want_text:
        return None
    cands = sorted({str(c).strip() for c in candidates if str(c).strip()})
    if not cands:
        return None
    want_norm = _scope_value_key(want_text)

    for c in cands:
        if _scope_value_key(c) == want_norm:
            return c

    for c in cands:
        cn = _scope_value_key(c)
        if cn and len(want_norm) >= 4 and (want_norm in cn or cn in want_norm):
            return c

    want_tokens = set(_tokenize(want_text))
    best, best_score = None, 0.0
    for c in cands:
        cn = _scope_value_key(c)
        c_tokens = set(_tokenize(c)) or {cn}
        score = 0.0
        for wt in want_tokens:
            if wt in c_tokens:
                score += 2.0
            elif len(wt) > 3 and any(ct.startswith(wt) or wt.startswith(ct) for ct in c_tokens):
                score += 1.0
        score = score / max(len(c_tokens), 1)
        if score > best_score:
            best, best_score = c, score
    if best is not None and best_score >= 0.5:
        return best

    best, best_ratio = None, 0.0
    for c in cands:
        ratio = SequenceMatcher(None, want_norm, _scope_value_key(c)).ratio()
        if ratio > best_ratio:
            best, best_ratio = c, ratio
    return best if best_ratio >= 0.6 else None


def _fetch_scope_records(col, theme: str = "", subtheme: str = "", source: str = "") -> list[dict]:
    """Run the exact metadata scope filter against the collection and build

    the record list. May raise the dimension-mismatch RuntimeError."""
    where_filter = _build_scope_filter(theme, subtheme, source)
    try:
        result = col.get(where=where_filter or None, include=["documents", "metadatas"])
    except Exception as e:
        if "dimension" in str(e).lower():
            raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e
        raise

    records = []
    docs = result.get("documents", []) or []
    metas = result.get("metadatas", []) or []
    seen = set()
    for doc, meta in zip(docs, metas):
        if not doc:
            continue
        # Dedupe multi-tag copies (same chunk stored once per tag pair):
        # identical (source, page, chunk_index) position = the same chunk.
        key = (meta.get("source", "unknown"),
               _safe_int(meta.get("page", 0)),
               _safe_int(meta.get("chunk_index", 0)))
        if key in seen:
            continue
        seen.add(key)
        records.append({
            "source": meta.get("source", "unknown"),
            "theme": meta.get("theme", ""),
            "subtheme": meta.get("subtheme", ""),
            "type": meta.get("type", ""),
            "page": _safe_int(meta.get("page", 0)),
            "chunk_index": _safe_int(meta.get("chunk_index", 0)),
            "text": str(doc).strip(),
        })

    records.sort(key=lambda r: (r["source"], r["page"], r["chunk_index"]))
    return records


def _collect_scope_records(theme: str = "", subtheme: str = "", source: str = "",

                           sources_scope: Optional[list] = None) -> list[dict]:
    col = models.get_chroma_collection()
    if col.count() == 0:
        return []

    records = _fetch_scope_records(col, theme, subtheme, source)
    if not records:
        # Exact scope matched nothing. The requesting agent (often a small GGUF
        # model) frequently paraphrases a stored theme/subtheme name, and the
        # metadata filter is an exact `$eq` β€” so nudge the requested values
        # toward the canonical stored values and retry. Each retry is STILL an
        # exact filter against a resolved stored value; if nothing resolves,
        # return the honest empty list rather than dumping the whole knowledge
        # base.
        metas = (col.get(include=["metadatas"]).get("metadatas", []) or []) if col.count() else []
        themes    = {str(m.get("theme", "")).strip() for m in metas if m.get("theme")}
        subthemes = {str(m.get("subtheme", "")).strip() for m in metas if m.get("subtheme")}
        sources   = {str(m.get("source", "")).strip() for m in metas if m.get("source")}
        r_theme = (_best_matching_scope_value(theme, themes) or "") if theme else ""
        r_sub   = (_best_matching_scope_value(subtheme, subthemes) or "") if subtheme else ""
        r_src   = (_best_matching_scope_value(source, sources) or "") if source else ""

        for t, s, src in (
            (r_theme, r_sub, r_src),
            (r_theme, "", r_src),
            ("", r_sub, r_src),
            (r_theme, "", ""),
            ("", r_sub, ""),
            ("", "", r_src),
        ):
            if not (t or s or src):
                continue
            recs = _fetch_scope_records(col, t, s, src)
            if recs:
                records = recs
                break

    # The RAG tab's multi-select FILE filter (`sources_scope`): an extra hard
    # restriction on top of whatever the model asked for β€” a summary must
    # never cover documents outside the user's selected files. Applied as a
    # post-filter so it holds for both the exact match and the fuzzy fallback
    # paths (and returns the honest empty list when the model's requested
    # scope lies entirely outside the selected files).
    allowed = {str(s).strip().casefold() for s in (sources_scope or []) if str(s).strip()}
    if allowed:
        records = [r for r in records
                   if str(r.get("source", "")).strip().casefold() in allowed]
    return records


def _tokenize(text: str) -> list[str]:
    return [t.lower() for t in re.findall(r"[A-Za-z0-9']+", text or "") if len(t) > 2 and t.lower() not in _SUMMARY_STOPWORDS]


def _extract_key_terms(texts: list[str], top_n: int = 8) -> list[str]:
    counter = Counter()
    for text in texts:
        counter.update(_tokenize(text))
    return [term for term, _ in counter.most_common(top_n)]


def _split_sentences(text: str) -> list[str]:
    parts = re.split(r"(?<=[.!?])\s+", re.sub(r"\s+", " ", text or "").strip())
    return [p.strip() for p in parts if p.strip()]


def _score_sentence(sentence: str, frequency: Counter, focus_terms: list[str] | None = None) -> float:
    tokens = _tokenize(sentence)
    if not tokens:
        return 0.0
    score = sum(frequency.get(tok, 0) for tok in tokens)
    if focus_terms:
        focus_set = {t.lower() for t in focus_terms if t}
        score += sum(4 for tok in tokens if tok in focus_set)
    length = len(tokens)
    quality = 1.0
    if length < 5:
        quality *= 0.35
    elif length < 9:
        quality *= 0.65
    if len(sentence) < 40:
        quality *= 0.85
    if not re.search(r"[.!?]['\")\]]?$", sentence.strip()):
        quality *= 0.9
    if sentence[:1].islower():
        quality *= 0.92
    if "  " in sentence or "..." in sentence:
        quality *= 0.9
    return (score / max(length, 1)) * quality


def _pick_top_sentences(sentences: list[str], freq: Counter, focus_terms: list[str] | None = None,

                        limit: int = 5, seen_keys: set | None = None) -> list[str]:
    """Pick top-scoring diverse sentences from a candidate list."""
    if seen_keys is None:
        seen_keys = set()
    scored = []
    for sentence in sentences:
        key = sentence.lower().strip()
        if key in seen_keys:
            continue
        score = _score_sentence(sentence, freq, focus_terms)
        if score > 0:
            scored.append((score, sentence, key))
    scored.sort(key=lambda item: item[0], reverse=True)
    picked = []
    for _, sentence, key in scored:
        if len(_tokenize(sentence)) < 4:
            continue
        seen_keys.add(key)
        picked.append(sentence)
        if len(picked) >= limit:
            break
    if not picked and sentences:
        for sentence in sentences:
            key = sentence.lower().strip()
            if key not in seen_keys and len(_tokenize(sentence)) >= 4:
                seen_keys.add(key)
                picked.append(sentence)
                if len(picked) >= limit:
                    break
    if not picked and sentences:
        for sentence in sentences[:limit]:
            key = sentence.lower().strip()
            seen_keys.add(key)
            picked.append(sentence)
    return picked


def _extract_stratified_points(source_records: list[dict], global_freq: Counter,

                               focus_terms: list[str] | None = None,

                               base_points: int = 4) -> list[tuple[str, list[str]]]:
    """Extract representative sentences across chronological strata of a document.

    Ensures broad, beginning-to-end coverage for research papers, manuals, reports, and contracts.

    """
    n_chunks = len(source_records)
    if not source_records:
        return []

    # Small document (< 5 chunks): single flat section with up to max(base_points, 4) points
    if n_chunks < 5:
        text = " ".join(r["text"] for r in source_records)
        sentences = _split_sentences(text)
        picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=max(base_points, 4))
        return [("", picked)] if picked else []

    # Dynamic target point calculation:
    # 5-12 chunks  -> max(base_points, 6)
    # 13-30 chunks -> max(base_points, 10)
    # 31+ chunks   -> max(base_points, 15)
    if n_chunks <= 12:
        total_target = max(base_points, 6)
    elif n_chunks <= 30:
        total_target = max(base_points, 10)
    else:
        total_target = max(base_points, 15)

    split1 = max(1, int(n_chunks * 0.28))
    split2 = max(split1 + 1, int(n_chunks * 0.72))

    zone1_recs = source_records[:split1]
    zone2_recs = source_records[split1:split2]
    zone3_recs = source_records[split2:]

    budget1 = max(2, int(total_target * 0.30))
    budget2 = max(3, int(total_target * 0.45))
    budget3 = max(2, total_target - budget1 - budget2)

    strata = [
        ("Overview & Objectives", zone1_recs, budget1),
        ("Core Substance & Details", zone2_recs, budget2),
        ("Conclusions, Terms & Outcomes", zone3_recs, budget3),
    ]

    results = []
    seen_keys = set()

    for label, recs, budget in strata:
        if not recs:
            continue
        text = " ".join(r["text"] for r in recs)
        sentences = _split_sentences(text)
        picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=budget, seen_keys=seen_keys)
        if picked:
            results.append((label, picked))

    if not results:
        all_text = " ".join(r["text"] for r in source_records)
        sentences = _split_sentences(all_text)
        picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=total_target)
        if picked:
            results.append(("", picked))

    return results


def _summarize_records(records: list[dict], *, title: str, focus: str = "", max_sources: int = 5,

                       max_points_per_source: int = 4,

                       visual_sources: Optional[set] = None) -> str:
    if not records:
        return f"{title}\n\nNo matching documents were found."

    grouped = defaultdict(list)
    for record in records:
        grouped[record["source"]].append(record)
    # Source filenames that ALSO have page images in the visual index β€”
    # the scanned / image-heavy docs whose text chunks may be OCR garbage
    # but whose PAGE IMAGES carry the real content. The manager routes
    # these to `knowledge_searcher` for a `visual_retriever` pass. Defaults
    # to the live visual-index lookup so EVERY caller (tool or direct)
    # gets the signal; an absent index yields the empty set (no signal).
    visual_sources = set(_visual_sources_set() if visual_sources is None else visual_sources)

    all_texts = [r["text"] for r in records]
    key_terms = _extract_key_terms(all_texts, top_n=8)
    focus_terms = _tokenize(focus) if focus else []
    global_freq = Counter()
    for t in all_texts:
        global_freq.update(_tokenize(t))

    lines = [title, ""]
    scope_bits = []
    first = records[0]
    if first.get("theme"):
        scope_bits.append(f"Theme: {first['theme']}")
    if first.get("subtheme"):
        scope_bits.append(f"Subtheme: {first['subtheme']}")
    if focus:
        scope_bits.append(f"Focus: {focus}")
    lines.append("Scope: " + " | ".join(scope_bits) if scope_bits else "Scope: all matching documents")
    lines.append(f"Documents matched: {len(grouped)}")
    lines.append(f"Chunks matched: {len(records)}")
    if key_terms:
        lines.append("Key terms: " + ", ".join(key_terms))
    lines.append("")

    source_items = sorted(grouped.items(), key=lambda item: (-len(item[1]), item[0]))[:max_sources]
    for source, source_records in source_items:
        lines.append(f"### {source}")
        lines.append(
            f"- Theme: {source_records[0].get('theme', '') or 'β€”'}"
            f" | Subtheme: {source_records[0].get('subtheme', '') or 'β€”'}"
            f" | Chunks: {len(source_records)}"
        )
        # Visual-index signal: this source ALSO has page images (charts /
        # scans / image-heavy PDFs). The text chunks may be unreadable OCR
        # β€” the manager must delegate to `knowledge_searcher` with an
        # explicit `visual_retriever` task so the actual pages are pulled.
        if source in visual_sources:
            lines.append("- πŸ–ΌοΈ Page images available in the visual index β€” delegate to "
                         "`knowledge_searcher` with a `visual_retriever` task to "
                         "read the ACTUAL page images.")

        stratified = _extract_stratified_points(
            source_records, global_freq, focus_terms=focus_terms,
            base_points=max_points_per_source
        )
        for label, points in stratified:
            if label:
                lines.append(f"- **{label}**:")
                for p in points:
                    lines.append(f"  - {p}")
            else:
                for p in points:
                    lines.append(f"- {p}")
        lines.append("")

    return "\n".join(lines).strip()


def _extract_key_points(records: list[dict], *, focus: str = "", max_points: int = 10,

                        visual_sources: Optional[set] = None) -> str:
    if not records:
        return "No matching documents were found."
    all_texts = [r["text"] for r in records]
    freq = Counter()
    for t in all_texts:
        freq.update(_tokenize(t))
    focus_terms = _tokenize(focus) if focus else []
    visual_sources = set(_visual_sources_set() if visual_sources is None else visual_sources)

    # If records span multiple chunks, sample across them chronologically
    grouped = defaultdict(list)
    for r in records:
        grouped[r.get("source", "doc")].append(r)

    all_stratified = []
    points_per_doc = max(2, max_points // max(1, len(grouped)))
    for src, src_records in grouped.items():
        strat = _extract_stratified_points(src_records, freq, focus_terms=focus_terms, base_points=points_per_doc)
        for _, pts in strat:
            all_stratified.extend(pts)

    if len(all_stratified) > max_points:
        all_stratified = all_stratified[:max_points]

    if not all_stratified:
        all_text = " ".join(all_texts)
        sentences = _split_sentences(all_text)
        all_stratified = _pick_top_sentences(sentences, freq, focus_terms=focus_terms, limit=max_points)

    lines = []
    if focus:
        lines.append(f"Key points for focus: {focus}")
    else:
        lines.append("Key points")
    lines.append("")
    for idx, sentence in enumerate(all_stratified, start=1):
        lines.append(f"{idx}. {sentence}")
    # Visual-index signal for the manager (scanned / image-heavy sources).
    visual_hits = sorted(src for src in grouped if src in visual_sources)
    if visual_hits:
        lines.append("")
        lines.append("πŸ–ΌοΈ Page images available in the visual index for: "
                     + ", ".join(visual_hits)
                     + " β€” delegate to `knowledge_searcher` with a "
                     "`visual_retriever` task to read the ACTUAL page images.")
    return "\n".join(lines).strip()


def _clean_mind_map_label(text: str, max_chars: int = 72) -> str:
    label = re.sub(r"\s+", " ", str(text or "")).strip()
    label = re.sub(r"^[\-*#\d.:\)\s]+", "", label).strip()
    if not label:
        return "Untitled"
    if len(label) <= max_chars:
        return label
    cut = label[:max_chars].rsplit(" ", 1)[0].strip()
    return (cut or label[:max_chars]).rstrip(".,;:") + "..."


def _mind_map_points_for_records(records: list[dict], max_points: int = 4) -> list[str]:
    if not records:
        return []
    text = " ".join(record["text"] for record in records)
    sentences = _split_sentences(text)
    freq = Counter(_tokenize(text))
    scored = []
    seen = set()
    for sentence in sentences:
        key = sentence.lower()
        if key in seen:
            continue
        seen.add(key)
        score = _score_sentence(sentence, freq)
        if score > 0:
            scored.append((score, sentence))
    scored.sort(key=lambda item: item[0], reverse=True)
    picked = []
    for _, sentence in scored:
        if len(_tokenize(sentence)) < 4:
            continue
        picked.append(_clean_mind_map_label(sentence))
        if len(picked) >= max_points:
            break
    if not picked:
        picked = [_clean_mind_map_label(s) for s in sentences[:max_points]]
    return picked


def _build_mind_map(records: list[dict], *, theme: str = "", subtheme: str = "",

                    source: str = "", output_format: str = "tree",

                    max_documents: int = 8,

                    max_points_per_document: int = 4) -> str:
    if not records:
        return "No matching documents were found."

    fmt = (output_format or "tree").strip().lower()
    max_documents = max(1, int(max_documents or 8))
    max_points_per_document = max(1, int(max_points_per_document or 4))
    root = source or subtheme or theme or "Knowledge Base"
    grouped = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
    for record in records:
        theme_name = record.get("theme") or "Unthemed"
        subtheme_name = record.get("subtheme") or "General"
        source_name = record.get("source") or "unknown"
        grouped[theme_name][subtheme_name][source_name].append(record)

    docs_added = 0
    if fmt == "mermaid":
        lines = ["mindmap", f"  root(({_clean_mind_map_label(root)}))"]
        for theme_name, subthemes in sorted(grouped.items()):
            lines.append(f"    {_clean_mind_map_label(theme_name)}")
            for subtheme_name, sources in sorted(subthemes.items()):
                lines.append(f"      {_clean_mind_map_label(subtheme_name)}")
                for source_name, source_records in sorted(sources.items()):
                    if docs_added >= max_documents:
                        break
                    docs_added += 1
                    lines.append(f"        {_clean_mind_map_label(source_name)}")
                    for point in _mind_map_points_for_records(source_records, max_points_per_document):
                        lines.append(f"          {_clean_mind_map_label(point)}")
                if docs_added >= max_documents:
                    break
            if docs_added >= max_documents:
                break
        return "\n".join(lines)

    lines = [_clean_mind_map_label(root)]
    for theme_name, subthemes in sorted(grouped.items()):
        lines.append(f"- {_clean_mind_map_label(theme_name)}")
        for subtheme_name, sources in sorted(subthemes.items()):
            lines.append(f"  - {_clean_mind_map_label(subtheme_name)}")
            for source_name, source_records in sorted(sources.items()):
                if docs_added >= max_documents:
                    break
                docs_added += 1
                lines.append(f"    - {_clean_mind_map_label(source_name)}")
                for point in _mind_map_points_for_records(source_records, max_points_per_document):
                    lines.append(f"      - {_clean_mind_map_label(point)}")
            if docs_added >= max_documents:
                break
        if docs_added >= max_documents:
            break
    return "\n".join(lines)


class RetrieverTool(Tool):
    """smolagents Tool wrapper around retrieve_context(), for agentic RAG

    (see rag_agent.py). Unlike the plain RAG Chat path, which always

    retrieves context before calling the LLM, this lets a CodeAgent decide

    for itself whether/when to search the knowledge base, and call it more

    than once (e.g. to refine a search) before giving a final answer.

    """
    name = "retriever"
    description = (
        "Uses semantic search over the indexed knowledge base (ChromaDB) to "
        "retrieve the document chunks most relevant to a query. This is the "
        "ONLY source of information you are permitted to use to answer the "
        "user β€” never supplement it with your own general knowledge. Call "
        "this before answering any question. It returns a clear 'no relevant "
        "documents found' message if the knowledge base is empty or has "
        "nothing relevant β€” treat that as a real answer (there is nothing to "
        "report), not as a reason to fall back on what you already know. "
        "Every returned chunk is tagged with its source filename in "
        "brackets, e.g. '[report.pdf]' β€” cite that exact tag in-text "
        "immediately after any claim you draw from it."
    )
    inputs = {
        "query": {
            "type": "string",
            "description": (
                "The search query. Prefer an affirmative statement close to "
                "the target content (e.g. 'steps to push a model to the "
                "Hub') rather than a literal question."
            ),
        }
    }
    output_type = "string"

    def __init__(self, theme: str = "", subtheme: str = "", sources=None, **kwargs):
        super().__init__(**kwargs)
        self._theme = theme
        self._subtheme = subtheme
        self._sources = sources or []
        # Self-tracked usage stats β€” used by rag_agent.py to verify (after
        # agent.run() returns) that the model actually searched the
        # knowledge base and actually found something, rather than trying
        # to introspect smolagents' internal step/memory structure, which
        # varies across versions and previously caused false negatives
        # (blocking correctly-grounded answers because the introspection
        # didn't match this installed version's real internals).
        self.call_count  = 0
        self.found_count = 0
        # Every unique source name actually returned by a successful
        # retrieval this run β€” lets chat.py print a guaranteed-accurate
        # References list after the agent answers, independent of whether
        # the model remembered to write its own in-text citations (same
        # "track it ourselves, don't just trust the model" reasoning as
        # call_count/found_count above).
        self.sources_used = set()

    def reset_stats(self):
        self.call_count  = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, query: str) -> str:
        assert isinstance(query, str), "Your search query must be a string"
        self.call_count += 1
        context, sources = retrieve_context(query, self._theme, self._subtheme, sources=self._sources)
        if not context:
            return "No relevant documents found β€” the knowledge base may be empty."
        self.found_count += 1
        self.sources_used.update(sources)
        return f"Retrieved documents (sources: {', '.join(sources)}):\n\n{context}"


class VisualRetrieverTool(Tool):
    """smolagents Tool wrapper around the VISUAL (image-based) index β€” the

    `knowledge_searcher` sub-agent's second retrieval tool, alongside the

    text `retriever`. ColPali page images cover what text extraction

    misses: charts, tables, scans and image-heavy PDFs whose page renders

    carry the information even when their extracted text doesn't.



    A text-only model can't see the images itself, so the tool returns a

    TEXT report of the retrieved pages (count + source filenames) and

    stashes the ACTUAL page images in the module-level visual-tool hits

    cache β€” chat.py's multimodal grounding pass (same-model VLM) then

    verifies/refines the agent's draft against those exact pages, so the

    "multimodal" half of agentic RAG is realized without the agent needing

    an image-capable model. Like RetrieverTool it self-tracks

    call_count / found_count / sources_used for the post-run grounding

    verification. Never raises."""
    name = "visual_retriever"
    description = (
        "Searches the visual (image-based) index of the knowledge base and "
        "returns the page images most relevant to a query β€” page renders of "
        "PDFs / images indexed for their VISUAL content (charts, tables, "
        "scans, image-heavy documents) that plain text search can miss. "
        "Use this IN ADDITION to `retriever` when the question is about "
        "numbers, figures, charts, screenshots, or anything that would live "
        "in a page's image rather than its extracted text, or when the text "
        "search came back thin. It returns the number of matching page "
        "images and their source filenames; the page images themselves are "
        "passed to the multimodal grounding pass so the final answer is "
        "verified against the actual pages. Cite the returned source "
        "filenames in your references exactly like text sources."
    )
    inputs = {
        "query": {
            "type": "string",
            "description": (
                "What to look for in the page images, e.g. 'quarterly revenue "
                "chart' or 'the table of tax rates'. Prefer a concrete "
                "description of the visual content over a literal question."
            ),
        },
        "top_k": {
            "type": "integer",
            "description": "Maximum number of page images to retrieve (default 3).",
            "default": 3,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.call_count = 0
        self.found_count = 0
        # Total page images actually decoded and stashed across this run's
        # successful calls β€” the REAL image count for the footer note (a
        # call that found 3 pages is one found_count, but 3 pages).
        self.pages_found = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.pages_found = 0
        self.sources_used = set()

    def forward(self, query: str, top_k: int = 3) -> str:
        assert isinstance(query, str), "Your search query must be a string"
        self.call_count += 1
        try:
            results = _visual_search_results(query, max(1, int(top_k or 3)))
        except Exception as e:
            print(f"[VIS] visual_retriever tool failed: {e}")
            return "The visual index search failed β€” rely on the text `retriever` results only."
        if not results:
            return (
                "No matching page images found in the visual index β€” either the "
                "visual index is empty or nothing visually relevant matched. "
                "Rely on the text `retriever` results for this question."
            )

        global _visual_tool_hits
        images, sources = [], set()
        for r in results:
            if not (hasattr(r, "base64") and r.base64):
                continue
            images.append(Image.open(BytesIO(base64.b64decode(r.base64))).convert("RGB"))
            meta = getattr(r, "metadata", None) or {}
            src = str(meta.get("source") or "")
            if src and src != "In-memory Image":
                sources.add(src)
        if not images:
            return (
                "The visual index matched pages but their images could not be "
                "decoded β€” rely on the text `retriever` results for this question."
            )
        # Stash the ACTUAL page images for chat.py's multimodal grounding
        # pass (the same-model VLM), which runs AFTER the agent's draft is
        # done β€” reusing these avoids a second 2-8 GB retriever-model load.
        _visual_tool_hits = images
        self.found_count += 1
        self.pages_found += len(images)
        self.sources_used.update(sources)
        src_line = (", ".join(sorted(sources)) if sources else "unknown source")
        plural = "image" if len(images) == 1 else "images"
        return (
            f"Retrieved {len(images)} page {plural} from the visual index "
            f"(sources: {src_line}). These page images will be visually "
            "verified against the final answer by the multimodal grounding "
            f"pass β€” cite their source filenames ({src_line}) in your "
            "references section as [N] entries."
        )


class ThemeSummaryTool(Tool):
    name = "summarize_theme"
    description = (
        "Summarize the indexed knowledge base for one theme, grouping the "
        "most relevant document chunks by source and extracting key points. "
        "Use this when the user asks for a summary, overview, or main themes "
        "within a theme."
    )
    inputs = {
        "theme": {
            "type": "string",
            "description": "Theme metadata value to summarize.",
        },
        "max_sources": {
            "type": "integer",
            "description": "Maximum number of source documents to include.",
            "default": 5,
            "nullable": True,
        },
        "max_points_per_source": {
            "type": "integer",
            "description": "Maximum summary bullets to extract per source.",
            "default": 3,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, theme: str, max_sources: int = 5, max_points_per_source: int = 3) -> str:
        self.call_count += 1
        records = _collect_scope_records(theme=theme, sources_scope=self._scope_sources)
        if records:
            self.found_count += 1
        self.sources_used.update({r["source"] for r in records})
        return _summarize_records(
            records,
            title=f"Theme summary: {theme}",
            max_sources=max_sources,
            max_points_per_source=max_points_per_source,
            visual_sources=_visual_sources_set(),
        )


class SubthemeSummaryTool(Tool):
    name = "summarize_subtheme"
    description = (
        "Summarize the indexed knowledge base for a specific theme and "
        "subtheme. Use this when the user wants a narrower summary of a "
        "particular subtopic."
    )
    inputs = {
        "theme": {
            "type": "string",
            "description": "Theme metadata value to summarize.",
        },
        "subtheme": {
            "type": "string",
            "description": "Subtheme metadata value to summarize.",
        },
        "max_sources": {
            "type": "integer",
            "description": "Maximum number of source documents to include.",
            "default": 5,
            "nullable": True,
        },
        "max_points_per_source": {
            "type": "integer",
            "description": "Maximum summary bullets to extract per source.",
            "default": 3,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, theme: str, subtheme: str, max_sources: int = 5, max_points_per_source: int = 3) -> str:
        self.call_count += 1
        records = _collect_scope_records(theme=theme, subtheme=subtheme, sources_scope=self._scope_sources)
        if records:
            self.found_count += 1
        self.sources_used.update({r["source"] for r in records})
        return _summarize_records(
            records,
            title=f"Subtheme summary: {theme} / {subtheme}",
            max_sources=max_sources,
            max_points_per_source=max_points_per_source,
            visual_sources=_visual_sources_set(),
        )


class DocumentSummaryTool(Tool):
    name = "summarize_document"
    description = (
        "Summarize one document identified by its source filename. Optionally "
        "scope it further by theme or subtheme metadata."
    )
    inputs = {
        "source": {
            "type": "string",
            "description": "Source filename to summarize.",
        },
        "theme": {
            "type": "string",
            "description": "Optional theme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "subtheme": {
            "type": "string",
            "description": "Optional subtheme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "max_points": {
            "type": "integer",
            "description": "Maximum key points to return.",
            "default": 6,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, source: str, theme: str = "", subtheme: str = "", max_points: int = 6) -> str:
        self.call_count += 1
        records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources)
        if records:
            self.found_count += 1
        self.sources_used.update({r["source"] for r in records})
        return _summarize_records(
            records,
            title=f"Document summary: {source}",
            max_sources=1,
            max_points_per_source=max_points,
            visual_sources=_visual_sources_set(),
        )


class KeyPointsTool(Tool):
    name = "find_key_points"
    description = (
        "Extract the most important points from documents within a theme, "
        "subtheme, or source scope. Use this when the user asks for key "
        "points, highlights, or takeaways."
    )
    inputs = {
        "focus": {
            "type": "string",
            "description": "Optional focus phrase to bias the ranking of key points.",
            "default": "",
            "nullable": True,
        },
        "theme": {
            "type": "string",
            "description": "Optional theme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "subtheme": {
            "type": "string",
            "description": "Optional subtheme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "source": {
            "type": "string",
            "description": "Optional source filename filter.",
            "default": "",
            "nullable": True,
        },
        "max_points": {
            "type": "integer",
            "description": "Maximum key points to return.",
            "default": 8,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, focus: str = "", theme: str = "", subtheme: str = "", source: str = "", max_points: int = 8) -> str:
        self.call_count += 1
        records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources)
        if records:
            self.found_count += 1
        self.sources_used.update({r["source"] for r in records})
        header_bits = []
        if theme:
            header_bits.append(f"theme={theme}")
        if subtheme:
            header_bits.append(f"subtheme={subtheme}")
        if source:
            header_bits.append(f"source={source}")
        title = "Key points"
        if header_bits:
            title += " (" + ", ".join(header_bits) + ")"
        points = _extract_key_points(records, focus=focus, max_points=max_points,
                                     visual_sources=_visual_sources_set())
        return f"{title}\n\n{points}"


class MindMapTool(Tool):
    name = "create_mind_map"
    description = (
        "Create a compact mind map or topic tree from indexed knowledge-base "
        "content using theme, subtheme, and source metadata. Use this when "
        "the user asks for a mind map, concept map, topic tree, branch "
        "structure, or visual outline of indexed documents."
    )
    inputs = {
        "theme": {
            "type": "string",
            "description": "Optional theme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "subtheme": {
            "type": "string",
            "description": "Optional subtheme metadata filter.",
            "default": "",
            "nullable": True,
        },
        "source": {
            "type": "string",
            "description": "Optional source filename filter.",
            "default": "",
            "nullable": True,
        },
        "output_format": {
            "type": "string",
            "description": "Use 'tree' for Markdown outline or 'mermaid' for Mermaid mindmap.",
            "default": "tree",
            "nullable": True,
        },
        "max_documents": {
            "type": "integer",
            "description": "Maximum source documents to include.",
            "default": 8,
            "nullable": True,
        },
        "max_points_per_document": {
            "type": "integer",
            "description": "Maximum key-point nodes under each document.",
            "default": 4,
            "nullable": True,
        },
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, theme: str = "", subtheme: str = "", source: str = "",

                output_format: str = "tree", max_documents: int = 8,

                max_points_per_document: int = 4) -> str:
        self.call_count += 1
        records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources)
        if records:
            self.found_count += 1
        self.sources_used.update({r["source"] for r in records})
        return _build_mind_map(
            records,
            theme=theme,
            subtheme=subtheme,
            source=source,
            output_format=output_format,
            max_documents=max_documents,
            max_points_per_document=max_points_per_document,
        )


class ListTopicsTool(Tool):
    name = "list_knowledge_base_topics"
    description = (
        "List all available themes, subthemes, and document source filenames "
        "indexed in the knowledge base. Use this when the user asks what topics, "
        "themes, subthemes, or files are available, or before summarizing when "
        "you need to identify valid theme/subtheme/source names from metadata."
    )
    inputs = {
        "theme": {
            "type": "string",
            "description": "Optional theme filter to list only subthemes and sources under this theme.",
            "default": "",
            "nullable": True,
        }
    }
    output_type = "string"

    def __init__(self, sources=None, **kwargs):
        super().__init__(**kwargs)
        # The RAG tab's multi-select FILE filter β€” the UI's selected source
        # filenames. Applied on top of whatever scope the model passes, so a
        # summary/topic listing never covers documents outside the user's
        # selected files (mirrors how RetrieverTool threads the selection).
        self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()]
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def reset_stats(self):
        self.call_count = 0
        self.found_count = 0
        self.sources_used = set()

    def forward(self, theme: str = "") -> str:
        self.call_count += 1
        themes, subthemes = get_existing_themes_and_subthemes(theme=theme)
        table = get_doc_table()
        # Scope the file listing to the requested theme β€” a doc-table row is
        # [source, type, pages, chunks, themes, subthemes] with the theme
        # column comma-joined for multi-tagged files (the same matching rule
        # the RAG tab's own rowMatchesFilters uses). Without this the tool
        # dumped EVERY indexed file regardless of the theme filter, so an
        # agent scoped to one theme saw unrelated documents (CVs, other
        # contracts) listed as if they were in scope.
        want = str(theme or "").strip().casefold()
        allowed = ({str(s).strip().casefold() for s in self._scope_sources}
                   if self._scope_sources else None)
        sources = []
        for row in table:
            if not row or not row[0]:
                continue
            if want:
                row_themes = {t.strip().casefold()
                              for t in str(row[4] or "").split(",") if t.strip()}
                if want not in row_themes:
                    continue
            # The RAG tab's selected files are a hard restriction on the
            # listing too β€” a file outside the selection is never advertised.
            if allowed is not None and str(row[0]).strip().casefold() not in allowed:
                continue
            sources.append(row[0])
        if themes or subthemes or sources:
            self.found_count += 1
        self.sources_used.update(sources)
        lines = []
        if theme:
            lines.append(f"Knowledge Base Topics (Theme: '{theme}'):")
        else:
            lines.append("Knowledge Base Topics:")
            if themes:
                lines.append(f"- Available Themes: {', '.join(themes)}")
            else:
                lines.append("- Available Themes: (None)")
        if subthemes:
            lines.append(f"- Available Subthemes: {', '.join(subthemes)}")
        if sources:
            lines.append(f"- Available Document Files: {', '.join(sources)}")
        if not themes and not subthemes and not sources:
            lines.append("- (Knowledge base is currently empty)")
        return "\n".join(lines)


def get_existing_themes_and_subthemes(theme: str = "") -> tuple[list[str], list[str]]:
    """Query ChromaDB for all unique non-empty theme and subtheme values in stored metadatas.

    If theme is specified and non-empty, subthemes will be filtered to those under that theme.

    """
    try:
        col = models.get_chroma_collection()
        if col.count() == 0:
            return [], []
        result = col.get(include=["metadatas"])
        themes = set()
        subthemes = set()
        theme_stripped = str(theme or "").strip()
        for m in result.get("metadatas", []):
            t = str(m.get("theme", "")).strip()
            st = str(m.get("subtheme", "")).strip()
            if t:
                themes.add(t)
            if st:
                if not theme_stripped or t == theme_stripped:
                    subthemes.add(st)
        return sorted(list(themes)), sorted(list(subthemes))
    except Exception:
        return [], []