File size: 12,101 Bytes
a43b986
 
 
 
e90de9a
a43b986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e90de9a
 
a43b986
 
 
 
 
 
 
 
 
 
00dc4ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e90de9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00dc4ac
 
 
e90de9a
 
 
 
00dc4ac
e90de9a
 
 
 
 
00dc4ac
 
e90de9a
 
00dc4ac
 
 
e90de9a
 
 
 
 
 
 
00dc4ac
 
 
e90de9a
 
 
 
 
 
 
00dc4ac
 
 
 
e90de9a
00dc4ac
 
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
"""Rank catalog LoRAs against an existing prompt using local text matching."""

import re
import unicodedata
from collections import Counter


_WORD = re.compile(r"[^\W_]+", re.UNICODE)
_SPLIT = re.compile(
    r"[;.!?\n]+|\b(?:but|instead|но|обаче|obache)\b|"
    r",\s*(?=(?:then|add|use|после|добави|след това|posle|dobavi)\b)"
)
_NEGATIVE = re.compile(
    r"\b(?:no|not|don['’]t|rather than|without|avoid|exclude|never|minus|без|не|избягвай|изключи|"
    r"bez|ne|izbyagvai|izbqgvai)\b"
)
_NEGATIVE_SECTION = re.compile(
    r"\b(?:negative(?: prompt)?|негативен промпт|отрицателен промпт|negativen prompt)\s*:"
)
_TITLE_NOISE = set(
    "wan wan2 wan22 ltx ltxv minimax h3 ph3 model video image diffusion lora loras adapter adapters "
    "i2v t2v i2i turbo flashgen checkpoint version v1 v2 v3 v4 high low rank alpha safetensors "
    "effect effects style camera motion animation movement cinematic realism realistic quality "
    "the a an for of by with and in on to pack update new better official trained nsfw sfw"
    .split()
)
_GENERIC_TRIGGERS = _TITLE_NOISE | set(
    "person people woman women man men girl boy adult background scene subject shot light body face "
    "full close up look looking move moving walk walking run running dance dancing hands hair bunny "
    "1girl 1boy none default description"
    .split()
)
_TRIGGER_FIELDS = ("trigger", "triggers", "trigger_words", "trainedWords", "trained_words", "activation_words")
_PLACEHOLDER = re.compile(r"^(?:see|check|read|refer to)\b.*\b(?:description|instructions|example|page)\b")
_PROMPT_ALIASES = {
    "черно бял филм": "black and white film",
    "cherno byal film": "black and white film",
    "мастилена рисунка": "ink wash illustration",
    "mastilena risunka": "ink wash illustration",
    "ръчно рисуван": "hand drawn",
    "rachno risuvan": "hand drawn",
    "камерата се върти около": "camera orbit",
    "kamerata se vyrti okolo": "camera orbit",
    "приближаване на камерата": "camera zoom in",
    "priblijavane na kamerata": "camera zoom in",
    "отдалечаване на камерата": "camera zoom out",
    "otdalechavane na kamerata": "camera zoom out",
}
_MOTION_PHRASES = tuple(tuple(phrase.split()) for phrase in (
    "camera orbit", "orbit camera", "zoom in", "zoom out", "camera shake", "camera pan", "dolly zoom",
))


def _words(text):
    return tuple(_WORD.findall(unicodedata.normalize("NFKC", str(text or "")).casefold()))


def _positive_clauses(prompt):
    text = unicodedata.normalize("NFKC", str(prompt or "")).casefold()
    text = _NEGATIVE_SECTION.split(text, maxsplit=1)[0]
    clauses = []
    for part in _SPLIT.split(text):
        positive = _NEGATIVE.split(part, maxsplit=1)[0]
        for fragment in positive.split(","):
            clause = " " + " ".join(_words(fragment)) + " "
            clauses.append(clause)
            for alias, target in _PROMPT_ALIASES.items():
                if f" {alias} " in clause:
                    clauses.append(f" {target} ")
    return clauses


def _trigger_phrases(value):
    if isinstance(value, (list, tuple)):
        for part in value:
            yield from _trigger_phrases(part)
    elif isinstance(value, str):
        for part in re.split(r"[,;\n]+", value):
            phrase = _words(part)
            if (not _PLACEHOLDER.match(" ".join(phrase))
                    and any(len(word) >= 3 and word not in _GENERIC_TRIGGERS for word in phrase)):
                yield phrase


