amisima commited on
Commit
e90de9a
·
verified ·
1 Parent(s): 00dc4ac

Search CPU LoRA catalogs by prompt keywords

Browse files
Files changed (2) hide show
  1. app.py +56 -44
  2. lora_cpu_picker.py +83 -14
app.py CHANGED
@@ -7842,7 +7842,7 @@ def _wan_cpu_model_key(item):
7842
  return ("civitai", match.group(1)) if match else None
7843
 
7844
 
7845
- def _wan_cpu_lora_choices(prompt, library, adapter_values, ranked=None, limit=2):
7846
  """Find compatible matches for vacant slots using catalogue text and file metadata."""
7847
  from concurrent.futures import ThreadPoolExecutor
7848
 
@@ -7920,7 +7920,8 @@ def _wan_cpu_lora_choices(prompt, library, adapter_values, ranked=None, limit=2)
7920
  if model_key:
7921
  used_models.add(model_key)
7922
  used_sources.update(keys)
7923
- used_bytes += sum(sizes)
 
7924
  if len(choices) >= limit:
7925
  break
7926
  return choices
@@ -10201,53 +10202,64 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
10201
  updates = [gr.update() for _ in values]
10202
  pool = _library_pool(library) if prompt_basis.strip() else []
10203
  strong = rank_prompt_loras(prompt_basis, pool)
10204
- choices = _wan_cpu_lora_choices(prompt_basis, library, values, ranked=strong) if strong else []
10205
- related = rank_wan_prompt_suggestions(prompt_basis, pool) if not choices else []
10206
- suggestions_only = bool(related and not choices)
10207
- if suggestions_only:
10208
- choices = _wan_cpu_lora_choices(prompt_basis, library, values, ranked=related, limit=4)
10209
- if not choices:
10210
- if not prompt_basis.strip():
10211
- note = "Write or paste a prompt first."
10212
- elif strong or related:
10213
- note = "Found related LoRAs, but none fit the available slots, file checks and size limits."
10214
- else:
10215
- note = "No clear LoRA match in the library for this prompt."
10216
- summary = _show_active_loras(library, state, *values)
10217
- return [note, gr.update(), *updates[3:], *(gr.update() for _ in _TRIGGER_OUTPUTS), *summary]
10218
-
10219
- rows = [lora_facts(item["name"], also=", ".join(_trigger_words(item))) for _, item in choices]
10220
- rows = score_lora_rows(rows, prompt_basis, identity_at, base=base)
10221
  page = list(state.get("page") or [])
10222
  keys = {_pick_key(item) for item in page}
10223
  picks = {key: record for key, record in _wan_cpu_current_picks(state, values).items()
10224
  if record["enabled"]}
