File size: 109,417 Bytes
29b445b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26d8df8
 
29b445b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26d8df8
 
 
 
29b445b
 
 
 
 
 
 
 
 
26d8df8
29b445b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26d8df8
 
29b445b
 
 
26d8df8
 
 
 
29b445b
 
26d8df8
29b445b
 
26d8df8
29b445b
 
 
 
 
26d8df8
 
 
 
 
 
29b445b
 
26d8df8
 
29b445b
26d8df8
29b445b
 
 
 
 
 
 
 
 
 
 
 
 
26d8df8
 
 
 
 
 
 
 
 
 
29b445b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Image Tagger Application
A Streamlit web app for tagging images using an AI model.
"""

import streamlit as st
import os
import sys
import traceback
import tempfile
import time
import platform
import subprocess
import webbrowser
import glob
import numpy as np
import matplotlib.pyplot as plt
import io
import base64
from matplotlib.colors import LinearSegmentedColormap
from PIL import Image
from pathlib import Path

# Add parent directory to path to allow importing from utils
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Import utilities
from utils.model_loader import load_exported_model, is_windows, check_flash_attention
from utils.image_processing import process_image, batch_process_images
from utils.file_utils import save_tags_to_file, get_default_save_locations
from utils.ui_components import display_progress_bar, show_example_images, display_batch_results
from utils.onnx_processing import batch_process_images_onnx

# Define the model directory
MODEL_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "model")
print(f"Using model directory: {MODEL_DIR}")

# Define threshold profile descriptions and explanations
threshold_profile_descriptions = {
    "Micro Optimized": "Maximizes micro-averaged F1 score (best for dominant classes). Optimal for overall prediction quality.",
    "Macro Optimized": "Maximizes macro-averaged F1 score (equal weight to all classes). Better for balanced performance across all tags.",
    "Balanced": "Provides a trade-off between precision and recall with moderate thresholds. Good general-purpose setting.",
    "High Precision": "Uses higher thresholds to prioritize accuracy over recall. Fewer but more confident predictions.",
    "High Recall": "Uses lower thresholds to capture more potential tags at the expense of accuracy. More comprehensive tagging.",
    "Overall": "Uses a single threshold value across all categories. Simplest approach for consistent behavior.",
    "Weighted": "Uses thresholds weighted by category importance. Better balance for tags that matter most.",
    "Category-specific": "Uses different optimal thresholds for each category. Best for fine-tuning results."
}

threshold_profile_explanations = {
    "Micro Optimized": """
    ### Micro Optimized Profile
    
    **Technical definition**: Maximizes micro-averaged F1 score, which calculates metrics globally across all predictions.
    
    **When to use**: When you want the best overall accuracy, especially for common tags and dominant categories.
    
    **Effects**:
    - Optimizes performance for the most frequent tags
    - Gives more weight to categories with many examples (like 'character' and 'general')
    - Provides higher precision in most common use cases
    
    **Threshold value**: Approximately 0.33 (optimized on validation data)
    
    **Performance metrics**:
    - Micro F1: ~0.62
    - Macro F1: ~0.35
    - Precision: ~0.63
    - Recall: ~0.60
    """,
    
    "Macro Optimized": """
    ### Macro Optimized Profile
    
    **Technical definition**: Maximizes macro-averaged F1 score, which gives equal weight to all categories regardless of size.
    
    **When to use**: When balanced performance across all categories is important, including rare tags.
    
    **Effects**:
    - More balanced performance across all tag categories
    - Better at detecting rare or unusual tags
    - Generally has lower thresholds than micro-optimized
    
    **Threshold value**: Approximately 0.19-0.21 (optimized on validation data)
    
    **Performance metrics**:
    - Micro F1: ~0.49
    - Macro F1: ~0.41
    - Precision: ~0.37
    - Recall: ~0.53
    """,
    
    "Balanced": """
    ### Balanced Profile
    
    **Technical definition**: Provides a compromise between precision and recall with moderate thresholds.
    
    **When to use**: For general-purpose tagging when you don't have specific recall or precision requirements.
    
    **Effects**:
    - Good middle ground between precision and recall
    - Works well for most common use cases
    - Default choice for most users
    
    **Threshold value**: Approximately 0.26 (optimized on validation data)
    
    **Performance metrics**:
    - Micro F1: ~0.59
    - Macro F1: ~0.39
    - Precision: ~0.51
    - Recall: ~0.70
    """,
    
    "High Precision": """
    ### High Precision Profile
    
    **Technical definition**: Uses higher thresholds to prioritize precision (correctness) over recall (coverage).
    
    **When to use**: When you need high confidence in the tags that are returned and prefer to miss tags rather than include incorrect ones.
    
    **Effects**:
    - Much higher precision (84-97% of returned tags are correct)
    - Lower recall (only captures 35-60% of relevant tags)
    - Returns fewer tags overall, but with higher confidence
    
    **Threshold value**: 0.50 (optimized for precision on validation data)
    
    **Performance metrics**:
    - Micro F1: ~0.50
    - Macro F1: ~0.22
    - Precision: ~0.84
    - Recall: ~0.35
    """,
    
    "High Recall": """
    ### High Recall Profile
    
    **Technical definition**: Uses lower thresholds to prioritize recall (coverage) over precision (correctness).
    
    **When to use**: When you want to capture as many potential tags as possible and don't mind some incorrect suggestions.
    
    **Effects**:
    - Very high recall (captures 90%+ of relevant tags)
    - Much lower precision (only 18-49% of returned tags may be correct)
    - Returns many more tags, including less confident ones
    
    **Threshold value**: 0.10-0.12 (optimized for recall on validation data)
    
    **Performance metrics**:
    - Micro F1: ~0.30
    - Macro F1: ~0.35
    - Precision: ~0.18
    - Recall: ~0.90
    """,
    
    "Overall": """
    ### Overall Profile
    
    **Technical definition**: Uses a single threshold value across all categories.
    
    **When to use**: When you want consistent behavior across all categories and a simple approach.
    
    **Effects**:
    - Consistent tagging threshold for all categories
    - Simpler to understand than category-specific thresholds
    - User-adjustable with a single slider
    
    **Default threshold value**: 0.35 (uses "balanced" threshold by default)
    
    **Note**: The threshold value is user-adjustable with the slider below.
    """,
    
    "Weighted": """
    ### Weighted Profile
    
    **Technical definition**: Uses thresholds weighted by category importance.
    
    **When to use**: When you want different sensitivity for different categories based on their importance.
    
    **Effects**:
    - More important categories (like character and copyright) get optimized thresholds
    - Less important categories get adjusted thresholds based on their contribution
    - Better balance for the tags that matter most
    
    **Default threshold values**: Varies by category (based on importance weighting)
    
    **Note**: This uses pre-calculated optimal thresholds that can't be adjusted directly.
    """,
    
    "Category-specific": """
    ### Category-specific Profile
    
    **Technical definition**: Uses different optimal thresholds for each category, allowing fine-tuning.
    
    **When to use**: When you want to customize tagging sensitivity for different categories.
    
    **Effects**:
    - Each category has its own independent threshold
    - Full control over category sensitivity
    - Best for fine-tuning results when some categories need different treatment
    
    **Default threshold values**: Starts with balanced thresholds for each category
    
    **Note**: Use the category sliders below to adjust thresholds for individual categories.
    """
}

def get_profile_metrics(thresholds, profile_name, model_type="refined"):
    """
    Extract metrics for the given profile from the thresholds dictionary
    
    Args:
        thresholds: The thresholds dictionary
        profile_name: Name of the profile (micro_opt, macro_opt, balanced, etc.)
        model_type: 'initial' or 'refined'
        
    Returns:
        Dictionary with metrics or None if not found
    """
    profile_key = None
    
    # Map UI-friendly names to internal keys
    if profile_name == "Micro Optimized":
        profile_key = "micro_opt"
    elif profile_name == "Macro Optimized":
        profile_key = "macro_opt"
    elif profile_name == "Balanced":
        profile_key = "balanced"
    elif profile_name == "High Precision":
        profile_key = "high_precision"
    elif profile_name == "High Recall":
        profile_key = "high_recall"
    
    # For overall/weighted/category-specific, we're using the balanced profile metrics
    elif profile_name in ["Overall", "Weighted", "Category-specific"]:
        profile_key = "balanced"
    
    # Handle the new JSON structure with "initial" and "refined" top-level keys
    if "initial" in thresholds and "refined" in thresholds:
        # Get the appropriate model type
        model_type_key = model_type  # Use the passed in model_type
        
        # Make sure the model_type_key is valid
        if model_type_key not in thresholds:
            model_type_key = "refined" if "refined" in thresholds else "initial"
        
        # Check if the profile exists
        if "overall" in thresholds[model_type_key] and profile_key in thresholds[model_type_key]["overall"]:
            return thresholds[model_type_key]["overall"][profile_key]
    else:
        # Fallback to the old structure
        if "overall" in thresholds and profile_key in thresholds["overall"]:
            return thresholds["overall"][profile_key]
    
    return None

def on_threshold_profile_change():
    """
    Handle threshold profile changes to ensure smooth transitions between modes
    and preserve user customizations
    """
    # Get the new profile
    new_profile = st.session_state.threshold_profile
    
    # Initialize active_threshold and active_category_thresholds based on profile
    if hasattr(st.session_state, 'thresholds') and hasattr(st.session_state, 'settings'):
        # Create category thresholds if they don't exist
        if st.session_state.settings['active_category_thresholds'] is None:
            st.session_state.settings['active_category_thresholds'] = {}
        
        # Get existing thresholds
        current_thresholds = st.session_state.settings['active_category_thresholds']
        
        # Get model type for accessing thresholds - handle the new JSON structure
        if "initial" in st.session_state.thresholds and "refined" in st.session_state.thresholds:
            model_type_key = "refined" if hasattr(st.session_state, 'model_type') and st.session_state.model_type == "full" else "initial"
            
            # Make sure the model_type_key is valid
            if model_type_key not in st.session_state.thresholds:
                model_type_key = "refined" if "refined" in st.session_state.thresholds else "initial"
        else:
            # Use None for old structure
            model_type_key = None
        
        # Map profile display names to internal keys
        profile_key = None
        if new_profile == "Micro Optimized":
            profile_key = "micro_opt"
        elif new_profile == "Macro Optimized":
            profile_key = "macro_opt"
        elif new_profile == "Balanced":
            profile_key = "balanced"
        elif new_profile == "High Precision":
            profile_key = "high_precision"
        elif new_profile == "High Recall":
            profile_key = "high_recall"
        
        # For specialized profiles, update thresholds from the thresholds dictionary
        if profile_key:
            # Set overall threshold based on JSON structure
            if model_type_key is not None:  # New structure
                if "overall" in st.session_state.thresholds[model_type_key] and profile_key in st.session_state.thresholds[model_type_key]["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds[model_type_key]["overall"][profile_key]["threshold"]
            else:  # Old structure
                if "overall" in st.session_state.thresholds and profile_key in st.session_state.thresholds["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds["overall"][profile_key]["threshold"]
            
            # Set category thresholds based on JSON structure
            for category in st.session_state.categories:
                if model_type_key is not None:  # New structure
                    if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                        if profile_key in st.session_state.thresholds[model_type_key]["categories"][category]:
                            current_thresholds[category] = st.session_state.thresholds[model_type_key]["categories"][category][profile_key]["threshold"]
                        else:
                            # Fallback to overall threshold if profile not found for this category
                            current_thresholds[category] = st.session_state.settings['active_threshold']
                else:  # Old structure
                    if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                        if profile_key in st.session_state.thresholds["categories"][category]:
                            current_thresholds[category] = st.session_state.thresholds["categories"][category][profile_key]["threshold"]
                        else:
                            current_thresholds[category] = st.session_state.settings['active_threshold']
        
        # For "Overall" profile, reset to use just the overall threshold
        elif new_profile == "Overall":
            # Use the balanced threshold for Overall profile based on JSON structure
            if model_type_key is not None:  # New structure
                if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
            else:  # Old structure
                if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds["overall"]["balanced"]["threshold"]
            
            # Clear any category-specific overrides
            st.session_state.settings['active_category_thresholds'] = {}
        
        # For "Weighted" profile, use weighted thresholds
        elif new_profile == "Weighted":
            # Use the balanced threshold as base for Weighted profile based on JSON structure
            if model_type_key is not None:  # New structure
                if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
            else:  # Old structure
                if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds["overall"]["balanced"]["threshold"]
            
            # Get weighted thresholds if they exist, otherwise use balanced
            if model_type_key is not None:  # New structure
                if "weighted" in st.session_state.thresholds[model_type_key]:
                    weighted_thresholds = st.session_state.thresholds[model_type_key]["weighted"]
                    for category in st.session_state.categories:
                        if category in weighted_thresholds:
                            current_thresholds[category] = weighted_thresholds[category]
                        else:
                            # Fallback to balanced threshold for categories not in weighted
                            if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                                if "balanced" in st.session_state.thresholds[model_type_key]["categories"][category]:
                                    current_thresholds[category] = st.session_state.thresholds[model_type_key]["categories"][category]["balanced"]["threshold"]
                                else:
                                    current_thresholds[category] = st.session_state.settings['active_threshold']
                            else:
                                current_thresholds[category] = st.session_state.settings['active_threshold']
            else:  # Old structure
                if "weighted" in st.session_state.thresholds:
                    weighted_thresholds = st.session_state.thresholds["weighted"]
                    for category in st.session_state.categories:
                        if category in weighted_thresholds:
                            current_thresholds[category] = weighted_thresholds[category]
                        else:
                            # Fallback to balanced threshold
                            if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                                if "balanced" in st.session_state.thresholds["categories"][category]:
                                    current_thresholds[category] = st.session_state.thresholds["categories"][category]["balanced"]["threshold"]
                                else:
                                    current_thresholds[category] = st.session_state.settings['active_threshold']
                            else:
                                current_thresholds[category] = st.session_state.settings['active_threshold']
        
        # For "Category-specific", initialize with balanced thresholds
        elif new_profile == "Category-specific":
            # Use the balanced threshold as base for Category-specific based on JSON structure
            if model_type_key is not None:  # New structure
                if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
            else:  # Old structure
                if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                    st.session_state.settings['active_threshold'] = st.session_state.thresholds["overall"]["balanced"]["threshold"]
            
            # Initialize with balanced thresholds for each category
            for category in st.session_state.categories:
                if model_type_key is not None:  # New structure
                    if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                        if "balanced" in st.session_state.thresholds[model_type_key]["categories"][category]:
                            current_thresholds[category] = st.session_state.thresholds[model_type_key]["categories"][category]["balanced"]["threshold"]
                        else:
                            current_thresholds[category] = st.session_state.settings['active_threshold']
                    else:
                        current_thresholds[category] = st.session_state.settings['active_threshold']
                else:  # Old structure
                    if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                        if "balanced" in st.session_state.thresholds["categories"][category]:
                            current_thresholds[category] = st.session_state.thresholds["categories"][category]["balanced"]["threshold"]
                        else:
                            current_thresholds[category] = st.session_state.settings['active_threshold']
                    else:
                        current_thresholds[category] = st.session_state.settings['active_threshold']

def create_micro_macro_comparison():
    """
    Creates a visual explanation of micro vs macro optimization
    
    Returns:
        HTML for the visualization
    """
    html = """
    <style>
    .optimization-container {
        font-family: sans-serif;
        margin: 20px 0;
    }
    .optimization-row {
        display: flex;
        margin-bottom: 15px;
    }
    .optimization-col {
        flex: 1;
        padding: 15px;
        border-radius: 8px;
        margin: 0 5px;
    }
    .optimization-col h3 {
        margin-top: 0;
        font-size: 18px;
    }
    .optimization-col p {
        font-size: 14px;
        line-height: 1.5;
    }
    .micro-col {
        background-color: #e6f3ff;
        border: 1px solid #99ccff;
    }
    .macro-col {
        background-color: #fff0e6;
        border: 1px solid #ffcc99;
    }
    .tag-example {
        display: inline-block;
        padding: 3px 8px;
        margin: 3px;
        border-radius: 12px;
        font-size: 12px;
    }
    .tag-common {
        background-color: #4CAF50;
        color: white;
    }
    .tag-rare {
        background-color: #9C27B0;
        color: white;
    }
    .comparison-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    .comparison-table th, .comparison-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    .comparison-table th {
        background-color: #f2f2f2;
    }
    </style>
