File size: 88,843 Bytes
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
 
 
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7043411
6c9a052
 
 
 
 
 
351c5e3
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351c5e3
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
6c9a052
 
 
 
 
 
 
570a57c
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
6c9a052
 
 
 
 
 
 
 
bb334c7
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
6c9a052
bb334c7
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
6c9a052
 
 
 
bb334c7
6c9a052
144c4c0
6c9a052
 
 
351c5e3
 
bb334c7
 
 
 
144c4c0
 
6c9a052
 
 
bb334c7
 
6c9a052
 
bb334c7
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
 
 
 
 
6c9a052
 
 
 
bb334c7
6c9a052
 
 
 
 
bb334c7
6c9a052
 
 
 
 
 
bb334c7
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78e073
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cfb45c
6c9a052
 
 
 
 
 
 
 
 
 
 
e78e073
 
 
 
 
 
 
 
 
3cfb45c
570a57c
 
3cfb45c
 
 
e78e073
 
 
 
570a57c
 
e78e073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
e78e073
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549b11b
6c9a052
 
 
 
 
 
 
 
549b11b
 
6c9a052
 
 
 
 
351c5e3
 
549b11b
 
 
 
 
 
 
 
351c5e3
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
6c9a052
 
 
 
549b11b
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7043411
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bb3b2d
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
6c9a052
d98e7b3
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78e073
 
6c9a052
e78e073
 
6c9a052
 
e78e073
6c9a052
 
 
 
 
7043411
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
785ad91
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78e073
3cfb45c
144c4c0
785ad91
549b11b
785ad91
 
549b11b
 
 
785ad91
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549b11b
 
 
6c9a052
e78e073
6c9a052
 
 
 
 
 
 
 
785ad91
6c9a052
 
 
 
 
785ad91
6c9a052
 
351c5e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549b11b
 
 
351c5e3
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
549b11b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
bb334c7
 
6c9a052
 
 
 
 
 
 
 
 
 
 
549b11b
6c9a052
549b11b
 
 
 
6c9a052
 
 
 
 
 
 
 
549b11b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
bb334c7
 
 
 
 
351c5e3
bb334c7
 
 
 
 
 
351c5e3
 
 
 
 
bb334c7
351c5e3
 
 
bb334c7
 
 
 
144c4c0
bb334c7
 
 
144c4c0
bb334c7
 
7043411
bb334c7
 
 
549b11b
bb334c7
 
351c5e3
 
 
 
 
 
549b11b
351c5e3
549b11b
 
bb334c7
351c5e3
 
 
 
 
 
bb334c7
351c5e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb334c7
6c9a052
 
 
 
 
 
 
 
 
 
 
 
bb334c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
 
 
7043411
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e78e073
 
6c9a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144c4c0
785ad91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9a052
 
 
bb334c7
 
 
 
 
6c9a052
 
 
 
 
bb334c7
6c9a052
 
 
 
 
 
 
 
bb334c7
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
"""
ui_nicegui.py
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
NiceGUI ๅ‰็ซฏๅฑ‚๏ผˆ้‡ๆž„็‰ˆ๏ผ‰ใ€‚

โ–ธ ๅช่ดŸ่ดฃๆธฒๆŸ“ / ไบคไบ’ใ€‚
โ–ธ ่ฐƒ็”จ core.engine.DanbooruTagger๏ผŒ้€š่ฟ‡ core.models ็š„ๆ•ฐๆฎ็ป“ๆž„้€šไฟกใ€‚
โ–ธ ไธๅŒ…ๅซไปปไฝ•็ฎ—ๆณ•้€ป่พ‘ใ€‚
โ–ธ ๅนณๅฐ็›ธๅ…ณ้…็ฝฎ๏ผˆhost/port/ไบ‘็ซฏๅˆคๆ–ญ๏ผ‰็ปŸไธ€็”ฑ platform_utils ๆไพ›ใ€‚
"""
import sys
sys.stdout.reconfigure(line_buffering=True)
print("[UI] ่„šๆœฌๅผ€ๅง‹ๆ‰ง่กŒ", flush=True)
import asyncio
import os
import json as _json
import subprocess
import traceback
from dataclasses import asdict
from fastapi.responses import PlainTextResponse

def _excepthook(exc_type, exc_value, exc_tb):
    print("[UI] FATAL ERROR ON STARTUP:", flush=True)
    traceback.print_exception(exc_type, exc_value, exc_tb)
    sys.__excepthook__(exc_type, exc_value, exc_tb)

sys.excepthook = _excepthook

from nicegui import ui, app, run
from core import counter
from api_fastapi import app as api_app
from core.engine import DanbooruTagger
from core.models import RelatedTag, SearchRequest
from platform_utils import is_cloud, get_host_port, nsfw_allowed
from mcp_server import mcp

import logging
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logging.getLogger("mcp").setLevel(logging.WARNING)
logging.getLogger("mcp.server").setLevel(logging.WARNING)
logging.getLogger("fastmcp").setLevel(logging.WARNING)
# suppress MCP streamable-HTTP transport noise ("No response returned" from Starlette middleware)
class _SuppressMCPNoise(logging.Filter):
    _MARKER = "No response returned"

    def filter(self, record: logging.LogRecord) -> bool:
        if self._MARKER in record.getMessage():
            return False
        if record.exc_info:
            import traceback
            tb_text = "".join(traceback.format_exception(*record.exc_info))
            if self._MARKER in tb_text:
                return False
        return True

logging.getLogger("uvicorn.error").addFilter(_SuppressMCPNoise())

# โ”€โ”€ ่กจๆ ผๅˆ—ๅฎšไน‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

TABLE_COLUMNS = [
    {'name': 'tag',         'label': 'ๅŒน้…ๆ ‡็ญพ', 'field': 'tag',         'align': 'left', 'sortable': True},
    {'name': 'cn_name',     'label': 'ๅซไน‰',     'field': 'cn_name',     'align': 'left'},
    {'name': 'nsfw',        'label': 'ๅˆ†็บง',     'field': 'nsfw',        'align': 'center', 'sortable': True},
    {'name': 'final_score', 'label': '็ปผๅˆๅˆ†',   'field': 'final_score', 'sortable': True},
    {'name': 'count',       'label': '็ƒญๅบฆ',     'field': 'count',       'sortable': True},
]

OPTIONAL_COLS = {
    'semantic': {'name': 'semantic_score', 'label': '่ฏญไน‰ๅˆ†',   'field': 'semantic_score', 'sortable': True},
    'layer':    {'name': 'layer',          'label': 'ๅŒน้…ๅฑ‚',   'field': 'layer'},
    'source':   {'name': 'source',         'label': 'ๅŒน้…ๆฅๆบ', 'field': 'source'},
}

# localStorage key ไธŽ้…็ฝฎ็‰ˆๆœฌ๏ผŒ็‰ˆๆœฌๅ˜ๆ›ดๆ—ถ่‡ชๅŠจไธขๅผƒๆ—ง้…็ฝฎ
_CONFIG_LS_KEY = 'danbooru_search_config'
_CONFIG_VERSION = 5

# ๆœ็ดขๆจกๅผ้ข„่ฎพ
_SEARCH_MODE_PRESETS: dict[str, dict] = {
    '็ฒพ็กฎๆŸฅ่ฏ': {'top_k': 20, 'limit': 10, 'popularity_weight': 0.15, 'use_segmentation': False, 'group_mode': 'off', 'max_per_group': 2},
    'ๆฆ‚ๅฟตๆ‰ฉๅฑ•': {'top_k': 80, 'limit': 80, 'popularity_weight': 0.15, 'use_segmentation': True,  'group_mode': 'expand', 'max_per_group': 2},
    'ๆ่ฟฐๆŸฅ่ฏ': {'top_k': 20, 'limit': 20, 'popularity_weight': 0.15, 'use_segmentation': False, 'group_mode': 'off', 'max_per_group': 2},
    'ๅฎŒๆ•ดๅœบๆ™ฏ': {'top_k': 5,  'limit': 80, 'popularity_weight': 0.15, 'use_segmentation': True,  'group_mode': 'diverse', 'max_per_group': 2},
}
_SEARCH_MODE_OPTIONS = ['่‡ชๅฎšไน‰'] + list(_SEARCH_MODE_PRESETS.keys())