10225
- for (index, item), row in zip(choices, rows):
10226
- if item.get("builtin"):
10227
- slot = (item["name"], row["high"], row["low"])
10228
- refs = slot[:1]
10229
- else:
10230
- slot = (item["url"], item.get("high") or "(None)", row["high"],
10231
- item.get("low") or "(None)", row["low"])
10232
- refs = (slot[0], slot[1], slot[3])
10233
- key = _pick_key(item)
10234
- record = dict(slot=index, item=item, refs=_wan_lora_slot_refs(refs), enabled=not suggestions_only)
10235
- picks[key] = record
10236
- if suggestions_only:
10237
- record["saved"] = slot
10238
- continue
10239
- _write_cpu_lora_slot(values, updates, index, slot)
10240
- if key not in keys:
10241
- page.append(item)
10242
- keys.add(key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10243
  state.update(page=page, cpu_picks=picks)
10244
- if suggestions_only:
10245
- note = f"Found {len(choices)} related LoRA{'s' if len(choices) != 1 else ''}. Tick a suggestion to use it."
10246
- trigger_updates = [gr.update() for _ in _TRIGGER_OUTPUTS]
10247
- trigger_updates[2] = state
10248
- return [note, gr.update(), *updates[3:], *trigger_updates, *_show_active_loras(library, state, *values)]
10249
- note = f"Added {len(choices)} LoRA{'s' if len(choices) != 1 else ''} from your prompt."
10250
- return [note, *_cpu_lora_result(prompt_text, sheet_text, library, state, values, updates)]
 
 
 
 
 
 
 
 
 
 
 
 
10251
 
10252
  def _toggle_cpu_lora(evt: gr.SelectData, prompt_text, sheet_text, library, state, *adapter_values):
10253
  state = copy.deepcopy(state or {})
 
7842
  return ("civitai", match.group(1)) if match else None
7843
 
7844
 
7845
+ def _wan_cpu_lora_choices(prompt, library, adapter_values, ranked=None, limit=2, *, reserve=True):
7846
  """Find compatible matches for vacant slots using catalogue text and file metadata."""
7847
  from concurrent.futures import ThreadPoolExecutor
7848
 
 
7920
  if model_key:
7921
  used_models.add(model_key)
7922
  used_sources.update(keys)
7923
+ if reserve:
7924
+ used_bytes += sum(sizes)
7925
  if len(choices) >= limit:
7926
  break
7927
  return choices
 
10202
  updates = [gr.update() for _ in values]
10203
  pool = _library_pool(library) if prompt_basis.strip() else []
10204
  strong = rank_prompt_loras(prompt_basis, pool)
10205
+ exact = _wan_cpu_lora_choices(prompt_basis, library, values, ranked=strong) if strong else []
10206
+ related = rank_wan_prompt_suggestions(prompt_basis, pool)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10207
  page = list(state.get("page") or [])
10208
  keys = {_pick_key(item) for item in page}
10209
  picks = {key: record for key, record in _wan_cpu_current_picks(state, values).items()
10210
  if record["enabled"]}
10211
+
10212
+ def stage(choices, enabled):
10213
+ if not choices:
10214
+ return
10215
+ rows = [lora_facts(item["name"], also=", ".join(_trigger_words(item))) for _, item in choices]
10216
+ rows = score_lora_rows(rows, prompt_basis, identity_at, base=base)
10217
+ for (index, item), row in zip(choices, rows):
10218
+ if item.get("builtin"):
10219
+ slot = (item["name"], row["high"], row["low"])
10220
+ refs = slot[:1]
10221
+ else:
10222
+ slot = (item["url"], item.get("high") or "(None)", row["high"],
10223
+ item.get("low") or "(None)", row["low"])
10224
+ refs = (slot[0], slot[1], slot[3])
10225
+ key = _pick_key(item)
10226
+ record = dict(slot=index, item=item, refs=_wan_lora_slot_refs(refs), enabled=enabled)
10227
+ picks[key] = record
10228
+ if not enabled:
10229
+ record["saved"] = slot
10230
+ continue
10231
+ _write_cpu_lora_slot(values, updates, index, slot)
10232
+ if key not in keys:
10233
+ page.append(item)
10234
+ keys.add(key)
10235
+
10236
+ stage(exact, True)
10237
+ active_models = {_wan_cpu_model_key(record["item"]) for record in picks.values()} - {None}
10238
+ remaining = [item for item in related if _pick_key(item) not in picks
10239
+ and _wan_cpu_model_key(item) not in active_models]
10240
+ suggestions = (_wan_cpu_lora_choices(prompt_basis, library, values, ranked=remaining, limit=4, reserve=False)
10241
+ if remaining else [])
10242
+ stage(suggestions, False)
10243
  state.update(page=page, cpu_picks=picks)
10244
+
10245
+ notes = []
10246
+ if exact:
10247
+ notes.append(f"Added {len(exact)} LoRA{'s' if len(exact) != 1 else ''} from your prompt.")
10248
+ if suggestions:
10249
+ notes.append(f"Found {len(suggestions)} related LoRA{'s' if len(suggestions) != 1 else ''}. Tick a suggestion to use it.")
10250
+ if exact:
10251
+ return [" ".join(notes), *_cpu_lora_result(prompt_text, sheet_text, library, state, values, updates)]
10252
+ if not notes:
10253
+ if not prompt_basis.strip():
10254
+ notes.append("Write or paste a prompt first.")
10255
+ elif strong or related:
10256
+ notes.append("Found related LoRAs, but none fit the available slots, file checks and size limits.")
10257
+ else:
10258
+ notes.append("No clear LoRA match in the library for this prompt.")
10259
+ trigger_updates = [gr.update() for _ in _TRIGGER_OUTPUTS]
10260
+ trigger_updates[2] = state
10261
+ return [" ".join(notes), gr.update(), *updates[3:], *trigger_updates,
10262
+ *_show_active_loras(library, state, *values)]
10263
 
10264
  def _toggle_cpu_lora(evt: gr.SelectData, prompt_text, sheet_text, library, state, *adapter_values):
10265
  state = copy.deepcopy(state or {})
lora_cpu_picker.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import re
4
  import unicodedata
 
5
 
6
 
7
  _WORD = re.compile(r"[^\W_]+", re.UNICODE)
@@ -109,7 +110,8 @@ def rank_prompt_loras(prompt, items):
109
  if not isinstance(item, dict):
110
  continue
111
  triggers = {phrase for field in _TRIGGER_FIELDS for phrase in _trigger_phrases(item.get(field))}
112
- hits = [phrase for phrase in triggers if _contains(clauses, phrase)]
 
113
  if hits:
114
  ranked.append(((2, max(map(len, hits))), item))
115
  continue
@@ -143,34 +145,101 @@ _WAN_OTHER_BUST = re.compile(
143
  r"\b(?:bust (?:through|out|open|up|down|of)|(?:bronze|marble|sculpted|stone|plaster) bust)\b"
144
  )
145
  _WAN_BIRD_TITS = re.compile(r"\b(?:great|blue|coal|crested|long tailed) tits?\b")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
 
148
  def rank_wan_prompt_suggestions(prompt, items):
149
- """Suggest title-related WAN adapters for an explicit broad term, without applying them."""
150
- requested = set()
151
- for clause in _positive_clauses(prompt):
 
152
  clause = _WAN_BIRD_TITS.sub(" ", _WAN_OTHER_BUST.sub(" ", clause))
153
- requested.update(_WAN_BUST_ALIASES[word] for word in _words(clause) if word in _WAN_BUST_ALIASES)
154
- if not requested:
 
 
 
155
  return []
156
 
157
- ranked = []
 
158
  for item in items:
159
  if not isinstance(item, dict):
160
  continue
 
 
 
 
 
 
 
161
  name = str(item.get("name") or item.get("title") or "")
162
  title, _, metadata = name.partition(" · ")
163
  words = set(_words(title))
164
- anatomy = {_WAN_BUST_ALIASES[word] for word in words if word in _WAN_BUST_ALIASES}
165
- if not anatomy or words & _WAN_BUST_UNRELATED:
166
- continue
167
- # An anatomy word in a title is not enough when the rest names a different concept.
168
- anatomy_title = all(word in _WAN_BUST_ALIASES for phrase in _title_phrases(item) for word in phrase)
169
- if not anatomy_title and not words & _WAN_BUST_FEATURES:
 
170
  continue
171
  # Saved library titles may name both modes. The actual version's base model wins.
172
  base_words = _words(item.get("base_model") or metadata.partition(" · ")[0])
173
  i2v = "i2v" in (base_words or words)
174
- ranked.append(((bool(anatomy & requested), i2v), item))
175
  ranked.sort(key=lambda row: row[0], reverse=True)
176
  return [item for _, item in ranked]
 
2
 
3
  import re
4
  import unicodedata
5
+ from collections import Counter
6
 
7
 
8
  _WORD = re.compile(r"[^\W_]+", re.UNICODE)
 
110
  if not isinstance(item, dict):
111
  continue
112
  triggers = {phrase for field in _TRIGGER_FIELDS for phrase in _trigger_phrases(item.get(field))}
113
+ hits = [phrase for phrase in triggers if _contains(clauses, phrase)
114
+ and (len(phrase) > 1 or phrase[0] not in _WAN_AMBIGUOUS_TRIGGERS)]
115
  if hits:
116
  ranked.append(((2, max(map(len, hits))), item))
117
  continue
 
145
  r"\b(?:bust (?:through|out|open|up|down|of)|(?:bronze|marble|sculpted|stone|plaster) bust)\b"
146
  )
