Wan-2.2-Studio / lora_cpu_picker.py
amisima's picture
Search CPU LoRA catalogs by prompt keywords
e90de9a verified
Raw History Blame Contribute Delete
12.1 kB
"""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]