"""
    return html

def apply_thresholds(all_probs, threshold_profile, active_threshold, active_category_thresholds, min_confidence, selected_categories):
    """
    Apply thresholds to raw probabilities and return filtered tags
    
    Args:
        all_probs: Dictionary with all probabilities organized by category
        threshold_profile: Current threshold profile
        active_threshold: Overall threshold value
        active_category_thresholds: Dictionary of category-specific thresholds
        min_confidence: Minimum confidence to include
        selected_categories: Dictionary of selected categories
        
    Returns:
        tags: Dictionary of filtered tags above threshold by category
        all_tags: List of all tags above threshold
    """
    # Apply thresholds to each category
    tags = {}
    all_tags = []
    
    for category, cat_probs in all_probs.items():
        # Get the appropriate threshold for this category
        # For Overall and Weighted profiles, respect per-category overrides if available
        threshold = active_category_thresholds.get(category, active_threshold) if active_category_thresholds else active_threshold
        
        # Filter tags above threshold
        tags[category] = [(tag, prob) for tag, prob in cat_probs if prob >= threshold]
        
        # Add to all_tags if selected
        if selected_categories.get(category, True):
            for tag, prob in tags[category]:
                all_tags.append(tag)
        
    return tags, all_tags

def image_tagger_app():
    """Main Streamlit application for image tagging."""
    st.set_page_config(layout="wide", page_title="Camie Tagger", page_icon="🖼️")
    
    st.title("Image Tagging Interface")
    st.markdown("---")
    
    # Check platform and Flash Attention
    windows_system = is_windows()
    flash_attn_installed = check_flash_attention()

    if 'settings' not in st.session_state:
        st.session_state.settings = {
            'show_all_tags': False,
            'compact_view': True,
            'min_confidence': 0.01,
            'threshold_profile': "Balanced",
            'active_threshold': 0.35,
            'active_category_thresholds': None,
            'selected_categories': {},
            'replace_underscores': False  # Added new setting
        }
        # Initialize show_profile_help state
        st.session_state.show_profile_help = False
 
    # Define default threshold values (initialized here to avoid errors)
    default_threshold_values = {
        'overall': 0.35,
        'weighted': 0.35,
        'category_thresholds': {},
        'high_precision_thresholds': {},
        'high_recall_thresholds': {}
    }
 
    # Session state initialization for model
    if 'model_loaded' not in st.session_state:
        st.session_state.model_loaded = False
        st.session_state.model = None
        st.session_state.thresholds = None
        st.session_state.metadata = None
        
        # Check if ONNX model files exist
        onnx_model_path = os.path.join(os.path.dirname(MODEL_DIR), "model_initial.onnx")
        onnx_metadata_path = os.path.join(os.path.dirname(MODEL_DIR), "model_initial_metadata.json")
        onnx_available = os.path.exists(onnx_model_path) and os.path.exists(onnx_metadata_path)
        
        # Default to ONNX if available, otherwise fallback to initial_only on Windows or full elsewhere
        if onnx_available:
            st.session_state.model_type = "onnx"
        else:
            st.session_state.model_type = "initial_only" if windows_system else "full"
    
    # Sidebar for model selection and information
    with st.sidebar:
        st.header("Model Selection")
        
        # Check if ONNX model files exist
        onnx_model_path = os.path.join(os.path.dirname(MODEL_DIR), "model_initial.onnx")
        onnx_metadata_path = os.path.join(os.path.dirname(MODEL_DIR), "model_initial_metadata.json")
        onnx_available = os.path.exists(onnx_model_path) and os.path.exists(onnx_metadata_path)
        
        # Define model options, including ONNX if available
        model_options = [
            "Refined (Tag Embeddings)",
            "Initial (Base Model)"
        ]
        
        # Add ONNX option if available
        if onnx_available:
            model_options.append("ONNX Accelerated (Fastest)")
        
        # Determine the default index for model selection
        if st.session_state.model_type == "onnx" and onnx_available:
            default_index = 2  # ONNX is first priority when available
        elif windows_system or st.session_state.model_type == "initial_only":
            default_index = 1  # Initial Only is second priority, default on Windows
        else:
            default_index = 0  # Full model is last priority
        
        # Model type selection with radio buttons
        model_type = st.radio(
            "Select Model Type:",
            model_options,
            index=min(default_index, len(model_options)-1),  # Ensure index is valid
            help="""
            Full Model: Uses both initial and refined predictions for highest accuracy (requires more VRAM)
            Initial Only: Uses only the initial classifier, reducing VRAM usage at slight quality cost
            ONNX Accelerated: Optimized for inference speed, best for batch processing (if available)
            """
        )
        
        # Convert selection to internal model type
        if model_type == "Full Model (Best Quality)":
            selected_model_type = "full"
        elif model_type == "ONNX Accelerated (Fastest)":
            selected_model_type = "onnx"
            # Store ONNX paths in session state for later use
            st.session_state.onnx_model_path = onnx_model_path
            st.session_state.onnx_metadata_path = onnx_metadata_path
        else:  # "Initial Only (Lower VRAM)"
            selected_model_type = "initial_only"
        
        # If the model type has changed, we need to reload the model
        if selected_model_type != st.session_state.model_type:
            st.session_state.model_loaded = False
            st.session_state.model_type = selected_model_type

        # Add Windows warning if relevant
        if windows_system and selected_model_type=="full":
            st.warning("""
            ### Windows Compatibility Note
            
            The refined model requires Flash Attention which is difficult to install on Windows.
            
            For Windows users, I recommend using the "Initial Only" or ONNX Accelerated model which:
            - Does not require Flash Attention
            - Uses less memory
            - Provides very close to full prediction quality (check performance notes on HF)        
            """)
        
        # Add a button to reload the model with current settings
        if st.button("Reload Model") and st.session_state.model_loaded:
            st.session_state.model_loaded = False
            st.info("Reloading model...")

    # Try to load the model when not loaded
    if not st.session_state.model_loaded:
        try:
            with st.spinner(f"Loading {st.session_state.model_type} model..."):
                if st.session_state.model_type == "onnx":
                    # Load ONNX model and metadata
                    import json
                    import onnxruntime as ort
                    
                    try:
                        # Check ONNX providers (for info display)
                        providers = ort.get_available_providers()
                        gpu_available = any('GPU' in provider for provider in providers)
                        
                        # Store provider info in session state
                        st.session_state.onnx_providers = providers
                        st.session_state.onnx_gpu_available = gpu_available
                        
                        # Load metadata
                        with open(st.session_state.onnx_metadata_path, 'r') as f:
                            metadata = json.load(f)
                        
                        # Load thresholds from a separate file or use defaults
                        thresholds_path = os.path.join(MODEL_DIR, "thresholds.json")
                        if os.path.exists(thresholds_path):
                            with open(thresholds_path, 'r') as f:
                                thresholds = json.load(f)
                        else:
                            # If no thresholds file, extract from metadata if available
                            if 'thresholds' in metadata:
                                thresholds = metadata['thresholds']
                            else:
                                # Use default thresholds if not available
                                thresholds = {
                                    'overall': {'balanced': {'threshold': 0.35}},
                                    'weighted': {'f1': {'threshold': 0.35}},
                                    'categories': {}
                                }
                                
                                # Build category thresholds if necessary
                                if 'tag_to_category' in metadata:
                                    categories = set(metadata['tag_to_category'].values())
                                    thresholds['categories'] = {
                                        cat: {
                                            'balanced': {'threshold': 0.35},
                                            'high_precision': {'threshold': 0.45},
                                            'high_recall': {'threshold': 0.25}
                                        } for cat in categories
                                    }
                        
                        # Set device info for display
                        device = "ONNX Runtime" + (" (GPU)" if gpu_available else " (CPU)")
                        param_dtype = "float32"  # Most ONNX models use float32
                        
                        # Store information in session state
                        st.session_state.model = None  # No PyTorch model for ONNX
                        st.session_state.device = device
                        st.session_state.param_dtype = param_dtype
                        st.session_state.thresholds = thresholds
                        st.session_state.metadata = metadata
                        st.session_state.model_loaded = True
                        
                        # Get categories from metadata
                        categories = list(set(metadata['tag_to_category'].values()))
                        st.session_state.categories = categories
                        
                        # Initialize selected categories if needed
                        if not st.session_state.settings['selected_categories']:
                            st.session_state.settings['selected_categories'] = {cat: True for cat in categories}
                        
                    except Exception as e:
                        st.error(f"Error loading ONNX model: {str(e)}")
                        st.info(f"Make sure the ONNX model and metadata files exist at: {st.session_state.onnx_model_path} and {st.session_state.onnx_metadata_path}")
                        st.code(traceback.format_exc())
                        st.stop()
                else:
                    # Load PyTorch model as before
                    model, thresholds, metadata = load_exported_model(
                        MODEL_DIR, 
                        model_type=st.session_state.model_type
                    )
                    
                    # Extract device and precision info
                    device = next(model.parameters()).device
                    param_dtype = next(model.parameters()).dtype
                    
                    # Store model in session state for PyTorch models
                    st.session_state.model = model
                
                # Common code for all model types
                # Get available categories
                categories = list(set(metadata['tag_to_category'].values()))
                
                # Initialize selected categories (all selected by default)
                if not st.session_state.settings['selected_categories']:
                    st.session_state.settings['selected_categories'] = {cat: True for cat in categories}
                
                # Store common info in session state
                st.session_state.device = device
                st.session_state.param_dtype = param_dtype
                st.session_state.thresholds = thresholds
                st.session_state.metadata = metadata
                st.session_state.model_loaded = True
                st.session_state.categories = categories

                # Debug: Print loaded thresholds to verify they're loaded correctly
                print("Loaded thresholds:", thresholds)
                
                if "initial" in thresholds and "refined" in thresholds:
                    # Choose which model type to use as default
                    model_type_key = "refined" if st.session_state.model_type == "full" else "initial"
                    
                    # Set overall threshold from the balanced profile
                    if "overall" in thresholds[model_type_key] and "balanced" in thresholds[model_type_key]["overall"]:
                        default_threshold_values['overall'] = thresholds[model_type_key]["overall"]["balanced"]["threshold"]
                    
                    # Get weighted threshold if available
                    if "weighted" in thresholds[model_type_key] and "f1" in thresholds[model_type_key]["weighted"]:
                        default_threshold_values['weighted'] = thresholds[model_type_key]["weighted"]["f1"]["threshold"]
                    
                    # Set category thresholds
                    if "categories" in thresholds[model_type_key]:
                        default_threshold_values['category_thresholds'] = {
                            cat: opt['balanced']['threshold'] 
                            for cat, opt in thresholds[model_type_key]["categories"].items()
                        }
                        
                        # Set high precision and high recall thresholds
                        default_threshold_values['high_precision_thresholds'] = {
                            cat: opt['high_precision']['threshold'] 
                            for cat, opt in thresholds[model_type_key]["categories"].items()
                        }
                        
                        default_threshold_values['high_recall_thresholds'] = {
                            cat: opt['high_recall']['threshold'] 
                            for cat, opt in thresholds[model_type_key]["categories"].items()
                        }
                else:
                    # Fallback to the old structure for backward compatibility
                    if "overall" in thresholds and "balanced" in thresholds["overall"]:
                        default_threshold_values['overall'] = thresholds["overall"]["balanced"]["threshold"]
                    
                    # Get weighted threshold if available
                    if "weighted" in thresholds and "f1" in thresholds["weighted"]:
                        default_threshold_values['weighted'] = thresholds["weighted"]["f1"]["threshold"]
                    
                    # Set category thresholds
                    if "categories" in thresholds:
                        default_threshold_values['category_thresholds'] = {
                            cat: opt['balanced']['threshold'] 
                            for cat, opt in thresholds["categories"].items()
                        }
                        
                        # Set high precision and high recall thresholds
                        default_threshold_values['high_precision_thresholds'] = {
                            cat: opt['high_precision']['threshold'] 
                            for cat, opt in thresholds["categories"].items()
                        }
                        
                        default_threshold_values['high_recall_thresholds'] = {
                            cat: opt['high_recall']['threshold'] 
                            for cat, opt in thresholds["categories"].items()
                        }
                
                # Update session state with current threshold values
                # This part is crucial - store the values in session state
                st.session_state.default_threshold_values = default_threshold_values
                
                # Update active threshold with default values
                if st.session_state.settings['threshold_profile'] == "Overall":
                    st.session_state.settings['active_threshold'] = default_threshold_values['overall']
                elif st.session_state.settings['threshold_profile'] == "Weighted":
                    st.session_state.settings['active_threshold'] = default_threshold_values['weighted']
                            
        except Exception as e:
            st.error(f"Error loading model: {str(e)}")
            st.info(f"Looking for model in: {os.path.abspath(MODEL_DIR)}")
            
            # Check for specific files
            if st.session_state.model_type == "initial_only":
                expected_model_paths = [
                    os.path.join(MODEL_DIR, "model_initial_only.pt"),
                    os.path.join(MODEL_DIR, "model_initial.pt")
                ]
                if not any(os.path.exists(p) for p in expected_model_paths):
                    st.error(f"Initial-only model file not found. Checked: {', '.join(expected_model_paths)}")
                    st.info("Make sure you've exported both model types.")
            else:
                expected_model_paths = [
                    os.path.join(MODEL_DIR, "model_refined.pt"),
                    os.path.join(MODEL_DIR, "model.pt"),
                    os.path.join(MODEL_DIR, "model_full.pt")
                ]
                if not any(os.path.exists(p) for p in expected_model_paths):
                    st.error(f"Full model file not found. Checked: {', '.join(expected_model_paths)}")
            
            st.code(traceback.format_exc())
            st.stop()
    
    with st.sidebar:
        st.header("Model Information")
        if st.session_state.model_loaded:
            # Show model type
            if st.session_state.model_type == "onnx":
                st.success("Using ONNX Accelerated Model")
                # Show ONNX-specific info
                if hasattr(st.session_state, 'onnx_gpu_available') and st.session_state.onnx_gpu_available:
                    st.write("Acceleration: GPU available")
                else:
                    st.write("Acceleration: CPU only")
            elif st.session_state.model_type == "full":
                st.success("Using Full Model (Best Quality)")
                # Show Flash Attention info for full model
                if not flash_attn_installed and is_windows():
                    st.warning("Note: Flash Attention not available on Windows")
            else:
                st.success("Using Initial-Only Model (Lower VRAM)")
            
            # Show common model info
            st.write(f"Device: {st.session_state.device}")
            st.write(f"Precision: {st.session_state.param_dtype}")
            st.write(f"Total tags: {st.session_state.metadata['total_tags']}")
            
            # Show categories in an expander
            with st.expander("Available Categories"):
                for category in sorted(st.session_state.categories):
                    st.write(f"- {category.capitalize()}")
            
            # Add an expander with information
            with st.expander("About this app"):
                st.write("""
                This app uses a trained image tagging model to analyze and tag images.
                
                **Model Options**:
                - **ONNX Accelerated (Fastest)**: Optimized for inference speed with minimal VRAM usage, ideal for batch processing
                - **Refined Model (Tag Embeddings)**: Higher quality predictions using both initial and refined layers (uses more VRAM)
                - **Initial Model (Base model)**: Reduced VRAM usage with slightly lower accuracy (good for systems with limited resources)
                
                **Platform Notes**:
                - **Windows Users**: ONNX Accelerated model is recommended for best performance
                - **CUDA Support**: GPU acceleration is available for ONNX models if CUDA 12.x and cuDNN are installed
                - **Linux Users**: The Refined Model with Flash Attention provides the best quality results
                
                **Features**:
                - Upload or select an image
                - Process multiple images in batch mode with customizable batch size
                - Choose from different threshold profiles
                - Adjust category-specific thresholds
                - View predictions organized by category
                - Limit results to top N tags within each category
                - Save tags to text files in various locations
                - Export tags with consistent formatting for external use
                - Fast batch processing
                
                **Threshold profiles**:
                - **Micro Optimized**: Optimizes micro-averaged F1 score (best for common tags)
                - **Macro Optimized**: Optimizes macro-averaged F1 score (better for rare tags)
                - **Balanced**: Provides a good balance of precision and recall
                - **High Precision**: Prioritizes accuracy over recall
                - **High Recall**: Captures more potential tags but may be less accurate
                """)

    with st.sidebar:
        # Add separator for visual clarity
        st.markdown("---")
        
        # Support information
        st.subheader("💡 Notes")
        
        st.markdown("""
        This tagger was trained on a subset of the available data and for limited epochs due to hardware limitations.
        
        A more comprehensive model trained on the full 3+ million image dataset and many more epochs would provide:
        - More recent characters and tags.
        - Improved accuracy.
        
        If you find this tool useful and would like to support future development:
        """)
        
        # Add Buy Me a Coffee button with Star of the City-like glow effect
        st.markdown("""
        <style>
        @keyframes coffee-button-glow {
            0% { box-shadow: 0 0 5px #FFD700; }
            50% { box-shadow: 0 0 15px #FFD700; }
            100% { box-shadow: 0 0 5px #FFD700; }
        }
        
        .coffee-button {
            display: inline-block;
            animation: coffee-button-glow 2s infinite;
            border-radius: 5px;
            transition: transform 0.3s ease;
        }
        
        .coffee-button:hover {
            transform: scale(1.05);
        }
        </style>
        
        <a href="https://buymeacoffee.com/camais" target="_blank" class="coffee-button">
            <img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" 
                alt="Buy Me A Coffee" 
                style="height: 45px; width: 162px; border-radius: 5px;" />
        </a>
        """, unsafe_allow_html=True)
        
        st.markdown("""
        Your support helps with:
        - GPU costs for training
        - Storage for larger datasets
        - Development of new features
        - Future projects
        
        Thank you! 🙏
                    
        Full Details: https://huggingface.co/Camais03/camie-tagger
        """)

    with st.sidebar:
        # Add game link at the bottom of the sidebar
        st.markdown("---")
        st.subheader("Try the Tag Collector Game!")
        st.write("Test your tagging skills in our gamified version of the image tagger!")
        
        if st.button("🎮 Launch Tag Collector Game", type="primary"):
            # Get the current port to determine the game URL
            current_port = os.environ.get("STREAMLIT_SERVER_PORT", "8501")
            # The game should run on a different port (8502 if this is 8501, or vice versa)
            game_port = "8502" if current_port == "8501" else "8501"
            
            # Check if the game file exists
            game_path = os.path.join(os.path.dirname(__file__), "tag_collector_game.py")
            if os.path.exists(game_path):
                # Launch the game in a new process
                try:
                    # Determine streamlit path
                    if sys.platform == "win32":
                        streamlit_path = os.path.join("venv", "Scripts", "streamlit.exe")
                    else:
                        streamlit_path = os.path.join("venv", "bin", "streamlit")
                    
                    if not os.path.exists(streamlit_path):
                        streamlit_path = "streamlit"  # Fallback to global streamlit
                    
                    # Build command to run game on different port
                    command = [streamlit_path, "run", game_path, "--server.port", game_port]
                    
                    # Launch in background
                    if sys.platform == "win32":
                        subprocess.Popen(command, shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE)
                    else:
                        subprocess.Popen(command)
                    
                    # Open in browser
                    game_url = f"http://localhost:{game_port}"
                    webbrowser.open(game_url)
                    st.success(f"Launching Tag Collector Game!")
                    
                except Exception as e:
                    st.error(f"Failed to launch game: {str(e)}")
            else:
                st.error(f"Game file not found: {game_path}")
                st.info("Make sure tag_collector_game.py is in the same directory as this app.")
    
    # Main content area
    col1, col2 = st.columns([1, 1.5])
    
    # Column 1: Image upload and display
    with col1:
        st.header("Image")
        
        # Add tabs for Upload, Examples, and Batch Processing
        upload_tab, batch_tab = st.tabs(["Upload Image", "Batch Processing"])
        
        image_path = None
        
        with upload_tab:
            uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
            
            if uploaded_file:
                # Create a temporary file
                with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
                    tmp_file.write(uploaded_file.getvalue())
                    image_path = tmp_file.name
                
                # Store the original filename for saving tags
                st.session_state.original_filename = uploaded_file.name
                
                # Display the image
                image = Image.open(uploaded_file)
                st.image(image, use_container_width=True)
            
        with batch_tab:
            st.subheader("Batch Process Images")
            st.write("Process multiple images from a folder and save tags to text files.")
            
            # Folder selection
            batch_folder = st.text_input("Enter folder path containing images:", "")
            if st.button("Browse Folder..."):
                # This is a dummy button since Streamlit doesn't have a native folder picker
                st.info("Please type the folder path manually in the text input above.")
            
            # Save location options
            save_options = st.radio(
                "Where to save tag files:",
                ["Same folder as images", "Custom location", "Default save folder"],
                index=0
            )

            # Add batch size control
            st.subheader("Performance Options")
            batch_size_text = st.text_input(
                "Batch size (images processed at once)",
                value="4",
                help="Higher values may improve processing speed but use more memory. Recommended: 4-16"
            )

            # Convert to integer with error handling
            try:
                batch_size = int(batch_size_text)
                if batch_size < 1:
                    st.warning("Batch size must be at least 1. Using batch size of 1.")
                    batch_size = 1
            except ValueError:
                st.warning("Please enter a valid number for batch size. Using default batch size of 4.")
                batch_size = 4

            # Performance note
            if batch_size > 8:
                st.info(f"Using larger batch size ({batch_size}). If you encounter memory issues, try reducing this value.")
            
            st.write("Set tag limits per category for batch processing:")

            # Create a toggle for enabling category limits
            enable_category_limits = st.checkbox("Limit tags per category in batch output", value=False)

            # Initialize the category limit dictionary if it doesn't exist
            if 'category_limits' not in st.session_state:
                st.session_state.category_limits = {}

            if enable_category_limits:
                # Create a two-column layout for more compact display
                limit_cols = st.columns(2)
                
                # Add an explanation about the values
                st.markdown("""
                **Limit Values:**
                * **-1** = No limit (include all tags)
                * **0** = Exclude category entirely
                * **N** (positive number) = Include only top N tags
                """)
                
                if hasattr(st.session_state, 'categories'):
                    # Create text inputs for each category
                    for i, category in enumerate(sorted(st.session_state.categories)):
                        col_idx = i % 2  # Alternate between columns
                        with limit_cols[col_idx]:
                            # Get current limit value (default to -1 for unlimited)
                            current_limit = st.session_state.category_limits.get(category, -1)
                            
                            # Add a text input for this category
                            limit_text = st.text_input(
                                f"{category.capitalize()} (top N):", 
                                value=str(current_limit),
                                key=f"limit_{category}",
                                help="-1 = no limit, 0 = exclude, N = top N tags"
                            )
                            
                            # Convert to integer with error handling
                            try:
                                limit = int(limit_text)
                                if limit < -1:
                                    st.warning(f"Limit for {category} must be -1 or greater. Using -1 (unlimited).")
                                    limit = -1
                            except ValueError:
                                st.warning(f"Invalid limit for {category}. Using -1 (unlimited).")
                                limit = -1
                            
                            # Display a clear indicator of what this setting means
                            if limit == -1:
                                st.caption(f"✅ Including all {category} tags")
                            elif limit == 0:
                                st.caption(f"❌ Excluding all {category} tags")
                            else:
                                st.caption(f"⚙️ Including top {limit} {category} tags")
                            
                            # Store the limit in session state
                            st.session_state.category_limits[category] = limit
                else:
                    st.info("Categories will be available after loading a model.")
            else:
                # Clear any existing limits if disabled
                st.session_state.category_limits = {}

            custom_save_dir = None
            if save_options == "Custom location":
                # Allow selecting a custom save location
                if 'custom_folders' not in st.session_state:
                    st.session_state.custom_folders = get_default_save_locations()
                    
                custom_save_dir = st.selectbox(
                    "Select save location:",
                    options=st.session_state.custom_folders,
                    format_func=lambda x: os.path.basename(x) if os.path.basename(x) else x
                )
                
                # Allow adding a new folder
                new_folder = st.text_input("Or enter a new folder path:", key="batch_new_folder")
                if st.button("Add Folder", key="batch_add_folder") and new_folder:
                    if os.path.isdir(new_folder):
                        if new_folder not in st.session_state.custom_folders:
                            st.session_state.custom_folders.append(new_folder)
                            st.success(f"Added folder: {new_folder}")
                            st.rerun()
                        else:
                            st.info("This folder is already in the list.")
                    else:
                        try:
                            # Try to create the folder if it doesn't exist
                            os.makedirs(new_folder, exist_ok=True)
                            st.session_state.custom_folders.append(new_folder)
                            st.success(f"Created and added folder: {new_folder}")
                            st.rerun()
                        except Exception as e:
                            st.error(f"Could not create folder: {str(e)}")
            
            # Check if folder exists and count images
            if batch_folder and os.path.isdir(batch_folder):
                # Count image files
                image_extensions = ['*.jpg', '*.jpeg', '*.png']
                image_files = []

                for ext in image_extensions:
                    image_files.extend(glob.glob(os.path.join(batch_folder, ext)))
                    image_files.extend(glob.glob(os.path.join(batch_folder, ext.upper())))

                # Use a set to remove duplicate files (Windows filesystems are case-insensitive)
                if os.name == 'nt':  # Windows
                    # Use lowercase paths for comparison on Windows
                    unique_paths = set()
                    unique_files = []
                    for file_path in image_files:
                        normalized_path = os.path.normpath(file_path).lower()
                        if normalized_path not in unique_paths:
                            unique_paths.add(normalized_path)
                            unique_files.append(file_path)
                    image_files = unique_files
                
                total_images = len(image_files)
                st.write(f"Found {total_images} image files in the folder.")
                
                # Show first few images as thumbnails (more compact layout)
                if image_files:
                    st.write("Sample images:")
                    num_preview = min(8, len(image_files))
                    thumbnail_cols = st.columns(4)
                    for i, img_path in enumerate(image_files[:num_preview]):
                        with thumbnail_cols[i % 4]:
                            try:
                                img = Image.open(img_path)
                                # Make thumbnails smaller for more compact view
                                st.image(img, width=80, caption=os.path.basename(img_path))
                            except:
                                st.write(f"Error loading {os.path.basename(img_path)}")
                    
                    # Determine save directory based on user selection
                    if save_options == "Same folder as images":
                        save_dir = batch_folder
                    elif save_options == "Custom location":
                        save_dir = custom_save_dir
                    else:  # Default save folder
                        app_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                        save_dir = os.path.join(app_dir, "saved_tags")
                        os.makedirs(save_dir, exist_ok=True)
                    
                    # Add a more prominent button for batch processing
                    st.markdown("---")
                    process_col1, process_col2 = st.columns([3, 1])
                    with process_col1:
                        st.write(f"Ready to process {total_images} images")
                        st.write(f"Tags will be saved to: **{save_dir}**")
                    
                    with process_col2:
                        # Check if model is loaded
                        process_button_disabled = not st.session_state.model_loaded
                        
                        # Add a prominent batch processing button
                        if st.button("🔄 Process All Images", 
                                    key="process_batch_btn",
                                    use_container_width=True,
                                    disabled=process_button_disabled,
                                    type="primary"):
                            
                            if not st.session_state.model_loaded:
                                st.error("Model not loaded. Please check the model settings.")
                            else:
                                with st.spinner("Processing images..."):
                                    # Create progress bar
                                    progress_bar = st.progress(0)
                                    status_text = st.empty()
                                    
                                    # Define progress callback
                                    def update_progress(current, total, image_path):
                                        if total > 0:
                                            progress = min(current / total, 1.0)
                                            progress_bar.progress(progress)
                                            if image_path:
                                                status_text.text(f"Processing {current}/{total}: {os.path.basename(image_path)}")
                                            else:
                                                status_text.text(f"Completed processing {current}/{total} images")
                                    
                                    # Get settings for batch processing
                                    curr_threshold_profile = st.session_state.settings['threshold_profile']
                                    curr_active_threshold = st.session_state.settings['active_threshold']
                                    curr_active_category_thresholds = st.session_state.settings['active_category_thresholds']
                                    curr_min_confidence = st.session_state.settings['min_confidence']

                                    # Get category limits if enabled
                                    curr_category_limits = None
                                    if 'category_limits' in st.session_state and enable_category_limits:
                                        curr_category_limits = st.session_state.category_limits
                                        
                                        # Print debugging info in a more structured way
                                        if curr_category_limits:
                                            st.write("Category limit settings:")
                                            
                                            # Group by type for cleaner display
                                            excluded = []
                                            limited = []
                                            unlimited = []
                                            
                                            for cat, limit in sorted(curr_category_limits.items()):
                                                if limit == 0:
                                                    excluded.append(cat)
                                                elif limit > 0:
                                                    limited.append(f"{cat}: top {limit}")
                                                else:  # limit == -1
                                                    unlimited.append(cat)
                                            
                                            # Show in a more structured way
                                            if excluded:
                                                st.write("❌ Excluded categories: " + ", ".join(excluded))
                                            
                                            if limited:
                                                st.write("⚙️ Limited categories: " + ", ".join(limited))
                                            
                                            if unlimited:
                                                st.write("✅ Unlimited categories: " + ", ".join(unlimited))
                                            
                                            if not excluded and not limited:
                                                st.write("No limits set (all categories included)")

                                    # Then when you call the batch processing functions, pass this parameter:
                                    if st.session_state.model_type == "onnx":
                                        # Use ONNX batch processing
                                        batch_results = batch_process_images_onnx(
                                            folder_path=batch_folder,
                                            model_path=st.session_state.onnx_model_path,
                                            metadata_path=st.session_state.onnx_metadata_path,
                                            threshold_profile=curr_threshold_profile,
                                            active_threshold=curr_active_threshold,
                                            active_category_thresholds=curr_active_category_thresholds,
                                            save_dir=save_dir,
                                            progress_callback=update_progress,
                                            min_confidence=curr_min_confidence,
                                            batch_size=batch_size,
                                            category_limits=curr_category_limits
                                        )
                                    else:
                                        # Use standard PyTorch processing
                                        batch_results = batch_process_images(
                                            folder_path=batch_folder,
                                            model=st.session_state.model,
                                            thresholds=st.session_state.thresholds,
                                            metadata=st.session_state.metadata,
                                            threshold_profile=curr_threshold_profile,
                                            active_threshold=curr_active_threshold,
                                            active_category_thresholds=curr_active_category_thresholds,
                                            save_dir=save_dir,
                                            progress_callback=update_progress,
                                            min_confidence=curr_min_confidence,
                                            batch_size=batch_size,
                                            category_limits=st.session_state.category_limits if enable_category_limits else None
                                        )
                                    
                                    # Display results
                                    display_batch_results(batch_results)
                        
                    # If model is not loaded, show a hint
                    if not st.session_state.model_loaded:
                        st.warning("Please load a model before processing images.")
                        
                else:
                    st.warning("No image files found in the selected folder.")
            elif batch_folder:
                st.error(f"Folder not found: {batch_folder}")
    
    # Column 2: Threshold controls and predictions
    with col2:
        st.header("Tagging Controls")
        
        # Define all available profiles
        all_profiles = [
            "Micro Optimized",
            "Macro Optimized", 
            "Balanced", 
            "High Precision", 
            "High Recall",
            "Overall",
            "Weighted",
            "Category-specific"
        ]

        # Define a default index based on what's most similar to the current setting
        default_index = 2  # Default to "Balanced"
        if "threshold_profile" in st.session_state.settings:
            # If there's an existing selection, try to match it
            existing_profile = st.session_state.settings['threshold_profile']
            if existing_profile in all_profiles:
                default_index = all_profiles.index(existing_profile)
            # Map old profile names to new ones
            elif existing_profile == "Overall":
                default_index = all_profiles.index("Overall")
            elif existing_profile == "Weighted":
                default_index = all_profiles.index("Weighted")
            elif existing_profile == "Category-specific":
                default_index = all_profiles.index("Category-specific")
            elif existing_profile == "High Precision":
                default_index = all_profiles.index("High Precision")
            elif existing_profile == "High Recall":
                default_index = all_profiles.index("High Recall")

        # Create the profile selection UI with help button
        profile_col1, profile_col2 = st.columns([3, 1])

        with profile_col1:
            # Create the profile dropdown
            threshold_profile = st.selectbox(
                "Select threshold profile",
                options=all_profiles,
                index=default_index,
                key="threshold_profile",
                on_change=on_threshold_profile_change
            )

        with profile_col2:
            # Add a help button that expands to show detailed information
            if st.button("ℹ️ Help", key="profile_help"):
                st.session_state.show_profile_help = not st.session_state.get('show_profile_help', False)

        # Display the help text if the button was clicked
        if st.session_state.get('show_profile_help', False):
            st.markdown(threshold_profile_explanations[threshold_profile])
        else:
            # Just show the description
            st.info(threshold_profile_descriptions[threshold_profile])

        # Get profile metrics from thresholds
        if st.session_state.model_loaded:
            # Try to get metrics for the selected profile
            model_type = "refined" if st.session_state.model_type == "full" else "initial"
            metrics = get_profile_metrics(st.session_state.thresholds, threshold_profile, model_type)
            
            if metrics:
                # Create metrics display
                metrics_cols = st.columns(3)
                
                with metrics_cols[0]:
                    # Display threshold
                    threshold_value = metrics.get("threshold", 0.35)
                    st.metric("Threshold", f"{threshold_value:.3f}")
                
                with metrics_cols[1]:
                    # Display micro F1
                    micro_f1 = metrics.get("micro_f1", metrics.get("micro_precision", 0))
                    st.metric("Micro F1", f"{micro_f1:.3f}" if micro_f1 else "N/A")
                    
                    # Show precision if available
                    precision = metrics.get("precision", metrics.get("micro_precision", 0))
                    if precision:
                        st.metric("Precision", f"{precision:.3f}")
                
                with metrics_cols[2]:
                    # Display macro F1
                    macro_f1 = metrics.get("macro_f1", 0)
                    st.metric("Macro F1", f"{macro_f1:.3f}" if macro_f1 else "N/A")
                    
                    # Show recall if available
                    recall = metrics.get("recall", metrics.get("micro_recall", 0))
                    if recall:
                        st.metric("Recall", f"{recall:.3f}")

        # Initialize thresholds based on the selected profile
        active_threshold = None
        active_category_thresholds = {}

        # Handle the new JSON structure
        if st.session_state.model_loaded:
            # Determine which model type key to use
            if "initial" in st.session_state.thresholds and "refined" in st.session_state.thresholds:
                model_type_key = "refined" if st.session_state.model_type == "full" else "initial"
                
                # Make sure the model_type_key is valid
                if model_type_key not in st.session_state.thresholds:
                    model_type_key = "refined" if "refined" in st.session_state.thresholds else "initial"
            else:
                model_type_key = None  # Old structure - access thresholds directly
            
            # Map profile display names to internal keys
            profile_key = None
            if threshold_profile == "Micro Optimized":
                profile_key = "micro_opt"
            elif threshold_profile == "Macro Optimized":
                profile_key = "macro_opt"
            elif threshold_profile == "Balanced":
                profile_key = "balanced"
            elif threshold_profile == "High Precision":
                profile_key = "high_precision"
            elif threshold_profile == "High Recall":
                profile_key = "high_recall"

            # For specialized profiles, get thresholds from the thresholds dictionary
            if profile_key:
                # Get overall threshold
                if model_type_key is not None:  # New structure
                    if "overall" in st.session_state.thresholds[model_type_key] and profile_key in st.session_state.thresholds[model_type_key]["overall"]:
                        active_threshold = st.session_state.thresholds[model_type_key]["overall"][profile_key]["threshold"]
                else:  # Old structure
                    if "overall" in st.session_state.thresholds and profile_key in st.session_state.thresholds["overall"]:
                        active_threshold = st.session_state.thresholds["overall"][profile_key]["threshold"]
                
                # Get category thresholds
                for category in st.session_state.categories:
                    if model_type_key is not None:  # New structure
                        if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                            if profile_key in st.session_state.thresholds[model_type_key]["categories"][category]:
                                active_category_thresholds[category] = st.session_state.thresholds[model_type_key]["categories"][category][profile_key]["threshold"]
                            else:
                                # Fallback to overall threshold if profile not found for this category
                                active_category_thresholds[category] = active_threshold
                        else:
                            active_category_thresholds[category] = active_threshold
                    else:  # Old structure
                        if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                            if profile_key in st.session_state.thresholds["categories"][category]:
                                active_category_thresholds[category] = st.session_state.thresholds["categories"][category][profile_key]["threshold"]
                            else:
                                active_category_thresholds[category] = active_threshold
                        else:
                            active_category_thresholds[category] = active_threshold

                # Show informational text for these profiles
                st.info(f"The '{threshold_profile}' profile uses pre-optimized thresholds.")
                
                # Show disabled slider for overall threshold (for informational purposes)
                st.slider(
                    "Overall threshold (reference)", 
                    min_value=0.01, 
                    max_value=1.0, 
                    value=float(active_threshold),
                    step=0.01,
                    disabled=True
                )

            elif threshold_profile == "Overall" and st.session_state.model_loaded:
                # Use the balanced threshold for Overall profile
                if model_type_key is not None:  # New structure
                    if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                        active_threshold = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
                else:  # Old structure
                    if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                        active_threshold = st.session_state.thresholds["overall"]["balanced"]["threshold"]
                
                # Show slider for adjusting the overall threshold
                active_threshold = st.slider(
                    "Overall threshold", 
                    min_value=0.01, 
                    max_value=1.0, 
                    value=float(active_threshold),
                    step=0.01
                )

            elif threshold_profile == "Weighted" and st.session_state.model_loaded:
                # Use the balanced threshold as base for Weighted profile
                if model_type_key is not None:  # New structure
                    if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                        active_threshold = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
                else:  # Old structure
                    if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                        active_threshold = st.session_state.thresholds["overall"]["balanced"]["threshold"]
                
                # Show disabled slider for overall threshold (for informational purposes)
                st.slider(
                    "Overall threshold (reference)", 
                    min_value=0.01, 
                    max_value=1.0, 
                    value=float(active_threshold),
                    step=0.01,
                    disabled=True
                )
                
                st.info("The 'Weighted' profile uses different optimized thresholds for each category.")
                
                # Get weighted thresholds if they exist, otherwise use balanced
                if model_type_key is not None:  # New structure
                    if "weighted" in st.session_state.thresholds[model_type_key]:
                        weighted_thresholds = st.session_state.thresholds[model_type_key]["weighted"]
                        for category in st.session_state.categories:
                            if category in weighted_thresholds:
                                active_category_thresholds[category] = weighted_thresholds[category]
                            else:
                                # Fallback to balanced threshold
                                if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                                    if "balanced" in st.session_state.thresholds[model_type_key]["categories"][category]:
                                        active_category_thresholds[category] = st.session_state.thresholds[model_type_key]["categories"][category]["balanced"]["threshold"]
                                    else:
                                        active_category_thresholds[category] = active_threshold
                                else:
                                    active_category_thresholds[category] = active_threshold
                else:  # Old structure
                    if "weighted" in st.session_state.thresholds:
                        weighted_thresholds = st.session_state.thresholds["weighted"]
                        for category in st.session_state.categories:
                            if category in weighted_thresholds:
                                active_category_thresholds[category] = weighted_thresholds[category]
                            else:
                                # Fallback to balanced threshold
                                if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                                    if "balanced" in st.session_state.thresholds["categories"][category]:
                                        active_category_thresholds[category] = st.session_state.thresholds["categories"][category]["balanced"]["threshold"]
                                    else:
                                        active_category_thresholds[category] = active_threshold
                                else:
                                    active_category_thresholds[category] = active_threshold

            elif threshold_profile == "Category-specific" and st.session_state.model_loaded:
                # Use the balanced threshold as base for Category-specific
                if model_type_key is not None:  # New structure
                    if "overall" in st.session_state.thresholds[model_type_key] and "balanced" in st.session_state.thresholds[model_type_key]["overall"]:
                        active_threshold = st.session_state.thresholds[model_type_key]["overall"]["balanced"]["threshold"]
                else:  # Old structure
                    if "overall" in st.session_state.thresholds and "balanced" in st.session_state.thresholds["overall"]:
                        active_threshold = st.session_state.thresholds["overall"]["balanced"]["threshold"]
                
                # Show disabled slider for overall threshold (for informational purposes)
                st.slider(
                    "Overall threshold (reference)", 
                    min_value=0.01, 
                    max_value=1.0, 
                    value=float(active_threshold),
                    step=0.01,
                    disabled=True
                )
                
                st.write("Adjust thresholds for individual categories:")
                
                # Create two columns for better layout of sliders
                slider_cols = st.columns(2)
                
                # Initialize with balanced thresholds
                for i, category in enumerate(sorted(st.session_state.categories)):
                    # Get the balanced threshold for this category
                    category_threshold = None
                    
                    if model_type_key is not None:  # New structure
                        if "categories" in st.session_state.thresholds[model_type_key] and category in st.session_state.thresholds[model_type_key]["categories"]:
                            if "balanced" in st.session_state.thresholds[model_type_key]["categories"][category]:
                                category_threshold = st.session_state.thresholds[model_type_key]["categories"][category]["balanced"]["threshold"]
                            else:
                                category_threshold = active_threshold
                        else:
                            category_threshold = active_threshold
                    else:  # Old structure
                        if "categories" in st.session_state.thresholds and category in st.session_state.thresholds["categories"]:
                            if "balanced" in st.session_state.thresholds["categories"][category]:
                                category_threshold = st.session_state.thresholds["categories"][category]["balanced"]["threshold"]
                            else:
                                category_threshold = active_threshold
                        else:
                            category_threshold = active_threshold
                    
                    # Add slider to appropriate column
                    col_idx = i % 2  # Alternate between columns
                    with slider_cols[col_idx]:
                        active_category_thresholds[category] = st.slider(
                            f"{category.capitalize()}", 
                            min_value=0.01, 
                            max_value=1.0, 
                            value=float(category_threshold),
                            step=0.01,
                            key=f"slider_{category}"
                        )
            
            # Update session state with the thresholds
            if active_threshold is not None:
                st.session_state.settings['active_threshold'] = active_threshold
            if active_category_thresholds:
                st.session_state.settings['active_category_thresholds'] = active_category_thresholds
        
        # Add threshold profile details expander
        with st.expander("Threshold Profile Details"):
            # Add tabs for the visualizations
            if st.session_state.model_loaded:
                threshold_tabs = st.tabs(["About Metrics"])
                
                with threshold_tabs[0]:
                    st.markdown("""
                    ### Understanding Performance Metrics
                    
                    **F1 Score** is the harmonic mean of precision and recall: `2 * (precision * recall) / (precision + recall)`
                    
                    **Micro F1** calculates metrics globally by considering each example/prediction pair. This gives more weight to categories with more examples.
                    
                    **Macro F1** calculates F1 separately for each category and then takes the average. This treats all categories equally regardless of their size.
                    """)
                    
                    st.markdown(create_micro_macro_comparison(), unsafe_allow_html=True)
                    
                    st.markdown("""
                    ### Other Metrics
                    
                    **Precision** measures how many of the predicted tags are correct: `true_positives / (true_positives + false_positives)`
                    
                    **Recall** measures how many of the relevant tags are captured: `true_positives / (true_positives + false_negatives)`
                    
                    ### The Precision-Recall Tradeoff
                    
                    There's an inherent tradeoff between precision and recall:
                    - Higher threshold → Higher precision, Lower recall
                    - Lower threshold → Lower precision, Higher recall
                    
                    The best threshold depends on your specific use case:
                    - **Prefer Precision**: When false positives are costly (e.g., you want only accurate tags)
                    - **Prefer Recall**: When false negatives are costly (e.g., you don't want to miss any potentially relevant tags)
                    - **Balanced**: When both types of errors are equally important
                    """)
            else:
                st.info("Load a model to see detailed threshold information.")
        
        # Display options
        display_options = st.expander("Display Options", expanded=False)
        with display_options:
            # Tag display options
            col1, col2 = st.columns(2)
            with col1:
                show_all_tags = st.checkbox("Show all tags (including below threshold)", 
                                        value=st.session_state.settings['show_all_tags'])
                compact_view = st.checkbox("Compact view (hide progress bars)", 
                                        value=st.session_state.settings['compact_view'])
                
                # Add the new checkbox for replacing underscores with spaces
                replace_underscores = st.checkbox("Replace underscores with spaces", 
                                            value=st.session_state.settings.get('replace_underscores', False))
            
            with col2:
                min_confidence = st.slider("Minimum confidence to display", 0.0, 0.5, 
                                        st.session_state.settings['min_confidence'], 0.01)
            
            # Update session state with display options
            st.session_state.settings['show_all_tags'] = show_all_tags
            st.session_state.settings['compact_view'] = compact_view
            st.session_state.settings['min_confidence'] = min_confidence
            st.session_state.settings['replace_underscores'] = replace_underscores
            
            # Category selection for the "All Tags" section
            st.write("Categories to include in 'All Tags' section:")
            
            # Create a multi-column layout for category checkboxes
            category_cols = st.columns(3)
            selected_categories = {}
            
            # If categories exist in session state, create checkboxes for each
            if hasattr(st.session_state, 'categories'):
                for i, category in enumerate(sorted(st.session_state.categories)):
                    col_idx = i % 3  # Distribute across 3 columns
                    with category_cols[col_idx]:
                        # Use previously selected value or default to True
                        default_val = st.session_state.settings['selected_categories'].get(category, True)
                        selected_categories[category] = st.checkbox(
                            f"{category.capitalize()}", 
                            value=default_val,
                            key=f"cat_select_{category}"
                        )
                
                # Update session state with selected categories
                st.session_state.settings['selected_categories'] = selected_categories
        
        if st.session_state.model_loaded:
            if st.session_state.model_type == "onnx":
                model_type_display = "ONNX Accelerated Model"
            elif st.session_state.model_type == "full":
                model_type_display = "Full Model"
            else:
                model_type_display = "Initial-Only Model (Lower VRAM)"
            
            st.info(f"Using: {model_type_display}")
        
        # Run inference button for single image
        if image_path and st.button("Run Tagging"):
            if not st.session_state.model_loaded:
                st.error("Model not loaded. Please check the model settings.")
            else:
                with st.spinner("Analyzing image..."):
                    try:
                        inference_start = time.time()
                        
                        # Different processing based on model type
                        if st.session_state.model_type == "onnx":
                            # Use the appropriate function for ONNX inference
                            from utils.onnx_processing import process_single_image_onnx
                            
                            # Run ONNX inference
                            result = process_single_image_onnx(
                                image_path=image_path,
                                model_path=st.session_state.onnx_model_path,
                                metadata=st.session_state.metadata,
                                threshold_profile=threshold_profile,
                                active_threshold=active_threshold,
                                active_category_thresholds=active_category_thresholds,
                                min_confidence=min_confidence
                            )
                        else:
                            # Run standard PyTorch inference
                            result = process_image(
                                image_path=image_path,
                                model=st.session_state.model,
                                thresholds=st.session_state.thresholds,
                                metadata=st.session_state.metadata,
                                threshold_profile=threshold_profile,
                                active_threshold=active_threshold,
                                active_category_thresholds=active_category_thresholds,
                                min_confidence=min_confidence
                            )
                        
                        inference_time = time.time() - inference_start
                        
                        if result['success']:
                            # Store results in session state
                            st.session_state.all_probs = result['all_probs']
                            st.session_state.tags = result['tags']
                            st.session_state.all_tags = result['all_tags']
                            
                            st.success(f"Analysis completed in {inference_time:.2f} seconds")
                        else:
                            st.error(f"Inference failed: {result.get('error', 'Unknown error')}")
                            
                    except Exception as e:
                        st.error(f"Inference error: {str(e)}")
                        st.code(traceback.format_exc())
        
        # Display the predictions if available
        if image_path and hasattr(st.session_state, 'all_probs'):
            st.header("Predictions")
            
            # Apply current thresholds to stored probabilities
            filtered_tags, current_all_tags = apply_thresholds(
                st.session_state.all_probs,
                threshold_profile,
                active_threshold,
                active_category_thresholds,
                min_confidence,
                st.session_state.settings['selected_categories']
            )
            
            # Store the updated results back to session state
            st.session_state.tags = filtered_tags
            st.session_state.all_tags = current_all_tags
            
            # Create an empty list to collect all tags that pass the thresholds
            # We'll rebuild this list as we process each category
            all_tags = []
            
            for category in sorted(st.session_state.all_probs.keys()):
                # Get all tags for this category and the filtered ones
                all_tags_in_category = st.session_state.all_probs.get(category, [])
                filtered_tags_in_category = filtered_tags.get(category, [])
                
                # Only show categories with tags
                if all_tags_in_category:
                    # Get the appropriate threshold for this category
                    if threshold_profile in ["Overall", "Weighted"]:
                        threshold = active_threshold
                    else:
                        threshold = active_category_thresholds.get(category, active_threshold)
                    
                    # Create expander with count information
                    expander_label = f"{category.capitalize()} ({len(filtered_tags_in_category)} tags)"
                    
                    with st.expander(expander_label, expanded=True):
                        # Add threshold control specific to this category
                        threshold_row = st.columns([1, 2])
                        with threshold_row[0]:
                            # Display the current threshold
                            pass
                        
                        with threshold_row[1]:
                            # Always show category slider regardless of threshold profile
                            cat_slider_key = f"cat_threshold_{category}"
                            
                            # For the initial value, respect the threshold profile
                            if threshold_profile in ["Overall", "Weighted"]:
                                # In these modes, start with the global threshold value
                                current_cat_threshold = active_threshold
                            else:
                                # In other modes, use the category-specific threshold
                                current_cat_threshold = active_category_thresholds.get(category, active_threshold)
                            
                            # Add a slider for this specific category
                            new_threshold = st.slider(
                                f"Adjust {category.capitalize()} threshold:", 
                                min_value=0.01,
                                max_value=1.0,
                                value=float(current_cat_threshold),
                                step=0.01,
                                key=cat_slider_key,
                                disabled=(threshold_profile in ["Overall", "Weighted"])  # Disable in Overall/Weighted modes
                            )
                            
                            # If in Overall/Weighted mode, add an explanation
                            if threshold_profile in ["Overall", "Weighted"]:
                                st.info(f"Using global {threshold_profile.lower()} threshold. Switch to Category-specific mode to adjust individual categories.")
                            else:
                                # In other modes, update the category threshold
                                active_category_thresholds[category] = new_threshold
                                threshold = new_threshold
                            
                            # Update the active_category_thresholds with the new value
                            active_category_thresholds[category] = new_threshold
                            
                            # Very important: Update the threshold variable for this iteration of the loop
                            # This ensures the new threshold is used in this category's display
                            threshold = new_threshold
                        
                        # Determine which tags to display based on show_all_tags setting
                        if show_all_tags:
                            tags_to_display = all_tags_in_category
                        else:
                            # Refilter the tags based on the updated threshold
                            # This ensures the display immediately reflects threshold changes
                            tags_to_display = [(tag, prob) for tag, prob in all_tags_in_category if prob >= threshold]
                            filtered_tags[category] = tags_to_display
                            
                        # Add per-category limit controls
                        limit_col1, limit_col2 = st.columns([1, 2])
                        with limit_col1:
                            # Generate a unique key for each category's limit checkbox
                            limit_key = f"limit_{category}_tags"
                            limit_tags_for_category = st.checkbox("Limit tags", value=False, key=limit_key)
                        
                        with limit_col2:
                            # Generate a unique key for each category's tag count slider
                            slider_key = f"top_n_{category}_tags"
                            
                            # Handle the slider values carefully to avoid Streamlit errors
                            tag_count = len(tags_to_display)
                            
                            # Skip slider if there are no tags to display
                            if tag_count > 0:
                                # Set sensible min and max values that avoid errors
                                min_value = 0
                                # Make sure max_value is at least 1 (Streamlit requires min < max)
                                max_value = max(1, min(999, tag_count))
                                # Default value should be between min and max
                                default_value = min(max_value, 5)  # Default to 5 tags if available
                                
                                top_n_tags_for_category = st.slider(
                                    "Show top", 
                                    min_value=min_value, 
                                    max_value=max_value,
                                    value=default_value, 
                                    step=1,
                                    disabled=not limit_tags_for_category,
                                    key=slider_key
                                )
                            else:
                                # If no tags, just set a default value without showing the slider
                                top_n_tags_for_category = 5
                                st.write("No tags to display")
                        
                        st.markdown("---")  # Add separator line after controls
                        
                        if not tags_to_display:
                            st.info(f"No tags above {min_confidence:.2f} confidence threshold")
                            continue
                        
                        # Apply the per-category limit if enabled
                        original_count = len(tags_to_display)
                        if limit_tags_for_category and tags_to_display:
                            limited_tags_to_display = tags_to_display[:top_n_tags_for_category]
                            display_count = len(limited_tags_to_display)
                        else:
                            limited_tags_to_display = tags_to_display
                            display_count = original_count
                        
                        # Display tags based on view mode
                        if compact_view:
                            # Compact view - show tags in a comma-separated list with %
                            tag_list = []

                            replace_underscores = st.session_state.settings.get('replace_underscores', False)
                            for tag, prob in limited_tags_to_display:
                                # Format: tag (percent%)
                                percentage = int(prob * 100)
                                
                                # Apply underscore replacement for display if enabled
                                display_tag = tag.replace('_', ' ') if replace_underscores else tag
                                tag_list.append(f"{display_tag} ({percentage}%)")
                                
                                # Add tag to all_tags list if it passes threshold and category is selected
                                # Note: always use original tag (with underscores) for all_tags collection
                                if prob >= threshold and selected_categories.get(category, True):
                                    all_tags.append(tag)

                            # Join with commas and display
                            st.markdown(", ".join(tag_list))
                        else:
                            # Expanded view with progress bars
                            for tag, prob in limited_tags_to_display:
                                # Get the replacement setting 
                                replace_underscores = st.session_state.settings.get('replace_underscores', False)
                                
                                # Apply underscore replacement for display if enabled
                                display_tag = tag.replace('_', ' ') if replace_underscores else tag
                                
                                # Add tag to all_tags list if it passes threshold and category is selected
                                if prob >= threshold and selected_categories.get(category, True):
                                    all_tags.append(tag)  # Add original tag to all_tags
                                    tag_display = f"**{display_tag}**"  # Bold for tags above threshold
                                else:
                                    tag_display = display_tag  # Regular for tags below threshold
                                
                                # Display tag with progress bar
                                st.write(tag_display)
                                st.markdown(display_progress_bar(prob), unsafe_allow_html=True)
                        
                        # If we're limiting tags and there are more available, show a message
                        if limit_tags_for_category and original_count > display_count:
                            st.caption(f"Showing top {display_count} of {original_count} qualifying tags.")
            
            # Show summary at bottom with the truly updated all_tags list
            st.markdown("---")
            st.subheader(f"All Tags ({len(all_tags)} total)")
            if all_tags:
                # Check if underscore replacement is enabled
                replace_underscores = st.session_state.settings.get('replace_underscores', False)
                
                if replace_underscores:
                    # Create a new list with underscores replaced by spaces for display only
                    display_tags = [tag.replace('_', ' ') for tag in all_tags]
                    st.write(", ".join(display_tags))
                else:
                    # Display original tags
                    st.write(", ".join(all_tags))
            else:
                st.info("No tags detected above the threshold.")

            # Add Save Tags section
            st.markdown("---")
            st.subheader("Save Tags")

            # Create column for save options
            save_col = st.columns(1)[0] 

            with save_col:
                # Option to save to custom location
                if 'custom_folders' not in st.session_state:
                    # Initialize with default save locations
                    st.session_state.custom_folders = get_default_save_locations()
                
                # Display folder selection dropdown
                selected_folder = st.selectbox(
                    "Select save location:",
                    options=st.session_state.custom_folders,
                    format_func=lambda x: os.path.basename(x) if os.path.basename(x) else x
                )
                
                # Allow adding a new folder path
                new_folder = st.text_input("Or enter a new folder path:")
                
                if st.button("Add Folder", key="add_folder") and new_folder:
                    if os.path.isdir(new_folder):
                        if new_folder not in st.session_state.custom_folders:
                            st.session_state.custom_folders.append(new_folder)
                            st.success(f"Added folder: {new_folder}")
                            st.rerun()
                        else:
                            st.info("This folder is already in the list.")
                    else:
                        try:
                            # Try to create the folder if it doesn't exist
                            os.makedirs(new_folder, exist_ok=True)
                            st.session_state.custom_folders.append(new_folder)
                            st.success(f"Created and added folder: {new_folder}")
                            st.rerun()
                        except Exception as e:
                            st.error(f"Could not create folder: {str(e)}")
                
                # Save to selected location button
                if st.button("💾 Save to Selected Location"):
                    try:
                        # Get the original filename if it exists
                        original_filename = st.session_state.original_filename if hasattr(st.session_state, 'original_filename') else None
                        
                        # Save tags to file in selected location
                        saved_path = save_tags_to_file(
                            image_path=image_path,
                            all_tags=all_tags,
                            original_filename=original_filename,
                            custom_dir=selected_folder,
                            overwrite=True
                        )
                        
                        st.success(f"Tags saved to: {os.path.basename(saved_path)}")
                        st.info(f"Full path: {saved_path}")

                        # Show preview of saved file
                        with st.expander("File Contents", expanded=True):
                            with open(saved_path, 'r', encoding='utf-8') as f:
                                content = f.read()
                            st.code(content, language='text')
                            
                    except Exception as e:
                        st.error(f"Error saving tags: {str(e)}")
                        st.code(traceback.format_exc())

if __name__ == "__main__":
    image_tagger_app()