# โ”€โ”€ ่พ…ๅŠฉๅ‡ฝๆ•ฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _get_git_commit() -> str:
    try:
        return subprocess.check_output(
            ['git', 'rev-parse', '--short', 'HEAD'],
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()
    except Exception:
        return os.environ.get('COMMIT_SHA', 'unknown')[:7]


def result_to_row(r, nsfw_visible: bool) -> dict:
    d = asdict(r)
    d['_nsfw_blocked'] = (r.nsfw == '1') and not nsfw_visible
    return d


def apply_nsfw_filter(rows: list[dict], show_nsfw: bool) -> list[dict]:
    result = []
    for row in rows:
        r = dict(row)
        r['_nsfw_blocked'] = (r.get('nsfw') == '1') and not show_nsfw
        result.append(r)
    return result


def _format_tag_with_weight(tag: str, weight: float, fmt: str = 'sdxl') -> str:
    """ๆ ผๅผๅŒ–ๅ•ไธชๆ ‡็ญพใ€‚
    sdxl: (tag:1.2)  ๆƒ้‡ 1.0 ๆ—ถ่พ“ๅ‡บ tag
    nai:  1.2::tag:: ๆƒ้‡ 1.0 ๆ—ถ่พ“ๅ‡บ tag
    """
    if weight == 1.0:
        return tag
    if fmt == 'nai':
        return f'{weight:.1f}::{tag}::'
    return f'({tag}:{weight:.1f})'


# โ”€โ”€ UI ็ฑป โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class DanbooruSearchUI:
    def __init__(self):
        self.search_count_label = None
        self.current_search_interacted = True

        self.full_table_data: list[dict] = []
        self.current_segments: list[str] = []   # ไปŽๅฅ็บงๅŽŸๅง‹็‰‡ๆฎต๏ผŒ็”จไบŽๅŒบๅˆ† chip ้ขœ่‰ฒ
        self.current_filter_keyword: str = 'ALL'  # ๅฝ“ๅ‰้€‰ไธญ็š„ๅˆ†่ฏ็ญ›้€‰ keyword๏ผˆNSFW ๅˆ‡ๆขๆ—ถๅค็”จ๏ผ‰
        self.current_query_str: str = ""
        self.full_tags_str: str = ""
        self.full_tags_str_sfw: str = ""

        self.result_table = None           # ๅทฆๆ ่กจๆ ผ
        self.related_list_container = None  # ๅณๆ ๅ…ณ่”ๆŽจ่ๅˆ—่กจ
        self.group_expansion_container = None  # ๅทฆๆ  Group ๅŒ็ฑปๆ‰ฉๅฑ•๏ผˆ่กจๆ ผไธ‹ๆ–น๏ผ‰
        self.results_section = None        # ๆ•ดไธช็ป“ๆžœๅŒบๅŸŸ๏ผˆๆœ็ดขๅ‰้š่—๏ผ‰
        self.selection_count_label = None
        self.selected_display = None       # ๅทฒๅบŸๅผƒ textarea๏ผŒไฟ็•™ๅ…ผๅฎน
        self.selected_chips_container = None  # ๅทฒ้€‰ๆ ‡็ญพ chip ๅฎนๅ™จ
        self.current_related: list = []
        self.chip_extra_selected: set = set()

        # tag -> prompt ๆƒ้‡๏ผŒ่Œƒๅ›ด [0.1, 1.9]๏ผŒ้ป˜่ฎค 1.0
        self.tag_weights: dict[str, float] = {}
        # ๅคๅˆถๆ ผๅผ๏ผš'sdxl' ๆˆ– 'nai'
        self.prompt_format: str = 'sdxl'
        self.format_toggle_btn = None

        self.init_banner = None
        self.input_top_k = None
        self.input_limit = None
        self.input_weight = None
        self.input_nsfw = None
        self.input_segment = None
        self.input_search_mode = None
        self.input_group_mode = None
        self.input_max_per_group = None
        self._applying_preset = False
        self.search_input = None
        self.keywords_container = None
        self.spinner = None
        self.search_btn = None

        self.selected_layers = {'่‹ฑๆ–‡': True, 'ไธญๆ–‡ๆ‰ฉๅฑ•่ฏ': True, '้‡Šไน‰': True, 'ไธญๆ–‡ๆ ธๅฟƒ่ฏ': True}
        self.selected_cats = {'General': True, 'Copyright': True, 'Character': True}

        self.bad_case_btn = None

        self.mcp_notice = None
        self.notice_expansion = None

        # ่กจๆ ผๆ˜พ็คบ้€‰้กนๅผ€ๅ…ณ
        self.sw_semantic = None
        self.sw_layer = None
        self.sw_source = None

        # ๅ…ณ่”ๆŽจ่็š„ checkbox ๅผ•็”จ
        self._related_checkboxes: dict[str, ui.checkbox] = {}
        # ๅŒ็ฑปๆ ‡็ญพ็š„ checkbox ๅผ•็”จ
        self._group_checkboxes: dict[str, ui.checkbox] = {}

        # ้ซ˜็บง้€‰้กนไธญๅ„ๅฑ‚/็ฑปๅž‹็š„ checkbox ๅผ•็”จ๏ผŒ็”จไบŽ restore ๆ—ถๅŒๆญฅๆŽงไปถ็Šถๆ€
        self._layer_checkboxes: dict[str, ui.checkbox] = {}
        self._cat_checkboxes: dict[str, ui.checkbox] = {}

    def _update_footer_text(self):
        if self.search_count_label is not None:
            try:
                total = counter.get()
                visits = counter.get_visits()
                commit = _get_git_commit()
                self.search_count_label.content = (
                    f'็ดฏ่ฎกๆœ็ดข {total:,} ๆฌก | ็ดฏ่ฎก่ฎฟ้—ฎ {visits:,} ๆฌก | '
                    f'<span class="font-mono text-gray-300">็‰ˆๆœฌๅท: {commit}</span>'
                    f'<br>'
                    f'<a href="/api/docs" '
                    f'target="_blank" rel="noopener noreferrer" '
                    f'class="text-blue-400 hover:text-blue-600 hover:underline">ไฝฟ็”จ API ๆœๅŠก</a>'
                    f' | <a href="https://github.com/SuzumiyaAkizuki/DanbooruSearchOnline#mcp-ๆŽฅๅฃ" '
                    f'target="_blank" rel="noopener noreferrer" '
                    f'class="text-blue-400 hover:text-blue-600 hover:underline">ไฝฟ็”จ MCP ๆœๅŠก</a>'
                )
            except AttributeError:
                pass

    def _mark_interaction(self, e=None):
        if not self.current_search_interacted:
            self.current_search_interacted = True

            async def silent_success_update():
                try:
                    await counter.increment_success()
                except Exception:
                    pass
            asyncio.create_task(silent_success_update())

    # โ”€โ”€ ๅˆ†้กต่พ…ๅŠฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _get_rows_per_page(self) -> int:
        if self.result_table is None:
            return 0
        p = self.result_table.pagination
        # pagination ๅฏ่ƒฝๆ˜ฏ int ๆˆ– dict
        if isinstance(p, dict):
            return int(p.get('rowsPerPage', 0))
        return int(p) if p else 0

    def _set_rows_per_page(self, value: int):
        if self.result_table is None:
            return
        allowed = {5, 7, 10, 15, 20, 25, 50, 0}  # 0 = All
        value = value if value in allowed else 0
        p = self.result_table.pagination
        if isinstance(p, dict):
            p['rowsPerPage'] = value
            self.result_table.pagination = p
        else:
            self.result_table.pagination = value

    # โ”€โ”€ ้…็ฝฎๆŒไน…ๅŒ– โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _save_config(self):
        """ๅฐ†ๅฝ“ๅ‰ๆŽงไปถ็Šถๆ€ๅบๅˆ—ๅŒ–ๅนถๅ†™ๅ…ฅ localStorageใ€‚"""
        cfg = {
            'version': _CONFIG_VERSION,
            'top_k': int(self.input_top_k.value) if self.input_top_k else 10,
            'limit': int(self.input_limit.value) if self.input_limit else 80,
            'popularity_weight': float(self.input_weight.value) if self.input_weight else 0.15,
            'show_nsfw': bool(self.input_nsfw.value) if self.input_nsfw else False,
            'use_segmentation': bool(self.input_segment.value) if self.input_segment else True,
            'selected_layers': dict(self.selected_layers),
            'selected_cats': dict(self.selected_cats),
            'sw_semantic': bool(self.sw_semantic.value) if self.sw_semantic else False,
            'sw_layer': bool(self.sw_layer.value) if self.sw_layer else False,
            'sw_source': bool(self.sw_source.value) if self.sw_source else False,
            'prompt_format': self.prompt_format,
            'rows_per_page': self._get_rows_per_page(),
            'search_query': self.search_input.value if self.search_input else '',
            'notice_expanded': bool(self.notice_expansion.value) if self.notice_expansion else True,
            'mcp_notice_dismissed': not bool(self.mcp_notice.visible) if self.mcp_notice else False,
            'search_mode': self.input_search_mode.value if self.input_search_mode else '่‡ชๅฎšไน‰',
            'group_mode': self.input_group_mode.value if self.input_group_mode else 'off',
            'max_per_group': int(self.input_max_per_group.value) if self.input_max_per_group else 2,
        }
        js = _json.dumps(cfg, ensure_ascii=False)
        ui.run_javascript(f"localStorage.setItem('{_CONFIG_LS_KEY}', {_json.dumps(js)});")

    async def _restore_config(self):
        """ไปŽ localStorage ่ฏปๅ–้…็ฝฎๅนถๆขๅคๆŽงไปถ็Šถๆ€ใ€‚"""
        try:
            if getattr(ui.context.client, '_deleted', False):
                return
            raw = await ui.run_javascript(
                f"localStorage.getItem('{_CONFIG_LS_KEY}');",
                timeout=5.0,
            )
        except Exception:
            return

        if not raw:
            return

        try:
            cfg = _json.loads(raw)
        except Exception:
            return

        if cfg.get('version') != _CONFIG_VERSION:
            # ็‰ˆๆœฌไธ็ฌฆ๏ผŒไธขๅผƒๆ—ง้…็ฝฎ
            ui.run_javascript(f"localStorage.removeItem('{_CONFIG_LS_KEY}');")
            return

        # ๆขๅคๆœ็ดขๆจกๅผ๏ผˆไผš่งฆๅ‘้ข„่ฎพๅกซๅ……๏ผŒไฝ† _applying_preset ้˜ฒๆญข่”ๅŠจ่ฆ†็›–๏ผ‰
        if self.input_search_mode and 'search_mode' in cfg:
            self.input_search_mode.set_value(cfg['search_mode'])

        if self.input_top_k and 'top_k' in cfg:
            self.input_top_k.set_value(cfg['top_k'])
        if self.input_limit and 'limit' in cfg:
            self.input_limit.set_value(cfg['limit'])
        if self.input_weight and 'popularity_weight' in cfg:
            self.input_weight.set_value(cfg['popularity_weight'])
        if self.input_segment and 'use_segmentation' in cfg:
            self.input_segment.set_value(cfg['use_segmentation'])
        if self.input_group_mode and 'group_mode' in cfg:
            self.input_group_mode.set_value(cfg['group_mode'])
        if self.input_max_per_group and 'max_per_group' in cfg:
            self.input_max_per_group.set_value(cfg['max_per_group'])

        # NSFW๏ผšไป…ๅœจๅนณๅฐๅ…่ฎธๆ—ถๆขๅค
        if nsfw_allowed() and self.input_nsfw and 'show_nsfw' in cfg:
            self.input_nsfw.set_value(cfg['show_nsfw'])

        if 'selected_layers' in cfg:
            for layer, val in cfg['selected_layers'].items():
                if layer in self.selected_layers:
                    self.selected_layers[layer] = bool(val)
                    if layer in self._layer_checkboxes:
                        self._layer_checkboxes[layer].set_value(bool(val))

        if 'selected_cats' in cfg:
            for cat, val in cfg['selected_cats'].items():
                if cat in self.selected_cats:
                    self.selected_cats[cat] = bool(val)
                    if cat in self._cat_checkboxes:
                        self._cat_checkboxes[cat].set_value(bool(val))

        if self.sw_semantic and 'sw_semantic' in cfg:
            self.sw_semantic.set_value(cfg['sw_semantic'])
        if self.sw_layer and 'sw_layer' in cfg:
            self.sw_layer.set_value(cfg['sw_layer'])
        if self.sw_source and 'sw_source' in cfg:
            self.sw_source.set_value(cfg['sw_source'])

        if 'prompt_format' in cfg and cfg['prompt_format'] in ('sdxl', 'nai'):
            self.prompt_format = cfg['prompt_format']
            if self.format_toggle_btn:
                if self.prompt_format == 'nai':
                    self.format_toggle_btn.text = 'NAI'
                    self.format_toggle_btn.props('color=purple-7')
                else:
                    self.format_toggle_btn.text = 'SDXL'
                    self.format_toggle_btn.props('color=grey-7')

        if 'rows_per_page' in cfg:
            self._set_rows_per_page(cfg['rows_per_page'])

        if self.search_input and cfg.get('search_query'):
            self.search_input.set_value(cfg['search_query'])

        if self.notice_expansion and 'notice_expanded' in cfg:
            self.notice_expansion.set_value(cfg['notice_expanded'])

        if self.mcp_notice and cfg.get('mcp_notice_dismissed'):
            self.mcp_notice.set_visibility(False)

        # ่‹ฅ้ซ˜็บง้€‰้กนๅˆ—ๆœ‰ๅ˜ๆ›ด๏ผŒๅŒๆญฅๆ›ดๆ–ฐ่กจๆ ผๅˆ—
        self._update_table_columns()

    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
    # ้กต้ขๆž„ๅปบ
    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

    def build_page(self):
        ui.colors(primary='#4A90E2', secondary='#5E6C84', accent='#FF6B6B')
        ui.add_head_html('''
            <meta name="description" content="ๅŸบไบŽ่ฏญไน‰ๅŒน้…็š„ Danbooru ๆ ‡็ญพๆœ็ดขๅผ•ๆ“Ž๏ผŒๆ”ฏๆŒไธญ่‹ฑๅŒ่ฏญๆ่ฟฐใ€ๅคš็ปดๅŒน้…ใ€ๆ™บ่ƒฝๅˆ†่ฏไธŽๅ…ฑ็Žฐๅ…ณ่”ๆŽจ่ใ€‚">
            <meta name="keywords" content="Danbooru, AI็ป˜็”ป, Stable Diffusion, ๆ็คบ่ฏ, ๆ ‡็ญพๆœ็ดข, RAG, Prompt, NovelAI">
            <meta name="google-site-verification" content="cx4sl9Mb172GUFL556JFwKCP-pT3naQcmlMriy5B8ls" />

            <style>
                .nsfw-blur-cell      { filter: blur(8px); opacity: 0.5; transition: all 0.3s ease;
                                       pointer-events: none !important; user-select: none !important; }
                .nsfw-checkbox-disabled { pointer-events: none !important; opacity: 0.3 !important; }
                .nsfw-row-blocked    { cursor: not-allowed !important; }
                .related-item { transition: background-color 0.15s ease; }
                .related-item:hover { background-color: rgba(74, 144, 226, 0.04); }
                .tag-link { text-decoration: none; font-family: 'Consolas', 'Monaco', 'Courier New', monospace; }
                .tag-link:hover { text-decoration: underline; }
                .weight-chip { display: inline-flex; align-items: center; gap: 2px;
                               border-radius: 16px; padding: 2px 6px 2px 4px;
                               background: #e3edf7; border: 1px solid #b3cde8;
                               font-size: 12px; margin: 3px; white-space: nowrap; }
                .weight-chip.boosted  { background: #fff3e0; border-color: #ffb74d; }
                .weight-chip.reduced  { background: #f3e5f5; border-color: #ce93d8; }
                .weight-btn { cursor: pointer; width: 18px; height: 18px; border-radius: 50%;
                              display: inline-flex; align-items: center; justify-content: center;
                              font-size: 13px; font-weight: bold; line-height: 1;
                              border: none; background: rgba(0,0,0,0.08);
                              color: #555; transition: background 0.15s; padding: 0; }
                .weight-btn:hover { background: rgba(0,0,0,0.18); }
                .weight-label { font-family: Consolas, Monaco, monospace; font-size: 11px;
                                color: #888; min-width: 28px; text-align: center; }

                /* ๅผบๅˆถๅŒๆ ๅนถๆŽ’ */
                .two-col-layout {
                    display: flex !important;
                    flex-wrap: nowrap !important;
                    align-items: flex-start !important;
                    gap: 16px !important;
                }
                .two-col-layout > .col-left {
                    flex: 0 0 62% !important;
                    min-width: 0 !important;
                    max-width: 62% !important;
                    overflow: hidden;
                }
                .two-col-layout > .col-right {
                    flex: 0 0 36% !important;
                    min-width: 0 !important;
                    max-width: 36% !important;
                    overflow: hidden;
                }

                /* ็ช„ๅฑๅ›ž้€€ไธบไธŠไธ‹ๆŽ’ๅˆ— */
                @media (max-width: 900px) {
                    .two-col-layout {
                        flex-wrap: wrap !important;
                    }
                    .two-col-layout > .col-left,
                    .two-col-layout > .col-right {
                        flex: 1 1 100% !important;
                        max-width: 100% !important;
                    }
                }
            </style>
            <script async src="https://www.googletagmanager.com/gtag/js?id=G-QPB7EEPR5G"></script>
            <script>
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', 'G-QPB7EEPR5G');
            </script>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    function openExternal(root) {
                        root.querySelectorAll('a[href^="http"]').forEach(function(a) {
                            a.setAttribute('target', '_blank');
                            a.setAttribute('rel', 'noopener noreferrer');
                        });
                    }
                    openExternal(document);
                    new MutationObserver(function(mutations) {
                        mutations.forEach(function(m) {
                            m.addedNodes.forEach(function(node) {
                                if (node.querySelectorAll) openExternal(node);
                            });
                        });
                    }).observe(document.body, { childList: true, subtree: true });
                });
            </script>
        ''')

        with ui.column().classes('w-full max-w-7xl mx-auto p-4 gap-4'):

            # โ”€โ”€ ๅˆๅง‹ๅŒ–ๆ็คบ โ”€โ”€
            self.init_banner = ui.card().classes(
                'w-full bg-blue-50 border-l-4 border-blue-400'
            )
            with self.init_banner:
                with ui.row().classes('items-center gap-3 p-2'):
                    ui.spinner(size='sm')
                    ui.label('ๅผ•ๆ“Žๅˆๅง‹ๅŒ–ไธญ๏ผŒ่ฏท็จๅ€™โ€ฆ้ฆ–ๆฌกๅŠ ่ฝฝ็บฆ้œ€ 15 ็ง’').classes('text-sm text-blue-700')
            self.init_banner.set_visibility(not DanbooruTagger.is_ready())
            if not DanbooruTagger.is_ready():
                asyncio.ensure_future(self._hide_banner_when_ready())

            # โ”€โ”€ 0. ๅ…ฌๅ‘Šๆ ๏ผˆๅŒ็ฑปๆ ‡็ญพ + MCP๏ผ‰โ”€โ”€
            self._build_group_notice()

            # โ”€โ”€ 1. ๆณจๆ„ไบ‹้กน โ”€โ”€
            self._build_notice()

            # โ”€โ”€ 2. ๆœ็ดขๅก็‰‡ โ”€โ”€
            self._build_search_card()

            # โ”€โ”€ 3~5. ็ป“ๆžœๅŒบๅŸŸ๏ผˆๆœ็ดขๅ‰้š่—๏ผ‰โ”€โ”€
            self.results_section = ui.column().classes('w-full gap-4')
            self.results_section.set_visibility(False)

            with self.results_section:
                # โ”€โ”€ 3. ๅทฒ้€‰ๆ ‡็ญพๆ  โ”€โ”€
                self._build_selection_bar()

                # โ”€โ”€ 4. ๅˆ†่ฏ็ญ›้€‰ chips โ”€โ”€
                self.keywords_container = ui.row().classes('gap-2 items-center flex-wrap')

                # โ”€โ”€ 5. ไธคๆ ็ป“ๆžœ โ”€โ”€
                self._build_results_columns()

            # โ”€โ”€ 6. ๅบ•้ƒจ โ”€โ”€
            with ui.element('div').classes('w-full text-center py-4 mt-2'):
                self.search_count_label = ui.html('ๆญฃๅœจๅŠ ่ฝฝๆ•ฐๆฎ...').classes('text-xs text-gray-400')
                self._update_footer_text()

    # โ”€โ”€ MCP ไธŠ็บฟ้€š็Ÿฅ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _build_group_notice(self):
        self.mcp_notice = ui.card().classes(
            'w-full bg-green-50 border-l-4 border-green-500 p-0 overflow-hidden'
        )
        with self.mcp_notice:
            with ui.column().classes('px-4 py-3 w-full gap-2'):
                with ui.row().classes('items-center justify-between w-full'):
                    ui.label('๐Ÿงช ๆ–ฐๅŠŸ่ƒฝ๏ผšๆ ‡็ญพ็ป„ๆ‰ฉๅฑ•๏ผˆbeta๏ผ‰').classes('text-sm font-bold text-green-800')
                    ui.button(icon='close').props('flat dense round color=grey-6') \
                        .on_click(self._dismiss_mcp_notice)
                ui.html(
                    'ๅ‹พ้€‰ๆ ‡็ญพๅŽ๏ผŒๆœ็ดข็ป“ๆžœไธ‹ๆ–นไผšๅ‡บ็Žฐ<b>ๅŒ็ฑปๆ ‡็ญพ</b>ๅŒบๅŸŸ๏ผŒ'
                    'ๅฑ•็คบๅทฒ้€‰ๆ ‡็ญพๆ‰€ๅฑžๅˆ†็ป„ไธญ็š„ๅ…ถไป–ๆ ‡็ญพใ€‚<b>ๅ‹พ้€‰ๅค้€‰ๆก†</b>ๅณๅฏๅŠ ๅ…ฅๅทฒ้€‰๏ผŒ'
                    '้€‰ไธญ็š„ๆ ‡็ญพไผšๅŠ ๅ…ฅๅทฒ้€‰ๅˆ—่กจ๏ผŒๅฏ็›ดๆŽฅๅคๅˆถไธบ Promptใ€‚'
                ).classes('text-xs text-green-900')
                ui.separator().classes('my-1')
                ui.html(
                    'ใ€MCP ๆœๅŠกๅทฒไธŠ็บฟใ€‘ ๆ”ฏๆŒ้€š่ฟ‡ MCP ๅ่ฎฎๆŽฅๅ…ฅ AI Agent๏ผˆๅฆ‚ Claude Desktop๏ผ‰ใ€‚'
                    'ๅ…้…็ฝฎๆ‰˜็ฎก็‰ˆไฝ“้ชŒ๏ผš'
                    '<a href="https://huggingface.co/spaces/SAkizuki/WenQiuYue" '
                    'target="_blank" rel="noopener noreferrer" '
                    'class="text-green-700 font-bold underline">้—ฎ็ง‹ๆœˆ Space</a>๏ผŒ'
                    '<span class="text-gray-500 ml-1">API ้ขๅบฆๆœ‰้™๏ผŒไป…ไพ›ไฝ“้ชŒใ€‚</span>'
                    '&nbsp;'
                    '<a href="https://github.com/SuzumiyaAkizuki/DanbooruSearchOnline#mcp-ๆŽฅๅฃ" '
                    'target="_blank" rel="noopener noreferrer" '
                    'class="text-green-700 underline">ๆŽฅๅ…ฅๆ–‡ๆกฃ โ†’</a>'
                ).classes('text-xs text-green-900')

    def _dismiss_mcp_notice(self):
        if self.mcp_notice:
            self.mcp_notice.set_visibility(False)
        self._save_config()

    # โ”€โ”€ ๆณจๆ„ไบ‹้กน โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _build_notice(self):
        with ui.card().classes('w-full bg-orange-50 border-l-4 border-orange-500 p-0 overflow-hidden'):
            with ui.expansion(value=True).classes('w-full') as notice_expansion:
                self.notice_expansion = notice_expansion
                notice_expansion.on('update:model-value', lambda _: self._save_config())
                notice_expansion.add_slot('header', '''
                    <div class="flex items-center gap-2 px-4 py-2 w-full flex-wrap">
                        <span class="text-base font-bold text-orange-800">โš ๏ธ ๆณจๆ„ไบ‹้กน / Note</span>
                        <span v-if="!props.expanded" class="text-sm text-gray-600 ml-1">
                             ๅฆ‚ๆžœ่ง‰ๅพ—ๅฅฝ็”จ๏ผŒ่ฏท็‚นๅ‡ป้กถ้ƒจ็ป™ๆœฌ Space ็‚นไธช
                            <strong>Like โค๏ธ</strong>๏ผŒๆˆ–ๅ‰ๅพ€ GitHub ็‚นไธช <strong>Star โญ</strong>๏ผ
                        </span>
                    </div>
                ''')
                ui.markdown("""
- **AI ่พ…ๅŠฉ**๏ผšๅŸบไบŽ่ฏญไน‰ๅŒน้…๏ผŒ็ป“ๆžœๆœชๅฟ…็ปๅฏนๅ‡†็กฎ(Results may contain errors)
- **ๅ†…ๅฎน่ญฆๅ‘Š**๏ผšๆŸฅๆ‰พ็ป“ๆžœๅฏ่ƒฝๅŒ…ๅซ NSFW ๅ†…ๅฎน (May include NSFW content)
- **ๆฃ€็ดข้™ๅˆถ**๏ผšไป…ๆ”ฏๆŒไธญ/่‹ฑๅŒ่ฏญๆŸฅๆ‰พ ๏ผŒๆ›ดๆŽจ่ไธญๆ–‡(CN/EN only,CN is preferred)
- **ๆ ‡็ญพ่Œƒๅ›ด**๏ผšไป…ๆ˜พ็คบ็‰นๅพใ€่ง’่‰ฒไธŽไฝœๅ“ๆ ‡็ญพ๏ผŒไธ”้ข‘ๆ•ฐ้กป โ‰ฅ 100 (General, Character & Copyright only, Freq โ‰ฅ 100)
- **้›†ๆˆไธŽๆŽฅๅฃ**๏ผš[ComfyUI ๆ’ไปถ](https://github.com/SuzumiyaAkizuki/ComfyUI-DanbooruSearcher) ยท [API ๆ–‡ๆกฃ](/api/docs) ยท [MCP ๆŽฅๅ…ฅ](https://github.com/SuzumiyaAkizuki/DanbooruSearchOnline#mcp-ๆŽฅๅฃ)
- **ๆ”ฏๆŒไฝœ่€…**๏ผšๅฆ‚ๆžœ่ง‰ๅพ—ๅฅฝ็”จ๏ผŒๆฌข่ฟŽ็‚นๅ‡ป้กถ้ƒจ็ป™ๆœฌ Space ็‚นไธช **Like โค๏ธ**๏ผŒๆˆ–ๅ‰ๅพ€ [GitHub](https://github.com/SuzumiyaAkizuki/DanbooruSearchOnline) ็‚นไธช **Star โญ**๏ผ
- **๐Ÿš€ ้ฆ–ๆฌกไฝฟ็”จ๏ผŸ[็‚นๅ‡ปๆŸฅ็œ‹ไฝฟ็”จๆŒ‡ๅ—](https://github.com/SuzumiyaAkizuki/DanbooruSearchOnline)**๏ผŒไบ†่งฃไบ”็งๆœ็ดขๆจกๅผไธŽ่ฟ›้˜ถๆŠ€ๅทง
""").classes('text-sm text-gray-800 px-4 pb-3')

    # โ”€โ”€ ๆœ็ดขๅก็‰‡ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _build_search_card(self):
        with ui.card().classes('w-full'):
            with ui.row().classes('items-center gap-2 mb-2'):
                ui.icon('search', size='2em', color='primary')
                ui.label('Danbooru ๆ ‡็ญพๆจก็ณŠๆœ็ดข').classes('text-2xl font-bold text-gray-800')
            ui.label('ๅŸบไบŽ่ฏญไน‰ๅŒน้…็š„ๆ ‡็ญพๆœ็ดขๅผ•ๆ“Ž๏ผŒๆ”ฏๆŒๅคš็ปดๅŒน้…ไธŽๅ…ฑ็Žฐๅ…ณ่”ๆŽจ่ใ€‚').classes(
                'text-sm text-gray-500 -mt-1 mb-3'
            )

            with ui.row().classes('w-full gap-3 items-stretch'):
                self.search_input = ui.textarea(
                    placeholder='่พ“ๅ…ฅ่‡ช็„ถ่ฏญ่จ€ๆ่ฟฐๆˆ–ๆจก็ณŠๆฆ‚ๅฟต๏ผŒไพ‹ๅฆ‚๏ผšไธ€ไธช็ฉฟ็€็™ฝ่‰ฒๆฐดๆ‰‹ๆœ็š„ๅฐ‘ๅฅณๅœจ้›จไธญๅฅ”่ท‘...'
                ).classes('flex-grow text-base').props('outlined rows=2')
                self.search_input.on('keydown.ctrl.enter', self.perform_search)

                with ui.column().classes('justify-center'):
                    self.search_btn = ui.button(
                        '', on_click=self.perform_search, icon='search'
                    ).classes('px-6 h-full min-h-16').props('unelevated color=dark')
                    with self.search_btn:
                        ui.label('ๆœ็ดข').classes('text-sm mt-1')
                    self.spinner = ui.spinner(size='2em').classes('hidden')

            with ui.row().classes('w-full gap-6 items-center mt-3 flex-wrap'):
                with ui.row().classes('items-center gap-2'):
                    ui.label('ๆœ็ดขๆจกๅผ (beta)').classes('text-sm text-gray-600')
                    self.input_search_mode = ui.select(
                        _SEARCH_MODE_OPTIONS, value='่‡ชๅฎšไน‰',
                    ).classes('w-28').props('outlined dense')
                    self.input_search_mode.on('update:model-value', self._on_search_mode_change)
                    with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                        ui.label('้€‰ๆ‹ฉๆจกๅผ่‡ชๅŠจๅกซๅ……ๅฏนๅบ”ๅ‚ๆ•ฐ๏ผ›ๆ‰‹ๅŠจไฟฎๆ”นๅ‚ๆ•ฐๅŽ่‡ชๅŠจๅ˜ไธบใ€Œ่‡ชๅฎšไน‰ใ€').style('font-size:14px;')

                with ui.row().classes('items-center gap-2'):
                    ui.label('Top K (่ฏญไน‰็›ธๅ…ณ)').classes('text-sm text-gray-600')
                    self.input_top_k = ui.number(value=10, min=1, max=200).classes('w-20') \
                        .props('outlined dense')
                    self.input_top_k.on('update:model-value', self._on_param_changed)

                with ui.row().classes('items-center gap-2'):
                    ui.label('็ป“ๆžœไธŠ้™').classes('text-sm text-gray-600')
                    self.input_limit = ui.number(value=80, min=10, max=500).classes('w-20') \
                        .props('outlined dense')
                    self.input_limit.on('update:model-value', self._on_param_changed)

                with ui.row().classes('items-center gap-2'):
                    ui.label('็ƒญๅบฆๆƒ้‡').classes('text-sm text-gray-600')
                    self.input_weight = ui.slider(min=0.0, max=1.0, value=0.15, step=0.05).classes('w-32')
                    ui.label().bind_text_from(self.input_weight, 'value', lambda v: f"{v:.2f}") \
                        .classes('text-sm font-mono text-gray-700 w-8')
                    self.input_weight.on('update:model-value', self._on_param_changed)

                with ui.switch('ๆ˜พ็คบ NSFW(ๆˆไบบ) ๅ†…ๅฎน', value=False).props('color=red') as _nsfw_sw:
                    if not nsfw_allowed():
                        with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                            ui.label('NSFW ๅ†…ๅฎนๅœจๅฝ“ๅ‰ๅนณๅฐไธๅฏ็”จ').style('font-size:14px;')
                self.input_nsfw = _nsfw_sw
                if not nsfw_allowed():
                    self.input_nsfw.disable()
                else:
                    self.input_nsfw.on('update:model-value', self.on_nsfw_toggle)

                with ui.switch('ๆ™บ่ƒฝๅˆ†่ฏ', value=True).props('color=primary') as _seg_sw:
                    with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                        ui.label('ๅ…ณ้—ญๅŽ็ณป็ปŸๅฐ†ๅชๅŒน้…ๅฎŒๆ•ดๅฅๅญ๏ผŒ้€‚็”จไบŽ็ฒพๅ‡†ๆœ็ดขๆ•ดๅฅใ€‚').style('font-size:14px;')
                self.input_segment = _seg_sw
                self.input_segment.on('update:model-value', self._on_param_changed)

            with ui.expansion('้ซ˜็บง้€‰้กน', icon='tune').classes('w-full mt-2'):
                with ui.column().classes('w-full p-3 gap-4'):
                    with ui.row().classes('w-full gap-8 flex-wrap'):
                        with ui.column().classes('gap-2'):
                            ui.label('ๅŒน้…ๅฑ‚็ญ›้€‰').classes('font-bold text-sm text-gray-700')
                            display_map = {
                                '่‹ฑๆ–‡': '่‹ฑๆ–‡ๆ ‡็ญพ', 'ไธญๆ–‡ๆ‰ฉๅฑ•่ฏ': 'ไธญๆ–‡ๆ‰ฉๅฑ•่ฏ',
                                '้‡Šไน‰': '็ปดๅŸบ้‡Šไน‰', 'ไธญๆ–‡ๆ ธๅฟƒ่ฏ': 'ไธญๆ–‡ๆ ธๅฟƒ่ฏ',
                            }
                            for layer in ['่‹ฑๆ–‡', 'ไธญๆ–‡ๆ‰ฉๅฑ•่ฏ', '้‡Šไน‰', 'ไธญๆ–‡ๆ ธๅฟƒ่ฏ']:
                                cb = ui.checkbox(
                                    display_map.get(layer, layer), value=True,
                                    on_change=lambda e, l=layer: self.selected_layers.__setitem__(l, e.value)
                                ).props('color=primary dense')
                                self._layer_checkboxes[layer] = cb

                        with ui.column().classes('gap-2'):
                            ui.label('็ฑปๅž‹็ญ›้€‰').classes('font-bold text-sm text-gray-700')
                            color_map = {'General': 'blue', 'Copyright': 'pink', 'Character': 'green'}
                            label_map = {
                                'General': '้€š็”จ (General)',
                                'Copyright': 'ไฝœๅ“ (Copyright)',
                                'Character': '่ง’่‰ฒ (Character)',
                            }
                            for cat in ['General', 'Copyright', 'Character']:
                                cb = ui.checkbox(
                                    label_map[cat], value=True,
                                    on_change=lambda e, c=cat: self.selected_cats.__setitem__(c, e.value)
                                ).props(f'color={color_map[cat]} dense')
                                self._cat_checkboxes[cat] = cb

                        with ui.column().classes('gap-2'):
                            ui.label('่กจๆ ผๆ˜พ็คบๅˆ—').classes('font-bold text-sm text-gray-700')
                            self.sw_semantic = ui.switch('ๆ˜พ็คบ่ฏญไน‰ๅˆ†', value=False)
                            self.sw_layer    = ui.switch('ๆ˜พ็คบๅŒน้…ๅฑ‚', value=False)
                            self.sw_source   = ui.switch('ๆ˜พ็คบๅŒน้…ๆฅๆบ', value=False)
                            self.sw_semantic.on('update:model-value', self._update_table_columns)
                            self.sw_layer.on('update:model-value', self._update_table_columns)
                            self.sw_source.on('update:model-value', self._update_table_columns)

                        with ui.column().classes('gap-2'):
                            ui.label('ๆ ‡็ญพๅˆ†็ป„ๆจกๅผ (beta)').classes('font-bold text-sm text-gray-700')
                            self.input_group_mode = ui.select(
                                ['off', 'expand', 'diverse'], value='off',
                            ).classes('w-40').props('outlined dense')
                            with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                                ui.label('off=ๅ…ณ้—ญ | expand=ๅŒ็ฑปๅฌๅ›žๅขžๅผบ | diverse=ๅคšๆ ทๆ€ง็บฆๆŸ').style('font-size:14px;')
                            self.input_group_mode.on('update:model-value', self._on_param_changed)

                            self.input_max_per_group = ui.number(
                                value=2, min=1, max=10,
                            ).classes('w-20').props('outlined dense')
                            ui.label('ๆฏ็ป„ๆœ€ๅคงๆ ‡็ญพๆ•ฐ๏ผˆdiverse ๆจกๅผ๏ผ‰').classes('text-xs text-gray-500')
                            self.input_max_per_group.on('update:model-value', self._on_param_changed)

    # โ”€โ”€ ๅทฒ้€‰ๆ ‡็ญพๆ  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _build_selection_bar(self):
        with ui.card().classes('w-full bg-blue-50 border border-blue-200'):
            with ui.row().classes('w-full items-center justify-between'):
                with ui.row().classes('items-center gap-2'):
                    ui.icon('check_circle', color='primary')
                    ui.label('ๅทฒ้€‰ๆ ‡็ญพ').classes('font-bold text-primary')
                    self.selection_count_label = ui.label('0').classes(
                        'bg-primary text-white px-2 rounded-full text-sm')
                    with ui.icon('info_outline', size='sm', color='grey').classes('cursor-help'):
                        with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                            ui.html(
                                '็‚นๅ‡ป <b>โˆ’</b> / <b>+</b> ๅฏ่ฐƒๆ•ดๆ ‡็ญพๆƒ้‡๏ผˆๆญฅ้•ฟ 0.1๏ผŒ่Œƒๅ›ด 0.1~1.9๏ผ‰ใ€‚<br>'
                                'ๆƒ้‡ 1.0 ๆ—ถ่พ“ๅ‡บๅŽŸๅง‹ๆ ‡็ญพ๏ผ›ๅ…ถไฝ™่พ“ๅ‡บ <code>(tag:1.2)</code> ๆ ผๅผใ€‚'
                            ).style('font-size:14px;line-height:1.6;')

                with ui.row().classes('items-center gap-2'):
                    with ui.button('ๆฒกๆœๅˆฐ๏ผŸ', icon='help_outline').props('dense flat color=grey-6').classes('text-sm') as _bad_btn:
                        with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                            ui.html('็‚นๅ‡ปๆญคๅค„ไปฅๅ้ฆˆๅคฑ่ดฅๆกˆไพ‹ใ€‚<br>ๆ‚จ็š„ๆœ็ดข่ฏๅฐ†่ขซๅŒฟๅๆ”ถ้›†็”จไบŽไผ˜ๅŒ–ๅผ•ๆ“Ž๏ผˆไธๅŒ…ๅซไธชไบบ้š็ง๏ผ‰ใ€‚').style('font-size:14px;line-height:1.5;')
                    self.bad_case_btn = _bad_btn
                    self.bad_case_btn.disable()
                    self.bad_case_btn.on_click(self.report_bad_case)
                    self.format_toggle_btn = ui.button(
                        'SDXL', icon='swap_horiz'
                    ).props('dense flat color=grey-7').classes('text-xs font-mono')
                    with self.format_toggle_btn:
                        with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                            ui.html(
                                'ๅˆ‡ๆขๅคๅˆถๆ ผๅผ๏ผš<br>'
                                '<b>SDXL</b>๏ผš<code>(tag:1.2)</code><br>'
                                '<b>NAI</b>๏ผš<code>1.2::tag::</code>'
                            ).style('font-size:13px;line-height:1.7;')
                    self.format_toggle_btn.on_click(self._toggle_prompt_format)
                    clear_btn = ui.button('ๆธ…็ฉบๅทฒ้€‰', icon='delete_sweep').props('dense flat color=red-7').classes('text-xs')
                    clear_btn.on_click(self._clear_all_staged)
                    copy_btn = ui.button('ๅคๅˆถ้€‰ไธญ', icon='content_copy').props('dense unelevated color=primary')
                    copy_btn.on_click(self.copy_selection)

            # chip ๅฎนๅ™จ๏ผšๆฏไธชๅทฒ้€‰ๆ ‡็ญพๆธฒๆŸ“ไธบไธ€ไธชๅธฆๅŠ ๅ‡ๆŒ‰้’ฎ็š„ chip
            self.selected_chips_container = ui.element('div').classes(
                'w-full mt-2 min-h-10 p-1 rounded bg-white border border-blue-100 flex flex-wrap'
            )

    def _render_selected_chips(self):
        """้‡ๆ–ฐๆธฒๆŸ“ๅทฒ้€‰ๆ ‡็ญพ็š„ chip ๅˆ—่กจใ€‚"""
        if self.selected_chips_container is None:
            return
        self.selected_chips_container.clear()
        tags = self._get_selected_tags()
        if not tags:
            with self.selected_chips_container:
                ui.label('ๆš‚ๆ— ๅทฒ้€‰ๆ ‡็ญพ').classes('text-xs text-gray-400 italic p-2 self-center')
            return
        with self.selected_chips_container:
            for tag in tags:
                w = self.tag_weights.get(tag, 1.0)
                extra_cls = 'boosted' if w > 1.0 else ('reduced' if w < 1.0 else '')
                w_str = f'{w:.1f}'
                with ui.element('div').classes(f'weight-chip {extra_cls}'):
                    # ๅˆ ้™คๆŒ‰้’ฎ๏ผˆร—๏ผ‰
                    with ui.element('button').classes('weight-btn').props(f'title="็งป้™ค {tag}"').on(
                        'click', lambda t=tag: self._remove_selected_tag(t)
                    ):
                        ui.html('&times;')
                    # ๅ‡ๅท
                    with ui.element('button').classes('weight-btn').on(
                        'click', lambda t=tag: self._adjust_weight(t, -0.1)
                    ):
                        ui.html('&minus;')
                    # ๆ ‡็ญพๅ
                    ui.label(tag).style(
                        'font-family:Consolas,Monaco,monospace;font-size:12px;'
                        'color:#2c5282;max-width:150px;overflow:hidden;'
                        'text-overflow:ellipsis;white-space:nowrap;'
                    )
                    # ๆƒ้‡ๅ€ผ๏ผˆไป…้ž 1.0 ๆ—ถๆ˜พ็คบ๏ผ‰
                    if w != 1.0:
                        ui.label(w_str).classes('weight-label').style('color:#e65100;font-weight:bold;')
                    # ๅŠ ๅท
                    with ui.element('button').classes('weight-btn').on(
                        'click', lambda t=tag: self._adjust_weight(t, +0.1)
                    ):
                        ui.html('&plus;')

    def _adjust_weight(self, tag: str, delta: float):
        """่ฐƒๆ•ดๅ•ไธชๆ ‡็ญพๆƒ้‡๏ผŒ้’ณไฝๅˆฐ [0.1, 1.9]ใ€‚"""
        current = self.tag_weights.get(tag, 1.0)
        new_w = round(current + delta, 1)
        if new_w < 0.1:
            ui.notify('ๆƒ้‡่Œƒๅ›ดไธบ 0.1 ~ 1.9๏ผŒๅทฒๅˆฐ่พพๆœ€ๅฐๅ€ผ', type='warning', timeout=2000)
            return
        if new_w > 1.9:
            ui.notify('ๆƒ้‡่Œƒๅ›ดไธบ 0.1 ~ 1.9๏ผŒๅทฒๅˆฐ่พพๆœ€ๅคงๅ€ผ', type='warning', timeout=2000)
            return
        self.tag_weights[tag] = new_w
        self._save_staged_tags()
        self._render_selected_chips()

    def _remove_selected_tag(self, tag: str):
        """ไปŽๅทฒ้€‰ไธญ็งป้™คๆ ‡็ญพ๏ผˆๅŒๆญฅ่กจๆ ผ้€‰ไธญ็Šถๆ€๏ผ‰ใ€‚"""
        self._mark_interaction()
        current = self._get_selected_tags()
        if tag in current:
            current.remove(tag)
        self.tag_weights.pop(tag, None)
        self._set_selected_tags(current)

    # โ”€โ”€ ๅค‡้€‰ๅŒบๆŒไน…ๅŒ– โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    _STAGED_LS_KEY = 'danbooru_staged_tags'

    def _save_staged_tags(self):
        """ๅฐ†ๅทฒ้€‰ๆ ‡็ญพๅŠๅ…ถๆƒ้‡ไฟๅญ˜ๅˆฐ localStorageใ€‚"""
        tags = self._get_selected_tags()
        weights = {t: self.tag_weights.get(t, 1.0) for t in tags}
        data = _json.dumps({'tags': tags, 'weights': weights}, ensure_ascii=False)
        try:
            if getattr(ui.context.client, '_deleted', False):
                return
            ui.run_javascript(f"localStorage.setItem('{self._STAGED_LS_KEY}', {_json.dumps(data)});")
        except RuntimeError:
            pass  # ไบ‹ไปถไธŠไธ‹ๆ–‡ๅทฒ้”€ๆฏ๏ผˆUI ้‡ๅปบไธญ๏ผ‰๏ผŒๆ•ฐๆฎไปๅœจๅ†…ๅญ˜้‡Œ๏ผŒไธ‹ๆฌกไฟๅญ˜ๆ—ถไผšๅŒๆญฅ

    async def _restore_staged_tags(self):
        """ไปŽ localStorage ๆขๅคๅทฒ้€‰ๆ ‡็ญพใ€‚"""
        try:
            if getattr(ui.context.client, '_deleted', False):
                return
            raw = await ui.run_javascript(
                f"localStorage.getItem('{self._STAGED_LS_KEY}');",
                timeout=5.0,
            )
        except Exception:
            return
        if not raw:
            return
        try:
            data = _json.loads(raw)
        except Exception:
            return
        tags = data.get('tags', [])
        weights = data.get('weights', {})
        if not tags:
            return
        self.chip_extra_selected.update(tags)
        for t in tags:
            self.tag_weights[t] = weights.get(t, 1.0)
        self._render_selected_chips()
        if self.selection_count_label is not None:
            self.selection_count_label.text = str(len(tags))

    def _clear_all_staged(self):
        """ๆธ…็ฉบๆ‰€ๆœ‰ๅทฒ้€‰ๆ ‡็ญพใ€‚"""
        self._mark_interaction()
        self.chip_extra_selected.clear()
        self.tag_weights.clear()
        if self.result_table is not None:
            self.result_table.selected = []
        self._render_selected_chips()
        if self.selection_count_label is not None:
            self.selection_count_label.text = '0'
        show_nsfw_val = self.input_nsfw.value
        self._refresh_related([], show_nsfw_val)
        # ๆธ…็ฉบ Group ๅŒ็ฑปๆ‰ฉๅฑ•
        if self.group_expansion_container is not None:
            self.group_expansion_container.clear()
            with self.group_expansion_container:
                ui.label('่ฏทๅ…ˆๆœ็ดขๅนถๅ‹พ้€‰ๆ ‡็ญพโ€ฆ').classes('text-sm text-gray-400 italic p-4')
        self._save_staged_tags()
        ui.notify('ๅทฒๆธ…็ฉบๆ‰€ๆœ‰ๅทฒ้€‰ๆ ‡็ญพ', type='warning')

        # โ”€โ”€ ไธคๆ ็ป“ๆžœ๏ผˆCSS ๅผบๅˆถๅนถๆŽ’๏ผ‰โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _build_results_columns(self):
        with ui.element('div').classes('w-full two-col-layout'):
            # โ”€โ”€ ๅทฆๆ ๏ผš่ฏญไน‰ๅŒน้…็ป“ๆžœ๏ผˆ่กจๆ ผ๏ผ‰โ”€โ”€
            with ui.card().classes('col-left'):
                with ui.row().classes('items-center justify-between mb-2 w-full'):
                    ui.label('ๅŒน้…ๆ ‡็ญพ็ป“ๆžœ').classes('font-bold text-lg text-gray-800')
                    ui.button('ๅคๅˆถๅ…จ้ƒจๆ ‡็ญพ', icon='content_copy', on_click=self._copy_all_tags) \
                        .props('dense flat color=primary').classes('text-sm')

                self.result_table = ui.table(
                    columns=TABLE_COLUMNS,
                    rows=[],
                    pagination=0,
                    selection='multiple',
                    row_key='tag',
                ).classes('w-full')
                self.result_table.on('selection', self._update_selection_display)
                self.result_table.on('link_click', self._mark_interaction)
                self.result_table.on('pagination', lambda _: self._save_config())

                # ่‡ชๅฎšไน‰่กŒๆจกๆฟ๏ผš่กŒ่ƒŒๆ™ฏ่‰ฒๆŒ‰ๅˆ†็ฑป๏ผŒๆ•ด่กŒๆ‚ฌๆตฎๆ˜พ็คบ wiki๏ผˆNSFWๆจก็ณŠ่กŒ้™คๅค–๏ผ‰
                self.result_table.add_slot('body', r'''
                    <q-tr :props="props"
                          :class="props.row._nsfw_blocked ? 'nsfw-row-blocked' : ''"
                          :style="{
                              'background-color':
                                  props.row.category === 'General'   ? 'rgba(59,130,246,0.06)' :
                                  props.row.category === 'Character' ? 'rgba(34,197,94,0.06)'  :
                                  props.row.category === 'Copyright' ? 'rgba(236,72,153,0.06)' : ''
                          }">
                        <q-td auto-width>
                            <q-checkbox v-model="props.selected"
                                :class="props.row._nsfw_blocked ? 'nsfw-checkbox-disabled' : ''"/>
                        </q-td>
                        <q-td v-for="col in props.cols" :key="col.name" :props="props">
                            <template v-if="col.name === 'tag' || col.name === 'cn_name'">
                                <div :class="props.row._nsfw_blocked ? 'nsfw-blur-cell' : ''">
                                    <template v-if="col.name === 'cn_name' && col.value">
                                        <span style="font-size:14px">
                                            {{ col.value.split(',')[0] }}
                                        </span>
                                    </template>
                                    <template v-else-if="col.name === 'tag'">
                                        <a :href="'https://danbooru.donmai.us/wiki_pages/'+col.value"
                                           target="_blank"
                                           class="text-primary hover:underline font-bold inline-flex items-center"
                                           style="text-decoration:none; font-family: Consolas, Monaco, Courier New, monospace;"
                                           @click.stop="$emit('link_click', col.value)">
                                            {{ col.value }}
                                            <q-icon name="open_in_new" size="xs" class="q-ml-xs opacity-50"/>
                                        </a>
                                    </template>
                                    <template v-else>{{ col.value }}</template>
                                </div>
                            </template>
                            <template v-else-if="col.name === 'nsfw'">
                                <div v-if="col.value === '1'" class="text-red-500">๐Ÿ”ด</div>
                                <div v-else class="text-green-500">๐ŸŸข</div>
                            </template>
                            <template v-else-if="col.name === 'final_score'">
                                <q-badge :color="col.value > 0.6 ? 'green' : (col.value > 0.5 ? 'teal' : 'orange')">
                                    {{ col.value }}
                                </q-badge>
                            </template>
                            <template v-else>{{ col.value }}</template>
                        </q-td>
                        <q-tooltip v-if="(props.row.wiki || props.row.cn_name) && !props.row._nsfw_blocked"
                            content-class="bg-black text-white shadow-4"
                            max-width="500px" :offset="[10,10]">
                            <div style="font-size:14px;line-height:1.5;">
                                <span style="opacity:0.7;margin-right:4px;">{{
                                    props.row.category === 'General'   ? '[้€š็”จ]' :
                                    props.row.category === 'Character' ? '[่ง’่‰ฒ]' :
                                    props.row.category === 'Copyright' ? '[ไฝœๅ“]' : ''
                                }}</span>{{ props.row.wiki }}
                                <div v-if="props.row.cn_name"
                                     style="margin-top:6px;opacity:0.85;">{{ props.row.cn_name }}</div>
                            </div>
                        </q-tooltip>
                    </q-tr>
                ''')

                # โ”€โ”€ Group ๅŒ็ฑปๆ‰ฉๅฑ•๏ผˆๅทฆๆ ๏ผŒ่กจๆ ผไธ‹ๆ–น๏ผ‰โ”€โ”€
                ui.separator().classes('my-2')
                with ui.row().classes('items-center justify-between w-full mb-1'):
                    with ui.row().classes('items-center gap-2'):
                        ui.label('ๅŒ็ฑปๆ ‡็ญพ (beta)').classes('font-bold text-sm text-gray-600')
                        with ui.icon('info_outline', size='xs', color='grey').classes('cursor-help'):
                            with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                                ui.label('ๅŸบไบŽๆ ‡็ญพๅˆ†็ป„ๆ•ฐๆฎ๏ผŒๅฑ•็คบๅทฒ้€‰ๆ ‡็ญพๆ‰€ๅฑžๅˆ†็ป„ไธญ็š„ๅ…ถไป–ๆ ‡็ญพใ€‚ๅ‹พ้€‰ๅฏๅŠ ๅ…ฅๅทฒ้€‰ใ€‚').style('font-size:14px;')
                    ui.button('ๆ นๆฎๅทฒ้€‰ๅˆทๆ–ฐ', icon='refresh', on_click=self._manual_refresh_group) \
                        .props('dense flat color=primary').classes('text-sm')
                self.group_expansion_container = ui.column().classes('w-full gap-0')
                with self.group_expansion_container:
                    ui.label('่ฏทๅ…ˆๆœ็ดขๅนถๅ‹พ้€‰ๆ ‡็ญพโ€ฆ').classes('text-sm text-gray-400 italic p-4')

            # โ”€โ”€ ๅณๆ ๏ผšๅ…ณ่”ๆŽจ่ โ”€โ”€
            with ui.card().classes('col-right'):
                with ui.row().classes('items-center justify-between w-full mb-2'):
                    with ui.row().classes('items-center gap-2'):
                        ui.label('ๅ…ณ่”ๆŽจ่').classes('font-bold text-lg text-gray-800')
                        with ui.icon('info_outline', size='sm', color='grey').classes('cursor-help'):
                            with ui.tooltip().props('content-class="bg-black text-white shadow-4"'):
                                ui.html(
                                    'ๅŸบไบŽๆ ‡็ญพๅ…ฑ็Žฐๆ•ฐๆฎ๏ผŒๅ‘ๆŽ˜่ฏญไน‰ไน‹ๅค–็š„็›ธๅ…ณๆ€ง๏ผŒไธบๆ‚จๆŽจ่ๆ›ดๅคšๅฏ่ƒฝ็š„ๆ ‡็ญพใ€‚<br>ๅ‹พ้€‰ๅฏๅŠ ๅ…ฅๆˆ–็งปๅ‡บๅทฒ้€‰ใ€‚ๅฆ‚้œ€ๆ นๆฎๆœ€ๆ–ฐ้€‰้กนๆ›ดๆ–ฐๆŽจ่๏ผŒ่ฏท็‚นๅ‡ปๅˆทๆ–ฐๆŒ‰้’ฎใ€‚').style(
                                    'font-size:14px;line-height:1.5;')

                    # ๆ–ฐๅขžๆ‰‹ๅŠจๅˆทๆ–ฐๆŒ‰้’ฎ
                    ui.button('ๆ นๆฎๅทฒ้€‰ๅˆทๆ–ฐ', icon='refresh', on_click=self._manual_refresh_related) \
                        .props('dense flat color=primary').classes('text-sm')

                self.related_list_container = ui.column().classes('w-full gap-0')
                with self.related_list_container:
                    ui.label('่ฏทๅ…ˆๆœ็ดขๅนถๅ‹พ้€‰ๆ ‡็ญพโ€ฆ').classes('text-sm text-gray-400 italic p-4')

    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
    # ๆธฒๆŸ“ๅ…ณ่”ๆŽจ่ๅˆ—่กจ
    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

    def _render_related_list(self, related: list, show_nsfw: bool):
        self.related_list_container.clear()
        self._related_checkboxes.clear()

        filtered = [r for r in related if not (r.nsfw == '1' and not show_nsfw)]
        if not filtered:
            with self.related_list_container:
                ui.label('ๆš‚ๆ— ๆŽจ่').classes('text-sm text-gray-400 italic p-4')
            return

        selected_now = set(self._get_selected_tags())

        with self.related_list_container:
            for r in filtered:
                tag = r.tag
                cn_first = r.cn_name.split(',')[0].strip() if r.cn_name else ''
                is_selected = tag in selected_now
                score_pct = f'+{r.cooc_score * 100:.0f}%'

                # ่Žทๅ– wiki
                wiki_text = ''
                try:
                    tagger = DanbooruTagger._instance
                    if tagger and tagger.df is not None and tag in tagger._name_to_idx:
                        idx = tagger._name_to_idx[tag]
                        wiki_text = str(tagger.df.iloc[idx].get('wiki', ''))
                except Exception:
                    pass

                sources_str = 'ใ€'.join(
                    s.replace('tag_group:', '') for s in r.sources
                ) if r.sources else 'โ€”'
                CAT_LABEL = {'General': '้€š็”จ', 'Character': '่ง’่‰ฒ', 'Copyright': 'ไฝœๅ“'}
                cat_label = CAT_LABEL.get(r.category, '')
                tooltip_html = ''
                if wiki_text:
                    prefix = f'<span style="opacity:0.7;margin-right:4px;">[{cat_label}]</span>' if cat_label else ''
                    tooltip_html += f'<div style="margin-bottom:6px;">{prefix}{wiki_text}</div>'
                tooltip_html += (
                    f'<div style="opacity:0.85;">'
                    f'{r.cn_name}<br>'
                    f'ๅ…ฑ็Žฐ: {r.cooc_count:,}  ็›ธๅ…ณๅบฆ: {r.cooc_score:.2f}<br>'
                    f'ๆฅ่‡ช้€‰ไธญ: {sources_str}'
                    f'</div>'
                )

                # ่กŒ่ƒŒๆ™ฏ่‰ฒๆŒ‰ๅˆ†็ฑปๅŒบๅˆ†
                CAT_BG = {
                    'General':   'background-color: rgba(59,130,246,0.06);',   # ๆทก่“
                    'Character': 'background-color: rgba(34,197,94,0.06);',    # ๆทก็ปฟ
                    'Copyright': 'background-color: rgba(236,72,153,0.06);',   # ๆทก็บข/็ฒ‰
                }
                row_bg = CAT_BG.get(r.category, '')

                # ๆ•ด่กŒๅฎนๅ™จ๏ผŒtooltip ๆŒ‚ๅœจ่กŒไธŠ
                with ui.row().classes(
                    'w-full items-center gap-2 px-3 py-2 related-item border-b border-gray-100'
                ).style(row_bg):
                    # ๆ•ด่กŒ wiki tooltip
                    if tooltip_html:
                        with ui.tooltip().props('content-class="bg-black text-white shadow-4" max-width="500px"'):
                            ui.html(tooltip_html).style('font-size:14px;line-height:1.5;max-width:480px;')

                    # Checkbox
                    cb = ui.checkbox(
                        '', value=is_selected,
                        on_change=lambda e, t=tag: self._on_related_checkbox_change(t, e.value)
                    ).props('dense')
                    self._related_checkboxes[tag] = cb

                    # ๆ ‡็ญพๅ๏ผˆๅฏ็‚นๅ‡ป่ทณ่ฝฌ๏ผ‰+ ไธญๆ–‡ๅ
                    with ui.column().classes('flex-grow gap-0 min-w-0'):
                        with ui.row().classes('items-center gap-1'):
                            link = ui.link(
                                tag,
                                f'https://danbooru.donmai.us/wiki_pages/{tag}',
                                new_tab=True
                            ).classes('tag-link text-primary font-bold text-xs')
                            link.on('click', self._mark_interaction)
                            if r.sources and r.sources[0].startswith('tag_group:'):
                                group_display = r.sources[0].replace('tag_group:', '')
                                ui.label(group_display).classes(
                                    'text-xs text-orange-500 font-bold bg-orange-50 px-1 rounded'
                                )

                        if cn_first:
                            ui.label(cn_first).classes('text-xs text-gray-500 truncate')

                    # ๅ…ณ่”ๅˆ†ๆ•ฐ
                    score_color = 'green' if r.cooc_score > 0.6 else ('teal' if r.cooc_score > 0.3 else 'grey')
                    ui.label(score_pct).classes(f'text-sm font-bold text-{score_color}-600 whitespace-nowrap')

    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
    # ไบคไบ’้€ป่พ‘
    # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

    async def _hide_banner_when_ready(self):
        while not DanbooruTagger.is_ready():
            await asyncio.sleep(1)
        if self.init_banner:
            self.init_banner.set_visibility(False)

    def _client_alive(self) -> bool:
        try:
            _ = self.search_btn.client
            return True
        except RuntimeError:
            return False

    # โ”€โ”€ ๅˆ†่ฏ็ญ›้€‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _filter_by_source(self, keyword: str):
        self.current_filter_keyword = keyword if keyword else 'ALL'
        show_nsfw_val = self.input_nsfw.value
        if not keyword or keyword == 'ALL':
            filtered = self.full_table_data
        else:
            filtered = [r for r in self.full_table_data if r['source'] == keyword]

        self.result_table.rows = apply_nsfw_filter(filtered, show_nsfw_val)

        for child in self.keywords_container.default_slot.children:
            if isinstance(child, ui.chip):
                selected = (
                    (keyword == 'ALL' and child.text == 'ๅ…จ้ƒจ')
                    or (keyword == self.current_query_str and child.text == 'ๆ•ดๅฅ')
                    or (child.text == keyword)
                )
                is_segment = child.text in self.current_segments
                if selected:
                    chip_color, text_color = 'primary', 'white'
                elif is_segment:
                    chip_color, text_color = 'blue-1', 'blue-8'
                else:
                    chip_color, text_color = 'grey-4', 'black'
                child.props(f'color={chip_color} text-color={text_color}')

    # โ”€โ”€ ๆœ็ดข โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    async def perform_search(self):
        query = self.search_input.value.strip()
        if not query:
            return

        # ๆœ็ดขๅ‰ๆ ก้ชŒๆ•ฐๅ€ผๅ‚ๆ•ฐ
        _err_fields = []
        if self.input_top_k and (self.input_top_k.value is None or str(self.input_top_k.value).strip() == ''):
            _err_fields.append('Top K')
        if self.input_limit and (self.input_limit.value is None or str(self.input_limit.value).strip() == ''):
            _err_fields.append('่ฟ”ๅ›žๆ•ฐ้‡')
        if self.input_weight and (self.input_weight.value is None or str(self.input_weight.value).strip() == ''):
            _err_fields.append('็ƒญๅบฆๆƒ้‡')
        if _err_fields:
            ui.notify(f'่ฏทๅกซๅ†™๏ผš{"ใ€".join(_err_fields)}', type='negative', timeout=3000)
            return

        # ๆœ็ดขๅ‰ไฟๅญ˜้…็ฝฎ
        self._save_config()

        self.current_query_str = query
        self.search_btn.disable()
        self.spinner.classes(remove='hidden')
        ui.notify('ๆญฃๅœจๆœ็ดข...', type='info')

        if self.bad_case_btn is not None:
            self.bad_case_btn.disable()

        target_layers_list = [k for k, v in self.selected_layers.items() if v]
        target_cats_list   = [k for k, v in self.selected_cats.items()   if v]

        if not target_layers_list:
            ui.notify('่ฏท่‡ณๅฐ‘้€‰ๆ‹ฉไธ€ไธชๅŒน้…ๅฑ‚๏ผ', type='warning')
            self.search_btn.enable()
            self.spinner.classes(add='hidden')
            return

        try:
            tagger = await DanbooruTagger.get_instance()

            # NSFW ไฟๆŠคๆจกๅผ๏ผšๅผ€ = ไธๆ˜พ็คบ NSFW
            show_nsfw_val = self.input_nsfw.value

            request = SearchRequest(
                query=query,
                top_k=int(self.input_top_k.value),
                limit=int(self.input_limit.value),
                popularity_weight=float(self.input_weight.value),
                show_nsfw=show_nsfw_val,
                use_segmentation=self.input_segment.value if self.input_segment else True,
                target_layers=target_layers_list,
                target_categories=target_cats_list,
                group_mode=self.input_group_mode.value if self.input_group_mode else 'off',
                max_per_group=int(self.input_max_per_group.value) if self.input_max_per_group else 2,
            )
            response = await tagger.search_async(request)

            # ๅŽๅฐ่ฎกๆ•ฐ
            async def silent_counter_update():
                try:
                    await counter.increment()
                    if response.keywords:
                        await counter.add_keywords(response.keywords)
                    self._update_footer_text()
                except Exception as e:
                    print(f"[UI] ๅŽๅฐ้™้ป˜ๆ›ดๆ–ฐ่ฎกๆ•ฐๅคฑ่ดฅ: {e}", flush=True)
            asyncio.create_task(silent_counter_update())

            if not self._client_alive():
                return

            table_data = [result_to_row(r, show_nsfw_val) for r in response.results]
            self.full_table_data = table_data
            self.full_tags_str = response.tags_all
            self.full_tags_str_sfw = response.tags_sfw
            self.current_segments = list(response.segments) if response.segments else []

            # ๆ˜พ็คบ็ป“ๆžœๅŒบๅŸŸ
            self.results_section.set_visibility(True)

            _saved_rpp = self._get_rows_per_page()
            self.result_table.rows = apply_nsfw_filter(table_data, show_nsfw_val)
            self._set_rows_per_page(_saved_rpp)
            # ๆœ็ดขๆ—ถไฟ็•™ๅทฒ้€‰ๆ ‡็ญพ๏ผˆ่ทจๆœ็ดข็งฏ็ดฏ๏ผ‰
            all_selected = self._get_selected_tags()
            self.chip_extra_selected.clear()
            self.chip_extra_selected.update(all_selected)
            self.result_table.selected = []
            self._render_selected_chips()
            self._update_selection_display(None)
            self._save_staged_tags()

            # ๆธ…็ฉบๅ…ณ่”ๆŽจ่
            self._refresh_related([], show_nsfw_val)

            # ๅˆ†่ฏ็ญ›้€‰ chips
            self.current_filter_keyword = 'ALL'   # ๆ–ฐๆœ็ดข้ป˜่ฎค้€‰ไธญ"ๅ…จ้ƒจ"
            self.keywords_container.clear()
            with self.keywords_container:
                ui.label('ๅˆ†่ฏ็ญ›้€‰:').classes('text-sm text-gray-500 font-bold mr-2')
                ui.chip('ๅ…จ้ƒจ', on_click=lambda: self._filter_by_source('ALL')) \
                    .props('color=primary text-color=white clickable')
                use_seg = self.input_segment.value if self.input_segment else True
                if use_seg:
                    ui.chip('ๆ•ดๅฅ',
                            on_click=lambda: self._filter_by_source(self.current_query_str)) \
                        .props('color=grey-4 text-color=black clickable')
                    # ไปŽๅฅ็บงๅŽŸๅง‹็‰‡ๆฎต๏ผˆๅˆ†้š”็ฌฆๅˆ‡ๅˆ†ๅŽๆœช jieba ็š„้•ฟ็‰‡ๆฎต๏ผŒๅŒบๅˆซไบŽๅ…ณ้”ฎ่ฏ๏ผ‰
                    for seg in response.segments:
                        ui.chip(seg,
                                on_click=lambda s=seg: self._filter_by_source(s)) \
                            .props('color=blue-1 text-color=blue-8 clickable')
                    for kw in response.keywords:
                        ui.chip(kw,
                                on_click=lambda k=kw: self._filter_by_source(k)) \
                            .props('color=grey-4 text-color=black clickable')
                else:
                    ui.label('(ๅˆ†่ฏๅทฒๅ…ณ้—ญ)').classes('text-xs text-gray-400')

            ui.notify(f'ๆ‰พๅˆฐ {len(table_data)} ไธชๆ ‡็ญพ', type='positive')
            self.current_search_interacted = False

            if self.bad_case_btn is not None:
                self.bad_case_btn.enable()

        except RuntimeError as e:
            if 'deleted' in str(e).lower() or 'client' in str(e).lower():
                return
            try:
                ui.notify(f'้”™่ฏฏ: {str(e)}', type='negative')
            except RuntimeError:
                pass
        except Exception as e:
            try:
                ui.notify(f'้”™่ฏฏ: {str(e)}', type='negative')
            except RuntimeError:
                pass
        finally:
            try:
                self.search_btn.enable()
                self.spinner.classes(add='hidden')
            except RuntimeError:
                pass

    # โ”€โ”€ ้€‰ๆ‹ฉ็ฎก็† โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _get_selected_tags(self) -> list[str]:
        table_tags = [row['tag'] for row in self.result_table.selected] if self.result_table else []
        seen = set(table_tags)
        extra = [t for t in self.chip_extra_selected if t not in seen]
        return table_tags + extra

    def _set_selected_tags(self, tags: list[str], skip_refresh: bool = False):
        tag_set = set(tags)
        table_tag_set = {row['tag'] for row in self.result_table.rows} if self.result_table else set()
        self.chip_extra_selected.clear()
        self.chip_extra_selected.update(t for t in tag_set if t not in table_tag_set)
        # clean up weights for deselected tags
        for t in list(self.tag_weights):
            if t not in tag_set:
                del self.tag_weights[t]

        if self.result_table is not None:
            self.result_table.selected = [row for row in self.result_table.rows if row.get('tag') in tag_set]

        all_tags = self._get_selected_tags()
        if self.selection_count_label is not None:
            self.selection_count_label.text = str(len(all_tags))
        self._save_staged_tags()
        self._render_selected_chips()
        # ๆ˜พๅผๅˆทๆ–ฐๅ…ณ่”ๆŽจ่ๅ’Œ Group ๅŒบๅŸŸ๏ผˆไธไพ่ต– table.on('selection') ไบ‹ไปถ๏ผŒ
        # ๅ› ไธบๅœจ chip ็‚นๅ‡ปๅ›ž่ฐƒไธŠไธ‹ๆ–‡ไธญ่ฏฅไบ‹ไปถๅฏ่ƒฝไธๅฏ้ ๏ผ‰ใ€‚
        # ไปŽๅ…ณ่”ๆŽจ่/ๅŒ็ฑปๆ ‡็ญพๅ‹พ้€‰ๆ—ถ่ทณ่ฟ‡๏ผŒ็”ฑๅ„่‡ชๅŠจๆ€ๅˆทๆ–ฐๆˆ–ๆ‰‹ๅŠจๆŒ‰้’ฎ่งฆๅ‘ใ€‚
        if not skip_refresh:
            show_nsfw_val = self.input_nsfw.value
            self._refresh_related_from_selection(all_tags, show_nsfw_val)
            self._refresh_group_from_selection(all_tags, show_nsfw_val)
            if not all_tags:
                self.chip_extra_selected.clear()

    def _update_selection_display(self, _e):
        if self.result_table is None:
            return
        self._mark_interaction()

        all_tags = self._get_selected_tags()
        # clean up weights for deselected tags
        tag_set = set(all_tags)
        for t in list(self.tag_weights):
            if t not in tag_set:
                del self.tag_weights[t]
        # init weight for newly selected tags
        for t in all_tags:
            self.tag_weights.setdefault(t, 1.0)

        if self.selection_count_label is not None:
            self.selection_count_label.text = str(len(all_tags))
        self._render_selected_chips()

        show_nsfw_val = self.input_nsfw.value
        self._refresh_related_from_selection(all_tags, show_nsfw_val)
        self._refresh_group_from_selection(all_tags, show_nsfw_val)
        if not all_tags:
            self.chip_extra_selected.clear()
        self._save_staged_tags()

    def _on_related_checkbox_change(self, tag: str, checked: bool):
        self._mark_interaction()
        current = self._get_selected_tags()
        if checked:
            if tag not in current:
                current.append(tag)
                self.tag_weights.setdefault(tag, 1.0)
                self._set_selected_tags(current, skip_refresh=True)
                ui.notify(f'ๅทฒๆทปๅŠ  {tag}', type='positive', timeout=1500)
        else:
            if tag in current:
                current.remove(tag)
                self.tag_weights.pop(tag, None)
                self._set_selected_tags(current, skip_refresh=True)
                ui.notify(f'ๅทฒ็งป้™ค {tag}', type='warning', timeout=1500)

    def _on_group_checkbox_change(self, tag: str, checked: bool):
        """ๅŒ็ฑปๆ ‡็ญพๅค้€‰ๆก†ๅ˜ๅŒ–ๅ›ž่ฐƒใ€‚"""
        self._mark_interaction()
        current = self._get_selected_tags()
        if checked:
            if tag not in current:
                current.append(tag)
                self.tag_weights.setdefault(tag, 1.0)
                self._set_selected_tags(current, skip_refresh=True)
                ui.notify(f'ๅทฒๆทปๅŠ  {tag}', type='positive', timeout=1500)
        else:
            if tag in current:
                current.remove(tag)
                self.tag_weights.pop(tag, None)
                self._set_selected_tags(current, skip_refresh=True)
                ui.notify(f'ๅทฒ็งป้™ค {tag}', type='warning', timeout=1500)
        # ๅณๅˆปๅˆทๆ–ฐๅ…ณ่”ๆŽจ่
        show_nsfw_val = self.input_nsfw.value
        self._refresh_related_from_selection(current, show_nsfw_val)

    def _manual_refresh_related(self):
        """ๆ‰‹ๅŠจ่งฆๅ‘ๅ…ณ่”ๆŽจ่ๅˆ—่กจ็š„ๅˆทๆ–ฐ"""
        self._mark_interaction()
        show_nsfw_val = self.input_nsfw.value
        all_tags = self._get_selected_tags()

        if all_tags:
            self._refresh_related_from_selection(all_tags, show_nsfw_val)
            ui.notify('ๅทฒ่งฆๅ‘ๅ…ณ่”ๆŽจ่ๆ›ดๆ–ฐ', type='info', timeout=1500)
        else:
            self.chip_extra_selected.clear()
            self._refresh_related([], show_nsfw_val)
            ui.notify('ๅทฒๆธ…็ฉบๅ…ณ่”ๆŽจ่', type='info', timeout=1500)

    def _manual_refresh_group(self):
        """ๆ‰‹ๅŠจ่งฆๅ‘ๅŒ็ฑปๆ‰ฉๅฑ•ๅŒบๅŸŸ็š„ๅˆทๆ–ฐ"""
        self._mark_interaction()
        show_nsfw_val = self.input_nsfw.value
        all_tags = self._get_selected_tags()

        if all_tags:
            self._refresh_group_from_selection(all_tags, show_nsfw_val)
            ui.notify('ๅทฒ่งฆๅ‘ๅŒ็ฑปๆ ‡็ญพๆ›ดๆ–ฐ', type='info', timeout=1500)
        else:
            if self.group_expansion_container is not None:
                self.group_expansion_container.clear()
                with self.group_expansion_container:
                    ui.label('่ฏทๅ…ˆๆœ็ดขๅนถๅ‹พ้€‰ๆ ‡็ญพโ€ฆ').classes('text-sm text-gray-400 italic p-4')
            ui.notify('ๆš‚ๆœช้€‰ไธญๆ ‡็ญพ', type='info', timeout=1500)

    # โ”€โ”€ ๅ…ณ่”ๆŽจ่ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _refresh_related(self, related: list, show_nsfw: bool):
        if related is None:
            related = []
        selected_now = set(self._get_selected_tags())
        old_related  = self.current_related
        new_tags  = {r.tag for r in related}
        preserved = [r for r in old_related if r.tag in selected_now and r.tag not in new_tags]
        merged = list(related) + preserved

        self.current_related = merged
        if self.related_list_container is not None:
            self._render_related_list(merged, show_nsfw)

    def _refresh_related_from_selection(self, selected_tags: list[str], show_nsfw: bool):
        """ไป…ๅˆทๆ–ฐๅ…ณ่”ๆŽจ่ๅˆ—่กจใ€‚"""
        async def _do():
            if not selected_tags:
                self._refresh_related([], show_nsfw)
                return
            tagger = await DanbooruTagger.get_instance()
            related = await run.io_bound(
                tagger.get_related,
                selected_tags,
                set(selected_tags),
                50,
                show_nsfw,
            )
            self._refresh_related(related, show_nsfw)
        asyncio.ensure_future(_do())

    def _refresh_group_from_selection(self, selected_tags: list[str], show_nsfw: bool):
        """ไป…ๅˆทๆ–ฐๅŒ็ฑปๆ‰ฉๅฑ•ๅŒบๅŸŸใ€‚"""
        async def _do():
            if not selected_tags:
                if self.group_expansion_container is not None:
                    self.group_expansion_container.clear()
                    with self.group_expansion_container:
                        ui.label('่ฏทๅ…ˆๆœ็ดขๅนถๅ‹พ้€‰ๆ ‡็ญพโ€ฆ').classes('text-sm text-gray-400 italic p-4')
                return
            tagger = await DanbooruTagger.get_instance()
            group_data = await run.io_bound(
                tagger.get_group_candidates,
                selected_tags,
                show_nsfw,
            )
            self._render_group_expansion(group_data, selected_tags, show_nsfw)
        asyncio.ensure_future(_do())

    def _render_group_expansion(self, group_data: list, selected_tags: list[str], show_nsfw: bool):
        """ๆธฒๆŸ“ Group ๅŒ็ฑปๆ‰ฉๅฑ•ๅŒบๅŸŸใ€‚"""
        if self.group_expansion_container is None:
            return
        self.group_expansion_container.clear()
        self._group_checkboxes.clear()

        if not group_data:
            with self.group_expansion_container:
                ui.label('ๅทฒ้€‰ๆ ‡็ญพๆ— ๅˆ†็ป„ไฟกๆฏ').classes('text-sm text-gray-400 italic p-2')
            return

        # ่กŒ่ƒŒๆ™ฏ่‰ฒๆŒ‰ๅˆ†็ฑปๅŒบๅˆ†๏ผˆไธŽๅ…ณ่”ๆŽจ่ไธ€่‡ด๏ผ‰
        CAT_BG = {
            'General':   'background-color: rgba(59,130,246,0.06);',
            'Character': 'background-color: rgba(34,197,94,0.06);',
            'Copyright': 'background-color: rgba(236,72,153,0.06);',
        }
        CAT_LABEL = {'General': '้€š็”จ', 'Character': '่ง’่‰ฒ', 'Copyright': 'ไฝœๅ“'}

        selected_now = set(self._get_selected_tags())

        with self.group_expansion_container:
            for group_info in group_data:
                group_name = group_info['group']
                group_cn = group_info.get('group_cn_name', group_name.replace('tag_group:', ''))
                tags = group_info['tags']

                with ui.expansion(
                    f'{group_cn} ({len(tags)} ไธชๆ ‡็ญพ)',
                    icon='label',
                ).classes('w-full').props('dense'):
                    with ui.element('div').classes('w-full grid grid-cols-2 gap-1 p-1').style('max-height: 600px; overflow-y: auto;'):
                        for t in tags:
                            tag = t['tag']
                            cn_first = t['cn_name'].split(',')[0].strip() if t['cn_name'] else ''
                            cn_full = t.get('cn_name', '')
                            cat = t['category']
                            wiki_text = str(t.get('wiki', ''))
                            row_bg = CAT_BG.get(cat, '')
                            is_selected = tag in selected_now

                            cat_label = CAT_LABEL.get(cat, '')
                            tooltip_html = ''
                            if wiki_text:
                                prefix = f'<span style="opacity:0.7;margin-right:4px;">[{cat_label}]</span>' if cat_label else ''
                                tooltip_html += f'<div style="margin-bottom:6px;">{prefix}{wiki_text}</div>'
                            if cn_full:
                                tooltip_html += f'<div style="opacity:0.85;">{cn_full}</div>'

                            with ui.row().classes(
                                'w-full items-center gap-1.5 px-2 py-1.5 rounded related-item'
                            ).style(row_bg):
                                if tooltip_html:
                                    with ui.tooltip().props('content-class="bg-black text-white shadow-4" max-width="500px"'):
                                        ui.html(tooltip_html).style('font-size:14px;line-height:1.5;max-width:480px;')

                                # ๅค้€‰ๆก†
                                cb = ui.checkbox(
                                    '', value=is_selected,
                                    on_change=lambda e, t=tag: self._on_group_checkbox_change(t, e.value),
                                ).props('dense')
                                self._group_checkboxes[tag] = cb

                                # ๆ ‡็ญพๅ + ไธญๆ–‡ๅ๏ผˆไธŽๅ…ณ่”ๆŽจ่ๅฏน้ฝๆ–นๅผไธ€่‡ด๏ผ‰
                                with ui.column().classes('flex-grow gap-0 min-w-0 overflow-hidden'):
                                    link = ui.link(
                                        tag,
                                        f'https://danbooru.donmai.us/wiki_pages/{tag}',
                                        new_tab=True,
                                    ).classes('tag-link text-primary font-bold text-xs truncate')
                                    if cn_first:
                                        ui.label(cn_first).classes('text-xs text-gray-500 truncate')

                                # ็ƒญๅบฆ
                                count = t['post_count']
                                if count > 0:
                                    if count >= 10000:
                                        count_str = f'{count/1000:.0f}k'
                                    elif count >= 1000:
                                        count_str = f'{count/1000:.1f}k'
                                    else:
                                        count_str = str(count)
                                    ui.label(count_str).classes('text-sm font-bold text-grey-600 whitespace-nowrap')

    # โ”€โ”€ ่กจๆ ผๅˆ—ๅŠจๆ€ๆ›ดๆ–ฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _update_table_columns(self, e=None):
        cols = list(TABLE_COLUMNS)
        if self.sw_semantic and self.sw_semantic.value:
            cols.append(OPTIONAL_COLS['semantic'])
        if self.sw_layer and self.sw_layer.value:
            cols.append(OPTIONAL_COLS['layer'])
        if self.sw_source and self.sw_source.value:
            cols.append(OPTIONAL_COLS['source'])
        self.result_table.columns = cols

    # โ”€โ”€ ๆœ็ดขๆจกๅผ / ๅ‚ๆ•ฐ่”ๅŠจ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _on_search_mode_change(self, _e=None):
        mode = self.input_search_mode.value if self.input_search_mode else None
        if not mode or mode == '่‡ชๅฎšไน‰' or mode not in _SEARCH_MODE_PRESETS:
            return
        preset = _SEARCH_MODE_PRESETS[mode]
        self._applying_preset = True
        try:
            if self.input_top_k:
                self.input_top_k.set_value(preset['top_k'])
            if self.input_limit:
                self.input_limit.set_value(preset['limit'])
            if self.input_weight:
                self.input_weight.set_value(preset['popularity_weight'])
            if self.input_segment:
                self.input_segment.set_value(preset['use_segmentation'])
            if self.input_group_mode:
                self.input_group_mode.set_value(preset['group_mode'])
            if self.input_max_per_group:
                self.input_max_per_group.set_value(preset['max_per_group'])
        finally:
            self._applying_preset = False

    def _on_param_changed(self, _e=None):
        if not self._applying_preset and self.input_search_mode:
            if self.input_search_mode.value != '่‡ชๅฎšไน‰':
                self.input_search_mode.set_value('่‡ชๅฎšไน‰')

    # โ”€โ”€ NSFW ๅˆ‡ๆข โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def on_nsfw_toggle(self, e):
        show_nsfw_val = self.input_nsfw.value

        # ๅค็”จๅฝ“ๅ‰ๅˆ†่ฏ็ญ›้€‰๏ผšๅŒๆ—ถๅฅ—็”จๆ–ฐ NSFW ็Šถๆ€ๅนถไฟๆŒ chip ้€‰ไธญๆ€
        self._filter_by_source(self.current_filter_keyword)
        if not show_nsfw_val:
            self.result_table.selected = [r for r in self.result_table.selected if r.get('nsfw') != '1']
        self._update_selection_display(None)

    # โ”€โ”€ ๅคๅˆถ / ๅ้ฆˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def _toggle_prompt_format(self):
        if self.prompt_format == 'sdxl':
            self.prompt_format = 'nai'
            if self.format_toggle_btn:
                self.format_toggle_btn.text = 'NAI'
                self.format_toggle_btn.props('color=purple-7')
        else:
            self.prompt_format = 'sdxl'
            if self.format_toggle_btn:
                self.format_toggle_btn.text = 'SDXL'
                self.format_toggle_btn.props('color=grey-7')

    def copy_selection(self):
        self._mark_interaction()
        tags = self._get_selected_tags()
        prompt = ', '.join(
            _format_tag_with_weight(t, self.tag_weights.get(t, 1.0), self.prompt_format)
            for t in tags
        )
        ui.clipboard.write(prompt)
        fmt_label = 'NAI' if self.prompt_format == 'nai' else 'SDXL'
        ui.notify(f'ๅทฒๅคๅˆถ้€‰ไธญๆ ‡็ญพ๏ผˆ{fmt_label} ๆ ผๅผ๏ผ‰!', type='positive')

        async def silent_copy_update():
            try:
                await counter.increment_copy()
            except Exception:
                pass
        asyncio.create_task(silent_copy_update())

    def _copy_all_tags(self):
        self._mark_interaction()
        show_nsfw_val = self.input_nsfw.value
        tags_str = self.full_tags_str if show_nsfw_val else self.full_tags_str_sfw
        if tags_str:
            ui.clipboard.write(tags_str)
            ui.notify('ๅทฒๅคๅˆถๅ…จ้ƒจๆ ‡็ญพ!', type='positive')
        else:
            ui.notify('ๆš‚ๆ— ๆ ‡็ญพๅฏๅคๅˆถ', type='warning')

    async def report_bad_case(self):
        from platform_utils import PLATFORM
        query = self.current_query_str.strip()
        if len(query) <= 1:
            ui.notify('ๆœ็ดข่ฏๅคช็Ÿญ๏ผŒๆ— ๆณ•ๆไบคๅ้ฆˆใ€‚', type='warning', timeout=2000)
            return
        if self.bad_case_btn is not None:
            self.bad_case_btn.disable()
        try:
            settings = {
                'top_k': int(self.input_top_k.value) if self.input_top_k else None,
                'segmentation': self.input_segment.value if self.input_segment else None,
                'nsfw': self.input_nsfw.value if self.input_nsfw else None,
            }
            await counter.add_bad_case(query, platform=PLATFORM, settings=settings)
            ui.notify('ๆ„Ÿ่ฐขๅ้ฆˆ๏ผๆˆ‘ไปฌไผšๆŒ็ปญไผ˜ๅŒ–ใ€‚', type='positive', timeout=3000)
        except Exception as e:
            print(f'[UI] bad_case ่ฎฐๅฝ•ๅผ‚ๅธธ: {e}')
            ui.notify('่ฎฐๅฝ•ๅคฑ่ดฅ๏ผŒ่ฏท็จๅŽๅ†่ฏ•ใ€‚', type='warning', timeout=3000)
            if self.bad_case_btn is not None:
                self.bad_case_btn.enable()

# โ”€โ”€ ้กต้ข่ทฏ็”ฑ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@ui.page('/')
async def main_page():
    app_ui = DanbooruSearchUI()
    app_ui.build_page()

    async def silent_visit_update():
        try:
            await counter.increment_visit()
            app_ui._update_footer_text()
        except Exception:
            pass
    asyncio.create_task(silent_visit_update())

    # ๆขๅค็”จๆˆท้…็ฝฎ๏ผˆๅœจ้กต้ขๆธฒๆŸ“ๅฎŒๆˆๅŽๆ‰ง่กŒ๏ผ‰
    await app_ui._restore_config()
    # ๆขๅคๅทฒ้€‰ๆ ‡็ญพ๏ผˆๅค‡้€‰ๅŒบ๏ผ‰
    await app_ui._restore_staged_tags()


# โ”€โ”€ ๅ…ฅๅฃ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

if __name__ in {'__main__', '__mp_main__'}:
    host, port = get_host_port()

    @app.on_startup
    def _warmup():
        async def background_init_tasks():
            await asyncio.sleep(5)
            print("[UI] ๅผ€ๅง‹้ข„็ƒญ่ฎกๆ•ฐๅ™จไธŽๅผ•ๆ“Ž", flush=True)
            await counter.init()
            await DanbooruTagger.get_instance()
            print("[UI] ๅŽๅฐ้ข„็ƒญๅ…จ้ƒจๅฎŒๆˆ๏ผ", flush=True)
        asyncio.create_task(background_init_tasks())

    @app.on_shutdown
    def _shutdown():
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                loop.create_task(counter.force_sync())
            else:
                asyncio.run(counter.force_sync())
        except Exception as e:
            print(f"[UI] ๅ…ณๆœบๅŒๆญฅๅคฑ่ดฅ: {e}")

    app.mount('/api', api_app)

    mcp_app = mcp.streamable_http_app()
    app.mount('/mcp', mcp_app)
    _mcp_lifespan_ctx = None
    @app.on_startup
    async def _start_mcp():
        global _mcp_lifespan_ctx
        _mcp_lifespan_ctx = mcp_app.router.lifespan_context(mcp_app)
        await _mcp_lifespan_ctx.__aenter__()
    @app.on_shutdown
    async def _stop_mcp():
        global _mcp_lifespan_ctx
        if _mcp_lifespan_ctx is not None:
            await _mcp_lifespan_ctx.__aexit__(None, None, None)


    @app.get('/googlebd34b54f8562aa06.html')
    def google_verification():
        return PlainTextResponse('google-site-verification: googlebd34b54f8562aa06.html')

    @app.get('/robots.txt')
    def robots_txt():
        content = (
            'User-agent: *\n'
            'Allow: /$\n'
            'Disallow: /api/\n'
            'Disallow: /_nicegui/\n'
            'Disallow: /socket.io/\n'
        )
        return PlainTextResponse(content)


    @app.get('/robots.txt')
    def robots_txt():
        content = (
            'User-agent: *\n'
            'Allow: /$\n'
            'Disallow: /api/\n'
            'Disallow: /_nicegui/\n'
            'Disallow: /socket.io/\n'
        )
        return PlainTextResponse(content)

    @app.head('/')
    async def head_root():
        return PlainTextResponse('')

    ui.run(
        host=host,
        port=port,
        title='Danbooru Tags Searcher',
        reload=not is_cloud(),
        show=not is_cloud(),
        reconnect_timeout=120,
    )