147
  _WAN_BIRD_TITS = re.compile(r"\b(?:great|blue|coal|crested|long tailed) tits?\b")
148
+ _WAN_VULVA_ALIASES = {
149
+ "pussy": "pussy", "pussies": "pussy", "putka": "pussy", "putki": "pussy",
150
+ "путка": "pussy", "путки": "pussy",
151
+ "vagina": "vagina", "vaginas": "vagina", "вагина": "vagina", "вагини": "vagina",
152
+ "vulva": "vulva", "vulvas": "vulva", "вулва": "vulva", "вулви": "vulva",
153
+ "labia": "labia", "labium": "labia", "лабии": "labia",
154
+ }
155
+ _WAN_VULVA_UNRELATED = frozenset(
156
+ "anus anal double finger fingering fingers kick kickbusting rub rubbing slap spreading spread "
157
+ "penetration pentration penetrate riding oral blowjob handjob fuck fucking cuntbusting pussyjob".split()
158
+ )
159
+ _WAN_VULVA_FEATURES = frozenset(
160
+ "close closeup puffy anatomy detailed natural shape realistic size".split()
161
+ )
162
+ _WAN_OTHER_PUSSY = re.compile(r"\bpussy (?:cat|willow)s?\b")
163
+ _WAN_AMBIGUOUS_TRIGGERS = _WAN_BUST_ALIASES.keys() | _WAN_VULVA_ALIASES.keys()
164
+ _WAN_GENERIC_SEARCH_WORDS = _GENERIC_TRIGGERS | set(
165
+ "about above across adult after against all along also anime another any around back beach beautiful because before "
166
+ "behind below black blue both branch bright building camera car change clean closeup clothing color dance dancer daylight "
167
+ "daytime details did dog dramatic end evening eyes fantasy fashion film flowers forest garden get girl green hand happy her him his how "
168
+ "horizon indoor indoors kitchen landscape lighting lowangle man mountain mountains night ocean outdoor outdoors "
169
+ "off our out outfit park perch photo photograph portrait rain red river road roof room scenery see she sits "
170
+ "sitting skin slider slowly sky smile smiling smooth snow spring standing street studio sun sunlight sunset table "
171
+ "texture than their them then there these they this those through too toward trees under until urban use very was "
172
+ "water wave waves way were what when which white wide window while who why you zoom".split()
173
+ )
174
+ _WAN_SEARCH_FRAME = frozenset("find for lora loras show search suggest please want using make create keep".split())
175
+
176
+
177
+ def _wan_distinctive_words(words):
178
+ return {word for word in words if len(word) >= 3 and any(char.isalpha() for char in word)
179
+ and word not in _WAN_GENERIC_SEARCH_WORDS and word not in _WAN_SEARCH_FRAME
180
+ and word not in _WAN_AMBIGUOUS_TRIGGERS}
181
+
182
+
183
+ def _wan_keyword_score(item, phrases, title_words, requested, frequency):
184
+ hits = title_words & requested
185
+ if hits:
186
+ exact_title = any(phrase and requested.issuperset(phrase) for phrase in phrases)
187
+ return (3 if exact_title else 2, len(hits), -sum(frequency[word] for word in hits))
188
+ triggers = {phrase[0] for field in _TRIGGER_FIELDS for phrase in _trigger_phrases(item.get(field))
189
+ if len(phrase) == 1 and phrase[0] in requested}
190
+ return (1, len(triggers), 0) if triggers else (0, 0, 0)
191
+
192
+
193
+ def _wan_anatomy_score(words, phrases, aliases, requested, blocked, features, known_title=None):
194
+ if not requested or words & blocked:
195
+ return 0
196
+ anatomy = {aliases[word] for word in words if word in aliases}
197
+ if known_title and known_title in phrases:
198
+ return 1
199
+ if not anatomy or (not words & features and any(word not in aliases for phrase in phrases for word in phrase)):
200
+ return 0
201
+ return 2 if anatomy & requested else 1
202
 