def _title_phrases(item):
    title = str(item.get("name") or item.get("title") or "").split(" · ", 1)[0]
    title = re.sub(r"^[\w.-]+/(?=\S)", "", title)
    title = re.sub(r"\bv\d+(?:\.\d+)*\b|\b\d+(?:\.\d+)+\b", " ", title, flags=re.I)
    for part in re.split(r"\||\s[-–—]\s", title):
        yield tuple(dict.fromkeys(word for word in _words(part) if not word.isdecimal() and word not in _TITLE_NOISE))


def _motion_phrases(item):
    title = str(item.get("name") or item.get("title") or "").split(" · ", 1)[0]
    title_words = [" " + " ".join(_words(title)) + " "]
    return (phrase for phrase in _MOTION_PHRASES if _contains(title_words, phrase))


def _contains(clauses, phrase):
    return bool(phrase) and any(" " + " ".join(phrase) + " " in clause for clause in clauses)


def rank_prompt_loras(prompt, items):
    """Return original catalog entries ordered by explicit positive trigger or title matches."""
    if not str(prompt or "").strip():
        return []
    clauses = _positive_clauses(prompt)
    ranked = []
    for item in items:
        if not isinstance(item, dict):
            continue
        triggers = {phrase for field in _TRIGGER_FIELDS for phrase in _trigger_phrases(item.get(field))}
        hits = [phrase for phrase in triggers if _contains(clauses, phrase)
                and (len(phrase) > 1 or phrase[0] not in _WAN_AMBIGUOUS_TRIGGERS)]
        if hits:
            ranked.append(((2, max(map(len, hits))), item))
            continue
        hits = [phrase for phrase in _title_phrases(item) if len(phrase) >= 2
                and any(all(f" {word} " in clause for word in phrase) for clause in clauses)]
        hits.extend(phrase for phrase in _motion_phrases(item) if _contains(clauses, phrase))
        if hits:
            ranked.append(((1, max(map(len, hits))), item))
    ranked.sort(key=lambda entry: entry[0], reverse=True)
    return [item for _, item in ranked]


_WAN_BUST_ALIASES = {
    "tit": "tits", "tits": "tits", "cici": "tits", "tsitsi": "tits", "цици": "tits",
    "boob": "boobs", "boobs": "boobs",
    "breast": "breasts", "breasts": "breasts", "гърда": "breasts", "гърди": "breasts",
    "gardi": "breasts", "gurdi": "breasts", "gyrdi": "breasts",
    "bust": "bust", "бюст": "bust", "byust": "bust", "biust": "bust",
}
_WAN_BUST_UNRELATED = frozenset(
    "crotch crotchboobs quadboob triboob lick licking squeeze squeezing play suck sucking "
    "grope groping fondle fondling grab grabbing motorboat motorboating blowjob handjob "
    "sex penetration porn topless nude nipples fetish flashing stripping fuck fucking titfuck "
    "titfucking titpounding pounding".split()
)
_WAN_BUST_FEATURES = frozenset(
    "best big bounce bouncing expansion full huge large natural physics round shaking shape size "
    "slider small torpedo".split()
)
_WAN_OTHER_BUST = re.compile(
    r"\b(?:bust (?:through|out|open|up|down|of)|(?:bronze|marble|sculpted|stone|plaster) bust)\b"
)
_WAN_BIRD_TITS = re.compile(r"\b(?:great|blue|coal|crested|long tailed) tits?\b")
_WAN_VULVA_ALIASES = {
    "pussy": "pussy", "pussies": "pussy", "putka": "pussy", "putki": "pussy",
    "путка": "pussy", "путки": "pussy",
    "vagina": "vagina", "vaginas": "vagina", "вагина": "vagina", "вагини": "vagina",
    "vulva": "vulva", "vulvas": "vulva", "вулва": "vulva", "вулви": "vulva",
    "labia": "labia", "labium": "labia", "лабии": "labia",
}
_WAN_VULVA_UNRELATED = frozenset(
    "anus anal double finger fingering fingers kick kickbusting rub rubbing slap spreading spread "
    "penetration pentration penetrate riding oral blowjob handjob fuck fucking cuntbusting pussyjob".split()
)
_WAN_VULVA_FEATURES = frozenset(
    "close closeup puffy anatomy detailed natural shape realistic size".split()
)
_WAN_OTHER_PUSSY = re.compile(r"\bpussy (?:cat|willow)s?\b")
_WAN_AMBIGUOUS_TRIGGERS = _WAN_BUST_ALIASES.keys() | _WAN_VULVA_ALIASES.keys()
_WAN_GENERIC_SEARCH_WORDS = _GENERIC_TRIGGERS | set(
    "about above across adult after against all along also anime another any around back beach beautiful because before "
    "behind below black blue both branch bright building camera car change clean closeup clothing color dance dancer daylight "
    "daytime details did dog dramatic end evening eyes fantasy fashion film flowers forest garden get girl green hand happy her him his how "
    "horizon indoor indoors kitchen landscape lighting lowangle man mountain mountains night ocean outdoor outdoors "
    "off our out outfit park perch photo photograph portrait rain red river road roof room scenery see she sits "
    "sitting skin slider slowly sky smile smiling smooth snow spring standing street studio sun sunlight sunset table "
    "texture than their them then there these they this those through too toward trees under until urban use very was "
    "water wave waves way were what when which white wide window while who why you zoom".split()
)
_WAN_SEARCH_FRAME = frozenset("find for lora loras show search suggest please want using make create keep".split())


