amisima commited on
Commit
faaa222
·
verified ·
1 Parent(s): e845340

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +47 -12
  2. app.py +441 -119
README.md CHANGED
@@ -7,7 +7,7 @@ sdk: gradio
7
  sdk_version: 6.24.0
8
  app_file: app.py
9
  pinned: false
10
- short_description: 'NEW: lighter GPU requests, looping LoRA Refresh & AI scenes'
11
  tags:
12
  - not-for-all-audiences
13
  - video
@@ -29,22 +29,47 @@ guided creation or **Pro — all tools & settings** for the full set of controls
29
 
30
  **🆕 AI Scene Planner · 🔒 Improved Identity Lock · 🔊 3 audio models · 🎞️ Up to 64 clips**
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  ## 🆕 Smaller GPU requests and steadier rendering
33
 
34
  Normal mode restores the earlier, lighter GPU reservation policy. It removes the unconditional
35
- 60-second minimum, the added 35% denoising margin and the 35/120-second adapter-loading surcharge.
36
- **Safe Mode** keeps conservative reserves for cold adapter loads and slow runs; it is off by default.
 
37
  Existing saved profiles and ready-made setups can still enable it.
38
 
39
  Suitable images keep their native size: a 512×768 upload stays 512×768 instead of being enlarged
40
  to 560×832. Dimensions still follow the checkpoint's 16-pixel grid and configured size bounds.
41
  The estimate now uses the same image-sizing policy and both guidance settings as generation.
42
 
43
- For a 512×768 input, 9 seconds, 32 FPS, 8 steps, guidance 1/1 and Safe Mode off, the code computes
44
  about **206 seconds of requested xlarge allowance**. At 3.5 seconds and 6 steps it computes about
45
  **54 seconds**. These are reservation calculations, not measured runtimes or a promise that a
46
- particular request will fit the quota remaining on your account. Cold adapter loading may need
47
- Safe Mode. Audio and AI planning have their own additional processing.
48
 
49
  RIFE frames are encoded as they become ready instead of keeping a second complete interpolated
50
  video in RAM. Joining normalises one clip at a time, then combines the prepared files without
@@ -59,11 +84,13 @@ replaces the oldest selection; the new choice is no longer silently ignored. It
59
  **Refresh does not call an AI model or request a GPU**. Suggestions are not random.
60
 
61
  General NSFW **all-in-one / AIO** entries, including **General NSFW Booster**, stay visible on every
62
- page as extra options. They are not enabled automatically, and do not displace the five rotating
63
- suggestions. Confirmed invalid entries remain excluded, including all-in-one entries.
 
64
 
65
- - Missing files and explicitly incompatible base-model metadata are excluded from suggestions.
66
- Confirmed bad entries are remembered for 24 hours, then checked again so repaired files can return.
 
67
  - Authentication errors, rate limits and timeouts do not permanently blacklist an adapter.
68
  All-in-one choices remain visible through temporary availability failures.
69
  - Link checks cannot prove that weights load correctly or that an effect will look good.
@@ -81,7 +108,8 @@ suggestions. Confirmed invalid entries remain excluded, including all-in-one ent
81
  Refresh preserves your choices and does not rewrite prompts with AI or regenerate the scene.
82
 
83
  The existing catalogue and manual controls in **Pro** remain available. Each panel gets its own
84
- Gradio update object to prevent stale selections falling outside the displayed choices.
 
85
 
86
  ## 🆕 AI Scene Planner — available in Simple
87
 
@@ -213,6 +241,11 @@ what a visitor loads is their own responsibility under that policy.
213
  separately request adapter selection. Repeated user clicks also start new requests.
214
  - Set `CIVITAI_TOKEN` in Settings → Variables and secrets for downloads that need authentication.
215
  Signing in to CivitAI in your own browser does not authenticate the Space's server.
 
 
 
 
 
216
  - A custom adapter can use a Hugging Face repo, an individual file or a CivitAI link. High and Low
217
  strengths are independently adjustable. Shared library entries include names and trigger words.
218
  - Built-in presets are read from the private repo named by `LORA_CATALOG_REPO`. With it unset, the
@@ -243,6 +276,8 @@ unhandled missing-file traceback; the app cannot recover an upload deleted by a
243
 
244
  Use **Runtime diagnostics** to download a bounded report with the boot ID, RAM figures, processing
245
  stages and cgroup memory/OOM counters when available. Reports contain no prompts or photo contents.
 
 
246
  The report is stored under writable `/data` or `/bucket` with file-lock support, otherwise the
247
  system temporary directory. History survives replacement only if the backing storage is persistent.
248
  The supplied startup/error log did not establish an OOM crash or repeated restart. These changes
@@ -252,7 +287,7 @@ The app still relies on the Space's existing model files, helper modules and dep
252
  Replace `app.py` and this `README.md` in the corresponding Space; this update is not a complete
253
  standalone repository. Local checks cover reservation and resize calculations, looping LoRA selection,
254
  Gradio choices, trigger replacement in both prompt fields, manual slot changes, remote
255
- authentication/retry limits, failure cleanup and real ffmpeg audio/video joins. Fifteen regression
256
  tests passed, and the added event bindings were checked with Gradio 6.24.0. GPU model inference and the live browser
257
  workflow must be verified in the Space.
258
 
 
7
  sdk_version: 6.24.0
8
  app_file: app.py
9
  pinned: false
10
+ short_description: 'NEW: LoRA size guard, CPU downloads & AI scene planning'
11
  tags:
12
  - not-for-all-audiences
13
  - video
 
29
 
30
  **🆕 AI Scene Planner · 🔒 Improved Identity Lock · 🔊 3 audio models · 🎞️ Up to 64 clips**
31
 
32
+ ## 🆕 LoRA preparation before GPU — size checks and complete downloads
33
+
34
+ All selected LoRA files, including built-in presets, Hugging Face files and CivitAI/direct
35
+ links, are downloaded and checked **before the video GPU request**. Progress shows preparation
36
+ and downloaded MiB for direct links. Valid cached downloads are reused across clips and runs
37
+ while the files remain on the Space's disk.
38
+
39
+ - **1024 MiB (1 GiB) per file** and **3072 MiB (3 GiB) across enabled adapter files** by default.
40
+ High and Low files both count; optional speed adapters count too. A zero-strength half is skipped.
41
+ - Prompt and Split into clips suggestions exclude adapters known to exceed the limits. General
42
+ all-in-one options stay pinned when they fit; General NSFW Booster's current High/Low pair fits.
43
+ - Manual Pro selections are checked too. Oversized or incomplete files stop preparation with a
44
+ clear error **before reserving the video GPU**. A size rejection does not blacklist the adapter.
45
+ - Missing size metadata is not treated as a small file: direct downloads enforce the byte limit
46
+ while streaming. New URL downloads become reusable only after size and safetensors extent checks.
47
+ Partial files from interrupted downloads are not accepted as ready weights.
48
+
49
+ Loading the prepared weights into the video model still takes GPU time. The reservation now adds
50
+ a size-based allowance: **2 seconds per enabled file plus 10 seconds per GiB**, with a larger margin
51
+ in Safe Mode. This is an estimate, not a benchmark or a guarantee against timeouts. Without optional
52
+ LoRAs there is no new loading allowance. File size is only a practical guard; it cannot prove model
53
+ compatibility or predict every adapter's memory use. These changes were tested locally without
54
+ running GPU inference.
55
+
56
  ## 🆕 Smaller GPU requests and steadier rendering
57
 
