"""Rank catalog LoRAs against an existing prompt using local text matching.""" import re import unicodedata _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() ) _WEAK_TITLE_NOISE = _GENERIC_TRIGGERS | set( "add change create draw edit enhance keep make new original paint portrait put remove render replace " "show use want base detail enhancer face outpaint swap qwen viggle moss " "please from into this that like some just another more less your their our have can could would" .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", )) _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", } _NON_BUST = re.compile( r"\b(?:(?:great|blue|coal|crested|long tailed) tits?|(?:chicken|turkey|duck) breasts?|" r"breast (?:cancer|feeding)|bust (?:through|out|open|up|down|of)|" r"(?:bronze|marble|sculpted|stone|plaster) bust)\b" ) _BUST_ACTIONS = set( "clamp licking lick squeezing squeeze sucking suck grabbing grab groping grope " "fondling fondle motorboating motorboat flashing stripping wank wanking".split() ) _PELVIC_ALIASES = { "pussy": "pussy", "pussies": "pussy", "vagina": "vagina", "vaginas": "vagina", "вагина": "vagina", "вагини": "vagina", "vulva": "vulva", "vulvas": "vulva", "vulvae": "vulva", "вулва": "vulva", "вулви": "vulva", } _NON_PELVIC = re.compile(r"\bpussy (?:cats?|willows?|riot|bows?)\b") _PELVIC_EXCLUSIONS = _BUST_ACTIONS | set( "animal anthro canine cat dog doggy equine feline feral furry horse wolf " "penetration penetrating insertion inserting fingering fisting masturbation masturbating".split() ) _SUGGESTION_GROUPS = ( (_BUST_ALIASES, _NON_BUST, _BUST_ACTIONS), (_PELVIC_ALIASES, _NON_PELVIC, _PELVIC_EXCLUSIONS), ) _ALIAS_WORDS = _BUST_ALIASES.keys() | _PELVIC_ALIASES.keys() _TITLE_QUALIFIERS = re.compile(r"\([^)]*\)|\[[^]]*\]") 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 _CLOTHES = r"(?:clothes|clothing|garments)" _WHOSE = r"(?:(?:all(?: of)?|the|my|your|her|his|their|our|any)\s+)*" _UNCLOTHED = re.compile( rf"\b(?:(?:without|no)\s+{_WHOSE}{_CLOTHES}|без дрехи|bez drehi)\b" ) _NUDITY_REQUEST = re.compile( rf"\b(?:nude|nudes|nudity|naked|undress(?:ed|es|ing)?|unclothed|disrobe[ds]?|disrobing|" rf"(?:remove|take off|strip off)\s+{_WHOSE}{_CLOTHES}|take\s+{_WHOSE}{_CLOTHES}\s+off|" r"гол[аио]?|голи|съблечи|съблечена?|съблечено|съблечени|syblechi|sublechi)\b" ) _NON_NUDITY = re.compile( r"\b(?:nude[- ](?:colou?r(?:ed|s)?|tone[ds]?|shades?|pink|beige|palette|make[- ]?up|lip(?:stick|s)?|" r"nails?|polish|heels?|shoes?|pumps?|dress|bodysuit|tights|stockings|underwear|bra)|" r"naked[- ](?:eye|truth|mole[- ]rat|flame|cake)|undress(?:ed)?\s+(?:the\s+)?salad)\b" ) _COVER_UP = re.compile( r"\b(?:remove|hide|cover|censor)\s+(?:the\s+)?(?:nudity|nude body)|" r"\b(?:keep (?:her|him|them|the subject) (?:fully )?(?:dressed|clothed)|" r"(?:to|make (?:her|him|them)) fully clothed|" r"(?:put|keep) (?:her|his|their|the) clothes (?:back )?on)\b" ) def requests_nudity(prompt): text = unicodedata.normalize("NFKC", str(prompt or "")).casefold().replace("’", "'") text = _NEGATIVE_SECTION.split(text, maxsplit=1)[0] text = _UNCLOTHED.sub("unclothed", text) text = _NON_NUDITY.sub(" ", text) return any(_NUDITY_REQUEST.search(part) for part in _positive_clauses(text)) and not _COVER_UP.search(text) 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_text(item): title = str(item.get("name") or item.get("title") or "").split(" · ", 1)[0] title = re.sub(r"^[\w.-]+/(?=\S)", "", title) return re.sub(r"\bv\d+(?:\.\d+)*\b|\b\d+(?:\.\d+)+\b", " ", title, flags=re.I) def _title_phrases(item): for part in re.split(r"\||\s[–—-]\s", _title_text(item)): 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 _alias_terms(text, aliases, ignored): return {aliases[word] for word in _words(ignored.sub(" ", text)) if word in aliases} def rank_prompt_loras(prompt, items, *, include_suggestions=False): """Rank exact matches, optionally followed by unselected title suggestions.""" if not str(prompt or "").strip(): return [] clauses = _positive_clauses(prompt) if include_suggestions: keywords = {word for clause in clauses for word in clause.split() if len(word) >= 3 and not word.isdecimal() and word not in _WEAK_TITLE_NOISE and word not in _ALIAS_WORDS} requested_groups = [] for aliases, ignored, excluded in _SUGGESTION_GROUPS: requested = {term for clause in clauses for term in _alias_terms(clause, aliases, ignored)} if requested: requested_groups.append((aliases, ignored, excluded, requested)) 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)] 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)) elif include_suggestions: title = _title_text(item) words = _words(_TITLE_QUALIFIERS.sub(" ", title)) literal_hits = keywords.intersection(words) alias_rank = 0 if requested_groups: full_title_words = set(_words(title)) clean_title = " ".join(words) for aliases, ignored, excluded, requested in requested_groups: if not excluded.intersection(full_title_words): matched = _alias_terms(clean_title, aliases, ignored) if matched: alias_rank = max(alias_rank, 2 if requested & matched else 1) if literal_hits or alias_rank: ranked.append(((0, alias_rank, len(literal_hits)), item)) ranked.sort(key=lambda entry: entry[0], reverse=True) return [item for _, item in ranked]