amisima commited on
Commit
287fdcd
·
verified ·
1 Parent(s): efaf3a3

Make CPU-picked LoRAs easy to toggle

Browse files
Files changed (1) hide show
  1. app.py +118 -28
app.py CHANGED
@@ -7707,6 +7707,11 @@ def _sync_slot_triggers(prompt_text, sheet_text, state, *slot_fields, library=No
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"))
@@ -7805,7 +7810,33 @@ def _wan_active_lora_summary(library, state, *adapter_values):
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
 
@@ -7853,7 +7884,8 @@ def _wan_cpu_lora_choices(prompt, library, adapter_values):
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)
@@ -8787,6 +8819,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
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 (Free · CPU)", size="sm", variant="secondary")
8789
  extension_cpu_status = gr.Markdown("Matches names and trigger words in your LoRA library.")
 
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.")
@@ -8873,6 +8906,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8873
  )
8874
  scene_cpu_lora = gr.Button("Pick LoRAs from scene (Free · 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",
@@ -9088,6 +9122,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
9088
  duration_seconds_input.render()
9089
  cpu_lora = gr.Button("Pick LoRAs from prompt (Free · CPU)", size="sm", variant="secondary")
9090
  cpu_lora_status = gr.Markdown("Matches names and trigger words in your LoRA library.")
 
9091
  active_loras = gr.Markdown(active_loras_default, elem_id="active-loras")
9092
  with gr.Row(elem_classes="studio-actions"):
9093
  generate_button.render()
@@ -10107,17 +10142,41 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
10107
 
10108
  _ACTIVE_LORA_FIELDS = ui_inputs[16:53]
10109
  _ACTIVE_LORA_INPUTS = [lora_catalog_state, basic_shortlist, *_ACTIVE_LORA_FIELDS]
10110
- _ACTIVE_LORA_OUTPUTS = [active_loras, extension_active_loras, scene_active_loras]
 
10111
 
10112
  def _show_active_loras(library, state, *adapter_values):
10113
  summary = _wan_active_lora_summary(library, state, *adapter_values)
10114
- return summary, summary, summary
 
 
 
10115
 
10116
  gr.on([component.change for component in _ACTIVE_LORA_INPUTS], _show_active_loras,
10117
  _ACTIVE_LORA_INPUTS, _ACTIVE_LORA_OUTPUTS,
10118
  queue=False, show_progress="hidden", trigger_mode="always_last", api_name=False)
10119
 
10120
  _CPU_LORA_FIELDS = _ACTIVE_LORA_FIELDS[3:]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10121
 
10122
  def _apply_cpu_loras(prompt_text, sheet_text, idea_text, library, state, base, identity_at,
10123
  *adapter_values, scene=False):
@@ -10135,39 +10194,59 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
10135
  summary = _show_active_loras(library, state, *values)
10136
  return [note, gr.update(), *updates[3:], *(gr.update() for _ in _TRIGGER_OUTPUTS), *summary]
10137
 
10138
- def put(index, value, options=None):
10139
- values[index] = value
10140
- updates[index] = (gr.update(value=value, choices=options) if options is not None
10141
- else gr.update(value=value))
10142
-
10143
  rows = [lora_facts(item["name"], also=", ".join(_trigger_words(item))) for _, item in choices]
10144
  rows = score_lora_rows(rows, prompt_basis, identity_at, base=base)
10145
  page = list(state.get("page") or [])
10146
  keys = {_pick_key(item) for item in page}
 
 
10147
  for (index, item), row in zip(choices, rows):
10148
  if item.get("builtin"):
10149
- put(index, item["name"])
10150
- put(index + 1, row["high"])
10151
- put(index + 2, row["low"])
10152
  else:
10153
- put(index, item["url"])
10154
- for offset, role in ((1, "high"), (3, "low")):
10155
- file = item.get(role) or "(None)"
10156
- options = ["(None)", file] if file != "(None)" else ["(None)"]
10157
- put(index + offset, file, options)
10158
- put(index + offset + 1, row[role])
10159
- if _pick_key(item) not in keys:
10160
  page.append(item)
10161
- keys.add(_pick_key(item))
10162
- state["page"] = page
10163
- presets = [values[index] for index in range(3, 12, 3)]
10164
- custom_refs = [values[index + offset] for index in range(12, 37, 5) for offset in (0, 1, 3)]
10165
- trigger_updates = _sync_slot_triggers(prompt_text, sheet_text, state, *presets, *custom_refs,
10166
- library=library, resolve_missing=False)
10167
- built = [name for name in presets if name and name != "(None)"]
10168
  note = f"Added {len(choices)} LoRA{'s' if len(choices) != 1 else ''} from your prompt."
10169
- summary = _show_active_loras(library, state, *values)
10170
- return [note, gr.update(value=built), *updates[3:], *trigger_updates, *summary]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10171
 
10172
  for _button, _prompt, _status, _scene, _api in (
10173
  (cpu_lora, prompt_input, cpu_lora_status, False, "pick_loras_cpu"),
@@ -10184,6 +10263,17 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
10184
  _cpu_picked.success(_gpu_estimate_text, _ESTIMATE_INPUTS, gpu_estimate,
10185
  show_progress="hidden", api_name=False)
10186
 
 
 
 
 
 
 
 
 
 
 
 
10187
  _PRO_ONLY = [pro_promptbuilder, pro_chips, pro_speed, pro_advanced,
10188
  pro_soundset, pro_loop, basic_panel, pro_lora_studio,
10189
  extension_lora_details, scene_lora_details, pro_lora_notice]
 
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
+ if state.get("cpu_picks"):
7711
+ references = {3 + index * 3: (name,) for index, name in enumerate(slot_fields[:3])}
7712
+ references.update({12 + index * 5: slot_fields[start:start + 3]
7713
+ for index, start in enumerate(range(3, len(slot_fields), 3))})
7714
+ state["cpu_picks"] = _wan_cpu_pick_records(state, references)
7715
  active, extras = _slot_trigger_items(slot_fields, state, library, resolve_missing)
7716
  prompt_text = _pick_clean(prompt_text, state.get("prompt_added"))
7717
  sheet_text = _pick_clean(sheet_text, state.get("sheet_added"))
 
7810
  return "**Active LoRAs**\n\n" + ("\n".join(rows) if rows else "No LoRAs selected.")
7811
 
7812
 
7813
+ def _wan_lora_slot_refs(values):
7814
+ return tuple("" if value == "(None)" else str(value or "").strip() for value in values)
7815
+
7816
+
7817
+ def _wan_cpu_pick_records(state, references):
7818
+ """A CPU toggle owns its slot only while the file references are still its own."""
7819
+ valid = {}
7820
+ for key, record in ((state or {}).get("cpu_picks") or {}).items():
7821
+ refs = _wan_lora_slot_refs(references.get(record["slot"], ()))
7822
+ if refs and (refs == record["refs"] if record["enabled"] else not any(refs)):
7823
+ valid[key] = record
7824
+ return valid
7825
+
7826
+
7827
+ def _wan_cpu_current_picks(state, values):
7828
+ references = {index: (values[index],) for index in range(3, 12, 3)}
7829
+ references.update({index: (values[index], values[index + 1], values[index + 3])
7830
+ for index in range(12, 37, 5)})
7831
+ return _wan_cpu_pick_records(state, references)
7832
+
7833
+
7834
+ def _wan_cpu_picker_panel():
7835
+ return gr.CheckboxGroup(choices=[], value=[], visible=False, interactive=True,
7836
+ label="CPU-picked LoRAs", info="Uncheck a LoRA to remove it.")
7837
+
7838
+
7839
+ def _wan_cpu_lora_choices(prompt, library, adapter_values, ranked=None):
7840
  """Find compatible matches for vacant slots using catalogue text and file metadata."""
7841
  from concurrent.futures import ThreadPoolExecutor
7842
 
 
7884
  return item, sources, keys
7885
 
7886
  candidates = []
7887
+ ranked = rank_prompt_loras(prompt, _library_pool(library)) if ranked is None else ranked
7888
+ for item in ranked:
7889
  candidate = describe(item)
7890
  if candidate is not None:
7891
  candidates.append(candidate)
 
8819
  step=duration_seconds_input.step, value=duration_seconds_input.value, label="Seconds to add")
8820
  extension_cpu_lora = gr.Button("Pick LoRAs from prompt (Free · CPU)", size="sm", variant="secondary")
8821
  extension_cpu_status = gr.Markdown("Matches names and trigger words in your LoRA library.")
8822
+ extension_cpu_picks = _wan_cpu_picker_panel()
8823
  extension_active_loras = gr.Markdown(active_loras_default)
8824
  extend_btn = gr.Button("➕ Extend & stitch", variant="primary")
8825
  extension_status = gr.Markdown("The original video is kept, including its audio. Each press adds one new clip.")
 
8906
  )