58
  Normal mode restores the earlier, lighter GPU reservation policy. It removes the unconditional
59
+ 60-second minimum, the added 35% denoising margin and the fixed 35/120-second adapter-loading surcharge.
60
+ Selected adapters now use the size-based loading allowance described above.
61
+ **Safe Mode** keeps conservative reserves for adapter loading and slow runs; it is off by default.
62
  Existing saved profiles and ready-made setups can still enable it.
63
 
64
  Suitable images keep their native size: a 512×768 upload stays 512×768 instead of being enlarged
65
  to 560×832. Dimensions still follow the checkpoint's 16-pixel grid and configured size bounds.
66
  The estimate now uses the same image-sizing policy and both guidance settings as generation.
67
 
68
+ For a 512×768 input, 9 seconds, 32 FPS, 8 steps, guidance 1/1, no optional LoRAs and Safe Mode off, the code computes
69
  about **206 seconds of requested xlarge allowance**. At 3.5 seconds and 6 steps it computes about
70
  **54 seconds**. These are reservation calculations, not measured runtimes or a promise that a
71
+ particular request will fit the quota remaining on your account. Adding LoRAs increases the loading
72
+ allowance. Audio and AI planning have their own additional processing.
73
 
74
  RIFE frames are encoded as they become ready instead of keeping a second complete interpolated
75
  video in RAM. Joining normalises one clip at a time, then combines the prepared files without
 
84
  **Refresh does not call an AI model or request a GPU**. Suggestions are not random.
85
 
86
  General NSFW **all-in-one / AIO** entries, including **General NSFW Booster**, stay visible on every
87
+ page as extra options when they fit the size limits. They are not enabled automatically, and do not
88
+ displace the five rotating suggestions. Confirmed invalid or oversized entries remain excluded,
89
+ including all-in-one entries.
90
 
91
+ - Unavailable links, oversized files and explicitly incompatible base-model metadata are filtered
92
+ from rotating suggestions. Confirmed bad entries are remembered for 24 hours, then checked again
93
+ so repaired files can return. Unknown file sizes are checked during preparation.
94
  - Authentication errors, rate limits and timeouts do not permanently blacklist an adapter.
95
  All-in-one choices remain visible through temporary availability failures.
96
  - Link checks cannot prove that weights load correctly or that an effect will look good.
 
108
  Refresh preserves your choices and does not rewrite prompts with AI or regenerate the scene.
109
 
110
  The existing catalogue and manual controls in **Pro** remain available. Each panel gets its own
111
+ Gradio update object to prevent stale selections falling outside the displayed choices. Manual
112
+ catalogue lists are not pruned; their selected files still pass the same limits before generation.
113
 
114
  ## 🆕 AI Scene Planner — available in Simple
115
 
 
241
  separately request adapter selection. Repeated user clicks also start new requests.
242
  - Set `CIVITAI_TOKEN` in Settings → Variables and secrets for downloads that need authentication.
243
  Signing in to CivitAI in your own browser does not authenticate the Space's server.
244
+ - `WAN_LORA_MAX_FILE_MB` (default `1024`) and `WAN_LORA_MAX_RUN_MB` (default `3072`) configure
245
+ the per-file and combined limits in **MiB**. Raising them allows heavier adapters and can bring
246
+ back memory pressure or timeouts. `WAN_LORA_DOWNLOAD_SECONDS` (default `600`) bounds streamed
247
+ direct downloads on the CPU; it does not increase the video GPU reservation. Hugging Face's
248
+ native downloader retains its own timeout/retry behavior.
249
  - A custom adapter can use a Hugging Face repo, an individual file or a CivitAI link. High and Low
250
  strengths are independently adjustable. Shared library entries include names and trigger words.
251
  - Built-in presets are read from the private repo named by `LORA_CATALOG_REPO`. With it unset, the
 
276
 
277
  Use **Runtime diagnostics** to download a bounded report with the boot ID, RAM figures, processing
278
  stages and cgroup memory/OOM counters when available. Reports contain no prompts or photo contents.
279
+ LoRA diagnostics also record prepared MiB and GPU adapter-loading wall time, helping distinguish
280
+ a slow download from slow loading or denoising.
281
  The report is stored under writable `/data` or `/bucket` with file-lock support, otherwise the
282
  system temporary directory. History survives replacement only if the backing storage is persistent.
283
  The supplied startup/error log did not establish an OOM crash or repeated restart. These changes
 
287
  Replace `app.py` and this `README.md` in the corresponding Space; this update is not a complete
288
  standalone repository. Local checks cover reservation and resize calculations, looping LoRA selection,
289
  Gradio choices, trigger replacement in both prompt fields, manual slot changes, remote
290
+ authentication/retry limits, failure cleanup and real ffmpeg audio/video joins. Twenty-eight offline regression
291
  tests passed, and the added event bindings were checked with Gradio 6.24.0. GPU model inference and the live browser
292
  workflow must be verified in the Space.
293
 