def _wan_distinctive_words(words):
    return {word for word in words if len(word) >= 3 and any(char.isalpha() for char in word)
            and word not in _WAN_GENERIC_SEARCH_WORDS and word not in _WAN_SEARCH_FRAME
            and word not in _WAN_AMBIGUOUS_TRIGGERS}


def _wan_keyword_score(item, phrases, title_words, requested, frequency):
    hits = title_words & requested
    if hits:
        exact_title = any(phrase and requested.issuperset(phrase) for phrase in phrases)
        return (3 if exact_title else 2, len(hits), -sum(frequency[word] for word in hits))
    triggers = {phrase[0] for field in _TRIGGER_FIELDS for phrase in _trigger_phrases(item.get(field))
                if len(phrase) == 1 and phrase[0] in requested}
    return (1, len(triggers), 0) if triggers else (0, 0, 0)


def _wan_anatomy_score(words, phrases, aliases, requested, blocked, features, known_title=None):
    if not requested or words & blocked:
        return 0
    anatomy = {aliases[word] for word in words if word in aliases}
    if known_title and known_title in phrases:
        return 1
    if not anatomy or (not words & features and any(word not in aliases for phrase in phrases for word in phrase)):
        return 0
    return 2 if anatomy & requested else 1


def rank_wan_prompt_suggestions(prompt, items):
    """Rank related titles for distinctive positive prompt words and recognized synonyms."""
    clauses = _positive_clauses(prompt)
    prompt_words = set()
    for clause in clauses:
        clause = _WAN_BIRD_TITS.sub(" ", _WAN_OTHER_BUST.sub(" ", clause))
        prompt_words.update(_words(_WAN_OTHER_PUSSY.sub(" ", clause)))
    bust = {_WAN_BUST_ALIASES[word] for word in prompt_words if word in _WAN_BUST_ALIASES}
    vulva = {_WAN_VULVA_ALIASES[word] for word in prompt_words if word in _WAN_VULVA_ALIASES}
    requested = _wan_distinctive_words(prompt_words)
    if not (bust or vulva or requested):
        return []

    catalog = []
    frequency = Counter()
    for item in items:
        if not isinstance(item, dict):
            continue
        phrases = tuple(_title_phrases(item))
        title_words = {word for phrase in phrases for word in phrase}
        frequency.update(title_words & requested)
        catalog.append((item, phrases, title_words))

    ranked = []
    for item, phrases, title_words in catalog:
        name = str(item.get("name") or item.get("title") or "")
        title, _, metadata = name.partition(" · ")
        words = set(_words(title))
        anatomy = max(
            _wan_anatomy_score(words, phrases, _WAN_BUST_ALIASES, bust, _WAN_BUST_UNRELATED, _WAN_BUST_FEATURES),
            _wan_anatomy_score(words, phrases, _WAN_VULVA_ALIASES, vulva, _WAN_VULVA_UNRELATED,
                               _WAN_VULVA_FEATURES, known_title=("godpussy",)),
        )
        keyword = _wan_keyword_score(item, phrases, title_words, requested, frequency) if requested else (0, 0, 0)
        if not (anatomy or keyword[0]):
            continue
        # Saved library titles may name both modes. The actual version's base model wins.
        base_words = _words(item.get("base_model") or metadata.partition(" · ")[0])
        i2v = "i2v" in (base_words or words)
        ranked.append(((anatomy, *keyword, i2v), item))
    ranked.sort(key=lambda row: row[0], reverse=True)
    return [item for _, item in ranked]