8907
  scene_cpu_lora = gr.Button("Pick LoRAs from scene (Free · CPU)", size="sm", variant="secondary")
8908
  scene_cpu_status = gr.Markdown("")
8909
+ scene_cpu_picks = _wan_cpu_picker_panel()
8910
  scene_active_loras = gr.Markdown(active_loras_default)
8911
  with gr.Row():
8912
  chain_btn = gr.Button("🎬 Make the whole scene and join it",
 
9122
  duration_seconds_input.render()
9123
  cpu_lora = gr.Button("Pick LoRAs from prompt (Free · CPU)", size="sm", variant="secondary")
9124
  cpu_lora_status = gr.Markdown("Matches names and trigger words in your LoRA library.")
9125
+ cpu_picks = _wan_cpu_picker_panel()
9126
  active_loras = gr.Markdown(active_loras_default, elem_id="active-loras")
9127
  with gr.Row(elem_classes="studio-actions"):
9128
  generate_button.render()
 
10142
 
10143
  _ACTIVE_LORA_FIELDS = ui_inputs[16:53]
10144
  _ACTIVE_LORA_INPUTS = [lora_catalog_state, basic_shortlist, *_ACTIVE_LORA_FIELDS]
10145
+ _CPU_LORA_PANELS = [cpu_picks, extension_cpu_picks, scene_cpu_picks]
10146
+ _ACTIVE_LORA_OUTPUTS = [active_loras, extension_active_loras, scene_active_loras, *_CPU_LORA_PANELS]
10147
 
10148
  def _show_active_loras(library, state, *adapter_values):
10149
  summary = _wan_active_lora_summary(library, state, *adapter_values)
10150
+ picks = _wan_cpu_current_picks(state, adapter_values)
10151
+ choices = [(record["item"]["name"], key) for key, record in picks.items()]
10152
+ checked = [key for key, record in picks.items() if record["enabled"]]
10153
+ return [summary] * 3 + [gr.update(choices=choices, value=checked, visible=bool(choices)) for _ in range(3)]
10154
 
10155
  gr.on([component.change for component in _ACTIVE_LORA_INPUTS], _show_active_loras,
10156
  _ACTIVE_LORA_INPUTS, _ACTIVE_LORA_OUTPUTS,
10157
  queue=False, show_progress="hidden", trigger_mode="always_last", api_name=False)
10158
 
10159
  _CPU_LORA_FIELDS = _ACTIVE_LORA_FIELDS[3:]
10160
+ _CPU_LORA_STATUS = [cpu_lora_status, extension_cpu_status, scene_cpu_status]
10161
+
10162
+ def _write_cpu_lora_slot(values, updates, index, row):
10163
+ for offset, value in enumerate(row):
10164
+ pos = index + offset
10165
+ if index >= 12 and offset in (1, 3):
10166
+ options = ["(None)"] if value == "(None)" else ["(None)", value]
10167
+ updates[pos] = gr.update(value=value, choices=options)
10168
+ elif value != values[pos]:
10169
+ updates[pos] = gr.update(value=value)
10170
+ values[pos] = value
10171
+
10172
+ def _cpu_lora_result(prompt_text, sheet_text, library, state, values, updates):
10173
+ presets = [values[index] for index in range(3, 12, 3)]
10174
+ custom_refs = [values[index + offset] for index in range(12, 37, 5) for offset in (0, 1, 3)]
10175
+ trigger_updates = _sync_slot_triggers(prompt_text, sheet_text, state, *presets, *custom_refs,
10176
+ library=library, resolve_missing=False)
10177
+ built = [name for name in presets if name and name != "(None)"]
10178
+ return [gr.update(value=built), *updates[3:], *trigger_updates,
10179
+ *_show_active_loras(library, trigger_updates[2], *values)]
10180
 
10181
  def _apply_cpu_loras(prompt_text, sheet_text, idea_text, library, state, base, identity_at,
10182
  *adapter_values, scene=False):
 
10194
  summary = _show_active_loras(library, state, *values)
10195
  return [note, gr.update(), *updates[3:], *(gr.update() for _ in _TRIGGER_OUTPUTS), *summary]
10196
 
 
 
 
 
 
10197
  rows = [lora_facts(item["name"], also=", ".join(_trigger_words(item))) for _, item in choices]
10198
  rows = score_lora_rows(rows, prompt_basis, identity_at, base=base)
10199
  page = list(state.get("page") or [])
10200
  keys = {_pick_key(item) for item in page}
10201
+ picks = {key: record for key, record in _wan_cpu_current_picks(state, values).items()
10202
+ if record["enabled"]}
10203
  for (index, item), row in zip(choices, rows):
10204
  if item.get("builtin"):
10205
+ slot = (item["name"], row["high"], row["low"])
10206
+ refs = slot[:1]
 
10207
  else:
10208
+ slot = (item["url"], item.get("high") or "(None)", row["high"],
10209
+ item.get("low") or "(None)", row["low"])
10210
+ refs = (slot[0], slot[1], slot[3])
10211
+ _write_cpu_lora_slot(values, updates, index, slot)
10212
+ key = _pick_key(item)
10213
+ picks[key] = dict(slot=index, item=item, refs=_wan_lora_slot_refs(refs), enabled=True)
10214
+ if key not in keys:
10215
  page.append(item)
10216
+ keys.add(key)
10217
+ state.update(page=page, cpu_picks=picks)
 
 
 
 
 
10218
  note = f"Added {len(choices)} LoRA{'s' if len(choices) != 1 else ''} from your prompt."
10219
+ return [note, *_cpu_lora_result(prompt_text, sheet_text, library, state, values, updates)]
10220
+
10221
+ def _toggle_cpu_lora(evt: gr.SelectData, prompt_text, sheet_text, library, state, *adapter_values):
10222
+ state = copy.deepcopy(state or {})
10223
+ values = list(adapter_values)
10224
+ updates = [gr.update() for _ in values]
10225
+ picks = _wan_cpu_current_picks(state, values)
10226
+ record = picks.get(evt.value) if evt and isinstance(evt.value, str) else None
10227
+ note = "Current LoRAs were kept."
10228
+ if record and record["enabled"] != evt.selected:
10229
+ index = record["slot"]
10230
+ if not evt.selected:
10231
+ row = values[index:index + (3 if index < 12 else 5)]
10232
+ record.update(saved=row, enabled=False)
10233
+ cleared = ["(None)", *row[1:]] if index < 12 else ["", "(None)", row[2], "(None)", row[4]]
10234
+ _write_cpu_lora_slot(values, updates, index, cleared)
10235
+ note = "LoRA removed."
10236
+ elif _wan_cpu_lora_choices("", library, values, ranked=[record["item"]]):
10237
+ _write_cpu_lora_slot(values, updates, index, record["saved"])
10238
+ record["enabled"] = True
10239
+ page = list(state.get("page") or [])
10240
+ if evt.value not in {_pick_key(item) for item in page}:
10241
+ state["page"] = [*page, record["item"]]
10242
+ note = "LoRA restored."
10243
+ else:
10244
+ note = "This LoRA could not be restored. Current LoRAs were kept."
10245
+ if record["enabled"] == evt.selected:
10246
+ state["cpu_picks"] = picks
10247
+ return [note] * 3 + _cpu_lora_result(prompt_text, sheet_text, library, state, values, updates)
10248
+ return [*[note] * 3, gr.update(), *updates[3:], *(gr.update() for _ in _TRIGGER_OUTPUTS),
10249
+ *_show_active_loras(library, state, *values)]
10250
 
10251
  for _button, _prompt, _status, _scene, _api in (
10252
  (cpu_lora, prompt_input, cpu_lora_status, False, "pick_loras_cpu"),
 
10263
  _cpu_picked.success(_gpu_estimate_text, _ESTIMATE_INPUTS, gpu_estimate,
10264
  show_progress="hidden", api_name=False)
10265
 
10266
+ for _panel, _prompt in zip(_CPU_LORA_PANELS, (prompt_input, extension_prompt, prompt_input)):
10267
+ _cpu_toggled = _panel.select(
10268
+ _toggle_cpu_lora,
10269
+ [_prompt, scene_prompts, lora_catalog_state, basic_shortlist, *_ACTIVE_LORA_FIELDS],
10270
+ [*_CPU_LORA_STATUS, simple_lora, *_CPU_LORA_FIELDS, *_TRIGGER_OUTPUTS, *_ACTIVE_LORA_OUTPUTS],
10271
+ show_progress="hidden", concurrency_id="lora-picker", concurrency_limit=1, api_name=False,
10272
+ trigger_mode="once",
10273
+ )
10274
+ _cpu_toggled.success(_gpu_estimate_text, _ESTIMATE_INPUTS, gpu_estimate,
10275
+ show_progress="hidden", api_name=False)
10276
+
10277
  _PRO_ONLY = [pro_promptbuilder, pro_chips, pro_speed, pro_advanced,
10278
  pro_soundset, pro_loop, basic_panel, pro_lora_studio,
10279
  extension_lora_details, scene_lora_details, pro_lora_notice]