Spaces:
Running on Zero
Running on Zero
Show active LoRAs and add CPU prompt matching
Browse files- app.py +220 -13
- lora_cpu_picker.py +122 -0
app.py
CHANGED
|
@@ -25,6 +25,7 @@ from PIL import Image, ImageDraw, ImageFilter
|
|
| 25 |
|
| 26 |
import gradio as gr
|
| 27 |
from prompt_assistant import assistant_choices, prepare_request, resolve_writer, writer_result
|
|
|
|
| 28 |
from economy_prompt import (ECONOMY_SPACE, ECONOMY_TOKENS, ECONOMY_NOTE, is_economy,
|
| 29 |
economy_instruction, economy_prompt, economy_status)
|
| 30 |
from end_frame_color import match_end_frame_preview
|
|
@@ -7110,7 +7111,7 @@ def _words(text, drop):
|
|
| 7110 |
return out
|
| 7111 |
|
| 7112 |
|
| 7113 |
-
def _library_pool():
|
| 7114 |
"""Everything that can be chosen: the built-in list first, then the library.
|
| 7115 |
|
| 7116 |
The built-in ones are already downloaded, already split into their High and Low
|
|
@@ -7122,13 +7123,14 @@ def _library_pool():
|
|
| 7122 |
if choice and choice != "(None)":
|
| 7123 |
pool.append({"name": choice, "builtin": True, "trigger": "",
|
| 7124 |
"strength": 1.0, "url": ""})
|
| 7125 |
-
|
| 7126 |
-
|
| 7127 |
-
|
| 7128 |
-
|
| 7129 |
-
|
|
|
|
| 7130 |
for section in ("nsfw", "normal"):
|
| 7131 |
-
for item in (
|
| 7132 |
if isinstance(item, dict) and item.get("url") and item.get("name"):
|
| 7133 |
pool.append({**item, "_picker_section": section,
|
| 7134 |
"trigger": ", ".join(_trigger_words(item))})
|
|
@@ -7660,9 +7662,9 @@ def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, st
|
|
| 7660 |
return state, page, selected, note, prompt_text, sheet_text, picks, old_picks
|
| 7661 |
|
| 7662 |
|
| 7663 |
-
def _slot_trigger_items(fields, state):
|
| 7664 |
"""Read actual adapter slots, resolving only explicit saved/API activation words."""
|
| 7665 |
-
pool = list((state or {}).get("page") or []) + list((state or {}).get("applied") or []) + _library_pool()
|
| 7666 |
pool.sort(key=lambda item: not bool(_trigger_words(item)))
|
| 7667 |
active, extras, seen = [], [], set()
|
| 7668 |
def remember(item, extra=False):
|
|
@@ -7670,7 +7672,8 @@ def _slot_trigger_items(fields, state):
|
|
| 7670 |
if key in seen:
|
| 7671 |
return
|
| 7672 |
seen.add(key)
|
| 7673 |
-
|
|
|
|
| 7674 |
active.append(item)
|
| 7675 |
if extra:
|
| 7676 |
extras.append(item)
|
|
@@ -7700,11 +7703,11 @@ def _slot_trigger_items(fields, state):
|
|
| 7700 |
return active, extras
|
| 7701 |
|
| 7702 |
|
| 7703 |
-
def _sync_slot_triggers(prompt_text, sheet_text, state, *slot_fields):
|
| 7704 |
"""One local update for manual changes; never ask a writing model."""
|
| 7705 |
import copy
|
| 7706 |
state = copy.deepcopy(state) if isinstance(state, dict) else {}
|
| 7707 |
-
active, extras = _slot_trigger_items(slot_fields, state)
|
| 7708 |
prompt_text = _pick_clean(prompt_text, state.get("prompt_added"))
|
| 7709 |
sheet_text = _pick_clean(sheet_text, state.get("sheet_added"))
|
| 7710 |
prompt_text, prompt_added = _pick_text(prompt_text, active)
|
|
@@ -7761,6 +7764,124 @@ def _simple_prompt_feedback(note):
|
|
| 7761 |
return "Prompt prepared. Review the text above."
|
| 7762 |
|
| 7763 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7764 |
CSS += """
|
| 7765 |
/* Shared LTX Studio refresh. Uses stable app IDs and Gradio theme classes. */
|
| 7766 |
.gradio-container {
|
|
@@ -8112,6 +8233,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8112 |
""", elem_id="studio-title")
|
| 8113 |
with gr.Row(equal_height=False, elem_id="studio-workspace") as simple_workspace:
|
| 8114 |
pass
|
|
|
|
| 8115 |
ui_mode = gr.Radio([("Simple", "simple"), ("Pro", "pro")], value="simple", label="Controls", elem_id="studio-mode")
|
| 8116 |
with gr.Accordion("More Settings", open=False, elem_id="studio-more-settings") as more_settings:
|
| 8117 |
gr.Markdown("Fine-tune your shot, continue a video, or plan a longer scene. Switch to Pro for the full controls.",
|
|
@@ -8564,7 +8686,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8564 |
(my4_repo, my4_high, my4_hs, my4_low, my4_ls) = _my_rows[3]
|
| 8565 |
(my5_repo, my5_high, my5_hs, my5_low, my5_ls) = _my_rows[4]
|
| 8566 |
|
| 8567 |
-
lora_library.library_tab(
|
| 8568 |
pair_slots=[(repo, high, high_scale, low, low_scale)
|
| 8569 |
for (repo, high, high_scale, low, low_scale) in _my_rows],
|
| 8570 |
prompt_box=prompt_input,
|
|
@@ -8663,6 +8785,9 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8663 |
extension_lora_about = gr.HTML(simple_lora_about.value)
|
| 8664 |
extension_seconds = gr.Slider(minimum=duration_seconds_input.minimum, maximum=duration_seconds_input.maximum,
|
| 8665 |
step=duration_seconds_input.step, value=duration_seconds_input.value, label="Seconds to add")
|
|
|
|
|
|
|
|
|
|
| 8666 |
extend_btn = gr.Button("➕ Extend & stitch", variant="primary")
|
| 8667 |
extension_status = gr.Markdown("The original video is kept, including its audio. Each press adds one new clip.")
|
| 8668 |
|
|
@@ -8746,6 +8871,9 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8746 |
info="Leave a line empty — or the whole box — and that clip uses the "
|
| 8747 |
"main prompt above, unchanged.",
|
| 8748 |
)
|
|
|
|
|
|
|
|
|
|
| 8749 |
with gr.Row():
|
| 8750 |
chain_btn = gr.Button("🎬 Make the whole scene and join it",
|
| 8751 |
variant="primary", elem_id="extend-btn")
|
|
@@ -8958,6 +9086,9 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8958 |
basic_btn.render()
|
| 8959 |
simple_prompt_status = gr.Markdown("")
|
| 8960 |
duration_seconds_input.render()
|
|
|
|
|
|
|
|
|
|
| 8961 |
with gr.Row(elem_classes="studio-actions"):
|
| 8962 |
generate_button.render()
|
| 8963 |
stop_button.render()
|
|
@@ -9974,6 +10105,82 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 9974 |
event.success(_sync_slot_triggers, _TRIGGER_INPUTS, _TRIGGER_OUTPUTS,
|
| 9975 |
show_progress="hidden", concurrency_id="lora-picker", trigger_mode="always_last")
|
| 9976 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9977 |
_PRO_ONLY = [pro_promptbuilder, pro_chips, pro_speed, pro_advanced,
|
| 9978 |
pro_soundset, pro_loop, basic_panel, pro_lora_studio,
|
| 9979 |
extension_lora_details, scene_lora_details, pro_lora_notice]
|
|
|
|
| 25 |
|
| 26 |
import gradio as gr
|
| 27 |
from prompt_assistant import assistant_choices, prepare_request, resolve_writer, writer_result
|
| 28 |
+
from lora_cpu_picker import rank_prompt_loras
|
| 29 |
from economy_prompt import (ECONOMY_SPACE, ECONOMY_TOKENS, ECONOMY_NOTE, is_economy,
|
| 30 |
economy_instruction, economy_prompt, economy_status)
|
| 31 |
from end_frame_color import match_end_frame_preview
|
|
|
|
| 7111 |
return out
|
| 7112 |
|
| 7113 |
|
| 7114 |
+
def _library_pool(library=None):
|
| 7115 |
"""Everything that can be chosen: the built-in list first, then the library.
|
| 7116 |
|
| 7117 |
The built-in ones are already downloaded, already split into their High and Low
|
|
|
|
| 7123 |
if choice and choice != "(None)":
|
| 7124 |
pool.append({"name": choice, "builtin": True, "trigger": "",
|
| 7125 |
"strength": 1.0, "url": ""})
|
| 7126 |
+
if library is None:
|
| 7127 |
+
try:
|
| 7128 |
+
library = lora_library.load_library()
|
| 7129 |
+
except Exception as error: # noqa: BLE001
|
| 7130 |
+
print(f"[simple] the library could not be read: {error}", flush=True)
|
| 7131 |
+
return pool
|
| 7132 |
for section in ("nsfw", "normal"):
|
| 7133 |
+
for item in (library.get(section) or []):
|
| 7134 |
if isinstance(item, dict) and item.get("url") and item.get("name"):
|
| 7135 |
pool.append({**item, "_picker_section": section,
|
| 7136 |
"trigger": ", ".join(_trigger_words(item))})
|
|
|
|
| 7662 |
return state, page, selected, note, prompt_text, sheet_text, picks, old_picks
|
| 7663 |
|
| 7664 |
|
| 7665 |
+
def _slot_trigger_items(fields, state, library=None, resolve_missing=True):
|
| 7666 |
"""Read actual adapter slots, resolving only explicit saved/API activation words."""
|
| 7667 |
+
pool = list((state or {}).get("page") or []) + list((state or {}).get("applied") or []) + _library_pool(library)
|
| 7668 |
pool.sort(key=lambda item: not bool(_trigger_words(item)))
|
| 7669 |
active, extras, seen = [], [], set()
|
| 7670 |
def remember(item, extra=False):
|
|
|
|
| 7672 |
if key in seen:
|
| 7673 |
return
|
| 7674 |
seen.add(key)
|
| 7675 |
+
if resolve_missing:
|
| 7676 |
+
item = _resolve_pick_triggers(item)
|
| 7677 |
active.append(item)
|
| 7678 |
if extra:
|
| 7679 |
extras.append(item)
|
|
|
|
| 7703 |
return active, extras
|
| 7704 |
|
| 7705 |
|
| 7706 |
+
def _sync_slot_triggers(prompt_text, sheet_text, state, *slot_fields, library=None, resolve_missing=True):
|
| 7707 |
"""One local update for manual changes; never ask a writing model."""
|
| 7708 |
import copy
|
| 7709 |
state = copy.deepcopy(state) if isinstance(state, dict) else {}
|
| 7710 |
+
active, extras = _slot_trigger_items(slot_fields, state, library, resolve_missing)
|
| 7711 |
prompt_text = _pick_clean(prompt_text, state.get("prompt_added"))
|
| 7712 |
sheet_text = _pick_clean(sheet_text, state.get("sheet_added"))
|
| 7713 |
prompt_text, prompt_added = _pick_text(prompt_text, active)
|
|
|
|
| 7764 |
return "Prompt prepared. Review the text above."
|
| 7765 |
|
| 7766 |
|
| 7767 |
+
def _wan_lora_name(reference):
|
| 7768 |
+
from urllib.parse import unquote, urlsplit
|
| 7769 |
+
|
| 7770 |
+
path = urlsplit(str(reference or "").replace("\\", "/")).path
|
| 7771 |
+
filename = unquote(path.rstrip("/").rsplit("/", 1)[-1])
|
| 7772 |
+
if CIVITAI_DOWNLOAD_RE.search(str(reference or "")) and filename.isdigit():
|
| 7773 |
+
return f"CivitAI version {filename}"
|
| 7774 |
+
return re.sub(r"\.(?:safetensors|pt|bin)$", "", filename, flags=re.I).replace("_", " ") or "Custom LoRA"
|
| 7775 |
+
|
| 7776 |
+
|
| 7777 |
+
def _wan_active_lora_summary(library, state, *adapter_values):
|
| 7778 |
+
from html import escape
|
| 7779 |
+
|
| 7780 |
+
entries = list((state or {}).get("page") or [])
|
| 7781 |
+
entries += [item for section in ("normal", "nsfw") for item in ((library or {}).get(section) or [])]
|
| 7782 |
+
names = {}
|
| 7783 |
+
for item in entries:
|
| 7784 |
+
for field in ("url", "high", "low"):
|
| 7785 |
+
if item.get(field) and item.get("name"):
|
| 7786 |
+
names.setdefault(item[field], item["name"])
|
| 7787 |
+
rows = []
|
| 7788 |
+
speed = (SPEED_PRESETS.get(adapter_values[0]) or {}).get("lora")
|
| 7789 |
+
for index, group in enumerate(_estimate_lora_groups(adapter_values)):
|
| 7790 |
+
try:
|
| 7791 |
+
sources = _lora_group_sources(group)
|
| 7792 |
+
except (TypeError, ValueError):
|
| 7793 |
+
continue
|
| 7794 |
+
if not sources:
|
| 7795 |
+
continue
|
| 7796 |
+
name = group.get("preset")
|
| 7797 |
+
if speed and index == 0:
|
| 7798 |
+
name = adapter_values[0].split(" · ", 1)[0]
|
| 7799 |
+
if not name:
|
| 7800 |
+
refs = [group.get("file_" + role) for role, _, _ in sources] + [group.get("repo")]
|
| 7801 |
+
name = next((names[ref] for ref in refs if ref in names), None) or _wan_lora_name(refs[0])
|
| 7802 |
+
name = re.sub(r"([\\`*_\[\]])", r"\\\1", escape(" ".join(str(name).split())))
|
| 7803 |
+
strengths = " · ".join(f"{role.title()} **{scale:g}**" for role, _, scale in sources)
|
| 7804 |
+
rows.append(f"- **{name}** · {strengths}")
|
| 7805 |
+
return "**Active LoRAs**\n\n" + ("\n".join(rows) if rows else "No LoRAs selected.")
|
| 7806 |
+
|
| 7807 |
+
|
| 7808 |
+
def _wan_cpu_lora_choices(prompt, library, adapter_values):
|
| 7809 |
+
"""Find compatible matches for vacant slots using catalogue text and file metadata."""
|
| 7810 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 7811 |
+
|
| 7812 |
+
def present(value):
|
| 7813 |
+
return bool(value and value != "(None)")
|
| 7814 |
+
|
| 7815 |
+
built_slots = [index for index in range(3, 12, 3) if not present(adapter_values[index])]
|
| 7816 |
+
custom_slots = [index for index in range(12, 37, 5)
|
| 7817 |
+
if not any(present(adapter_values[index + offset]) for offset in (0, 1, 3))]
|
| 7818 |
+
if not (built_slots or custom_slots):
|
| 7819 |
+
return []
|
| 7820 |
+
|
| 7821 |
+
groups = _estimate_lora_groups(adapter_values)
|
| 7822 |
+
current_sources = []
|
| 7823 |
+
for group in groups:
|
| 7824 |
+
try:
|
| 7825 |
+
current_sources.extend(source for _, source, _ in _lora_group_sources(group))
|
| 7826 |
+
except (TypeError, ValueError):
|
| 7827 |
+
continue
|
| 7828 |
+
used_sources = {_lora_source_key(source) for source in current_sources}
|
| 7829 |
+
used_refs = {str(value).casefold() for group in groups for field, value in group.items()
|
| 7830 |
+
if field in ("preset", "repo", "file_high", "file_low") and present(value)}
|
| 7831 |
+
|
| 7832 |
+
def describe(item):
|
| 7833 |
+
if item.get("builtin"):
|
| 7834 |
+
if not built_slots or item["name"].casefold() in used_refs:
|
| 7835 |
+
return None
|
| 7836 |
+
group = {"preset": item["name"]}
|
| 7837 |
+
else:
|
| 7838 |
+
high, low = item.get("high"), item.get("low")
|
| 7839 |
+
if not custom_slots or not any(present(ref) for ref in (high, low)):
|
| 7840 |
+
return None
|
| 7841 |
+
if any(str(ref).casefold() in used_refs for ref in (item["url"], high, low) if present(ref)):
|
| 7842 |
+
return None
|
| 7843 |
+
group = {"repo": item["url"], "file_high": high, "file_low": low}
|
| 7844 |
+
if _pick_all_in_one(item) or _health_read(_pick_key(item)).get("status") == "bad":
|
| 7845 |
+
return None
|
| 7846 |
+
try:
|
| 7847 |
+
sources = [source for _, source, _ in _lora_group_sources(group)]
|
| 7848 |
+
except (TypeError, ValueError):
|
| 7849 |
+
return None
|
| 7850 |
+
keys = {_lora_source_key(source) for source in sources}
|
| 7851 |
+
if not keys or keys & used_sources:
|
| 7852 |
+
return None
|
| 7853 |
+
return item, sources, keys
|
| 7854 |
+
|
| 7855 |
+
candidates = []
|
| 7856 |
+
for item in rank_prompt_loras(prompt, _library_pool(library)):
|
| 7857 |
+
candidate = describe(item)
|
| 7858 |
+
if candidate is not None:
|
| 7859 |
+
candidates.append(candidate)
|
| 7860 |
+
if len(candidates) >= LORA_PICK_PAGE:
|
| 7861 |
+
break
|
| 7862 |
+
if not candidates:
|
| 7863 |
+
return []
|
| 7864 |
+
|
| 7865 |
+
with ThreadPoolExecutor(max_workers=LORA_PICK_PAGE) as workers:
|
| 7866 |
+
current_info = workers.map(_lora_source_info, current_sources)
|
| 7867 |
+
used_bytes = sum(int(info.get("size") or 0) for info in current_info)
|
| 7868 |
+
candidate_info = list(workers.map(lambda row: [_lora_source_info(source) for source in row[1]], candidates))
|
| 7869 |
+
|
| 7870 |
+
choices = []
|
| 7871 |
+
for (item, _, keys), infos in zip(candidates, candidate_info):
|
| 7872 |
+
slots = built_slots if item.get("builtin") else custom_slots
|
| 7873 |
+
sizes = [int(info.get("size") or 0) for info in infos]
|
| 7874 |
+
if (not slots or keys & used_sources or any(info.get("status") == "unavailable" for info in infos)
|
| 7875 |
+
or any(size > LORA_MAX_FILE_BYTES for size in sizes) or used_bytes + sum(sizes) > LORA_MAX_RUN_BYTES):
|
| 7876 |
+
continue
|
| 7877 |
+
choices.append((slots.pop(0), item))
|
| 7878 |
+
used_sources.update(keys)
|
| 7879 |
+
used_bytes += sum(sizes)
|
| 7880 |
+
if len(choices) >= 2:
|
| 7881 |
+
break
|
| 7882 |
+
return choices
|
| 7883 |
+
|
| 7884 |
+
|
| 7885 |
CSS += """
|
| 7886 |
/* Shared LTX Studio refresh. Uses stable app IDs and Gradio theme classes. */
|
| 7887 |
.gradio-container {
|
|
|
|
| 8233 |
""", elem_id="studio-title")
|
| 8234 |
with gr.Row(equal_height=False, elem_id="studio-workspace") as simple_workspace:
|
| 8235 |
pass
|
| 8236 |
+
active_loras_default = "**Active LoRAs**\n\nNo LoRAs selected."
|
| 8237 |
ui_mode = gr.Radio([("Simple", "simple"), ("Pro", "pro")], value="simple", label="Controls", elem_id="studio-mode")
|
| 8238 |
with gr.Accordion("More Settings", open=False, elem_id="studio-more-settings") as more_settings:
|
| 8239 |
gr.Markdown("Fine-tune your shot, continue a video, or plan a longer scene. Switch to Pro for the full controls.",
|
|
|
|
| 8686 |
(my4_repo, my4_high, my4_hs, my4_low, my4_ls) = _my_rows[3]
|
| 8687 |
(my5_repo, my5_high, my5_hs, my5_low, my5_ls) = _my_rows[4]
|
| 8688 |
|
| 8689 |
+
lora_catalog_state = lora_library.library_tab(
|
| 8690 |
pair_slots=[(repo, high, high_scale, low, low_scale)
|
| 8691 |
for (repo, high, high_scale, low, low_scale) in _my_rows],
|
| 8692 |
prompt_box=prompt_input,
|
|
|
|
| 8785 |
extension_lora_about = gr.HTML(simple_lora_about.value)
|
| 8786 |
extension_seconds = gr.Slider(minimum=duration_seconds_input.minimum, maximum=duration_seconds_input.maximum,
|
| 8787 |
step=duration_seconds_input.step, value=duration_seconds_input.value, label="Seconds to add")
|
| 8788 |
+
extension_cpu_lora = gr.Button("Pick LoRAs from prompt (CPU)", size="sm", variant="secondary")
|
| 8789 |
+
extension_cpu_status = gr.Markdown("")
|
| 8790 |
+
extension_active_loras = gr.Markdown(active_loras_default)
|
| 8791 |
extend_btn = gr.Button("➕ Extend & stitch", variant="primary")
|
| 8792 |
extension_status = gr.Markdown("The original video is kept, including its audio. Each press adds one new clip.")
|
| 8793 |
|
|
|
|
| 8871 |
info="Leave a line empty — or the whole box — and that clip uses the "
|
| 8872 |
"main prompt above, unchanged.",
|
| 8873 |
)
|
| 8874 |
+
scene_cpu_lora = gr.Button("Pick LoRAs from scene (CPU)", size="sm", variant="secondary")
|
| 8875 |
+
scene_cpu_status = gr.Markdown("")
|
| 8876 |
+
scene_active_loras = gr.Markdown(active_loras_default)
|
| 8877 |
with gr.Row():
|
| 8878 |
chain_btn = gr.Button("🎬 Make the whole scene and join it",
|
| 8879 |
variant="primary", elem_id="extend-btn")
|
|
|
|
| 9086 |
basic_btn.render()
|
| 9087 |
simple_prompt_status = gr.Markdown("")
|
| 9088 |
duration_seconds_input.render()
|
| 9089 |
+
cpu_lora = gr.Button("Pick LoRAs from prompt (CPU)", size="sm", variant="secondary")
|
| 9090 |
+
cpu_lora_status = gr.Markdown("")
|
| 9091 |
+
active_loras = gr.Markdown(active_loras_default, elem_id="active-loras")
|
| 9092 |
with gr.Row(elem_classes="studio-actions"):
|
| 9093 |
generate_button.render()
|
| 9094 |
stop_button.render()
|
|
|
|
| 10105 |
event.success(_sync_slot_triggers, _TRIGGER_INPUTS, _TRIGGER_OUTPUTS,
|
| 10106 |
show_progress="hidden", concurrency_id="lora-picker", trigger_mode="always_last")
|
| 10107 |
|
| 10108 |
+
_ACTIVE_LORA_FIELDS = ui_inputs[16:53]
|
| 10109 |
+
_ACTIVE_LORA_INPUTS = [lora_catalog_state, basic_shortlist, *_ACTIVE_LORA_FIELDS]
|
| 10110 |
+
|
| 10111 |
+
def _show_active_loras(library, state, *adapter_values):
|
| 10112 |
+
summary = _wan_active_lora_summary(library, state, *adapter_values)
|
| 10113 |
+
return summary, summary, summary
|
| 10114 |
+
|
| 10115 |
+
gr.on([component.change for component in _ACTIVE_LORA_INPUTS], _show_active_loras,
|
| 10116 |
+
_ACTIVE_LORA_INPUTS, [active_loras, extension_active_loras, scene_active_loras],
|
| 10117 |
+
queue=False, show_progress="hidden", trigger_mode="always_last", api_name=False)
|
| 10118 |
+
|
| 10119 |
+
_CPU_LORA_FIELDS = _ACTIVE_LORA_FIELDS[3:]
|
| 10120 |
+
|
| 10121 |
+
def _apply_cpu_loras(prompt_text, sheet_text, idea_text, library, state, base, identity_at,
|
| 10122 |
+
*adapter_values, scene=False):
|
| 10123 |
+
state = copy.deepcopy(state or {})
|
| 10124 |
+
prompt_basis = _pick_clean(prompt_text, state.get("prompt_added"))
|
| 10125 |
+
if scene:
|
| 10126 |
+
scene_basis = _pick_clean(sheet_text, state.get("sheet_added"))
|
| 10127 |
+
prompt_basis = "\n".join(value for value in (idea_text, scene_basis) if value).strip() or prompt_basis
|
| 10128 |
+
values = list(adapter_values)
|
| 10129 |
+
updates = [gr.update() for _ in values]
|
| 10130 |
+
choices = _wan_cpu_lora_choices(prompt_basis, library, values) if prompt_basis.strip() else []
|
| 10131 |
+
if not choices:
|
| 10132 |
+
note = ("Write or paste a prompt first." if not prompt_basis.strip()
|
| 10133 |
+
else "No compatible match could be added. Current LoRAs were kept.")
|
| 10134 |
+
return [note, gr.update(), *updates[3:], *(gr.update() for _ in _TRIGGER_OUTPUTS)]
|
| 10135 |
+
|
| 10136 |
+
def put(index, value, options=None):
|
| 10137 |
+
values[index] = value
|
| 10138 |
+
updates[index] = (gr.update(value=value, choices=options) if options is not None
|
| 10139 |
+
else gr.update(value=value))
|
| 10140 |
+
|
| 10141 |
+
rows = [lora_facts(item["name"], also=", ".join(_trigger_words(item))) for _, item in choices]
|
| 10142 |
+
rows = score_lora_rows(rows, prompt_basis, identity_at, base=base)
|
| 10143 |
+
page = list(state.get("page") or [])
|
| 10144 |
+
keys = {_pick_key(item) for item in page}
|
| 10145 |
+
for (index, item), row in zip(choices, rows):
|
| 10146 |
+
if item.get("builtin"):
|
| 10147 |
+
put(index, item["name"])
|
| 10148 |
+
put(index + 1, row["high"])
|
| 10149 |
+
put(index + 2, row["low"])
|
| 10150 |
+
else:
|
| 10151 |
+
put(index, item["url"])
|
| 10152 |
+
for offset, role in ((1, "high"), (3, "low")):
|
| 10153 |
+
file = item.get(role) or "(None)"
|
| 10154 |
+
options = ["(None)", file] if file != "(None)" else ["(None)"]
|
| 10155 |
+
put(index + offset, file, options)
|
| 10156 |
+
put(index + offset + 1, row[role])
|
| 10157 |
+
if _pick_key(item) not in keys:
|
| 10158 |
+
page.append(item)
|
| 10159 |
+
keys.add(_pick_key(item))
|
| 10160 |
+
state["page"] = page
|
| 10161 |
+
presets = [values[index] for index in range(3, 12, 3)]
|
| 10162 |
+
custom_refs = [values[index + offset] for index in range(12, 37, 5) for offset in (0, 1, 3)]
|
| 10163 |
+
trigger_updates = _sync_slot_triggers(prompt_text, sheet_text, state, *presets, *custom_refs,
|
| 10164 |
+
library=library, resolve_missing=False)
|
| 10165 |
+
built = [name for name in presets if name and name != "(None)"]
|
| 10166 |
+
note = f"Added {len(choices)} LoRA{'s' if len(choices) != 1 else ''} from your prompt."
|
| 10167 |
+
return [note, gr.update(value=built), *updates[3:], *trigger_updates]
|
| 10168 |
+
|
| 10169 |
+
for _button, _prompt, _status, _scene, _api in (
|
| 10170 |
+
(cpu_lora, prompt_input, cpu_lora_status, False, "pick_loras_cpu"),
|
| 10171 |
+
(extension_cpu_lora, extension_prompt, extension_cpu_status, False, False),
|
| 10172 |
+
(scene_cpu_lora, prompt_input, scene_cpu_status, True, False),
|
| 10173 |
+
):
|
| 10174 |
+
_cpu_picked = _button.click(
|
| 10175 |
+
functools.partial(_apply_cpu_loras, scene=_scene),
|
| 10176 |
+
[_prompt, scene_prompts, scene_idea, lora_catalog_state, basic_shortlist,
|
| 10177 |
+
simple_lora_strength, identity_strength_slider, *_ACTIVE_LORA_FIELDS],
|
| 10178 |
+
[_status, simple_lora, *_CPU_LORA_FIELDS, *_TRIGGER_OUTPUTS],
|
| 10179 |
+
show_progress="minimal", concurrency_id="lora-picker", concurrency_limit=1, api_name=_api,
|
| 10180 |
+
)
|
| 10181 |
+
_cpu_picked.success(_gpu_estimate_text, _ESTIMATE_INPUTS, gpu_estimate,
|
| 10182 |
+
show_progress="hidden", api_name=False)
|
| 10183 |
+
|
| 10184 |
_PRO_ONLY = [pro_promptbuilder, pro_chips, pro_speed, pro_advanced,
|
| 10185 |
pro_soundset, pro_loop, basic_panel, pro_lora_studio,
|
| 10186 |
extension_lora_details, scene_lora_details, pro_lora_notice]
|
lora_cpu_picker.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rank catalog LoRAs against an existing prompt using local text matching."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import unicodedata
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
_WORD = re.compile(r"[^\W_]+", re.UNICODE)
|
| 8 |
+
_SPLIT = re.compile(
|
| 9 |
+
r"[;.!?\n]+|\b(?:but|instead|но|обаче|obache)\b|"
|
| 10 |
+
r",\s*(?=(?:then|add|use|после|добави|след това|posle|dobavi)\b)"
|
| 11 |
+
)
|
| 12 |
+
_NEGATIVE = re.compile(
|
| 13 |
+
r"\b(?:no|not|don['’]t|rather than|without|avoid|exclude|never|minus|без|не|избягвай|изключи|"
|
| 14 |
+
r"bez|ne|izbyagvai|izbqgvai)\b"
|
| 15 |
+
)
|
| 16 |
+
_NEGATIVE_SECTION = re.compile(
|
| 17 |
+
r"\b(?:negative(?: prompt)?|негативен промпт|отрицателен промпт|negativen prompt)\s*:"
|
| 18 |
+
)
|
| 19 |
+
_TITLE_NOISE = set(
|
| 20 |
+
"wan wan2 wan22 ltx ltxv minimax h3 ph3 model video image diffusion lora loras adapter adapters "
|
| 21 |
+
"i2v t2v i2i turbo flashgen checkpoint version v1 v2 v3 v4 high low rank alpha safetensors "
|
| 22 |
+
"effect effects style camera motion animation movement cinematic realism realistic quality "
|
| 23 |
+
"the a an for of by with and in on to pack update new better official trained nsfw sfw"
|
| 24 |
+
.split()
|
| 25 |
+
)
|
| 26 |
+
_GENERIC_TRIGGERS = _TITLE_NOISE | set(
|
| 27 |
+
"person people woman women man men girl boy adult background scene subject shot light body face "
|
| 28 |
+
"full close up look looking move moving walk walking run running dance dancing hands hair bunny "
|
| 29 |
+
"1girl 1boy none default description"
|
| 30 |
+
.split()
|
| 31 |
+
)
|
| 32 |
+
_TRIGGER_FIELDS = ("trigger", "triggers", "trigger_words", "trainedWords", "trained_words", "activation_words")
|
| 33 |
+
_PLACEHOLDER = re.compile(r"^(?:see|check|read|refer to)\b.*\b(?:description|instructions|example|page)\b")
|
| 34 |
+
_PROMPT_ALIASES = {
|
| 35 |
+
"черно бял филм": "black and white film",
|
| 36 |
+
"cherno byal film": "black and white film",
|
| 37 |
+
"мастилена рисунка": "ink wash illustration",
|
| 38 |
+
"mastilena risunka": "ink wash illustration",
|
| 39 |
+
"ръчно рисуван": "hand drawn",
|
| 40 |
+
"rachno risuvan": "hand drawn",
|
| 41 |
+
"камерата се върти около": "camera orbit",
|
| 42 |
+
"kamerata se vyrti okolo": "camera orbit",
|
| 43 |
+
"приближаване на камерата": "camera zoom in",
|
| 44 |
+
"priblijavane na kamerata": "camera zoom in",
|
| 45 |
+
"отдалечаване на камерата": "camera zoom out",
|
| 46 |
+
"otdalechavane na kamerata": "camera zoom out",
|
| 47 |
+
}
|
| 48 |
+
_MOTION_PHRASES = tuple(tuple(phrase.split()) for phrase in (
|
| 49 |
+
"camera orbit", "orbit camera", "zoom in", "zoom out", "camera shake", "camera pan", "dolly zoom",
|
| 50 |
+
))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _words(text):
|
| 54 |
+
return tuple(_WORD.findall(unicodedata.normalize("NFKC", str(text or "")).casefold()))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _positive_clauses(prompt):
|
| 58 |
+
text = unicodedata.normalize("NFKC", str(prompt or "")).casefold()
|
| 59 |
+
text = _NEGATIVE_SECTION.split(text, maxsplit=1)[0]
|
| 60 |
+
clauses = []
|
| 61 |
+
for part in _SPLIT.split(text):
|
| 62 |
+
positive = _NEGATIVE.split(part, maxsplit=1)[0]
|
| 63 |
+
for fragment in positive.split(","):
|
| 64 |
+
clause = " " + " ".join(_words(fragment)) + " "
|
| 65 |
+
clauses.append(clause)
|
| 66 |
+
for alias, target in _PROMPT_ALIASES.items():
|
| 67 |
+
if f" {alias} " in clause:
|
| 68 |
+
clauses.append(f" {target} ")
|
| 69 |
+
return clauses
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _trigger_phrases(value):
|
| 73 |
+
if isinstance(value, (list, tuple)):
|
| 74 |
+
for part in value:
|
| 75 |
+
yield from _trigger_phrases(part)
|
| 76 |
+
elif isinstance(value, str):
|
| 77 |
+
for part in re.split(r"[,;\n]+", value):
|
| 78 |
+
phrase = _words(part)
|
| 79 |
+
if (not _PLACEHOLDER.match(" ".join(phrase))
|
| 80 |
+
and any(len(word) >= 3 and word not in _GENERIC_TRIGGERS for word in phrase)):
|
| 81 |
+
yield phrase
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _title_phrases(item):
|
| 85 |
+
title = str(item.get("name") or item.get("title") or "").split(" · ", 1)[0]
|
| 86 |
+
title = re.sub(r"^[\w.-]+/(?=\S)", "", title)
|
| 87 |
+
title = re.sub(r"\bv\d+(?:\.\d+)*\b|\b\d+(?:\.\d+)+\b", " ", title, flags=re.I)
|
| 88 |
+
for part in re.split(r"\||\s[-–—]\s", title):
|
| 89 |
+
yield tuple(dict.fromkeys(word for word in _words(part) if not word.isdecimal() and word not in _TITLE_NOISE))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _motion_phrases(item):
|
| 93 |
+
title = str(item.get("name") or item.get("title") or "").split(" · ", 1)[0]
|
| 94 |
+
title_words = [" " + " ".join(_words(title)) + " "]
|
| 95 |
+
return (phrase for phrase in _MOTION_PHRASES if _contains(title_words, phrase))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _contains(clauses, phrase):
|
| 99 |
+
return bool(phrase) and any(" " + " ".join(phrase) + " " in clause for clause in clauses)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def rank_prompt_loras(prompt, items):
|
| 103 |
+
"""Return original catalog entries ordered by explicit positive trigger or title matches."""
|
| 104 |
+
if not str(prompt or "").strip():
|
| 105 |
+
return []
|
| 106 |
+
clauses = _positive_clauses(prompt)
|
| 107 |
+
ranked = []
|
| 108 |
+
for item in 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
|
| 116 |
+
hits = [phrase for phrase in _title_phrases(item) if len(phrase) >= 2
|
| 117 |
+
and any(all(f" {word} " in clause for word in phrase) for clause in clauses)]
|
| 118 |
+
hits.extend(phrase for phrase in _motion_phrases(item) if _contains(clauses, phrase))
|
| 119 |
+
if hits:
|
| 120 |
+
ranked.append(((1, max(map(len, hits))), item))
|
| 121 |
+
ranked.sort(key=lambda entry: entry[0], reverse=True)
|
| 122 |
+
return [item for _, item in ranked]
|