app.py CHANGED
@@ -1666,9 +1666,8 @@ def get_num_frames(duration_seconds: float):
1666
  return ((raw - 1) // 4) * 4 + 1
1667
 
1668
 
1669
- # Adapters that have already been put on this Space's disk. A slot that is known costs
1670
- # seconds to fuse; a slot that has never been used has to be downloaded first, and that
1671
- # is minutes rather than seconds. The booking has to be told which of the two it is.
1672
  _LORA_SEEN = set()
1673
 
1674
 
@@ -1676,6 +1675,8 @@ def _lora_slot_key(group):
1676
  """One identifier per filled adapter slot, or None when the slot is empty."""
1677
  if not isinstance(group, dict):
1678
  return None
 
 
1679
  preset = str(group.get("preset") or "").strip()
1680
  if preset and preset != "(None)":
1681
  return f"preset:{preset}"
@@ -1687,53 +1688,405 @@ def _lora_slot_key(group):
1687
  return repo + "|" + "|".join(files)
1688
 
1689
 
1690
- def _prefetch_lora_files(lora_groups):
1691
- """Put custom adapters on the disk before the card is booked.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1692
 
1693
- The first use of an adapter downloads it, and that download used to happen inside the
1694
- GPU booking - which is why a run with a lora attached is killed for running over while
1695
- the same run without one finishes. Fetched here it runs on the processor, costs no
1696
- allowance at all, and the booking that follows only has to fuse a file that is already
1697
- there.
1698
  """
 
1699
  for group in lora_groups or []:
1700
- key = _lora_slot_key(group)
1701
- if not key or key in _LORA_SEEN or key.startswith("preset:"):
1702
- continue
1703
- repo = str(group.get("repo") or "").strip()
1704
- wanted = [str(group.get(role) or "").strip() for role in ("file_high", "file_low")]
1705
- wanted = [f for f in wanted if f and f != "(None)"]
1706
- if not repo or repo.lower().startswith("http"):
1707
  continue
1708
- if any(f.lower().startswith("http") for f in wanted):
1709
- continue
1710
- fetched = True
1711
- for filename in wanted:
1712
- try:
1713
- from huggingface_hub import hf_hub_download
1714
- hf_hub_download(repo_id=repo, filename=filename,
1715
- token=os.environ.get("HF_TOKEN") or None)
1716
- except Exception as error: # noqa: BLE001
1717
- fetched = False
1718
- print(f"[lora] {repo}/{filename} could not be fetched in advance: {error}",
1719
- flush=True)
1720
- if fetched:
1721
- _LORA_SEEN.add(key)
1722
- print(f"[lora] {repo} is on the disk before the booking", flush=True)
1723
 
1724
 
1725
  def _lora_booking_extra(lora_groups):
1726
- """Seconds to add to the booking for the adapters attached to this run."""
1727
- first_use, repeat_use = 0, 0
1728
- for group in lora_groups or []:
1729
- key = _lora_slot_key(group)
1730
- if not key:
1731
- continue
1732
- if key in _LORA_SEEN:
1733
- repeat_use += 1
1734
- else:
1735
- first_use += 1
1736
- return 35.0 * repeat_use + 120.0 * first_use
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1737
 
1738
 
1739
  def get_inference_duration(
@@ -1770,7 +2123,7 @@ def get_inference_duration(
1770
  # 16/32 fps use the previous working policy. High interpolation rates retain
1771
  # more RIFE time. No unconditional 60 s floor, 35/120 s adapter surcharge or 35% margin.
1772
  rife_seconds = extra_frames * (0.06 if multiplier <= 2 else 0.10)
1773
- requested = 10 + denoise_seconds + rife_seconds
1774
  return min(max(requested, 10.0), 600.0)
1775
 
1776
 
@@ -1829,7 +2182,9 @@ def run_inference(
1829
  print(f"[request {task_name}] lora: {', '.join(active)}")
1830
  start = time.time()
1831
 
 
1832
  _runtime_event("load_adapters")
 
1833
  lora_loaded = False
1834
  lora_problems = []
1835
  if lora_groups:
@@ -1841,7 +2196,7 @@ def run_inference(
1841
  lora_loaded, lora_problems = outcome
1842
  else:
1843
  lora_loaded = bool(outcome)
1844
- print(f"lora loaded: {lora_groups}")
1845
  except Exception as e:
1846
  print(f"lora warning: {e}")
1847
  lora_problems = [str(e)[:200]]
@@ -1850,6 +2205,8 @@ def run_inference(
1850
  except Exception:
1851
  pass
1852
 
 
 
1853
  _runtime_event("denoise_and_decode")
1854
  result = pipe(
1855
  image=resized_image,
@@ -2026,8 +2383,8 @@ def generate_video(
2026
  if speed_group:
2027
  lora_groups.insert(0, speed_group)
2028
 
2029
- # On the processor, before the card is booked: whatever can be downloaded in advance is.
2030
- _prefetch_lora_files(lora_groups)
2031
 
2032
  requested_seconds = get_inference_duration(
2033
  resized_image, processed_last_image, prompt, steps, negative_prompt, num_frames,
@@ -5364,8 +5721,8 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5364
  f"output {out_frames} frames @ {out_fps} fps{note}. Runtime limit: {int(secs)} s. "
5365
  "xlarge uses a 2× quota multiplier. Requested allowance is checked before generation; "
5366
  "this is not a receipt for actual GPU usage. Normal mode restores smaller reservations; "
5367
- "Safe Mode adds conservative time and adapter-loading margins. Cold downloads or slow "
5368
- "runs may need Safe Mode. Joining and looping do not book a GPU.</sub>"
5369
  )
5370
  return "\n".join(lines)
5371
 
@@ -5873,11 +6230,13 @@ def _shortlist_loras(prompt_text, pool, limit=5):
5873
  def _pick_label(index, item):
5874
  text = f"{index + 1}. {item.get('name', '')}"
5875
  if _pick_all_in_one(item):
5876
- text += " · always listed"
5877
  if item.get("builtin"):
5878
  text += " · built in"
5879
  elif not str(item.get("trigger") or "").strip():
5880
  text += " · no trigger words saved"
 
 
5881
  return text[:200]
5882
 
5883
 
@@ -6113,6 +6472,12 @@ def _record_wan_lora_failures(groups, problems):
6113
  if len(matches) != 1:
6114
  continue # An ambiguous loader warning is not evidence against every adapter.
6115
  group = matches[0]
 
 
 
 
 
 
6116
  source = str(group.get("repo") or "").strip()
6117
  if group.get("preset") and group["preset"] != "(None)":
6118
  source = "builtin:" + group["preset"]
@@ -6121,67 +6486,19 @@ def _record_wan_lora_failures(groups, problems):
6121
 
6122
 
6123
  def _pick_probe(item):
6124
- from urllib.parse import urlparse
6125
  key = _pick_key(item)
6126
  cached = _health_read(key)
6127
- if cached:
6128
- return cached.get("status", "unknown")
6129
- # Only use an explicit base-model field; a model name is not reliable metadata.
6130
  base = str(item.get("baseModel") or item.get("base_model") or "").lower()
6131
- other_family = ((LORA_PICK_FAMILY == "ltx" and "wan" in base)
6132
- or (LORA_PICK_FAMILY == "wan" and "ltx" in base)
6133
- or any(term in base for term in ("sdxl", "stable diffusion", "flux", "sd 1.")))
6134
- if other_family:
6135
  _health_write(key, "bad", "incompatible-base-model")
6136
  return "bad"
6137
- if item.get("builtin"):
6138
- return "ok"
6139
- import requests
6140
- urls = list(dict.fromkeys(str(item.get(field) or "").strip()
6141
- for field in ("high", "low") if item.get(field)))
6142
- if not urls:
6143
- urls = [str(item.get("url") or "").strip()]
6144
- result = "ok"
6145
- for url in urls:
6146
- try:
6147
- parsed = urlparse(url)
6148
- except ValueError:
6149
- return "unavailable"
6150
- if parsed.scheme not in ("http", "https"):
6151
- result = "unknown"
6152
- continue
6153
- host = (parsed.hostname or "").lower()
6154
- headers = {"User-Agent": "LoRA-availability-check/1.0"}
6155
- # Never attach credentials to a substring match or an unrelated host.
6156
- if host == "huggingface.co":
6157
- token = os.environ.get("HF_TOKEN", "").strip()
6158
- elif host in ("civitai.com", "civitai.red", "civitai.green", "civitai.work"):
6159
- token = os.environ.get("CIVITAI_TOKEN", "").strip()
6160
- else:
6161
- token = ""
6162
- if token:
6163
- headers["Authorization"] = "Bearer " + token
6164
- try:
6165
- with requests.head(url, headers=headers, allow_redirects=True, timeout=(3, 6)) as reply:
6166
- code = reply.status_code
6167
- if code in (404, 410):
6168
- # Some gated services deliberately answer 404 to anonymous callers.
6169
- if host in ("huggingface.co", "civitai.com", "civitai.red", "civitai.green", "civitai.work") and not token:
6170
- return "unavailable"
6171
- _health_write(key, "bad", "http-" + str(code))
6172
- return "bad"
6173
- if code in (401, 403, 429) or code >= 500:
6174
- return "unavailable"
6175
- if code == 405 or not 200 <= code < 300:
6176
- result = "unknown"
6177
- elif "text/html" in str(reply.headers.get("content-type", "")).lower():
6178
- # A challenge/login page can be temporary; do not blacklist the weights.
6179
- return "unavailable"
6180
- except requests.RequestException:
6181
- return "unavailable"
6182
- if result == "ok":
6183
- _health_write(key, "ok", "link-available")
6184
- return result
6185
 
6186
 
6187
  def _pick_all_in_one(item):
@@ -6221,7 +6538,7 @@ def _pick_page(basis, state, advance=False, keep=None):
6221
  # Pinned means visible, not enabled. Keep general options through transient
6222
  # link failures, but exclude confirmed invalid/incompatible files.
6223
  for item, status in zip(pins, workers.map(_pick_probe, pins)):
6224
- if status == "bad":
6225
  skipped += 1
6226
  continue
6227
  page.append(item)
@@ -6230,7 +6547,7 @@ def _pick_page(basis, state, advance=False, keep=None):
6230
  key = _pick_key(item)
6231
  if key in page_keys:
6232
  continue
6233
- if _pick_probe(item) == "bad":
6234
  skipped += 1
6235
  continue
6236
  page.append(item)
@@ -6247,7 +6564,7 @@ def _pick_page(basis, state, advance=False, keep=None):
6247
  key = _pick_key(item)
6248
  if key in page_keys:
6249
  continue
6250
- if status in ("bad", "unavailable"):
6251
  skipped += 1
6252
  continue
6253
  page.append(item)
@@ -6329,11 +6646,11 @@ def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, st
6329
  judged = _ask_which_loras(space_id, basis, [item for _, item in eligible])
6330
  chosen = [eligible[i][0] for i in judged if 0 <= i < len(eligible)]
6331
  state.update(basis=basis, cursor=cursor, page=page)
6332
- detail = f"{len(page)} suggestions shown; {skipped} unavailable entries skipped."
6333
  if kept:
6334
  detail += f" {len(kept)} kept ticked; only the unticked ones were replaced."
6335
  detail += (" Refresh uses no AI/GPU call, loops through up to 5 relevant candidates and returns to the beginning. "
6336
- "General NSFW all-in-one entries stay visible; select them explicitly when needed.")
6337
  else:
6338
  page = list(state.get("page") or [])
6339
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
@@ -6362,7 +6679,7 @@ def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, st
6362
  if missing:
6363
  note += " No activation words available for: " + ", ".join(missing) + "."
6364
  note += " Available trigger words are synced to the main prompt and every clip."
6365
- note += " Link availability does not guarantee model compatibility."
6366
  return state, page, selected, note, prompt_text, sheet_text, picks, old_picks
6367
 
6368
 
@@ -6462,6 +6779,11 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6462
  delete_cache=(3600, 259200)) as demo:
6463
  gr.HTML("<style>" + CSS + "</style>")
6464
  gr.HTML(HERO)
 
 
 
 
 
6465
  with gr.Accordion("Runtime diagnostics", open=False):
6466
  gr.Markdown("If the Space restarts or gets stuck, download this report and attach it to your bug report.")
6467
  runtime_button = gr.Button("Check runtime / download report", size="sm")
@@ -6540,7 +6862,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6540
  "**Picture in, a few words above, one press.** The prompt is "
6541
  "rewritten from your photo, the library is searched for effects "
6542
  "that match it, and their strengths are set. Whatever it picks "
6543
- "is shown underneath. NEW: Refresh loops through relevant LoRAs; general NSFW all-in-one entries stay visible."
6544
  )
6545
  basic_btn = gr.Button("✨ Prepare prompt & effects", variant="primary",
6546
  elem_id="enhance-btn")
@@ -6658,7 +6980,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6658
  "**Pick from the list and press Generate. That is the whole thing.** "
6659
  "Elsewhere these are called *loras* and people talk about files, slots "
6660
  "and high/low weights - none of that is needed here. Every name in the "
6661
- "list is already downloaded, tested and wired up for you.\n\n"
6662
  "Most clips are better with nothing selected. Add one only when you want "
6663
  "that specific thing to happen."
6664
  )
@@ -7030,8 +7352,8 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7030
  scene_pick = gr.CheckboxGroup(
7031
  choices=[], value=[], visible=False,
7032
  label="Effects chosen for this scene — tick another one to swap",
7033
- info="Two at a time is the limit. Every tick updates the shared selection. Trigger hints are added "
7034
- "only to matching clip prompts.",
7035
  )
7036
  scene_links = gr.Markdown("")
7037
  scene_refresh_btn = gr.Button("🔄 Refresh — next group ↻", variant="secondary")
@@ -7206,9 +7528,9 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7206
  "- Cropping happens after upload, so pre-cropping your image to roughly the "
7207
  "render aspect is the only way to control exactly what survives.\n\n"
7208
  "**Loras**\n"
7209
- "- Custom loras download on first use. A lora given as a Hugging Face repo is "
7210
- "fetched before the card is booked and costs no GPU time; a pasted direct link "
7211
- "is still fetched during the booking, so the first take with it asks for more.\n"
7212
  "- **High** and **Low** strength apply to the two noise stages. If a lora is "
7213
  "overpowering the composition, drop High first and leave Low alone."
7214
  )
 
1666
  return ((raw - 1) // 4) * 4 + 1
1667
 
1668
 
1669
+ # Recently prepared adapter slots. Every file is still checked before GPU admission;
1670
+ # an in-memory cache marker is not proof that the complete file remains on disk.
 
1671
  _LORA_SEEN = set()
1672
 
1673
 
 
1675
  """One identifier per filled adapter slot, or None when the slot is empty."""
1676
  if not isinstance(group, dict):
1677
  return None
1678
+ if group.get("_source_key"):
1679
+ return group["_source_key"]
1680
  preset = str(group.get("preset") or "").strip()
1681
  if preset and preset != "(None)":
1682
  return f"preset:{preset}"
 
1688
  return repo + "|" + "|".join(files)
1689
 
1690
 
1691
+ # All adapter I/O happens before the ZeroGPU call. Limits are policy defaults,
1692
+ # not measured model compatibility or a guarantee about inference duration.
1693
+ def _lora_limit(name, default, maximum):
1694
+ try:
1695
+ return max(1, min(maximum, int(os.environ.get(name, default))))
1696
+ except (TypeError, ValueError):
1697
+ return default
1698
+
1699
+
1700
+ LORA_MAX_FILE_BYTES = _lora_limit("WAN_LORA_MAX_FILE_MB", 1024, 16384) * 1048576
1701
+ LORA_MAX_RUN_BYTES = _lora_limit("WAN_LORA_MAX_RUN_MB", 3072, 32768) * 1048576
1702
+ LORA_DOWNLOAD_SECONDS = _lora_limit("WAN_LORA_DOWNLOAD_SECONDS", 600, 1800)
1703
+ _LORA_SOURCE_INFO = {}
1704
+ _LORA_LOAD_INFO = {}
1705
+ _LORA_PREP_LOCK = threading.RLock()
1706
+
1707
+
1708
+ def _lora_source(repo, filename):
1709
+ """Resolve local files, HF repo paths/file URLs, or direct download URLs."""
1710
+ from urllib.parse import urlsplit, unquote
1711
+ text = str(filename or "").strip().strip('"').strip("'")
1712
+ if not text or text == "(None)":
1713
+ return None
1714
+ if os.path.isfile(text):
1715
+ return {"path": os.path.abspath(text)}
1716
+ parsed = urlsplit(text)
1717
+ if parsed.scheme in ("http", "https"):
1718
+ if parsed.hostname == "huggingface.co":
1719
+ parts = parsed.path.strip("/").split("/")
1720
+ if len(parts) < 5 or parts[2] not in ("resolve", "blob"):
1721
+ raise ValueError("Choose a specific .safetensors file from the Hugging Face repository.")
1722
+ return {"repo": "/".join(parts[:2]), "revision": unquote(parts[3]),
1723
+ "file": unquote("/".join(parts[4:]))}
1724
+ return {"url": text}
1725
+ # A repo-relative subdirectory must not be mistaken for owner/repo/file.
1726
+ repo_id = lora_loader.parse_repo_link(str(repo or ""))
1727
+ if not repo_id:
1728
+ repo_id, text = lora_loader.parse_hf_file_link(text)
1729
+ if not repo_id:
1730
+ raise ValueError("Choose a repository and a file, or paste a direct file link.")
1731
+ return {"repo": repo_id, "file": text,
1732
+ "revision": getattr(lora_loader, "PINNED_REVISIONS", {}).get(repo_id) or "main"}
1733
+
1734
+
1735
+ def _lora_group_sources(group):
1736
+ """Only active halves; zero strength must not become 1.0 in the old loader."""
1737
+ if not isinstance(group, dict):
1738
+ return []
1739
+ preset = str(group.get("preset") or "").strip()
1740
+ pair = None
1741
+ if preset and preset != "(None)":
1742
+ clean = re.sub(r"\s*\((?:HIGH|LOW) only\)", "", preset)
1743
+ pair = getattr(lora_loader, "LORA_PAIRS", {}).get(clean)
1744
+ if not pair:
1745
+ raise ValueError("The selected built-in LoRA is no longer in the loader catalogue.")
1746
+ result = []
1747
+ for role in ("high", "low"):
1748
+ raw_scale = group.get(role + "_scale", 1.0)
1749
+ scale = 1.0 if raw_scale is None else float(raw_scale)
1750
+ if not np.isfinite(scale):
1751
+ raise ValueError("LoRA strength must be a finite number.")
1752
+ if scale == 0:
1753
+ continue
1754
+ if pair is not None:
1755
+ entry = pair.get(role.upper())
1756
+ source = _lora_source(*entry) if entry else None
1757
+ else:
1758
+ source = _lora_source(group.get("repo"), group.get("file_" + role))
1759
+ if source:
1760
+ result.append((role, source, scale))
1761
+ return result
1762
+
1763
+
1764
+ def _lora_source_key(source):
1765
+ import hashlib
1766
+ return hashlib.sha256(json.dumps(source, sort_keys=True).encode()).hexdigest()
1767
+
1768
+
1769
+ def _lora_headers(url):
1770
+ from urllib.parse import urlsplit
1771
+ host = (urlsplit(url).hostname or "").lower()
1772
+ token = ""
1773
+ if host == "huggingface.co":
1774
+ token = os.environ.get("HF_TOKEN", "")
1775
+ elif host in ("civitai.com", "civitai.red", "civitai.green", "civitai.work"):
1776
+ token = os.environ.get("CIVITAI_TOKEN", "")
1777
+ headers = {"User-Agent": "WAN-LoRA-preparation/1.0", "Accept-Encoding": "identity"}
1778
+ if token:
1779
+ headers["Authorization"] = "Bearer " + token
1780
+ return headers
1781
+
1782
+
1783
+ def _lora_request_url(url):
1784
+ """Preserve the existing CivitAI download-token convention on exact hosts."""
1785
+ from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
1786
+ parsed = urlsplit(url)
1787
+ if parsed.hostname not in ("civitai.com", "civitai.red", "civitai.green", "civitai.work"):
1788
+ return url
1789
+ query = parse_qsl(parsed.query, keep_blank_values=True)
1790
+ token = os.environ.get("CIVITAI_TOKEN", "")
1791
+ if token and not any(key == "token" for key, _ in query):
1792
+ query.append(("token", token))
1793
+ return urlunsplit(parsed._replace(query=urlencode(query)))
1794
+ return url
1795
+
1796
+
1797
+ def _lora_open_download(url):
1798
+ """Keep the loader's CivitAI mirrors; retry only before accepting a body."""
1799
+ import requests
1800
+ from urllib.parse import urlsplit, urlunsplit
1801
+ parsed = urlsplit(url)
1802
+ hosts = ("civitai.com", "civitai.red", "civitai.green", "civitai.work")
1803
+ candidates = [url]
1804
+ if parsed.hostname in hosts:
1805
+ candidates += [urlunsplit(parsed._replace(netloc=host)) for host in hosts if host != parsed.hostname]
1806
+ last_error = "download unavailable"
1807
+ for candidate in candidates:
1808
+ response = None
1809
+ try:
1810
+ response = requests.get(_lora_request_url(candidate), headers=_lora_headers(candidate),
1811
+ stream=True, allow_redirects=True, timeout=(10, 30))
1812
+ response.raise_for_status()
1813
+ if "text/html" in response.headers.get("content-type", "").lower():
1814
+ last_error = "web page returned instead of weights"
1815
+ response.close()
1816
+ continue
1817
+ return response
1818
+ except requests.RequestException as error:
1819
+ last_error = type(error).__name__ # Never include token-bearing URLs.
1820
+ if response is not None:
1821
+ response.close()
1822
+ raise ValueError(f"LoRA download failed ({last_error}); no GPU was requested. Check the file link or CIVITAI_TOKEN.")
1823
+
1824
+
1825
+ def _lora_source_info(source):
1826
+ """Small metadata requests only. Unknown size remains unknown, not zero."""
1827
+ key = _lora_source_key(source)
1828
+ if source.get("path"):
1829
+ return {"size": os.path.getsize(source["path"]), "status": "ok"}
1830
+ with _LORA_PREP_LOCK:
1831
+ record = _LORA_SOURCE_INFO.get(key)
1832
+ if record and time.monotonic() - record["at"] < (600 if record["status"] == "ok" else 60):
1833
+ return dict(record)
1834
+ result = {"size": None, "status": "unknown", "at": time.monotonic()}
1835
+ try:
1836
+ if source.get("repo"):
1837
+ from huggingface_hub import hf_hub_url, get_hf_file_metadata
1838
+ url = hf_hub_url(source["repo"], source["file"], revision=source["revision"])
1839
+ metadata = get_hf_file_metadata(url, token=os.environ.get("HF_TOKEN") or False, timeout=8)
1840
+ result.update(size=metadata.size, status="ok")
1841
+ else:
1842
+ import requests
1843
+ with requests.head(_lora_request_url(source["url"]), headers=_lora_headers(source["url"]),
1844
+ allow_redirects=True, timeout=(3, 6)) as response:
1845
+ code = response.status_code
1846
+ if 200 <= code < 300 and "text/html" not in response.headers.get("content-type", "").lower():
1847
+ raw = response.headers.get("x-linked-size") or response.headers.get("content-length")
1848
+ result.update(size=int(raw) if raw and str(raw).isdigit() else None, status="ok")
1849
+ elif code in (401, 403, 404, 410, 429) or code >= 500:
1850
+ result["status"] = "unavailable"
1851
+ elif "text/html" in response.headers.get("content-type", "").lower():
1852
+ result["status"] = "unavailable"
1853
+ except Exception:
1854
+ result["status"] = "unavailable"
1855
+ with _LORA_PREP_LOCK:
1856
+ if len(_LORA_SOURCE_INFO) >= 512:
1857
+ _LORA_SOURCE_INFO.pop(next(iter(_LORA_SOURCE_INFO)))
1858
+ _LORA_SOURCE_INFO[key] = dict(result)
1859
+ return result
1860
+
1861
+
1862
+ def _check_lora_file(path):
1863
+ """Validate safetensors extents without loading tensors into CPU/GPU memory."""
1864
+ import struct
1865
+ size = os.path.getsize(path)
1866
+ if size > LORA_MAX_FILE_BYTES:
1867
+ raise ValueError(f"LoRA is {size / 1048576:.0f} MiB; this Space's per-file limit is {LORA_MAX_FILE_BYTES / 1048576:.0f} MiB.")
1868
+ with open(path, "rb") as handle:
1869
+ raw = handle.read(8)
1870
+ length = struct.unpack("<Q", raw)[0] if len(raw) == 8 else 0
1871
+ if not 1 <= length <= min(16 * 1048576, size - 8):
1872
+ raise ValueError("LoRA has an invalid safetensors header or an incomplete download.")
1873
+ try:
1874
+ header = json.loads(handle.read(length))
1875
+ except (ValueError, UnicodeError) as error:
1876
+ raise ValueError("LoRA has an unreadable safetensors header.") from error
1877
+ if not isinstance(header, dict):
1878
+ raise ValueError("LoRA safetensors header must be an object.")
1879
+ entries = [value for key, value in header.items() if key != "__metadata__"]
1880
+ ends = []
1881
+ for value in entries:
1882
+ offsets = value.get("data_offsets") if isinstance(value, dict) else None
1883
+ if (not isinstance(offsets, list) or len(offsets) != 2
1884
+ or not all(isinstance(n, int) and not isinstance(n, bool) for n in offsets)
1885
+ or not 0 <= offsets[0] <= offsets[1] <= size - 8 - length):
1886
+ raise ValueError("LoRA download is incomplete or its tensor offsets are invalid.")
1887
+ ends.append(offsets[1])
1888
+ if not ends or max(ends) != size - 8 - length:
1889
+ raise ValueError("LoRA download has missing or unexpected tensor data.")
1890
+ return size
1891
+
1892
+
1893
+ def _download_lora_source_unlocked(source, progress=None):
1894
+ if source.get("path"):
1895
+ _check_lora_file(source["path"])
1896
+ return source["path"]
1897
+ if source.get("repo"):
1898
+ from huggingface_hub import hf_hub_download, hf_hub_url, try_to_load_from_cache
1899
+ existing = try_to_load_from_cache(source["repo"], source["file"], revision=source["revision"])
1900
+ if isinstance(existing, str) and os.path.isfile(existing):
1901
+ _check_lora_file(existing)
1902
+ return existing
1903
+ if _lora_source_info(source).get("size") is None:
1904
+ # Unknown remote sizes still get a byte-limited streamed download.
1905
+ return _download_lora_source({"url": hf_hub_url(source["repo"], source["file"],
1906
+ revision=source["revision"])}, progress)
1907
+ path = hf_hub_download(source["repo"], source["file"], revision=source["revision"],
1908
+ token=os.environ.get("HF_TOKEN") or False)
1909
+ _check_lora_file(path)
1910
+ return path
1911
+ import requests
1912
+ root = os.path.join(tempfile.gettempdir(), "wan-loras-ready")
1913
+ os.makedirs(root, exist_ok=True)
1914
+ cached = os.path.join(root, _lora_source_key(source) + ".safetensors")
1915
+ if os.path.isfile(cached):
1916
+ try:
1917
+ _check_lora_file(cached)
1918
+ return cached
1919
+ except ValueError:
1920
+ os.remove(cached) # Only our own invalid cache; never delete uploaded files.
1921
+ url = source["url"]
1922
+ import hashlib
1923
+ legacy = os.path.join(tempfile.gettempdir(), "url-loras",
1924
+ hashlib.sha256(url.encode()).hexdigest()[:16] + ".safetensors")
1925
+ if os.path.isfile(legacy):
1926
+ try:
1927
+ _check_lora_file(legacy)
1928
+ return legacy
1929
+ except ValueError:
1930
+ pass # Old partial files are never trusted merely because they exceed 1 MB.
1931
+ fd, temporary = tempfile.mkstemp(prefix="download-", suffix=".partial", dir=root)
1932
+ started, last_report = time.monotonic(), 0.0
1933
+ try:
1934
+ with os.fdopen(fd, "wb") as handle:
1935
+ with _lora_open_download(url) as response:
1936
+ raw = response.headers.get("content-length")
1937
+ expected = int(raw) if raw and str(raw).isdigit() else None
1938
+ if expected and expected > LORA_MAX_FILE_BYTES:
1939
+ raise ValueError(f"LoRA exceeds the {LORA_MAX_FILE_BYTES / 1048576:.0f} MiB per-file limit.")
1940
+ written = 0
1941
+ for chunk in response.iter_content(chunk_size=1048576):
1942
+ if not chunk:
1943
+ continue
1944
+ written += len(chunk)
1945
+ if written > LORA_MAX_FILE_BYTES:
1946
+ raise ValueError("LoRA exceeded the per-file size limit during download.")
1947
+ now = time.monotonic()
1948
+ if now - started > LORA_DOWNLOAD_SECONDS:
1949
+ raise ValueError("LoRA download timed out before GPU reservation. Try again later.")
1950
+ if shutil.disk_usage(root).free < len(chunk) + 128 * 1048576:
1951
+ raise ValueError("Not enough disk space to finish the LoRA download.")
1952
+ handle.write(chunk)
1953
+ if progress and now - last_report > 1:
1954
+ progress(None, desc=f"Downloading LoRA on CPU · {written / 1048576:.0f} MiB · no GPU reserved")
1955
+ last_report = now
1956
+ if expected is not None and written != expected:
1957
+ raise ValueError("LoRA download ended before the complete file arrived.")
1958
+ _check_lora_file(temporary)
1959
+ os.replace(temporary, cached)
1960
+ return cached
1961
+ except requests.RequestException as error:
1962
+ # requests exceptions can contain the URL's token: do not echo them.
1963
+ raise ValueError(f"LoRA download failed ({type(error).__name__}); no GPU was requested. Check access to the file.") from None
1964
+ finally:
1965
+ if os.path.exists(temporary):
1966
+ os.remove(temporary)
1967
+
1968
+
1969
+ def _download_lora_source(source, progress=None):
1970
+ if not source.get("url"):
1971
+ return _download_lora_source_unlocked(source, progress)
1972
+ from filelock import FileLock
1973
+ root = os.path.join(tempfile.gettempdir(), "wan-loras-ready")
1974
+ os.makedirs(root, exist_ok=True)
1975
+ # Lock only this download; metadata/Refresh need not wait for large files.
1976
+ with FileLock(os.path.join(root, _lora_source_key(source) + ".lock"), timeout=LORA_DOWNLOAD_SECONDS + 60):
1977
+ return _download_lora_source_unlocked(source, progress)
1978
+
1979
+
1980
+ def _prefetch_lora_files(lora_groups, progress=None):
1981
+ """Resolve every enabled file before GPU admission, returning local-only slots."""
1982
+ prepared, descriptions, known_total = [], [], 0
1983
+ try:
1984
+ for group in lora_groups or []:
1985
+ entries = _lora_group_sources(group)
1986
+ if not entries:
1987
+ continue
1988
+ for role, source, scale in entries:
1989
+ info = _lora_source_info(source)
1990
+ size = info.get("size")
1991
+ if size is not None:
1992
+ if size > LORA_MAX_FILE_BYTES:
1993
+ raise ValueError(f"An enabled LoRA file is {size / 1048576:.0f} MiB; limit {LORA_MAX_FILE_BYTES / 1048576:.0f} MiB. Select a lighter LoRA.")
1994
+ known_total += size
1995
+ descriptions.append((group, entries))
1996
+ if known_total > LORA_MAX_RUN_BYTES:
1997
+ raise ValueError(f"Selected LoRAs total at least {known_total / 1048576:.0f} MiB; limit {LORA_MAX_RUN_BYTES / 1048576:.0f} MiB. Use fewer or smaller adapters.")
1998
+ paths, actual_total = {}, 0
1999
+ for index, (original, entries) in enumerate(descriptions, 1):
2000
+ ready = {"repo": "", "preset": "(None)", "file_high": "(None)", "file_low": "(None)",
2001
+ "high_scale": 0.0, "low_scale": 0.0, "_source_key": _lora_slot_key(original),
2002
+ "_load_bytes": 0, "_load_files": 0,
2003
+ "_health_key": _pick_key({"url": original.get("repo") or (
2004
+ original.get("file_high") if str(original.get("file_high", "")).startswith(("http://", "https://")) else ""),
2005
+ "name": original.get("preset") or ""})}
2006
+ for role, source, scale in entries:
2007
+ key = _lora_source_key(source)
2008
+ if progress:
2009
+ progress(None, desc=f"Preparing LoRA {index}/{len(descriptions)} · {role} · no GPU reserved")
2010
+ if key not in paths:
2011
+ paths[key] = _download_lora_source(source, progress)
2012
+ size = _check_lora_file(paths[key])
2013
+ actual_total += size
2014
+ if actual_total > LORA_MAX_RUN_BYTES:
2015
+ raise ValueError("Selected LoRAs exceed the total size limit. Use fewer adapters.")
2016
+ ready["file_" + role] = paths[key]
2017
+ ready[role + "_scale"] = scale
2018
+ ready["_load_bytes"] += size
2019
+ ready["_load_files"] += 1
2020
+ prepared.append(ready)
2021
+ with _LORA_PREP_LOCK:
2022
+ _LORA_LOAD_INFO[ready["_source_key"]] = (ready["_load_bytes"], ready["_load_files"])
2023
+ while len(_LORA_LOAD_INFO) > 256:
2024
+ _LORA_LOAD_INFO.pop(next(iter(_LORA_LOAD_INFO)))
2025
+ _LORA_SEEN.add(ready["_source_key"])
2026
+ if progress and prepared:
2027
+ progress(None, desc=f"LoRAs ready · {actual_total / 1048576:.0f} MiB · requesting GPU next")
2028
+ _runtime_event("lora_preparation_complete", adapter_files=sum(g["_load_files"] for g in prepared),
2029
+ adapter_mib=round(actual_total / 1048576, 1))
2030
+ return prepared
2031
+ except Exception as error:
2032
+ # All preparatory failures stop locally, rather than silently dropping a
2033
+ # selected effect or retrying the same download during a GPU lease.
2034
+ detail = str(error) if isinstance(error, ValueError) else type(error).__name__
2035
+ raise gr.Error("LoRA preparation stopped before GPU reservation. " + detail) from None
2036
+
2037
 
2038
+ def _lora_loading_seconds(lora_groups):
2039
+ """Size-based allowance for disk loading/adapter setup, never for downloads.
2040
+
2041
+ This is a heuristic reservation, not measured time or a billing receipt.
2042
+ Unknown sizes are resolved before the actual GPU call.
2043
  """
2044
+ total_bytes, total_files = 0, 0
2045
  for group in lora_groups or []:
2046
+ if all(group.get(role + "_scale", 1.0) == 0 for role in ("high", "low")):
 
 
 
 
 
 
2047
  continue
2048
+ info = (group.get("_load_bytes", 0), group.get("_load_files", 0))
2049
+ if not info[1]:
2050
+ info = _LORA_LOAD_INFO.get(_lora_slot_key(group), (0, 0))
2051
+ total_bytes += info[0]
2052
+ total_files += info[1]
2053
+ return 2.0 * total_files + 10.0 * total_bytes / 1073741824
 
 
 
 
 
 
 
 
 
2054
 
2055
 
2056
  def _lora_booking_extra(lora_groups):
2057
+ return _lora_loading_seconds(lora_groups) * 1.5
2058
+
2059
+
2060
+ def _lora_candidate_size(item):
2061
+ """Automatic suggestions use metadata; never download weights while browsing."""
2062
+ if item.get("builtin"):
2063
+ group = {"preset": item.get("name")}
2064
+ else:
2065
+ group = {"repo": item.get("url"), "file_high": item.get("high") or item.get("url"),
2066
+ "file_low": item.get("low") or "(None)"}
2067
+ try:
2068
+ sources = _lora_group_sources(group)
2069
+ infos = [_lora_source_info(source) for _, source, _ in sources]
2070
+ except (ValueError, TypeError):
2071
+ return None, False
2072
+ known = [int(info["size"]) for info in infos if info.get("size") is not None]
2073
+ item["_size_status"] = "unavailable" if any(info.get("status") == "unavailable" for info in infos) else "ok"
2074
+ total = sum(known) if sources and len(known) == len(sources) else None
2075
+ if total is not None:
2076
+ item["_size_bytes"] = total
2077
+ return total, any(size > LORA_MAX_FILE_BYTES for size in known) or sum(known) > LORA_MAX_RUN_BYTES
2078
+
2079
+
2080
+ def _require_local_lora_slots(groups):
2081
+ """Last boundary check: the GPU loader never receives a repo or remote URL."""
2082
+ for group in groups or []:
2083
+ if group.get("preset") not in (None, "", "(None)"):
2084
+ raise ValueError("LoRA was not prepared before GPU reservation.")
2085
+ for role in ("high", "low"):
2086
+ filename = group.get("file_" + role)
2087
+ if filename and filename != "(None)" and not os.path.isfile(filename):
2088
+ raise ValueError("A prepared LoRA file disappeared. Retry preparation before generating.")
2089
+
2090
 
2091
 
2092
  def get_inference_duration(
 
2123
  # 16/32 fps use the previous working policy. High interpolation rates retain
2124
  # more RIFE time. No unconditional 60 s floor, 35/120 s adapter surcharge or 35% margin.
2125
  rife_seconds = extra_frames * (0.06 if multiplier <= 2 else 0.10)
2126
+ requested = 10 + denoise_seconds + rife_seconds + _lora_loading_seconds(lora_groups)
2127
  return min(max(requested, 10.0), 600.0)
2128
 
2129
 
 
2182
  print(f"[request {task_name}] lora: {', '.join(active)}")
2183
  start = time.time()
2184
 
2185
+ _require_local_lora_slots(lora_groups)
2186
  _runtime_event("load_adapters")
2187
+ adapter_start = time.perf_counter()
2188
  lora_loaded = False
2189
  lora_problems = []
2190
  if lora_groups:
 
2196
  lora_loaded, lora_problems = outcome
2197
  else:
2198
  lora_loaded = bool(outcome)
2199
+ print(f"[lora] {len(lora_groups)} prepared slot(s); loaded={bool(lora_loaded)}")
2200
  except Exception as e:
2201
  print(f"lora warning: {e}")
2202
  lora_problems = [str(e)[:200]]
 
2205
  except Exception:
2206
  pass
2207
 
2208
+ _runtime_event("adapters_ready", load_wall_s=round(time.perf_counter() - adapter_start, 2),
2209
+ adapter_mib=round(sum(g.get("_load_bytes", 0) for g in lora_groups or []) / 1048576, 1))
2210
  _runtime_event("denoise_and_decode")
2211
  result = pipe(
2212
  image=resized_image,
 
2383
  if speed_group:
2384
  lora_groups.insert(0, speed_group)
2385
 
2386
+ # Resolve and validate every enabled adapter before booking the GPU.
2387
+ lora_groups = _prefetch_lora_files(lora_groups, progress=progress)
2388
 
2389
  requested_seconds = get_inference_duration(
2390
  resized_image, processed_last_image, prompt, steps, negative_prompt, num_frames,
 
5721
  f"output {out_frames} frames @ {out_fps} fps{note}. Runtime limit: {int(secs)} s. "
5722
  "xlarge uses a 2× quota multiplier. Requested allowance is checked before generation; "
5723
  "this is not a receipt for actual GPU usage. Normal mode restores smaller reservations; "
5724
+ "LoRA downloads finish on CPU before the GPU request; a size-based loading reserve is then added. "
5725
+ "Unknown adapter sizes are checked before generation. Safe Mode adds extra runtime margin. Joining and looping do not book a GPU.</sub>"
5726
  )
5727
  return "\n".join(lines)
5728
 
 
6230
  def _pick_label(index, item):
6231
  text = f"{index + 1}. {item.get('name', '')}"
6232
  if _pick_all_in_one(item):
6233
+ text += " · pinned when within size limit"
6234
  if item.get("builtin"):
6235
  text += " · built in"
6236
  elif not str(item.get("trigger") or "").strip():
6237
  text += " · no trigger words saved"
6238
+ if item.get("_size_bytes") is not None:
6239
+ text += f" · {item['_size_bytes'] / 1048576:.0f} MiB"
6240
  return text[:200]
6241
 
6242
 
 
6472
  if len(matches) != 1:
6473
  continue # An ambiguous loader warning is not evidence against every adapter.
6474
  group = matches[0]
6475
+ if group.get("_health_key"):
6476
+ low = message.lower()
6477
+ if any(term in low for term in ("bad header", "unreadable header", "invalidheader", "header too large",
6478
+ "size mismatch", "incompatible lora", "not a wan", "do not fit")):
6479
+ _health_write(group["_health_key"], "bad", "missing-or-invalid-file")
6480
+ continue
6481
  source = str(group.get("repo") or "").strip()
6482
  if group.get("preset") and group["preset"] != "(None)":
6483
  source = "builtin:" + group["preset"]
 
6486
 
6487
 
6488
  def _pick_probe(item):
 
6489
  key = _pick_key(item)
6490
  cached = _health_read(key)
6491
+ if cached.get("status") == "bad":
6492
+ return "bad"
 
6493
  base = str(item.get("baseModel") or item.get("base_model") or "").lower()
6494
+ if ("ltx" in base or any(term in base for term in ("sdxl", "stable diffusion", "flux", "sd 1."))):
 
 
 
6495
  _health_write(key, "bad", "incompatible-base-model")
6496
  return "bad"
6497
+ _size, too_large = _lora_candidate_size(item)
6498
+ if too_large:
6499
+ return "too_large" # A size limit is not an invalid-file blacklist.
6500
+ # The metadata request already checked availability. Do not repeat its HEAD.
6501
+ return item.get("_size_status", "unknown")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6502
 
6503
 
6504
  def _pick_all_in_one(item):
 
6538
  # Pinned means visible, not enabled. Keep general options through transient
6539
  # link failures, but exclude confirmed invalid/incompatible files.
6540
  for item, status in zip(pins, workers.map(_pick_probe, pins)):
6541
+ if status in ("bad", "too_large"):
6542
  skipped += 1
6543
  continue
6544
  page.append(item)
 
6547
  key = _pick_key(item)
6548
  if key in page_keys:
6549
  continue
6550
+ if _pick_probe(item) in ("bad", "too_large"):
6551
  skipped += 1
6552
  continue
6553
  page.append(item)
 
6564
  key = _pick_key(item)
6565
  if key in page_keys:
6566
  continue
6567
+ if status in ("bad", "unavailable", "too_large"):
6568
  skipped += 1
6569
  continue
6570
  page.append(item)
 
6646
  judged = _ask_which_loras(space_id, basis, [item for _, item in eligible])
6647
  chosen = [eligible[i][0] for i in judged if 0 <= i < len(eligible)]
6648
  state.update(basis=basis, cursor=cursor, page=page)
6649
+ detail = f"{len(page)} suggestions shown; {skipped} unavailable or oversized entries skipped."
6650
  if kept:
6651
  detail += f" {len(kept)} kept ticked; only the unticked ones were replaced."
6652
  detail += (" Refresh uses no AI/GPU call, loops through up to 5 relevant candidates and returns to the beginning. "
6653
+ "General NSFW all-in-one entries within the size limit stay visible; select them explicitly when needed.")
6654
  else:
6655
  page = list(state.get("page") or [])
6656
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
 
6679
  if missing:
6680
  note += " No activation words available for: " + ", ".join(missing) + "."
6681
  note += " Available trigger words are synced to the main prompt and every clip."
6682
+ note += f" Files above {LORA_MAX_FILE_BYTES / 1048576:.0f} MiB are hidden from suggestions. Link availability does not guarantee model compatibility."
6683
  return state, page, selected, note, prompt_text, sheet_text, picks, old_picks
6684
 
6685
 
 
6779
  delete_cache=(3600, 259200)) as demo:
6780
  gr.HTML("<style>" + CSS + "</style>")
6781
  gr.HTML(HERO)
6782
+ gr.Markdown(
6783
+ f"**🆕 LoRA preparation before GPU** · Downloads finish first. "
6784
+ f"Suggestions skip files above {LORA_MAX_FILE_BYTES / 1048576:.0f} MiB; "
6785
+ f"selected adapters have a {LORA_MAX_RUN_BYTES / 1048576:.0f} MiB combined limit."
6786
+ )
6787
  with gr.Accordion("Runtime diagnostics", open=False):
6788
  gr.Markdown("If the Space restarts or gets stuck, download this report and attach it to your bug report.")
6789
  runtime_button = gr.Button("Check runtime / download report", size="sm")
 
6862
  "**Picture in, a few words above, one press.** The prompt is "
6863
  "rewritten from your photo, the library is searched for effects "
6864
  "that match it, and their strengths are set. Whatever it picks "
6865
+ "is shown underneath. NEW: Refresh loops through relevant LoRAs; general NSFW all-in-one entries stay visible when they fit the size limits."
6866
  )
6867
  basic_btn = gr.Button("✨ Prepare prompt & effects", variant="primary",
6868
  elem_id="enhance-btn")
 
6980
  "**Pick from the list and press Generate. That is the whole thing.** "
6981
  "Elsewhere these are called *loras* and people talk about files, slots "
6982
  "and high/low weights - none of that is needed here. Every name in the "
6983
+ "list is wired up for you. All enabled files are prepared on CPU before GPU reservation.\n\n"
6984
  "Most clips are better with nothing selected. Add one only when you want "
6985
  "that specific thing to happen."
6986
  )
 
7352
  scene_pick = gr.CheckboxGroup(
7353
  choices=[], value=[], visible=False,
7354
  label="Effects chosen for this scene — tick another one to swap",
7355
+ info="Two at a time is the limit. Every tick updates the shared selection. Trigger words are synced "
7356
+ "to the main prompt and every nonempty clip prompt.",
7357
  )
7358
  scene_links = gr.Markdown("")
7359
  scene_refresh_btn = gr.Button("🔄 Refresh — next group ↻", variant="secondary")
 
7528
  "- Cropping happens after upload, so pre-cropping your image to roughly the "
7529
  "render aspect is the only way to control exactly what survives.\n\n"
7530
  "**Loras**\n"
7531
+ "- All enabled LoRAs download and validate before the video GPU request, including "
7532
+ "Hugging Face and CivitAI/direct links. Oversized or incomplete files stop preparation "
7533
+ "before generation. Loading the ready files into the model still takes GPU time.\n"
7534
  "- **High** and **Low** strength apply to the two noise stages. If a lora is "
7535
  "overpowering the composition, drop High first and leave Low alone."
7536
  )