Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
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>'
' '
'<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('×')
# ๅๅท
with ui.element('button').classes('weight-btn').on(
'click', lambda t=tag: self._adjust_weight(t, -0.1)
):
ui.html('−')
# ๆ ็ญพๅ
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('+')
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,
)
|