203
 
204
  def rank_wan_prompt_suggestions(prompt, items):
205
+ """Rank related titles for distinctive positive prompt words and recognized synonyms."""
206
+ clauses = _positive_clauses(prompt)
207
+ prompt_words = set()
208
+ for clause in clauses:
209
  clause = _WAN_BIRD_TITS.sub(" ", _WAN_OTHER_BUST.sub(" ", clause))
210
+ prompt_words.update(_words(_WAN_OTHER_PUSSY.sub(" ", clause)))
211
+ bust = {_WAN_BUST_ALIASES[word] for word in prompt_words if word in _WAN_BUST_ALIASES}
212
+ vulva = {_WAN_VULVA_ALIASES[word] for word in prompt_words if word in _WAN_VULVA_ALIASES}
213
+ requested = _wan_distinctive_words(prompt_words)
214
+ if not (bust or vulva or requested):
215
  return []
216
 
217
+ catalog = []
218
+ frequency = Counter()
219
  for item in items:
220
  if not isinstance(item, dict):
221
  continue
222
+ phrases = tuple(_title_phrases(item))
223
+ title_words = {word for phrase in phrases for word in phrase}
224
+ frequency.update(title_words & requested)
225
+ catalog.append((item, phrases, title_words))
226
+
227
+ ranked = []
228
+ for item, phrases, title_words in catalog:
229
  name = str(item.get("name") or item.get("title") or "")
230
  title, _, metadata = name.partition(" · ")
231
  words = set(_words(title))
232
+ anatomy = max(
233
+ _wan_anatomy_score(words, phrases, _WAN_BUST_ALIASES, bust, _WAN_BUST_UNRELATED, _WAN_BUST_FEATURES),
234
+ _wan_anatomy_score(words, phrases, _WAN_VULVA_ALIASES, vulva, _WAN_VULVA_UNRELATED,
235
+ _WAN_VULVA_FEATURES, known_title=("godpussy",)),
236
+ )
237
+ keyword = _wan_keyword_score(item, phrases, title_words, requested, frequency) if requested else (0, 0, 0)
238
+ if not (anatomy or keyword[0]):
239
  continue
240
  # Saved library titles may name both modes. The actual version's base model wins.
241
  base_words = _words(item.get("base_model") or metadata.partition(" · ")[0])
242
  i2v = "i2v" in (base_words or words)
243
+ ranked.append(((anatomy, *keyword, i2v), item))
244
  ranked.sort(key=lambda row: row[0], reverse=True)
245
  return [item for _, item in ranked]