Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
7144 lines (6647 loc) · 294 KB
/
Copy pathserver.py
File metadata and controls
7144 lines (6647 loc) · 294 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""KlockUI 本地服务:静态页 + ComfyUI 引擎适配(Forge/A1111 API 兼容层)。"""
import base64
import getpass
import gzip
import hashlib
import hmac
import html
import io
import json
import logging
import os
import random
import re
import secrets
import shutil
import struct
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
import zipfile
import zlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from logging.handlers import RotatingFileHandler
from urllib.parse import parse_qs, quote, urlparse
import comfy_bridge # Forge/A1111 API -> ComfyUI 工作流适配层(同目录)
import interrogate # WD14 图反推(懒加载 onnxruntime,不点就不占内存)
try:
from PIL import Image, ImageOps
except Exception: # noqa: BLE001
Image = None
ImageOps = None
class PromptSafetyError(RuntimeError):
"""用户输入无法生成有效提示词。"""
# 版本号:issue 里请带上它,能省掉一轮"你装的哪版"
VERSION = "0.1.0"
ROOT = os.path.dirname(os.path.abspath(__file__))
# 模型根目录由桥接层统一解析(环境变量 + 目录探测),这里直接复用,避免两套路径。
MODELS_ROOT = comfy_bridge.MODELS_ROOT
# 引擎已由 Forge Neo(7860) 迁移为 ComfyUI(8188)。FORGE 仅为历史命名别名,
# 所有 /sdapi/v1/* 由 comfy_bridge.dispatch 翻译成 ComfyUI 工作流。
ENGINE = os.environ.get("KLOCK_COMFY_URL", "http://127.0.0.1:8188")
FORGE = ENGINE
# 出图根目录:环境变量 → 同级 outputs(老布局)→ 仓库内 outputs。
# 加同级探测是为了兼容「仓库放在 D:/AI/KlockUI、图在 D:/AI/outputs」这种历史用法:
# 只看仓库内目录的话,老历史和缩略图会全部 404。
def _detect_output_root():
env = os.environ.get("KLOCK_OUTPUT_DIR")
if env:
return os.path.abspath(os.path.expanduser(env))
local = os.path.join(ROOT, "outputs")
legacy = os.path.join(os.path.dirname(ROOT), "outputs")
legacy_images = os.path.join(legacy, "txt2img-images")
if os.path.isdir(legacy_images):
try:
if any(True for _root, _dirs, files in os.walk(legacy_images) for _ in files):
return legacy
except OSError:
pass
return local
OUTPUT_ROOT = _detect_output_root()
PORT = int(os.environ.get("KLOCKUI_PORT", "7861"))
MAX_JSON_BYTES = 1024 * 1024
MAX_PROXY_BYTES = 64 * 1024 * 1024
STATIC_DIRS = ("vendor", "assets")
# 远程访问:密码只存 scrypt 派生值;会话用 HMAC 签名的 HttpOnly Cookie。
AUTH_DIR = os.path.join(ROOT, ".private")
AUTH_FILE = os.environ.get("KLOCK_AUTH_FILE") or os.path.join(AUTH_DIR, "auth.json")
SESSION_COOKIE = "klock_session"
SESSION_TTL = int(os.environ.get("KLOCK_SESSION_DAYS", "30")) * 86400
LOGIN_WINDOW = 15 * 60
LOGIN_MAX_FAILS = 5
GENERATION_JOB_TTL = 15 * 60
GENERATION_JOB_MAX = 12
GENERATION_QUEUE_MAX = 12
IDLE_UNLOAD_SECONDS = int(os.environ.get("KLOCK_IDLE_UNLOAD_SECONDS", "600"))
# 4B 常驻约 2GB 物理内存,而它只在 Anima/SDXL 需要中文转英文时才用得上。
# 空闲这么久就直接退出,下次需要时冷启动(约 10-30 秒)。设 0 可关闭该行为。
PROMPT_LLM_IDLE_SECONDS = int(os.environ.get("KLOCK_PROMPT_IDLE_SECONDS", "600"))
HISTORY_MAX = 60
# 缓存目录(历史、缩略图、导出)。支持改路径,方便多实例并存或做干净演示环境。
CACHE_DIR = os.environ.get("KLOCK_CACHE_DIR") or os.path.join(ROOT, ".cache")
HISTORY_FILE = os.path.join(CACHE_DIR, "history.json")
JOBS = {}
JOB_QUEUE = []
JOBS_LOCK = threading.Lock()
_QUEUE_ACTIVE = False
HISTORY_LOCK = threading.Lock()
_ACTIVITY_LOCK = threading.Lock()
_last_activity = time.time()
SCRYPT_N = 32768
SCRYPT_R = 8
SCRYPT_P = 1
SCRYPT_MEM = 64 * 1024 * 1024
# 只服务本机:远程访问(Cloudflare Tunnel)功能已移除(2026-11-15)。
LOCAL_HOSTS = frozenset(("127.0.0.1:%d" % PORT, "localhost:%d" % PORT))
LOCAL_ORIGINS = frozenset(("http://127.0.0.1:%d" % PORT, "http://localhost:%d" % PORT))
ALLOWED_HOSTS = LOCAL_HOSTS
HTML_FRAME_HEADERS = {
"X-Frame-Options": "DENY",
"Content-Security-Policy": "frame-ancestors 'none'",
}
LOGIN_SECURITY_HEADERS = {
"Content-Security-Policy": (
"default-src 'none'; style-src 'unsafe-inline'; "
"form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
),
"Referrer-Policy": "same-origin",
"X-Frame-Options": "DENY",
}
# 模型架构与配套模块:只读 safetensors 头部,供工作台切换 Anima 时自动配置预设。
# 统一模型库:D:/AI/models 是唯一来源,ComfyUI/models 只留占位文件。
# checkpoints/ SDXL 整模型
# diffusion_models/ DiT 族(Anima 2.9B + MOSS-Image)
CHECKPOINT_DIRS = (
comfy_bridge.CKPT_DIR,
comfy_bridge.DIFF_DIR,
)
TEXT_ENCODER_DIRS = (
comfy_bridge.TE_DIR,
)
MODULE_VAE_DIRS = (
comfy_bridge.VAE_DIR,
)
ENGINE_CATALOG_TTL = 20
_ENGINE_CATALOG = {"stamp": 0.0, "payload": None}
_ENGINE_CATALOG_LOCK = threading.Lock()
_HEADER_KEYS = {}
_HEADER_KEYS_LOCK = threading.Lock()
# 本地提示词生成:Qwen3.5-4B abliterated(中文直出)+ llama.cpp(CPU,不占显存)。
# llama-engine 只放运行时,模型放在 D:\AI\models 下,升级运行时不必搬模型。
LLAMA_ENGINE_DIR = os.environ.get("KLOCK_LLAMA_DIR") or os.path.join(MODELS_ROOT, "..", "llama-engine")
PROMPT_LLM = {
"alias": "qwen3.5-4b-abliterated",
"label": "Qwen3.5-4B abliterated",
"port": int(os.environ.get("KLOCK_PROMPT_LLM_PORT", "7865")),
"ctx": 4096,
"threads": int(os.environ.get("KLOCK_PROMPT_LLM_THREADS", "10")),
"model": os.environ.get(
"KLOCK_PROMPT_LLM_MODEL",
os.environ.get("KLOCK_PROMPT_LLM_MODEL") or os.path.join(MODELS_ROOT, "prompt-llm", "prompt-llm.gguf"),
),
"exe": os.path.join(LLAMA_ENGINE_DIR, "llama", "llama-server.exe"),
"log": "llama-prompt-llm",
"no_think": True,
}
def _discover_prompt_llm_model():
"""默认文件名不存在时,扫 prompt-llm/ 下唯一的 .gguf 顶上。
官方发行包里的模型叫 Huihui-Qwen3.5-4B-abliterated.Q4_K_M.gguf,
而历史默认路径写的是 prompt-llm.gguf —— 不自动发现的话转写开箱即坏。
用户通过 KLOCK_PROMPT_LLM_MODEL 显式指定时永远优先,不覆盖。
"""
model = PROMPT_LLM.get("model") or ""
if os.path.isfile(model):
return model
if os.environ.get("KLOCK_PROMPT_LLM_MODEL"):
return model # 显式指定就是用户说了算,缺失就报缺失,别偷偷换
folder = os.path.dirname(model)
if not folder or not os.path.isdir(folder):
return model
found = sorted(
os.path.join(folder, name)
for name in os.listdir(folder)
if name.lower().endswith(".gguf") and os.path.isfile(os.path.join(folder, name))
)
if len(found) == 1:
return found[0]
return model # 0 个还是坏;多个不猜,交给用户指定
PROMPT_LLM["model"] = _discover_prompt_llm_model()
PROMPT_LLM["url"] = "http://127.0.0.1:%d" % PROMPT_LLM["port"]
PROMPT_LLM["err_log"] = os.path.join(LLAMA_ENGINE_DIR, PROMPT_LLM["log"] + ".err.log")
PROMPT_LLM["last_error"] = ""
PROMPT_LLM["proc"] = None
# 空闲退出用:idle_seconds 为阈值,last_used 是最后一次真正调用 4B 的时间戳。
PROMPT_LLM["idle_seconds"] = PROMPT_LLM_IDLE_SECONDS
PROMPT_LLM["last_used"] = 0.0
PROMPT_LLM["lock"] = threading.Lock()
PROMPT_LLM["start_lock"] = threading.Lock()
PROMPT_CACHE = {}
PROMPT_CACHE_LOCK = threading.Lock()
PROMPT_CACHE_TTL = 1800
PROMPT_CACHE_MAX = 48
STYLE_TAGS = {
"photo": ["photorealistic", "realistic", "natural skin texture"],
"cinematic": ["cinematic lighting", "film grain", "depth of field"],
"illustration": ["illustration", "painterly", "detailed"],
"anime": ["anime coloring", "cel shading", "clean lineart"],
}
# 2026-10-27 晚:按要求清空提示词层的评级过滤词。
# 不再做 auto 评级、不再注入 safe/sensitive/nsfw/explicit,模型写的评级标签也会被剔除;
# 画面内容完全由 nude/sex/lingerie 这类内容标签表达。
RATING_TAG_RE = re.compile(
r"(?:rating[:_ ]?)?(?:general|safe|sensitive|questionable|nsfw|explicit)"
)
# 手动评级:默认 auto 不写评级标签,保持 raw 直出;用户选定后才注入一个。
MANUAL_RATINGS = ("auto", "safe", "sensitive", "nsfw", "explicit")
RATING_TAGS_BY_ARCH = {
"anima": {"safe": "safe", "sensitive": "sensitive", "nsfw": "nsfw", "explicit": "explicit"},
# Ponydiffusion 系的评级标签是 rating_safe / rating_questionable / rating_explicit,
# 没有 sensitive,用最接近的 questionable 承接敏感档。
"sdxl": {
"safe": "rating_safe",
"sensitive": "rating_questionable",
"nsfw": "rating_questionable",
"explicit": "rating_explicit",
},
}
def normalize_manual_rating(value):
rating = str(value or "auto").strip().lower()
return rating if rating in MANUAL_RATINGS else "auto"
def manual_rating_tag(rating, arch):
value = normalize_manual_rating(rating)
if value == "auto":
return ""
if arch == "krea":
# Krea 2 不用 booru 评级标签,评级只影响提示词语义。
return ""
table = RATING_TAGS_BY_ARCH.get("sdxl" if arch == "sdxl" else "anima", {})
return table.get(value, "")
TAG_ALIASES = {
"2girl": "2girls", "3girl": "3girls", "4girl": "4girls", "5girl": "5girls",
"2boy": "2boys", "3boy": "3boys", "4boy": "4boys", "5boy": "5boys",
"swimming suit": "swimsuit", "swimwear": "swimsuit",
"shoulders exposed": "bare shoulders", "shoulder reveal": "bare shoulders",
"shoulder exposed": "bare shoulders", "kissing": "kiss",
"movie style": "cinematic lighting", "looking at camera": "looking at viewer",
"hands behind back": "arms behind back",
"adult female": "mature female", "adult male": "mature male",
"adult woman": "mature female", "adult man": "mature male",
"smiling": "smile", "kimonos": "kimono", "back to camera": "from behind",
"full nude": "completely nude", "fully nude": "completely nude",
"naked": "nude",
"big breasts": "large breasts", "huge breasts": "large breasts",
"one person": "solo", "single person": "solo",
"double-tail": "twintails", "double tail": "twintails",
"twin-tail": "twintails", "twin tails": "twintails",
"twin ponytails": "twintails", "twin ponytail": "twintails",
"twin-ponytails": "twintails", "twin-ponytail": "twintails",
"compact framing": "tight framing", "compact composition": "tight framing",
"tight composition": "tight framing", "tightly framed": "tight framing",
"flat coloring": "flat color", "flat colour": "flat color",
"flat colours": "flat color", "flat colors": "flat color",
"flat shading": "flat color", "flat tone": "flat color", "flat tones": "flat color",
"half-body": "upper body", "half body": "upper body",
# 4B 对中文镜头词的字面翻译:统一成 Danbooru 能认的写法。
"seven-part portrait": "cowboy shot", "seven part portrait": "cowboy shot",
"seven-body": "cowboy shot", "seven body": "cowboy shot",
"mid-body": "upper body", "midbody": "upper body",
"standing pose": "standing",
"full-body": "full body", "fullbody": "full body",
"upper-body": "upper body", "upperbody": "upper body",
"cowboy-shot": "cowboy shot",
"cosswoy shot": "cowboy shot", "cossboy shot": "cowboy shot",
"cowboi shot": "cowboy shot", "cowbow shot": "cowboy shot",
"cowboyy shot": "cowboy shot",
# 连字符机位写法先归一,CAMERA_ANGLE_TAGS 才能按原文决定保留/删除。
"wide-angle": "wide angle", "low-angle": "low angle",
"high-angle": "high angle", "dutch-angle": "dutch angle",
"wide-shot": "wide shot", "extreme-wide-shot": "wide shot",
"side-view": "side view", "front-view": "front view",
"back-view": "back view", "eye-level": "eye level",
# 4B 爱把 night 拆成多个同义词;统一后由去重收敛,避免占满标签位。
"night time": "night", "nighttime": "night", "night scene": "night",
"night city": "city night", "night cityscape": "city night",
"close up": "close-up", "closeup": "close-up",
"waist up": "upper body", "waist-up": "upper body", "waistup": "upper body",
"full length": "full body", "full-length": "full body",
"seven-part": "cowboy shot", "seven part": "cowboy shot",
"seven-part view": "cowboy shot", "seven part view": "cowboy shot",
"mid-body shot": "upper body", "midbody shot": "upper body",
# 4B 常把双马尾写成 double braid;归一后由发型冲突清理接管。
"double braid": "braid", "double braids": "braid",
"twin braid": "braid", "twin braids": "braid",
"cyber-punk": "cyberpunk", "cyber punk": "cyberpunk",
# 4B 常见手部姿势错拼。
"head on hip": "hand on hip", "hand on hips": "hand on hip",
}
# 4B 偶尔把中文术语直接音译成拼音标签(pingtuo、jifan yishu),
# 这些不是 Danbooru 标签,按固定术语翻译回来。
TAG_ALIASES.update({
"pingtuo": "flat color", "ping tu": "flat color", "pingtu": "flat color",
"jifan yishu": "maximalism", "jifan zhuyi": "maximalism", "jifan": "maximalism",
"ji fan yi": "maximalism", "jifanyi": "maximalism",
"jijian zhuyi": "minimalism", "jijian": "minimalism",
"houtu": "impasto", "hou tu": "impasto",
"sailulu": "cel shading", "sai lu lu": "cel shading",
"banxieshi": "semi-realistic", "ban xieshi": "semi-realistic",
"jincou goutu": "tight framing", "jincou": "tight framing",
"flat tone": "flat color", "flat tones": "flat color",
"shangbanshen": "upper body", "shang banshen": "upper body",
"banshen": "upper body",
"qifenshen": "cowboy shot", "qifen shen": "cowboy shot",
"quanshen": "full body", "quan shen": "full body",
"texie": "close-up",
"zhanzi": "standing", "zuozi": "sitting",
"tangzi": "lying", "pazi": "on stomach",
"rouhe guangxian": "soft lighting",
"ziran guang": "natural lighting",
"niguang": "backlighting", "ceguang": "side lighting",
"jingshen": "depth of field", "liubai": "negative space",
})
QUALITY_TAGS = frozenset({
"masterpiece", "best quality", "great quality", "good quality", "normal quality",
"low quality", "worse quality", "worst quality", "very aesthetic", "aesthetic",
"displeasing", "very displeasing", "newest", "recent", "mid", "early", "old",
"absurdres", "highres", "amazing quality", "score_9", "score_8_up", "score_7_up",
"score_6_up", "score_5_up", "score_4_up", "source_anime", "source_cartoon",
"source_furry", "source_pony", "source_photo",
})
# 4B 爱写的“元标签”:不是画面内容,占位置还会稀释主体。直接丢。
META_TAGS = frozenset({
"detailed", "details", "detailed illustration", "highly detailed", "intricate details",
"intricate detail", "extreme detail", "extreme details", "ultra detailed", "ultra-detailed",
"hyper detailed", "hyper-detailed", "sharp detail", "sharp details", "fine detail",
"fine details", "crisp detail", "crisp details", "pure tone", "central focus", "soft focus",
"straightforward pose", "animation",
"dynamic composition", "tension composition", "tense composition",
"camera angle", "viewing angle", "eye level", "eye-level",
"eye level shot", "eye-level shot",
"image quality", "high resolution", "composition", "framing", "shot type",
"excessive style", "excessive detail", "excessive details",
"confident pose", "dynamic pose", "pose", "dense style", "dense details",
"artist tag", "auto-quality", "auto quality",
# 4B 偶尔把 compact composition 拼成 compacted composition;
# 用户自己写的 clean composition 保留,不要做通配过滤。
"compacted composition", "compact composition", "compressed composition",
# 4B 给夜景补的“氛围”同义词,不改变画面内容,只占标签位。
"night atmosphere", "night ambiance", "night ambience",
"night vibe", "night vibes", "night mood",
})
# 混合输入(英文标签 + 中文短语)会整段交给 4B,模型容易改写或丢掉英文标签。
# 这里维护两类确定性回填:固定中文术语的英文对应,以及“看起来就是标签”的英文段。
ZH_TAG_GLOSSARY = {
"极繁主义": "maximalism",
"极简主义": "minimalism",
"厚涂": "impasto",
"赛璐璐": "cel shading",
"半写实": "semi-realistic",
"平涂": "flat color",
"紧凑构图": "tight framing",
"上半身": "upper body",
"半身": "upper body",
"七分身": "cowboy shot",
"全身": "full body",
"特写": "close-up",
"站姿": "standing",
"坐姿": "sitting",
"躺姿": "lying",
"趴姿": "on stomach",
"柔和光线": "soft lighting",
"自然光": "natural lighting",
"逆光": "backlighting",
"侧光": "side lighting",
"景深": "depth of field",
"留白": "negative space",
}
# 用户点名具体服装时,4B 常换成同类但不同的款式(皮夹克→风衣、牛仔裤→西裤)。
# 这里按“原文词 → 标准标签 + 需要替换掉的同类词”确定性校正。
IDEA_GARMENT_RULES = (
(
re.compile(r"皮夹克|皮衣|皮外套|leather jacket", re.I),
"leather jacket",
re.compile(r"\b(?:trench coat|overcoat|coat|jacket|blazer|parka|windbreaker)\b", re.I),
),
(
re.compile(r"风衣|大衣|trench coat", re.I),
"trench coat",
re.compile(r"\b(?:leather jacket|overcoat|coat|jacket|blazer|parka)\b", re.I),
),
(
re.compile(r"牛仔裤|jeans", re.I),
"jeans",
re.compile(r"\b(?:pants|trousers|slacks)\b", re.I),
),
(
re.compile(r"连衣裙|one[- ]piece dress", re.I),
"dress",
re.compile(r"\b(?:skirt|gown|kimono)\b", re.I),
),
(
re.compile(r"短裙|迷你裙|miniskirt|short skirt", re.I),
"skirt",
re.compile(r"\b(?:dress|gown)\b", re.I),
),
(
re.compile(r"白衬衫|白色衬衫|white shirt", re.I),
"white shirt",
re.compile(r"\b(?:shirt|blouse)\b", re.I),
),
(
re.compile(r"黑衬衫|黑色衬衫|black shirt", re.I),
"black shirt",
re.compile(r"\b(?:shirt|blouse)\b", re.I),
),
(
re.compile(r"毛衣|sweater", re.I),
"sweater",
re.compile(r"\b(?:cardigan|pullover)\b", re.I),
),
(
re.compile(r"卫衣|连帽衫|hoodie", re.I),
"hoodie",
re.compile(r"\b(?:sweatshirt|sweater)\b", re.I),
),
(
re.compile(r"制服|uniform", re.I),
"uniform",
re.compile(r"\b(?:suit|outfit)\b", re.I),
),
(
re.compile(r"高跟鞋|high heels", re.I),
"high heels",
re.compile(r"\b(?:heels|stilettos)\b", re.I),
),
)
USER_TAG_SPLIT_RE = re.compile(r"[,,;;\n]+")# Anima 的画师标签以 @ 开头;混合输入回填时必须原样保留 @,否则画风会失效。
USER_TAG_CHARS_RE = re.compile(r"^@?[a-z0-9][a-z0-9 '\-+().]*$")
# 画师权重写作 (@wlop:1.2);消歧括号在提示词里转义成 \( \),否则会被当成权重。
ARTIST_WEIGHT_RE = re.compile(r"^\((.+):([0-9]+(?:\.[0-9]+)?)\)$")
def split_artist_tag(tag):
"""拆出画师名与权重文本;不是画师标签时返回 None。"""
value = str(tag or "").strip()
weight = ""
match = ARTIST_WEIGHT_RE.match(value)
if match:
value = match.group(1).strip()
weight = match.group(2)
if not value.startswith("@"):
return None
name = value[1:].strip()
if not name:
return None
return name, weight
def artist_tag_identity(tag):
"""去重用:hiten、@hiten (hitenkei)、(@hiten:0.6) 视为同一画师。"""
parts = split_artist_tag(tag)
if not parts:
return ""
value = parts[0].replace("\\", "").strip().lower()
return re.sub(r"\s*\([^()]*\)\s*$", "", value).strip()
# 已知 Danbooru 画师标签:用户漏写 @ 时补上,避免 Anima 把它当普通词或角色名。
KNOWN_ARTIST_TAGS = frozenset({"miku master"})
# 英文散文里常见的虚词;命中就整段放弃,交回 4B 转写。
USER_TAG_PROSE_RE = re.compile(
r"\b(?:a|an|the|she|he|her|his|him|they|them|their|we|our|i|you|your|"
r"is|are|was|were|be|been|being|has|have|had|with|without|while|when|"
r"because|that|this|these|those)\b",
re.I,
)
TAG_DENYLIST = frozenset({
"artist name", "web address", "patreon username", "fanbox username", "twitter username",
"english text", "signature", "watermark", "logo", "text", "speech bubble",
"censored", "bar censor", "mosaic censoring", "blurry", "jpeg artifacts",
"reference sheet", "character sheet", "multiple views", "comic", "4koma", "scan",
# 构图/质量/元信息不是内容标签,留给下面的 caption 与质量前缀。
"camera angle", "viewing angle", "composition",
"framing", "shot type", "image quality", "high resolution", "eye level", "eye-level",
"two people", "three people", "mature", "intimate", "passion", "mood",
"atmosphere", "vibe", "body", "skin",
# 模型名/档案名常被 4B 当成标签写回来,必须挡掉。
"miaomiao", "miao miao", "miaomiao harem", "miaomiaoharem", "harem",
"silvermoon", "silvermoonmix", "silvermoon mix", "cyberrealistic",
"cyberrealisticpony", "pony", "sdxl", "anima",
"female", "male", "1 person", "2 person", "one person", "two people",
# 4B 爱补的元信息:不是 Danbooru 内容标签,直接丢掉。
"18+", "adult", "adult female", "adult woman", "adult male", "adult man",
"1 adult", "1 adult female", "1 adult male", "environment",
# 泛主体词:Anima 本身就是动漫模型,写这些只会稀释角色与服装。
"anime girl", "anime boy", "anime woman", "anime man",
# 4B 对中文“日系/立绘”一类词的错拼噪声,原文没写就当不存在。
"rika",
})
HAIR_COLORS = frozenset({
"black hair", "blonde hair", "brown hair", "red hair", "silver hair", "white hair",
"grey hair", "gray hair", "blue hair", "pink hair", "purple hair", "green hair",
"orange hair", "aqua hair", "two-tone hair", "multicolored hair", "colored inner hair",
})
EYE_COLORS = frozenset({
"blue eyes", "red eyes", "green eyes", "brown eyes", "yellow eyes", "purple eyes",
"grey eyes", "gray eyes", "gold eyes", "aqua eyes", "pink eyes", "black eyes",
})
# 颜色保真:模型爱给没写发色/衣服颜色的角色补颜色,按原始描述做确定性过滤。
COLOR_WORDS = {
"black": r"黑|black",
"white": r"白|white",
"red": r"红|red",
"blue": r"蓝|blue",
"green": r"绿|green",
"yellow": r"黄|yellow",
"pink": r"粉|pink",
"purple": r"紫|purple",
"brown": r"棕|褐|brown",
"grey": r"灰|grey|gray",
"silver": r"银|silver",
"gold": r"金|gold|golden|blonde",
"orange": r"橙|橘|orange",
"aqua": r"青|水色|aqua|cyan",
}
COLOR_TAG_RE = re.compile(
r"\b(black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|silver|gold|golden|blonde|orange|aqua|cyan)\b",
re.I,
)
COLOR_ALIAS = {"gray": "grey", "golden": "gold", "blonde": "gold", "cyan": "aqua"}
def _idea_color_words(text):
"""按 COLOR_WORDS 同时识别中英文颜色词,避免只认英文。"""
return {name for name, pattern in COLOR_WORDS.items() if re.search(pattern, str(text or ""), re.I)}
def _color_key(word):
word = str(word or "")
for name, pattern in COLOR_WORDS.items():
if re.search(pattern, word, re.I):
return name
return ""
# 发色/瞳色只在颜色与部位相邻时才算数:避免 "long hair ... white background"
# 被误判成“用户写了白色头发”,进而挡掉角色官方发色。
IDEA_HAIR_COLOR_RE = re.compile(
r"(?P<color>black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|blonde|orange|aqua|cyan|黑|白|红|蓝|绿|黄|粉|紫|棕|褐|灰|银|金|橙|青)"
r"(?:色)?(?:的)?(?:长|短|中长|及腰)?"
r"(?:头发|发丝|发|hair|双马尾|马尾|丸子头|发髻|麻花辫|编发|"
r"twintails?|twin[- ]?tails?|twin[- ]?ponytails?|ponytail|braids?|"
r"double[- ]?buns?|double[- ]?bunch)",
re.I,
)
IDEA_EYE_COLOR_RE = re.compile(
r"(?P<color>black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|orange|aqua|cyan|黑|白|红|蓝|绿|黄|粉|紫|棕|褐|灰|银|金|橙|青)"
r"(?:色)?(?:的)?(?:眼睛|眼眸|瞳孔|瞳|眼|eyes?|iris)",
re.I,
)
# 英文常写 "hair is red" / 中文 "头发是红色",颜色不在部位前面。
IDEA_HAIR_COLOR_LINK_RE = re.compile(
r"(?:头发|发丝|hair)\s*(?:是|为|is|are|was|were)\s*"
r"(?P<color>black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|orange|aqua|cyan|黑|白|红|蓝|绿|黄|粉|紫|棕|褐|灰|银|金|橙|青)(?:色)?",
re.I,
)
IDEA_EYE_COLOR_LINK_RE = re.compile(
r"(?:眼睛|眼眸|瞳孔|瞳|眼|eyes?|iris)\s*(?:是|为|is|are|was|were)\s*"
r"(?P<color>black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|orange|aqua|cyan|黑|白|红|蓝|绿|黄|粉|紫|棕|褐|灰|银|金|橙|青)(?:色)?",
re.I,
)
def _idea_attribute_colors(text, kind="hair"):
patterns = (
(IDEA_HAIR_COLOR_RE, IDEA_HAIR_COLOR_LINK_RE)
if kind == "hair"
else (IDEA_EYE_COLOR_RE, IDEA_EYE_COLOR_LINK_RE)
)
found = set()
for pattern in patterns:
for match in pattern.finditer(str(text or "")):
key = _color_key(match.group("color"))
if key:
found.add(key)
return found
def _character_attribute_colors(idea, kind="hair"):
"""用户没写该部位颜色时,允许官方设定的颜色进入 caption/标签。"""
text = str(idea or "")
# 用户自己写了该部位的颜色就以用户为准;另一部位仍按官方设定补。
if _idea_attribute_colors(text, kind):
return set()
suffix = " hair" if kind == "hair" else " eyes"
colors = set()
for pattern, char_tag, _series in CHARACTER_TAG_RULES:
if not pattern.search(text):
continue
for tag in CHARACTER_APPEARANCE.get(char_tag, ()):
if not tag.endswith(suffix):
continue
for word in COLOR_TAG_RE.findall(tag):
colors.add(COLOR_ALIAS.get(word.lower(), word.lower()))
return colors
def _character_color_allowance(idea):
"""用户没写发色/瞳色时,允许官方设定的颜色进入 caption/标签。"""
return (
_character_attribute_colors(idea, "hair")
| _character_attribute_colors(idea, "eyes")
)
IDEA_HAIR_COLOR_ADJ_RE = re.compile(
r"\b(?:black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|blonde|orange|aqua|cyan)[- ]haired\b",
re.I,
)
IDEA_EYE_COLOR_ADJ_RE = re.compile(
r"\b(?:black|white|red|blue|green|yellow|pink|purple|brown|grey|gray|"
r"silver|gold|golden|orange|aqua|cyan)[- ]eyed\b",
re.I,
)
def _strip_attribute_color_phrases(text):
out = str(text or "")
for pattern in (
IDEA_HAIR_COLOR_RE,
IDEA_HAIR_COLOR_LINK_RE,
IDEA_HAIR_COLOR_ADJ_RE,
IDEA_EYE_COLOR_RE,
IDEA_EYE_COLOR_LINK_RE,
IDEA_EYE_COLOR_ADJ_RE,
):
out = pattern.sub(" ", out)
return out
def _idea_object_color_words(idea):
"""只统计挂在衣服/道具/背景上的颜色;发色不算,避免红发染红裙子。"""
raw = str(idea or "")
if re.search(r"彩色|多彩|多色|colorful|multicolor", raw, re.I):
return None
return _idea_color_words(_strip_attribute_color_phrases(raw))
def allowed_colors(idea):
"""原文明确写给衣服/背景等普通标签的颜色。"""
return _idea_object_color_words(idea)
def color_tag_ok(tag, allowed, idea=None):
if allowed is None:
return True
low_tag = str(tag or "").lower()
# 发色/瞳色单独判断:白色背景不代表可以给角色补白头发。
if idea is not None:
if low_tag.endswith(" hair"):
allowed = (
_idea_attribute_colors(idea, "hair")
| _character_attribute_colors(idea, "hair")
)
elif low_tag.endswith(" eyes"):
allowed = (
_idea_attribute_colors(idea, "eyes")
| _character_attribute_colors(idea, "eyes")
)
for word in COLOR_TAG_RE.findall(low_tag):
key = COLOR_ALIAS.get(word.lower(), word.lower())
if key not in allowed:
return False
return True
def _scrub_caption_sentence(sentence, hair_allowed, eye_allowed, object_allowed):
text = str(sentence or "")
removed_attribute = False
for match in reversed(list(COLOR_TAG_RE.finditer(text))):
key = COLOR_ALIAS.get(match.group(0).lower(), match.group(0).lower())
before = text[max(0, match.start() - 28):match.start()].lower()
after = text[match.end():match.end() + 28].lower()
if (
re.match(r"[- ]?haired\b", after)
or re.match(r"\s+hair\b", after)
or re.match(
r"\s+(?:double[- ]?)?(?:bunch|bun|braid|tail|ponytail)s?\b",
after,
)
):
category = "hair"
elif re.match(r"[- ]?eyed\b", after) or re.match(r"\s+eyes?\b", after):
category = "eye"
elif re.search(r"\bhair\s+(?:is|are|was|were)\s*$", before):
category = "hair"
elif re.search(r"\beyes?\s+(?:is|are|was|were)\s*$", before):
category = "eye"
else:
category = "object"
allowed = (
hair_allowed if category == "hair"
else eye_allowed if category == "eye"
else object_allowed
)
if key in allowed:
continue
if re.search(r"\b(?:is|are|was|were)\s*$", before):
# 颜色作表语(Her dress is red.)时删掉颜色会留下病句,整句放弃。
return ""
tail = re.match(r"[- ]?(?:haired|eyed)\b", after)
if tail:
text = text[:match.start()] + text[match.end() + tail.end():]
else:
end = match.end()
if end < len(text) and text[end] == " ":
end += 1
text = text[:match.start()] + text[end:]
if category in ("hair", "eye"):
removed_attribute = True
if removed_attribute:
# 删掉发色/瞳色后可能留下 "hair and eyes" 这类残句。
text = re.sub(r"\b(hair|eyes)\s+and\s+(?:eyes|hair)\b", r"\1", text, flags=re.I)
text = re.sub(r",\s*(?:and\s+)?(?:eyes|hair)\b", "", text, flags=re.I)
text = re.sub(r"\s+and\s+(?:eyes|hair)\b", "", text, flags=re.I)
text = re.sub(r"\s{2,}", " ", text).strip()
if text and text[0].islower():
text = text[0].upper() + text[1:]
return text
def scrub_caption_colors(caption, idea):
"""按部位清理未提及的颜色,保留句子而不是整句删掉。"""
text = str(caption or "").strip()
object_allowed = _idea_object_color_words(idea)
if not text or object_allowed is None:
return text
hair_allowed = (
_idea_attribute_colors(idea, "hair")
| _character_attribute_colors(idea, "hair")
)
eye_allowed = (
_idea_attribute_colors(idea, "eyes")
| _character_attribute_colors(idea, "eyes")
)
kept = []
for sentence in re.split(r"(?<=[.!?])\s+", text):
cleaned = _scrub_caption_sentence(sentence, hair_allowed, eye_allowed, object_allowed)
if cleaned:
kept.append(cleaned.strip())
return " ".join(part for part in kept if part).strip()
NUDITY_TAGS = frozenset({
"nude", "completely nude", "nude only", "naked", "topless", "bottomless",
})
# 4B 会把普通舞台/睡姿/泳装场景补成性行为;原文没有性/裸体线索时全部剔除。
SEX_CONTENT_TAGS = frozenset({
"sex", "having sex", "sex scene", "vaginal", "anal", "oral", "fellatio",
"blowjob", "paizuri", "handjob", "masturbation", "doggy style", "missionary",
"girl on top", "cowgirl position", "cowgirl", "reverse cowgirl", "creampie",
"cum", "cumshot", "cum in pussy", "cum on body", "facial", "bukkake",
"squirting", "sex from behind", "standing sex", "spread legs", "pussy",
"penis", "vagina", "anus", "nipples", "areola", "areolae", "penetration",
"ejaculation", "completely nude", "nude", "nude only", "naked",
"topless", "bottomless", "no bra", "no panties", "pantyshot",
})
SEX_CAPTION_RE = re.compile(
r"\b(?:having sex|has sex|sex scene|sex act|sexual act|girl on top|cowgirl|missionary|"
r"doggy style|fellatio|blowjob|paizuri|handjob|masturbat\w*|creampie|"
r"cumshot|cumming|squirting|penetrat\w+|ejaculat\w+|"
r"spread(?:ing)? (?:her|their|the) legs|genitals?|"
r"nude|naked|topless|bottomless)\b",
re.I,
)
# 4B 会把底模/档案名当画风词写进 caption,必须整句剔除。
MODEL_CAPTION_RE = re.compile(
r"\b(?:miaomiao|miao miao|silvermoon(?:mix)?|cyberrealistic(?: pony)?|"
r"anima|pony|sdxl|auto[- ]quality|score_\d)\b",
re.I,
)
POSE_TAGS = frozenset({
"lying on side", "on side", "on back", "lying on back", "on stomach", "lying on stomach",
"seiza", "standing", "sitting",
})
BASE_GARMENTS = frozenset({
"shirt", "dress", "coat", "jacket", "skirt", "pants", "shorts", "jeans",
"uniform", "sweater", "hoodie", "vest", "robe", "cloak", "cape",
})
# 原文没有人物时,4B 会虚构一个“站在湖边的人”并给他穿衣服;
# 这些衣服标签只有原文提到对应中文/英文词时才保留。
GARMENT_IDEA_HINTS = {
"shirt": ("衬衫", "shirt"),
"dress": ("裙", "dress", "gown"),
"coat": ("外套", "大衣", "风衣", "coat"),
"jacket": ("夹克", "外套", "jacket"),
"skirt": ("裙", "skirt"),
"pants": ("裤", "pants", "trousers"),
"shorts": ("短裤", "shorts"),
"jeans": ("牛仔裤", "jeans"),
"uniform": ("制服", "uniform"),
"sweater": ("毛衣", "sweater"),
"hoodie": ("卫衣", "hoodie"),
"vest": ("马甲", "背心", "vest"),
"robe": ("长袍", "robe"),
"cloak": ("斗篷", "披风", "cloak"),
"cape": ("斗篷", "披风", "cape"),
}
# 这些名词前的颜色可以安全地删除;其他标签(如 blue archive)不做词内删除,
# 避免把系列名拆成 archive。
COLORABLE_NOUNS = frozenset({
"shirt", "dress", "skirt", "coat", "jacket", "pants", "shorts", "jeans",
"uniform", "sweater", "hoodie", "vest", "robe", "swimsuit", "bikini",
"lingerie", "bra", "panties", "stockings", "thighhighs", "kimono", "gown",
"suit", "tie", "scarf", "gloves", "hat", "boots", "shoes", "heels",
"sandals", "socks", "background", "wall", "walls", "floor", "ceiling",
"bed", "sheet", "sheets", "blanket", "pillow", "curtain", "curtains",
"carpet", "sky", "cloud", "clouds", "snow", "sand", "water", "sea",
"ocean", "lake", "mountain", "mountains", "grass", "flower", "flowers",
"rose", "roses", "hair", "eyes", "skin", "lips", "nails",
})
def sanitize_color_tag(tag, allowed, idea=None):
"""未提及的颜色优先从可染色名词里删掉,整条标签保留。
red dress -> dress,white background -> background;
系列名/角色名里的颜色(blue archive)不能拆词,整条丢弃。
"""
low = re.sub(r"\s+", " ", str(tag or "").lower()).strip()
if not low or allowed is None:
return low
# 发色/瞳色整条按部位判断,避免把 "red hair" 修成 "hair"。
if idea is not None and low.endswith((" hair", " eyes")):
return low if color_tag_ok(low, allowed, idea) else ""
if re.search(r"\b(?:haired|eyed)\b", low):
return low if color_tag_ok(low, allowed, idea) else ""
words = low.split()
if not any(word in COLORABLE_NOUNS for word in words):
return low if color_tag_ok(low, allowed, idea) else ""
out = low
for word in COLOR_TAG_RE.findall(low):
key = COLOR_ALIAS.get(word.lower(), word.lower())
if key in allowed:
continue
out = re.sub(r"\b%s\b\s*" % re.escape(word), "", out)
out = re.sub(r"^(?:a|an|the|and|of|with)\s+", "", out.strip())
out = re.sub(r"\s{2,}", " ", out).strip(" ,-")
return out
PERSON_TAG_RE = re.compile(r"^(\d+)\+?(girl|girls|boy|boys|other|others)$")
PERSON_TAGS = frozenset({
"solo", "multiple girls", "multiple boys", "multiple others", "male focus", "female focus",
})
PERSON_WORD_RE = re.compile(r"女|男|人|娘|少女|男孩|女孩|woman|girl|boy|man|male|female|person|couple|lady", re.I)
# 明确的非人物主体:只有这类描述才允许服务端推翻 4B 的人物标签。
# 街头、海边、樱花树下这类场景不算,避免把“初音未来在海边”误判成风景。
NON_PERSON_SUBJECT_RE = re.compile(
r"(?:一只|一头|一匹|一条|一群|两只|两头)[^,。;,;]{0,10}"
r"(?:猫|狗|鸟|鱼|马|牛|羊|兔子|动物|昆虫)"
r"|(?:一座|一片|一条|一泓|一汪|一湾)[^,。;,;]{0,8}"
r"(?:山|雪山|山峰|湖|湖泊|湖面|河|河流|森林|沙漠|草原|海|大海|星空|银河|城市)"
r"|纯风景|静物|无人物|没有人物|不要人物"
r"|\b(?:landscape|scenery|still life|no people|no person)\b",
re.I,
)
# 无人物场景里,4B 有时仍会写一个“站在湖边的人”。caption 出现这些词
# 就整句丢弃,避免风景图凭空多出一个与输入无关的角色。
NO_PERSON_CAPTION_RE = re.compile(
r"\b(?:adult|figure|silhouette|person|people|someone|anyone|"
r"woman|women|man|men|girl|boy|female|male|lady|gentleman|"
r"she|he|her|his|him|they|their|"
r"standing|sitting|walking|running|kneeling|lying|"
r"wearing|dressed|hands?|arms?|legs?|hair|eyes|pose|poses)\b",
re.I,
)
# 用确定性映射修正 4B 的拼写/音译错误。
# 只修正常见角色,未列出的角色仍由 4B 自己给 Danbooru 标签。
CHARACTER_TAG_RULES = (
# "miku master" 是画师标签,不是初音未来;不能把它当角色名。
(re.compile(r"(?:初音未来|初音ミク|hatsune miku|\bmiku\b)(?![\s_]+master\b)", re.I), "hatsune miku", "vocaloid"),
(re.compile(r"雷电将军|雷电影|raiden shogun|raiden shougun", re.I), "raiden shogun", "genshin impact"),
(re.compile(r"八重神子|yae miko", re.I), "yae miko", "genshin impact"),
(re.compile(r"甘雨|ganyu", re.I), "ganyu", "genshin impact"),
(re.compile(r"刻晴|keqing", re.I), "keqing", "genshin impact"),
(re.compile(r"胡桃|hu tao", re.I), "hu tao", "genshin impact"),
(re.compile(r"芙宁娜|furina", re.I), "furina", "genshin impact"),
(re.compile(r"神里绫华|kamisato ayaka", re.I), "kamisato ayaka", "genshin impact"),
(re.compile(r"优菈|eula", re.I), "eula", "genshin impact"),
(re.compile(r"蒂法|tifa lockhart", re.I), "tifa lockhart", "final fantasy vii"),
(re.compile(r"\b2b\b|ヨルハ2号b型", re.I), "2b", "nier:automata"),
(re.compile(r"不知火舞|mai shiranui", re.I), "mai shiranui", "fatal fury"),
(re.compile(r"春丽|chun-li", re.I), "chun-li", "street fighter"),
(re.compile(r"艾达王|ada wong", re.I), "ada wong", "resident evil"),
(re.compile(r"劳拉|laracroft|lara croft", re.I), "lara croft", "tomb raider"),
)
CHARACTER_TAG_FUZZ = {
"hatsune miku": re.compile(r"(?:hatsune miku|hatune miku|\bmiku\b)(?![\s_]+master\b)", re.I),
"raiden shogun": re.compile(r"raiden|raiten|shogun|shougun|genryu|genryuu", re.I),
"yae miko": re.compile(r"yae|miko", re.I),
"ganyu": re.compile(r"ganyu|gan yue", re.I),
"keqing": re.compile(r"keqing|ke qing", re.I),
"hu tao": re.compile(r"hu ?tao|hutao", re.I),
"furina": re.compile(r"furina", re.I),
"kamisato ayaka": re.compile(r"kamisato|ayaka", re.I),
"eula": re.compile(r"eula", re.I),
"tifa lockhart": re.compile(r"tifa", re.I),
"2b": re.compile(r"\b2b\b|yorha", re.I),
"mai shiranui": re.compile(r"shiranui|mai shiranui", re.I),
"chun-li": re.compile(r"chun[- ]?li", re.I),
"ada wong": re.compile(r"ada wong", re.I),
"lara croft": re.compile(r"lara croft", re.I),
}
# caption 里的角色名同样要归一到 Danbooru 的拼写。
CHARACTER_DISPLAY = {
"hatsune miku": (
re.compile(r"(?:\b(?:hatune|hatsune)\s+miku\b|\bmiku\b)(?![\s_]+master\b)", re.I),
"Hatsune Miku",
),
"raiden shogun": (
re.compile(r"\b(?:genryu|genryuu|raiden)\s+(?:shougun|shogun)\b|\braiden shogun\b", re.I),
"Raiden Shogun",
),
"yae miko": (re.compile(r"\byae\s+miko\b|\bmiko\b", re.I), "Yae Miko"),
"ganyu": (re.compile(r"\bganyu\b", re.I), "Ganyu"),
"keqing": (re.compile(r"\bke ?qing\b", re.I), "Keqing"),
"hu tao": (re.compile(r"\bhu ?tao\b", re.I), "Hu Tao"),
"furina": (re.compile(r"\bfurina\b", re.I), "Furina"),
"kamisato ayaka": (re.compile(r"\b(?:kamisato\s+)?ayaka\b", re.I), "Kamisato Ayaka"),
"eula": (re.compile(r"\beula\b", re.I), "Eula"),
"tifa lockhart": (re.compile(r"\btifa(?:\s+lockhart)?\b", re.I), "Tifa Lockhart"),
"2b": (re.compile(r"\b2b\b", re.I), "2B"),
"mai shiranui": (re.compile(r"\b(?:mai\s+)?shiranui\b", re.I), "Mai Shiranui"),
"chun-li": (re.compile(r"\bchun[- ]?li\b", re.I), "Chun-Li"),
"ada wong": (re.compile(r"\bada\s+wong\b", re.I), "Ada Wong"),
"lara croft": (re.compile(r"\blara\s+croft\b", re.I), "Lara Croft"),
}
# Anima 的 caption 权重很高;只写角色标签、不写外观时,角色容易退回通用脸。
# 用户没指定发色/瞳色时,补 2-3 个官方设定里的可见特征(不写服装,避免和用户服装冲突)。
CHARACTER_APPEARANCE = {
"hatsune miku": ("twintails", "aqua hair", "aqua eyes"),
"raiden shogun": ("purple hair", "purple eyes", "braid"),
"yae miko": ("pink hair", "purple eyes", "fox ears"),
"ganyu": ("blue hair", "purple eyes", "horns"),
"keqing": ("purple hair", "purple eyes", "twintails"),
"hu tao": ("brown hair", "red eyes", "twin tails"),
"furina": ("white hair", "blue eyes", "heterochromia"),
"kamisato ayaka": ("light blue hair", "blue eyes"),
"eula": ("blue hair", "blue eyes"),
"tifa lockhart": ("black hair", "red eyes"),
"2b": ("white hair", "blue eyes"),
"mai shiranui": ("brown hair", "brown eyes"),
"chun-li": ("brown hair", "brown eyes"),
"ada wong": ("black hair", "brown eyes"),
"lara croft": ("brown hair", "brown eyes"),
}
NON_PERSON_EXTRA = frozenset({
"animal ears", "cat ears", "dog ears", "fox ears", "fake animal ears", "kemonomimi",
"tail", "cat tail", "humanization", "personification", "looking at viewer", "looking back",
"full body", "cowboy shot", "upper body",
"standing", "sitting", "walking", "running", "kneeling", "lying",
"facing away", "from behind", "from side", "profile", "three-quarter view",
})
HAIR_LENGTH = frozenset({
"short hair", "medium hair", "long hair", "very long hair", "absurdly long hair",
})
# 无人物场景里,4B 会顺手补上“站在湖边的人”穿/拿的东西;原文没提就一并清掉。
NO_PERSON_PROP_HINTS = {
"boots": ("靴", "boots"),
"shoes": ("鞋", "shoes"),
"sneakers": ("鞋", "sneakers"),
"sandals": ("凉鞋", "sandals"),
"heels": ("高跟鞋", "heels"),
"hat": ("帽", "hat"),
"gloves": ("手套", "gloves"),
"scarf": ("围巾", "scarf"),
"bag": ("包", "bag", "backpack"),
"backpack": ("背包", "backpack", "包"),
"coffee cup": ("咖啡", "杯", "coffee", "cup", "mug"),
"cup": ("杯", "cup", "mug"),
"coffee": ("咖啡", "coffee"),
"food": ("食物", "food", "餐"),
"drink": ("饮料", "drink", "杯"),
# 手持道具同样是“虚构人物”的伴生物;原文没提就清掉。
"wooden staff": ("木杖", "法杖", "长棍", "staff", "杖", "棍"),
"staff": ("木杖", "法杖", "长棍", "staff", "杖", "棍"),
"sword": ("剑", "刀", "sword", "katana"),
"katana": ("剑", "刀", "katana"),
"umbrella": ("伞", "umbrella"),
"lantern": ("灯笼", "提灯", "lantern"),
"bouquet": ("花束", "bouquet"),