amisima commited on
Commit
d745bdd
·
verified ·
1 Parent(s): 1c8f729

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +81 -22
  2. app.py +748 -474
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: AI scene plans, 64 clips, face lock & 3 audio models'
11
  tags:
12
  - not-for-all-audiences
13
  - video
@@ -29,28 +29,50 @@ 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
- ## 🆕 LoRA Refresh — prompt and scene, 5 suggestions at a time
33
 
34
- **Prepare prompt & LoRA/effects** and **Split into clips** now use the same selection.
35
- Press **🔄 Refresh — next 5 LoRAs** beside either panel to read the current catalogue and
36
- browse the next group of up to five relevant candidates. Choose up to **two** at a time;
37
- the two panels stay synchronised. Fewer than five means fewer usable matches were found.
38
- The writer may select **NONE**; the app no longer forces the first suggestion in that case.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  - Missing files and explicitly incompatible base-model metadata are excluded from suggestions.
41
  Confirmed bad entries are remembered for 24 hours, then checked again so repaired files can return.
42
- - Login errors, rate limits, server errors and timeouts are skipped for that refresh, without
43
- permanently blacklisting the adapter. A hidden/gated 404 without credentials is treated cautiously.
44
- - Link checks cannot prove that weights load correctly or that a visual effect will look good.
45
- File-specific invalid-weight errors also exclude a known adapter when the app can identify it.
46
- - Swapping choices removes the trigger suffixes inserted by the picker. Words originally written
47
- by you are preserved. In a scene, trigger hints are added only to matching clip lines.
48
- - Refresh changes recommendations and the selected adapters; it does not rewrite the scene plan,
49
- change its timing or generate a video. The writer used for selection has its own inference allowance.
50
-
51
- These are pages of suggestions from the existing catalogue, not downloaded LoRA bundles.
52
- The catalogue itself is preserved. Two adapters is the guided picker's limit; the existing
53
- manual LoRA controls remain available in **Pro**.
54
 
55
  ## 🆕 AI Scene Planner — available in Simple
56
 
@@ -89,7 +111,8 @@ lets you resume a stopped run while the session's images and generated clips are
89
 
90
  The planner uses the **Big model Space** selected in **Pro → Prompt Assist**, initially
91
  `amisima/Qwen3.8-27B-Uncensored-Demo`. It sends that Space the idea and reference image and uses
92
- its inference allowance. This is separate from the allowance used to generate Wan video.
 
93
 
94
  ## ✨ Simple — guided creation
95
 
@@ -169,6 +192,16 @@ what a visitor loads is their own responsibility under that policy.
169
 
170
  - `EXPANDER_SPACE` sets the initial writing Space. Visitors can select another **Big model Space**
171
  in Pro → Prompt Assist.
 
 
 
 
 
 
 
 
 
 
172
  - Set `CIVITAI_TOKEN` in Settings → Variables and secrets for downloads that need authentication.
173
  Signing in to CivitAI in your own browser does not authenticate the Space's server.
174
  - A custom adapter can use a Hugging Face repo, an individual file or a CivitAI link. High and Low
@@ -192,9 +225,35 @@ There is no fixed chain of 64 empty callbacks after a short scene. The scene but
192
  available again on completion, Stop or a handled error. Finished clips remain in the queue.
193
  Use **🔗 Join queued clips / retry** to retry stitching without generating or adding a clip again.
194
  Stitching subprocesses have time limits; an incomplete merge is not presented as success.
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
  The app still relies on the Space's existing model files, helper modules and dependencies.
197
  Replace `app.py` and this `README.md` in the corresponding Space; this update is not a complete
198
- standalone repository. Local checks cover planner/profile compatibility, LoRA selection,
199
- error recovery and a small ffmpeg audio/video join. GPU model inference and the live browser
200
  workflow must be verified in the Space.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
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
51
+ another video encode. Video, audio, local enhancement and joining share one heavy-work queue.
52
+
53
+ ## 🆕 LoRA Refresh — relevant choices, continuous browsing
54
+
55
+ **Prepare prompt & LoRA/effects** and **Split into clips** share one selection.
56
+ Refresh browses up to **five relevant rotating suggestions**, wraps back to the beginning and
57
+ keeps up to **two selected adapters** ticked. It uses local name/trigger matching and link checks;
58
+ **Refresh does not call an AI model or request a GPU**. Suggestions are not random.
59
+
60
+ General NSFW **all-in-one / AIO** entries, including **General NSFW Booster**, stay visible on every
61
+ page as extra options. They are not enabled automatically, and do not displace the five rotating
62
+ suggestions. Confirmed invalid entries remain excluded, including all-in-one entries.
63
 
64
  - Missing files and explicitly incompatible base-model metadata are excluded from suggestions.
65
  Confirmed bad entries are remembered for 24 hours, then checked again so repaired files can return.
66
+ - Authentication errors, rate limits and timeouts do not permanently blacklist an adapter.
67
+ All-in-one choices remain visible through temporary availability failures.
68
+ - Link checks cannot prove that weights load correctly or that an effect will look good.
69
+ - Swapping choices removes trigger suffixes inserted by the picker while preserving your original
70
+ words. In a scene, trigger hints are added only to matching clip lines.
71
+ - Initial preparation can ask the writing model to choose suitable adapters; it can choose none.
72
+ Refresh preserves your choices and does not rewrite prompts with AI or regenerate the scene.
73
+
74
+ The existing catalogue and manual controls in **Pro** remain available. Each panel gets its own
75
+ Gradio update object to prevent stale selections falling outside the displayed choices.
 
 
76
 
77
  ## 🆕 AI Scene Planner — available in Simple
78
 
 
111
 
112
  The planner uses the **Big model Space** selected in **Pro → Prompt Assist**, initially
113
  `amisima/Qwen3.8-27B-Uncensored-Demo`. It sends that Space the idea and reference image and uses
114
+ a separate request to that Space. Public writer calls are anonymous by default. A private or
115
+ restricted writer may require the owner to configure `EXPANDER_HF_TOKEN`; see the notes below.
116
 
117
  ## ✨ Simple — guided creation
118
 
 
192
 
193
  - `EXPANDER_SPACE` sets the initial writing Space. Visitors can select another **Big model Space**
194
  in Pro → Prompt Assist.
195
+ - `HF_TOKEN` remains for model downloads and the existing catalogue/storage operations. It is no
196
+ longer automatically passed to the external writing Space. This prevents visitors' AI calls
197
+ silently inheriting the owner's download token.
198
+ - `EXPANDER_HF_TOKEN` is an **optional explicit opt-in** for authenticated writing requests. Those
199
+ requests can use that token owner's quota/credits. Leave it unset for anonymous public writers;
200
+ restricted/private writers can require it. This change can affect access to your existing writer.
201
+ - A failed or timed-out writing request is not automatically replayed against other endpoints.
202
+ Timeout cancellation is best effort; a job already running remotely can still consume resources.
203
+ Large scene plans can intentionally use several batches, and initial prompt preparation can
204
+ separately request adapter selection. Repeated user clicks also start new requests.
205
  - Set `CIVITAI_TOKEN` in Settings → Variables and secrets for downloads that need authentication.
206
  Signing in to CivitAI in your own browser does not authenticate the Space's server.
207
  - A custom adapter can use a Hugging Face repo, an individual file or a CivitAI link. High and Low
 
225
  available again on completion, Stop or a handled error. Finished clips remain in the queue.
226
  Use **🔗 Join queued clips / retry** to retry stitching without generating or adding a clip again.
227
  Stitching subprocesses have time limits; an incomplete merge is not presented as success.
228
+ Stop cancels queued work and prevents the next scene step. An already-running synchronous GPU
229
+ operation may take time to return before its resources can be released.
230
+
231
+ The app uses the platform-installed `spaces` package instead of upgrading it during each boot.
232
+ Gradio SSR is disabled. An expired image now gives a specific re-upload message rather than an
233
+ unhandled missing-file traceback; the app cannot recover an upload deleted by a container restart.
234
+
235
+ Use **Runtime diagnostics** to download a bounded report with the boot ID, RAM figures, processing
236
+ stages and cgroup memory/OOM counters when available. Reports contain no prompts or photo contents.
237
+ The report is stored under writable `/data` or `/bucket` with file-lock support, otherwise the
238
+ system temporary directory. History survives replacement only if the backing storage is persistent.
239
+ The supplied startup/error log did not establish an OOM crash or repeated restart. These changes
240
+ reduce concrete memory risks; the real restart cause still requires a live runtime report.
241
 
242
  The app still relies on the Space's existing model files, helper modules and dependencies.
243
  Replace `app.py` and this `README.md` in the corresponding Space; this update is not a complete
244
+ standalone repository. Local checks cover reservation and resize calculations, looping LoRA selection,
245
+ Gradio choices, remote authentication/retry limits, failure cleanup and real ffmpeg audio/video joins. GPU model inference and the live browser
246
  workflow must be verified in the Space.
247
+
248
+ ## Quota and credit accounting
249
+
250
+ [ZeroGPU documentation](https://huggingface.co/docs/hub/en/spaces-zerogpu) distinguishes the requested
251
+ runtime limit from actual usage. xlarge has a 2× usage multiplier; eligible plans can consume prepaid
252
+ credits after included quota is exhausted. A larger reservation is not itself a billing receipt.
253
+
254
+ The [Inference Providers model breakdown](https://huggingface.co/docs/inference-providers/en/pricing)
255
+ is a different usage view. A screenshot showing $0.09 for ERNIE and $0.07 for DeepSeek accounts for
256
+ $0.16 of displayed provider charges. This Wan file does not directly call either model. A remote
257
+ writing Space's internals and the account's complete usage/billing history were not available,
258
+ so the originating application and any other credit consumption cannot be determined from that
259
+ screenshot. Included compute credits can be shared across eligible Hugging Face services.
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import os; os.system('pip install --upgrade --no-deps spaces')
2
  import spaces
3
  import shutil
4
  import subprocess
@@ -22,6 +22,241 @@ from PIL import Image, ImageDraw, ImageFilter
22
 
23
  import gradio as gr
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  # A slider or number box that has been emptied arrives as None, and gradio compares that
27
  # against the component's minimum before any handler is called - so the event dies in
@@ -61,7 +296,6 @@ from diffusers import (
61
  DPMSolverSinglestepScheduler,
62
  )
63
  from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
64
- from diffusers.utils.export_utils import export_to_video
65
 
66
  from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
67
  import aoti
@@ -143,73 +377,69 @@ rife_model.load_model("train_log", -1)
143
  rife_model.eval()
144
 
145
 
146
- @torch.no_grad()
147
  def interpolate_bits(frames_np, multiplier=2, scale=1.0):
148
- if isinstance(frames_np, list):
149
- T = len(frames_np)
150
- H, W, C = frames_np[0].shape
151
- else:
152
- T, H, W, C = frames_np.shape
153
-
154
- if multiplier < 2:
155
- if isinstance(frames_np, np.ndarray):
156
- return list(frames_np)
157
- return frames_np
158
-
159
- n_interp = multiplier - 1
160
-
161
- tmp = max(128, int(128 / scale))
162
- ph = ((H - 1) // tmp + 1) * tmp
163
- pw = ((W - 1) // tmp + 1) * tmp
164
- padding = (0, pw - W, 0, ph - H)
165
-
166
- def to_tensor(frame_np):
167
- t = torch.from_numpy(frame_np).to(device)
168
- t = t.permute(2, 0, 1).unsqueeze(0)
169
- return F.pad(t, padding).half()
170
-
171
- def from_tensor(tensor):
172
- t = tensor[0, :, :H, :W]
173
- t = t.permute(1, 2, 0)
174
- return t.float().cpu().numpy()
175
-
176
- def make_inference(I0, I1, n):
177
- if rife_model.version >= 3.9:
178
- res = []
179
- for i in range(n):
180
- res.append(rife_model.inference(I0, I1, (i+1) * 1. / (n+1), scale))
181
- return res
182
  else:
183
- middle = rife_model.inference(I0, I1, scale)
184
- if n == 1:
185
- return [middle]
186
- first_half = make_inference(I0, middle, n=n//2)
187
- second_half = make_inference(middle, I1, n=n//2)
188
- if n % 2:
189
- return [*first_half, middle, *second_half]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  else:
191
- return [*first_half, *second_half]
192
-
193
- output_frames = []
194
- I1 = to_tensor(frames_np[0])
195
- total_steps = T - 1
196
-
197
- with tqdm(total=total_steps, desc="Interpolating", unit="frame") as pbar:
198
- for i in range(total_steps):
199
- I0 = I1
200
- output_frames.append(from_tensor(I0))
201
- I1 = to_tensor(frames_np[i+1])
202
- mid_tensors = make_inference(I0, I1, n_interp)
203
- for mid in mid_tensors:
204
- output_frames.append(from_tensor(mid))
205
- if (i + 1) % 50 == 0:
206
- pbar.update(50)
207
- pbar.update(total_steps % 50)
208
- output_frames.append(from_tensor(I1))
209
-
210
- del I0, I1, mid_tensors
211
- torch.cuda.empty_cache()
212
- return output_frames
 
 
 
213
 
214
 
215
  # WAN
@@ -443,7 +673,8 @@ def resize_image(image: Image.Image, aspect_mode: str = "crop") -> Image.Image:
443
  `crop` takes the middle out, `pad` keeps the whole picture and fills the rest with black."""
444
  width, height = image.size
445
  if width == height:
446
- return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)
 
447
 
448
  aspect_ratio = width / height
449
  MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
@@ -474,12 +705,10 @@ def resize_image(image: Image.Image, aspect_mode: str = "crop") -> Image.Image:
474
  top = (height - crop_height) // 2
475
  image_to_resize = image.crop((0, top, width, top + crop_height))
476
  else:
477
- if width > height:
478
- target_w = MAX_DIM
479
- target_h = int(round(target_w / aspect_ratio))
480
- else:
481
- target_h = MAX_DIM
482
- target_w = int(round(target_h * aspect_ratio))
483
 
484
  final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
485
  final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
@@ -1526,46 +1755,23 @@ def get_inference_duration(
1526
  lora_groups,
1527
  progress
1528
  ):
1529
- # Recalibrated after a report of an 8 s clip at 128 fps fluidity being killed mid-interpolation.
1530
- # Two numbers were optimistic: the per-step cost, and above all the 0.02 s per interpolated frame -
1531
- # at 128 fps RIFE produces eight frames for every one the model made, so a 129-frame clip becomes
1532
- # over a thousand, and the error compounds there rather than in the diffusion.
1533
- BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624
1534
- BASE_STEP_DURATION = 7.
1535
  width, height = resized_image.size
1536
- factor = num_frames * width * height / BASE_FRAMES_HEIGHT_WIDTH
1537
- step_duration = BASE_STEP_DURATION * factor ** 1.5
1538
- gen_time = int(steps) * step_duration
1539
-
1540
- if guidance_scale > 1:
1541
- gen_time = gen_time * 2.4
1542
-
1543
- frame_factor = max(1, frame_multiplier // FIXED_FPS)
1544
- extra_time = 0.0
1545
- if frame_factor > 1:
1546
- total_out_frames = (num_frames * frame_factor) - num_frames
1547
- extra_time += total_out_frames * 0.10
1548
-
1549
- # Writing the mp4 and the lossless closing frame is done on the booking too.
1550
- extra_time += 5.0 + (num_frames * frame_factor) * 0.02
1551
-
1552
- # Custom adapters are fused inside the booking, and one that has never been used here
1553
- # has to be downloaded first.
1554
- extra_time += _lora_booking_extra(lora_groups)
1555
-
1556
- # Headroom. The diffusion itself is predicted closely, but everything around it -
1557
- # swapping the scheduler, clearing the card, the two noise experts, the VAE - is not,
1558
- # and a booking that runs one second over is killed and the whole clip is lost. A
1559
- # request that is a little too big only costs allowance; one that is too small costs
1560
- # the run.
1561
- total_time = 25 + gen_time * 1.35 + extra_time
1562
  if safe_mode:
1563
- total_time = total_time * 1.15
1564
-
1565
- # ZeroGPU refuses a booking above its own ceiling outright, and `size="xlarge"` doubles what is
1566
- # asked for, so a runaway estimate fails before it starts. The floor is there because a very
1567
- # short clip is still fixed overhead, and asking for less than that aborts every time.
1568
- return min(max(total_time, 60.0), 600)
 
 
 
1569
 
1570
 
1571
  @spaces.GPU(duration=get_inference_duration, size='xlarge')
@@ -1588,119 +1794,138 @@ def run_inference(
1588
  lora_groups=None,
1589
  progress=gr.Progress(track_tqdm=True),
1590
  ):
1591
- scheduler_class = SCHEDULER_MAP.get(scheduler_name)
1592
- if scheduler_class.__name__ != pipe.scheduler.config._class_name or flow_shift != pipe.scheduler.config.get("flow_shift", "shift"):
1593
- config = copy.deepcopy(original_scheduler.config)
1594
- if scheduler_class == FlowMatchEulerDiscreteScheduler:
1595
- config['shift'] = flow_shift
1596
- else:
1597
- config['flow_shift'] = flow_shift
1598
- pipe.scheduler = scheduler_class.from_config(config)
 
 
 
1599
 
1600
- clear_vram()
1601
 
1602
- task_name = str(uuid.uuid4())[:8]
1603
 
1604
- # Only the shape of the request: no prompt text, and adapters by name rather than by what the
1605
- # visitor typed. Enough to read a report or spot a bad adapter, without recording anybody's words.
1606
- active = []
1607
- for group in lora_groups or []:
1608
- if group.get("preset") and group["preset"] != "(None)":
1609
- active.append(f"{group['preset']} @ {group.get('high_scale')}/{group.get('low_scale')}")
1610
- continue
1611
- for role in ("file_high", "file_low"):
1612
- value = group.get(role)
1613
- if value and value != "(None)":
1614
- scale = group.get("high_scale" if role == "file_high" else "low_scale")
1615
- active.append(f"{os.path.basename(str(value))[:60]} ({role[5:]}) @ {scale}")
1616
-
1617
- print(f"[request {task_name}] {num_frames} frames, {duration_seconds}s, {resized_image.size}, "
1618
- f"{int(steps)} steps, seed {current_seed}")
1619
- if active:
1620
- print(f"[request {task_name}] lora: {', '.join(active)}")
1621
- start = time.time()
1622
-
1623
- lora_loaded = False
1624
- lora_problems = []
1625
- if lora_groups:
1626
- try:
1627
- # Newer loader: one bad file is skipped rather than taking the whole
1628
- # request down with it, and it hands back a line explaining each skip.
1629
- outcome = lora_loader.load_lora_slots(pipe, lora_groups)
1630
- if isinstance(outcome, tuple):
1631
- lora_loaded, lora_problems = outcome
1632
- else:
1633
- lora_loaded = bool(outcome)
1634
- print(f"lora loaded: {lora_groups}")
1635
- except Exception as e:
1636
- print(f"lora warning: {e}")
1637
- lora_problems = [str(e)[:200]]
1638
- try:
1639
- lora_loader.unload_lora(pipe)
1640
- except Exception:
1641
- pass
1642
 
1643
- result = pipe(
1644
- image=resized_image,
1645
- last_image=processed_last_image,
1646
- prompt=prompt,
1647
- negative_prompt=negative_prompt,
1648
- height=resized_image.height,
1649
- width=resized_image.width,
1650
- num_frames=num_frames,
1651
- guidance_scale=float(guidance_scale),
1652
- guidance_scale_2=float(guidance_scale_2),
1653
- num_inference_steps=int(steps),
1654
- generator=torch.Generator(device="cuda").manual_seed(current_seed),
1655
- output_type="np"
1656
- )
 
 
 
 
 
 
1657
 
1658
- if lora_loaded:
1659
- lora_loader.unload_lora(pipe)
 
 
 
 
 
 
 
 
 
 
 
 
 
1660
 
1661
- print("gen time passed:", time.time() - start)
 
1662
 
1663
- raw_frames_np = result.frames[0]
1664
- pipe.scheduler = original_scheduler
1665
 
1666
- frame_factor = frame_multiplier // FIXED_FPS
1667
- if frame_factor > 1:
1668
- start = time.time()
1669
- print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")
1670
- rife_model.device()
1671
- rife_model.flownet = rife_model.flownet.half()
1672
- final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
1673
- print("Interpolation time passed:", time.time() - start)
1674
- else:
1675
- final_frames = list(raw_frames_np)
1676
 
1677
- final_fps = FIXED_FPS * int(frame_factor)
 
 
 
 
 
 
 
 
 
1678
 
1679
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
1680
- video_path = tmpfile.name
1681
 
1682
- start = time.time()
1683
- with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
1684
- pbar.update(2)
1685
- export_to_video(final_frames, video_path, fps=final_fps, quality=quality)
1686
- pbar.update(1)
1687
- print(f"Export time passed, {final_fps} FPS:", time.time() - start)
1688
 
1689
- # Keep the closing frame losslessly beside the clip. A chain that continues
1690
- # from the h264 file re-encodes the same picture again at every link, and the
1691
- # blocking and colour banding pile up clip after clip; continuing from this
1692
- # png instead means the tenth shot starts from the same quality as the first.
1693
- try:
1694
- tail = final_frames[-1]
1695
- tail = np.asarray(tail)
1696
- if tail.dtype != np.uint8:
1697
- tail = (tail * 255.0 if float(tail.max()) <= 1.001 else tail)
1698
- tail = tail.clip(0, 255).astype(np.uint8)
1699
- Image.fromarray(tail[..., :3]).save(video_path + ".last.png")
1700
- except Exception as error:
1701
- print(f"[chain] could not keep the closing frame: {error}", flush=True)
 
 
 
 
 
 
 
1702
 
1703
- return video_path, task_name, list(lora_problems)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1704
 
1705
 
1706
  def generate_video(
@@ -1804,6 +2029,13 @@ def generate_video(
1804
  # On the processor, before the card is booked: whatever can be downloaded in advance is.
1805
  _prefetch_lora_files(lora_groups)
1806
 
 
 
 
 
 
 
 
1807
  try:
1808
  inference = run_inference(
1809
  resized_image,
@@ -1830,7 +2062,7 @@ def generate_video(
1830
  # ZeroGPU speaks in stack traces. Say what happened and what to do about it.
1831
  message = _scene_trouble(error)
1832
  fit = _what_would_fit(str(error), resized_image, steps, duration_seconds,
1833
- guidance_scale, frame_multiplier)
1834
  raise gr.Error(message + fit) from error
1835
  video_path, task_n, lora_problems = inference
1836
  _record_wan_lora_failures(lora_groups, lora_problems)
@@ -2178,19 +2410,16 @@ def _last_frame_bgr(path, tail=40):
2178
  total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
2179
  if total > tail:
2180
  capture.set(cv2.CAP_PROP_POS_FRAMES, max(0, total - tail))
2181
- frames = []
2182
  while True:
2183
  ok, candidate = capture.read()
2184
  if not ok or candidate is None:
2185
  break
2186
- frames.append(candidate)
2187
- capture.release()
2188
- if not frames:
2189
- return None
2190
- for candidate in reversed(frames):
2191
  if float(candidate.mean()) > 2.0:
2192
- return candidate
2193
- return frames[-1]
 
2194
 
2195
 
2196
  def _last_frame_small(path):
@@ -2241,29 +2470,32 @@ def _video_duration(path):
2241
  return max(1.0, total / fps)
2242
 
2243
 
2244
- def _normalise_clip(path, width, height, fps, out_path, trim_head=False, colour=""):
2245
- """One frame size, one frame rate, one audio format. A clip with no sound gets silence, so a
2246
- dubbed clip and a silent one still concatenate. `trim_head` drops the duplicated first frame
2247
- and the matching sliver of audio together."""
2248
  fps_str = f"{fps:.6f}".rstrip("0").rstrip(".")
2249
  video_chain = (f"{colour}scale={width}:{height}:force_original_aspect_ratio=decrease,"
2250
  f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps_str}")
2251
- audio_chain = "aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo"
2252
  if trim_head:
2253
- video_chain += ",trim=start_frame=1,setpts=PTS-STARTPTS"
2254
- audio_chain += f",atrim=start={1.0 / fps:.6f},asetpts=PTS-STARTPTS"
2255
-
2256
- tail = ["-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p",
2257
- "-c:a", "aac", "-ar", "48000", "-ac", "2", out_path]
2258
- if _has_audio(path):
2259
- command = [_ffmpeg_exe(), "-y", "-i", path,
2260
- "-filter_complex", f"[0:v]{video_chain}[v];[0:a]{audio_chain}[a]",
2261
- "-map", "[v]", "-map", "[a]", *tail]
 
 
 
 
 
 
 
 
 
 
2262
  else:
2263
- command = [_ffmpeg_exe(), "-y", "-i", path,
2264
- "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo",
2265
- "-filter_complex", f"[0:v]{video_chain}[v];[1:a]{audio_chain}[a]",
2266
- "-map", "[v]", "-map", "[a]", "-shortest", *tail]
2267
  subprocess.run(command, check=True, capture_output=True, timeout=600)
2268
  return out_path
2269
 
@@ -2357,69 +2589,39 @@ def concat_videos(paths, name_hint=""):
2357
 
2358
  colour_fixes = _colour_fix_filters(valid)
2359
 
2360
- # Sound. Once anything in the queue has been dubbed the whole join has to carry an audio
2361
- # track, so every clip is rewritten to a common format first and the silent ones are given
2362
- # silence. Nothing in the queue has sound - the usual case - and the fast one-pass route
2363
- # below is used instead.
2364
- if any(_has_audio(p) for p in valid):
2365
- work_dir = tempfile.mkdtemp(prefix="stitch-")
2366
- try:
2367
- parts = [
2368
- _normalise_clip(path, width, height, fps,
2369
- os.path.join(work_dir, f"part{index}.mp4"),
2370
- trim_head=bool(trims[index]),
2371
- colour=colour_fixes[index])
2372
- for index, path in enumerate(valid)
2373
- ]
2374
- inputs = []
2375
- for part in parts:
2376
- inputs += ["-i", part]
2377
- chain = "".join(f"[{i}:v][{i}:a]" for i in range(len(parts)))
2378
- subprocess.run(
2379
- [_ffmpeg_exe(), "-y", *inputs,
2380
- "-filter_complex", f"{chain}concat=n={len(parts)}:v=1:a=1[outv][outa]",
2381
- "-map", "[outv]", "-map", "[outa]", "-r", fps_str,
2382
- "-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p",
2383
- "-c:a", "aac", "-ar", "48000", "-ac", "2",
2384
- "-movflags", "+faststart", out_path],
2385
- check=True, capture_output=True, timeout=1800,
2386
- )
2387
- if os.path.exists(out_path):
2388
- _persist(out_path)
2389
- return out_path
2390
- except Exception as error:
2391
- if os.path.exists(out_path):
2392
- os.remove(out_path)
2393
- raise gr.Error("Joining failed; original clips and their audio remain in the queue.") from error
2394
- finally:
2395
- shutil.rmtree(work_dir, ignore_errors=True)
2396
-
2397
- inputs, chains = [], []
2398
- for index, path in enumerate(valid):
2399
- inputs += ["-i", path]
2400
- cut = (f"trim=start_frame={trims[index]},setpts=PTS-STARTPTS," if trims[index] else "")
2401
- chains.append(
2402
- f"[{index}:v]{cut}{colour_fixes[index]}"
2403
- f"scale={width}:{height}:force_original_aspect_ratio=decrease,"
2404
- f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,"
2405
- f"fps={fps_str},settb=1/{int(round(fps * 1000))},setpts=PTS-STARTPTS[v{index}];"
2406
- )
2407
- joined = "".join(f"[v{i}]" for i in range(len(valid)))
2408
- filter_str = "".join(chains) + f"{joined}concat=n={len(valid)}:v=1:a=0[outv]"
2409
-
2410
- command = [_ffmpeg_exe(), "-y", *inputs, "-filter_complex", filter_str,
2411
- "-map", "[outv]", "-r", fps_str,
2412
- "-c:v", "libx264", "-preset", "fast", "-crf", "20",
2413
- "-pix_fmt", "yuv420p", "-movflags", "+faststart", out_path]
2414
  try:
2415
- subprocess.run(command, check=True, capture_output=True, timeout=1800)
2416
- if not os.path.isfile(out_path) or os.path.getsize(out_path) == 0:
2417
- raise RuntimeError("Joining produced no complete output.")
2418
- except Exception as error:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2419
  if os.path.exists(out_path):
2420
  os.remove(out_path)
 
 
 
2421
  raise gr.Error("Joining failed; all original clips remain in the queue. Retry Join.") from error
2422
  _persist(out_path)
 
2423
  return out_path
2424
 
2425
 
@@ -3232,6 +3434,7 @@ def add_sound(video_path, engine_label, prompt, negative, steps, guidance, seed=
3232
  raise gr.Error("Generate a video first — there is nothing to add sound to.")
3233
 
3234
  engine = FOLEY_ENGINES.get(engine_label, FOLEY_ENGINES[FOLEY_DEFAULT])
 
3235
  prompt = str(prompt or "").strip()
3236
  negative = FOLEY_NEGATIVE if negative is None else str(negative).strip()
3237
  out_path = os.path.join(tempfile.gettempdir(), f"{uuid.uuid4().hex[:4]}_sound.mp4")
@@ -3240,11 +3443,13 @@ def add_sound(video_path, engine_label, prompt, negative, steps, guidance, seed=
3240
  try:
3241
  if engine == "hunyuan":
3242
  model_path, config_path = _hunyuan_paths()
 
3243
  _hunyuan_run(str(video_path), prompt, negative, steps, guidance,
3244
  model_path, config_path, out_path)
3245
  else:
3246
  cfg = _mmaudio_config(engine)
3247
  seconds = _video_duration(video_path)
 
3248
  _mmaudio_run(str(video_path), prompt, negative, steps, guidance, seconds,
3249
  int(seed) or random.randint(0, 10_000), out_path,
3250
  engine=engine, model_path=str(cfg.model_path))
@@ -3253,8 +3458,10 @@ def add_sound(video_path, engine_label, prompt, negative, steps, guidance, seed=
3253
  except gr.Error:
3254
  raise
3255
  except Exception as error:
 
3256
  raise gr.Error(f"Sound failed: {error}")
3257
 
 
3258
  if not os.path.exists(out_path):
3259
  raise gr.Error("The sound model produced nothing.")
3260
 
@@ -3408,6 +3615,11 @@ def _fetch_enhancer_files():
3408
  )
3409
 
3410
 
 
 
 
 
 
3411
  def _load_enhancer_cpu():
3412
  """Read the weights into CPU RAM. Deliberately outside the GPU call: 8 GB off disk is 30 s or
3413
  more, and a ZeroGPU booking that spends its whole allowance loading is a booking that times out
@@ -3481,12 +3693,13 @@ def enhance_prompt(prompt, use_model, camera, framing, lighting, pace, add_quali
3481
 
3482
  try:
3483
  # Said out loud because the first press downloads ~8 GB and a bare spinner looks like a hang.
3484
- # None of this is GPU time: the files land on the CPU and stay in RAM for the next press.
3485
  progress(0.05, desc="Fetching the model (first time only, no GPU time)...")
3486
  _fetch_enhancer_files()
3487
  progress(0.5, desc="Loading it into memory...")
3488
  _load_enhancer_cpu()
3489
  except Exception as error:
 
3490
  return built, (
3491
  "<div class='status-idle'>Model unavailable, so the built prompt is shown "
3492
  f"instead: {type(error).__name__}</div>"
@@ -3501,6 +3714,9 @@ def enhance_prompt(prompt, use_model, camera, framing, lighting, pace, add_quali
3501
  f"instead: {error!r}</div>"
3502
  )
3503
 
 
 
 
3504
  if len(written) < 40:
3505
  return built, "<div class='status-idle'>The model returned too little; built prompt kept.</div>"
3506
  return written, (
@@ -3549,36 +3765,20 @@ def _remote_reply_text(result):
3549
 
3550
 
3551
  def _make_remote_client(space_id):
3552
- """`Client(src, hf_token=...)` is what the documentation says and what the installed
3553
- client may no longer accept - the argument has been spelled three ways across
3554
- versions. Ask the signature which name it wants, fall back to sending the token as a
3555
- header, and connect anonymously rather than not at all."""
3556
- import inspect
3557
 
 
 
 
 
 
3558
  from gradio_client import Client
3559
-
3560
- token = os.environ.get("HF_TOKEN") or None
3561
- if not token:
3562
- return Client(space_id)
3563
-
3564
- try:
3565
- accepted = list(inspect.signature(Client.__init__).parameters)
3566
- except (TypeError, ValueError): # a C-level or wrapped __init__
3567
- accepted = []
3568
-
3569
- for name in ("hf_token", "token", "auth_token", "api_key"):
3570
- if name in accepted:
3571
- try:
3572
- return Client(space_id, **{name: token})
3573
- except TypeError:
3574
- break
3575
-
3576
- for extra in ({"headers": {"Authorization": f"Bearer {token}"}}, {}):
3577
- try:
3578
- return Client(space_id, **extra)
3579
- except TypeError:
3580
- continue
3581
- return Client(space_id)
3582
 
3583
 
3584
  def _remote_plan(client, payload, message, max_new_tokens=None):
@@ -3633,49 +3833,54 @@ def _remote_plan(client, payload, message, max_new_tokens=None):
3633
 
3634
 
3635
  def _remote_ask(space_id, message, image=None, temperature=0.7, max_new_tokens=None):
3636
- """One turn on a Gradio chat Space. `gradio_client` ships with gradio itself, so
3637
- there is nothing to add to requirements."""
3638
  from gradio_client import handle_file
3639
-
3640
  client = _REMOTE_CLIENTS.get(space_id)
3641
  if client is None:
3642
  client = _make_remote_client(space_id)
 
 
3643
  _REMOTE_CLIENTS[space_id] = client
3644
-
3645
- files = []
3646
- if image is not None:
3647
- try:
 
3648
  picture = image.convert("RGB")
3649
  picture.thumbnail((1024, 1024))
3650
- handle, path = tempfile.mkstemp(suffix=".png")
3651
- os.close(handle)
3652
- picture.save(path, format="PNG")
3653
- files.append(handle_file(path))
3654
- except Exception:
3655
- files = []
3656
-
3657
- payload = {"text": message, "files": files}
3658
- plan, seen = _remote_plan(client, payload, message, max_new_tokens=max_new_tokens)
3659
- attempts = tuple(plan) + (
3660
- # Only reached when the Space reports nothing useful about itself: a multimodal
3661
- # ChatInterface with the sampling knobs exposed, the same without them, then a
3662
- # plain text-in text-out Space.
3663
- ((payload, "off", temperature, 0.95, 20), {"api_name": "/chat"}),
3664
- ((payload,), {"api_name": "/chat"}),
3665
- ((message,), {"api_name": "/chat"}),
3666
- ((payload, "off", temperature, 0.95, 20), {}),
3667
- ((message,), {}),
3668
- )
3669
- problems = []
3670
- for args, kwargs in attempts:
3671
- try:
3672
- return _remote_reply_text(client.predict(*args, **kwargs))
3673
- except Exception as error: # noqa: BLE001
3674
- problems.append(f"{type(error).__name__}: {error}")
3675
- print(f"[big-space] attempt failed - {problems[-1]}", flush=True)
3676
- # The first two carry the real reason; the later shapes fail for their own reasons,
3677
- # and saying only the last one sends you hunting the wrong thing.
3678
- raise RuntimeError((" || ".join(problems[:2]) + f" || endpoints seen: {seen}")[:600])
 
 
 
3679
 
3680
 
3681
  def _big_space_message(built, rows, has_image=False):
@@ -4521,7 +4726,7 @@ def scene_sheet_preview(text, clip_count, seconds, scene_seconds=""):
4521
 
4522
 
4523
  def _what_would_fit(text, image, steps, duration_seconds, guidance_scale, frame_multiplier,
4524
- as_numbers=False):
4525
  """Given how many seconds ZeroGPU says are left, name a clip that would fit.
4526
 
4527
  "Make it shorter" is not much of an instruction when the numbers are doubled behind
@@ -4540,9 +4745,9 @@ def _what_would_fit(text, image, steps, duration_seconds, guidance_scale, frame_
4540
  seconds = get_inference_duration(
4541
  _SizeOnly(width, height), None, "", int(clip_steps), "", frames,
4542
  float(guidance_scale), 1.0, 0, "UniPCMultistep", 3.0,
4543
- int(frame_multiplier), 5, float(clip_seconds), bool(safe), None, None,
4544
  )
4545
- return int(round(seconds * 2)), frames # xlarge doubles the request
4546
 
4547
  attempts = []
4548
  for clip_steps in (int(steps), 4):
@@ -4592,7 +4797,7 @@ def _scene_trouble(error):
4592
  f"mode off, may bring it under what is left.")
4593
  except Exception:
4594
  extra = ""
4595
- return ("The ZeroGPU allowance ran out part-way through. " + text + extra)
4596
  if "token" in low and any(word in low for word in ("expire", "invalid", "not found",
4597
  "missing", "unauthor")):
4598
  return ("The page's GPU pass went stale while the tab sat open. Refresh the page and "
@@ -4754,7 +4959,8 @@ def scene_step(state, scene_prompts, sound_on, sound_engine, sound_prompt, sound
4754
  try:
4755
  retry = _what_would_fit(str(error), _SizeOnly(*_target_size(values[0])),
4756
  values[3], values[5], values[6], values[13],
4757
- as_numbers=True)
 
4758
  except Exception:
4759
  retry = None
4760
  if retry:
@@ -5000,7 +5206,8 @@ def _target_size(image):
5000
  return (832, 624)
5001
  width, height = image.size
5002
  if width == height:
5003
- return (SQUARE_DIM, SQUARE_DIM)
 
5004
 
5005
  aspect_ratio = width / height
5006
  MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
@@ -5011,12 +5218,8 @@ def _target_size(image):
5011
  elif aspect_ratio < MIN_ASPECT_RATIO:
5012
  target_w, target_h = MIN_DIM, MAX_DIM
5013
  else:
5014
- if width > height:
5015
- target_w = MAX_DIM
5016
- target_h = int(round(target_w / aspect_ratio))
5017
- else:
5018
- target_h = MAX_DIM
5019
- target_w = int(round(target_h * aspect_ratio))
5020
 
5021
  final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
5022
  final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
@@ -5098,24 +5301,26 @@ def check_identity_photo(lock_image, start_image):
5098
 
5099
  def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5100
  frame_multiplier, safe_mode, clip_count=1,
5101
- sound_on=False, sound_engine=None, sound_steps=25, scene_seconds=""):
5102
  """Live ZeroGPU cost readout, using the exact same formula the
5103
  @spaces.GPU decorator asks for at generation time."""
 
5104
  try:
 
5105
  num_frames = get_num_frames(float(duration_seconds))
5106
  w, h = _target_size(input_image)
5107
  secs = get_inference_duration(
5108
  _SizeOnly(w, h), None, "", steps, "", num_frames,
5109
- float(guidance_scale), 1.0, 0, "UniPCMultistep", 3.0,
5110
  int(frame_multiplier), 5, float(duration_seconds),
5111
- bool(safe_mode), None, None,
5112
  )
5113
  except Exception as exc: # never break the UI over a readout
5114
  return f"⏳ **ZeroGPU cost:** estimate unavailable ({exc})"
5115
 
5116
  note = "" if input_image is not None else " · upload an image for an exact number"
5117
  out_fps = int(frame_multiplier)
5118
- out_frames = num_frames * max(1, out_fps // FIXED_FPS)
5119
 
5120
  # Sound is a second booking on top of every clip: model load plus the denoise.
5121
  sound_secs = 0.0
@@ -5126,27 +5331,25 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5126
  else:
5127
  sound_secs = min(200.0, 70.0 + float(sound_steps) * 0.9 + float(duration_seconds) * 2.0)
5128
 
5129
- # The video pass books on the xlarge tier, and ZeroGPU doubles an xlarge request
5130
- # internally. It also charges what was asked for, not what was used - so this,
5131
- # not the raw estimate, is what comes off the daily allowance.
5132
- video_cost = secs * 2.0
5133
  per_clip = video_cost + sound_secs
5134
  try:
5135
  clips = _scene_count(clip_count)
5136
  scene_durations = _scene_durations(scene_seconds, clips, duration_seconds)
5137
  except (TypeError, ValueError) as error:
5138
  return f"⏳ **ZeroGPU cost:** check the scene timing plan — {error}"
5139
- lines = ["⏳ **ZeroGPU cost** "]
5140
  sound_bit = f" + ~{int(round(sound_secs))} s sound" if sound_secs else ""
5141
- lines.append(f"one clip **~{int(round(per_clip))} s off your daily allowance**"
5142
  f" ({int(round(video_cost))} s video{sound_bit}) ")
5143
  # In a chain the sound is added once, to the joined scene, not to every clip.
5144
  scene_video_cost = sum(
5145
- 2.0 * get_inference_duration(
5146
  _SizeOnly(w, h), None, "", steps, "", get_num_frames(seconds),
5147
- float(guidance_scale), 1.0, 0, "UniPCMultistep", 3.0,
5148
- int(frame_multiplier), 5, seconds, bool(safe_mode), None, None,
5149
- ) for seconds in scene_durations
5150
  )
5151
  scene_sound_cost = sound_secs
5152
  if sound_on and engine != "hunyuan":
@@ -5154,15 +5357,15 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5154
  scene_total = scene_video_cost + scene_sound_cost
5155
  lines.append(f"🎬 whole scene, {clips} clips: **~{int(round(scene_total))} s**"
5156
  f"{' (sound is added once, to the finished scene)' if sound_secs and clips > 1 else ''} ")
 
 
5157
  lines.append(
5158
- f"<sub>{num_frames} frames · {w}×{h} · {int(steps)} steps · "
5159
- f"output {out_frames} frames @ {out_fps} fps{note} \n"
5160
- f"the clip itself takes about {int(round(secs))} s, but the video runs on the "
5161
- f"xlarge tier and ZeroGPU doubles what an xlarge job asks for - and it charges "
5162
- f"what was asked for, not what was used. Shorter clips, fewer steps and Safe mode "
5163
- f"off all shrink the request. Joining and looping run on the processor and cost "
5164
- f"nothing. The first press of a sound model downloads it, which takes longer than "
5165
- f"the figure above.</sub>"
5166
  )
5167
  return "\n".join(lines)
5168
 
@@ -5634,7 +5837,7 @@ def _library_pool():
5634
  for section in ("nsfw", "normal"):
5635
  for item in (data.get(section) or []):
5636
  if isinstance(item, dict) and item.get("url") and item.get("name"):
5637
- pool.append(item)
5638
  return pool
5639
 
5640
 
@@ -5661,6 +5864,8 @@ def _shortlist_loras(prompt_text, pool, limit=5):
5661
 
5662
  def _pick_label(index, item):
5663
  text = f"{index + 1}. {item.get('name', '')}"
 
 
5664
  if item.get("builtin"):
5665
  text += " · built in"
5666
  elif not str(item.get("trigger") or "").strip():
@@ -5688,7 +5893,7 @@ def _ask_which_loras(space_id, prompt_text, shortlist):
5688
  "of them match. Write nothing else - no explanation, no names, only numbers."
5689
  )
5690
  try:
5691
- reply = _remote_ask(space, message)
5692
  except Exception as error: # noqa: BLE001
5693
  print(f"[simple] the Space did not answer the pick question: {error}", flush=True)
5694
  return []
@@ -5922,51 +6127,80 @@ def _pick_probe(item):
5922
  return result
5923
 
5924
 
 
 
 
 
 
 
 
 
 
5925
  def _pick_page(basis, state, advance=False, keep=None):
5926
  from concurrent.futures import ThreadPoolExecutor
5927
- pool = _library_pool() # Read the current catalogue on every press.
5928
  ranked = _shortlist_loras(basis, pool, limit=len(pool))
5929
- unique, seen = [], set()
 
 
 
 
 
 
5930
  for item in ranked:
5931
  key = _pick_key(item)
5932
  if key not in seen:
5933
  seen.add(key)
5934
- unique.append(item)
5935
- count = len(unique)
5936
- same = state.get("basis") == basis
5937
- start = int(state.get("cursor", 0)) % count if count and advance and same else 0
5938
- ordered = unique[start:] + unique[:start]
5939
-
5940
- # A ticked entry stays where it is. Refresh replaces only the ones that were not
5941
- # chosen, so browsing for a second effect never drops the first one.
5942
- page, held = [], set()
5943
- for item in (keep or []):
5944
- key = _pick_key(item)
5945
- if key in held or _health_read(key).get("status") == "bad":
5946
- continue
5947
- held.add(key)
5948
- page.append(item)
5949
- if len(page) >= LORA_PICK_PAGE:
5950
- break
5951
- ordered = [item for item in ordered if _pick_key(item) not in held]
5952
-
5953
- checked, skipped = 0, 0
5954
- # Bound each refresh even if an entire remote catalogue is unavailable.
5955
  with ThreadPoolExecutor(max_workers=LORA_PICK_PAGE) as workers:
5956
- for offset in range(0, min(len(ordered), 20), LORA_PICK_PAGE):
5957
- batch = ordered[offset:offset + LORA_PICK_PAGE]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5958
  statuses = list(workers.map(_pick_probe, batch))
5959
  for item, status in zip(batch, statuses):
5960
  checked += 1
 
 
 
5961
  if status in ("bad", "unavailable"):
5962
  skipped += 1
5963
- else:
5964
- page.append(item)
5965
- if len(page) == LORA_PICK_PAGE:
 
 
5966
  break
5967
- if len(page) == LORA_PICK_PAGE:
5968
  break
5969
- return page, ((start + checked) % count if count else 0), skipped, count
5970
 
5971
 
5972
  def _pick_text(text, picks, sheet=False):
@@ -6013,13 +6247,18 @@ def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, st
6013
  page, cursor, skipped, available = _pick_page(basis, state, advance, keep=held)
6014
  held_keys = {_pick_key(item) for item in held}
6015
  kept = [i for i, item in enumerate(page) if _pick_key(item) in held_keys]
6016
- chosen = kept if kept else _ask_which_loras(space_id, basis, page)
 
 
 
 
 
6017
  state.update(basis=basis, cursor=cursor, page=page)
6018
  detail = f"{len(page)} suggestions shown; {skipped} unavailable entries skipped."
6019
  if kept:
6020
  detail += f" {len(kept)} kept ticked; only the unticked ones were replaced."
6021
- if available > len(page):
6022
- detail += " Refresh shows the next group of up to 5."
6023
  else:
6024
  page = list(state.get("page") or [])
6025
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
@@ -6067,6 +6306,12 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6067
  delete_cache=(3600, 259200)) as demo:
6068
  gr.HTML("<style>" + CSS + "</style>")
6069
  gr.HTML(HERO)
 
 
 
 
 
 
6070
 
6071
  with gr.Group(elem_classes="panel"):
6072
  ui_mode = gr.Radio(
@@ -6093,12 +6338,12 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6093
  with gr.Tabs():
6094
  with gr.Tab("🖼️ Start frame"):
6095
  input_image_component = gr.Image(
6096
- type="pil", label=None, show_label=False,
6097
  sources=["upload", "clipboard"], height=300,
6098
  )
6099
  with gr.Tab("🏁 End frame (optional)"):
6100
  last_image_component = gr.Image(
6101
- type="pil", label=None, show_label=False,
6102
  sources=["upload", "clipboard"], height=300,
6103
  )
6104
 
@@ -6115,7 +6360,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6115
  "otherwise the app uses alignment checks."
6116
  )
6117
  identity_ref_component = gr.Image(
6118
- type="pil", label="Photo of the person", height=160,
6119
  sources=["upload", "clipboard"],
6120
  )
6121
  identity_check = gr.HTML("")
@@ -6139,7 +6384,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6139
  "**Picture in, a few words above, one press.** The prompt is "
6140
  "rewritten from your photo, the library is searched for effects "
6141
  "that match it, and their strengths are set. Whatever it picks "
6142
- "is shown underneath. NEW: refresh to browse 5 more LoRA suggestions."
6143
  )
6144
  basic_btn = gr.Button("✨ Prepare prompt & effects", variant="primary",
6145
  elem_id="enhance-btn")
@@ -6154,7 +6399,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6154
  )
6155
  basic_links = gr.Markdown("")
6156
  basic_shortlist = gr.State({})
6157
- basic_refresh_btn = gr.Button("🔄 Refresh — next 5 LoRAs", variant="secondary")
6158
 
6159
  with gr.Accordion("✨ Prompt Assist — build your shot", open=False,
6160
  visible=False) as pro_promptbuilder:
@@ -6566,11 +6811,11 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6566
  gpu_estimate_btn = gr.Button("🔄", variant="secondary", scale=1, min_width=60,
6567
  elem_id="estimate-btn")
6568
  safe_mode_checkbox = gr.Checkbox(
6569
- label="🛠️ Safe mode — adds 15% to the numbers above",
6570
- value=True,
6571
- info="On, the booking asks for extra time so a busy server cannot cut your "
6572
- "clip short half way through. Off is cheaper and the figures above drop "
6573
- "straight away, but a long clip is more likely to be stopped part-done.",
6574
  )
6575
  with gr.Group(elem_classes="panel"):
6576
  video_output = gr.Video(
@@ -6633,7 +6878,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6633
  "only to matching clip prompts.",
6634
  )
6635
  scene_links = gr.Markdown("")
6636
- scene_refresh_btn = gr.Button("🔄 Refresh — next 5 LoRAs", variant="secondary")
6637
  with gr.Row():
6638
  chain_count = gr.Slider(
6639
  1, MAX_SCENE_CLIPS, value=3, step=1, label="How many clips in a row",
@@ -6955,6 +7200,8 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
6955
  except Exception as error:
6956
  headline = (f"the model was not available ({type(error).__name__}), so these "
6957
  "are the instant figures")
 
 
6958
 
6959
  return [render_lora_reading(rows, headline)] + _lora_updates(rows, entries)
6960
 
@@ -7049,7 +7296,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7049
 
7050
  lora_auto_btn.click(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7051
  lora_auto_chk.change(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7052
- lora_ai_btn.click(_read_effects_model, _LORA_READ_IN, _LORA_READ_OUT)
7053
 
7054
  # A prompt is retyped far more often than an effect is picked, so the reading follows
7055
  # the text box as well - on leaving it, not on every keystroke.
@@ -7173,36 +7420,34 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7173
  fn=add_sound,
7174
  inputs=[file_output, *_SOUND_INPUTS],
7175
  outputs=[video_output, file_output, sound_status],
 
7176
  )
7177
 
7178
- gen_event = generate_button.click(
7179
- fn=mark_running,
7180
- inputs=None,
7181
- outputs=[video_output, status_box],
7182
- show_progress="hidden",
7183
- ).then(
7184
- fn=generate_video,
7185
- inputs=ui_inputs,
7186
  outputs=[video_output, file_output, seed_input, status_box],
7187
- ).then(
7188
- # Keeps the clip when the Space has persistent storage, then grows the
7189
- # stitched file if auto-merge is on. Both are CPU-only.
7190
- fn=lambda path: (_persist(path), gr.update())[1],
7191
- inputs=[file_output],
7192
- outputs=[status_box],
7193
- show_progress="hidden",
7194
- ).then(
7195
- fn=maybe_sound,
7196
- inputs=[file_output, sound_auto, *_SOUND_INPUTS],
7197
  outputs=[video_output, file_output, sound_status],
7198
- ).then(
7199
- fn=auto_queue,
7200
- inputs=[file_output, auto_merge, merge_queue, merge_name],
7201
- outputs=[merged_video, merged_file, merge_queue, merge_status],
7202
- show_progress="hidden",
7203
  )
7204
-
7205
- stop_button.click(fn=None, inputs=None, outputs=None, cancels=[gen_event])
 
 
 
 
 
7206
 
7207
  clear_button.click(
7208
  fn=_clear_all,
@@ -7242,20 +7487,23 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7242
  fn=lambda path: boomerang(path, "full"),
7243
  inputs=[file_output],
7244
  outputs=[video_output, file_output],
 
7245
  )
7246
  boomerang_end_btn.click(
7247
  fn=lambda path, tail: boomerang(path, "ending", tail),
7248
  inputs=[file_output, boomerang_tail],
7249
  outputs=[video_output, file_output],
 
7250
  )
7251
 
7252
  merge_add_btn.click(
7253
  fn=add_to_queue,
7254
  inputs=[file_output, merge_queue, merge_name],
7255
  outputs=[merged_video, merged_file, merge_queue, merge_status],
 
7256
  )
7257
  merge_retry_btn.click(join_queued_clips, [merge_queue, merge_name],
7258
- [merged_video, merged_file, merge_status], show_progress="minimal")
7259
  merge_clear_btn.click(
7260
  fn=clear_queue,
7261
  inputs=None,
@@ -7266,29 +7514,47 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7266
  # finished clip in the queue and hand back its last frame, generate from that frame with the settings
7267
  # untouched, then join the new clip on. `ui_inputs` starts with the image box, so the second step reads
7268
  # the still the first step just put there.
7269
- extend_btn.click(
7270
  fn=lambda: mark_running("Continuing the scene\u2026")[1], inputs=None,
7271
  outputs=[status_box], show_progress="hidden",
7272
- ).then(
 
7273
  fn=stage_extension,
7274
  inputs=[file_output, merge_queue, merge_name,
7275
  input_image_component, identity_ref_component],
7276
  outputs=[input_image_component, last_image_component, video_output,
7277
  merged_video, merged_file,
7278
  merge_queue, merge_status, identity_ref_component],
7279
- ).then(
 
 
7280
  fn=generate_video_continued,
7281
  inputs=ui_inputs + [merge_queue],
7282
  outputs=[video_output, file_output, seed_input, status_box],
7283
- ).then(
 
 
7284
  fn=maybe_sound,
7285
  inputs=[file_output, sound_auto, *_SOUND_INPUTS],
7286
  outputs=[video_output, file_output, sound_status],
7287
- ).then(
 
 
7288
  fn=add_to_queue,
7289
  inputs=[file_output, merge_queue, merge_name],
7290
  outputs=[merged_video, merged_file, merge_queue, merge_status],
7291
  show_progress="hidden",
 
 
 
 
 
 
 
 
 
 
 
7292
  )
7293
 
7294
  # One button, a whole scene: N clips in a row, each starting where the last one ended,
@@ -7312,7 +7578,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7312
  _chain_first = _chain_begin.success(scene_kick, [scene_state], [scene_tick, chain_btn],
7313
  show_progress="hidden")
7314
  _chain_step = scene_tick.change(scene_step, _scene_inputs, _scene_outputs,
7315
- show_progress="hidden", trigger_mode="always_last")
7316
  _chain_next = _chain_step.success(scene_kick, [scene_state], [scene_tick, chain_btn],
7317
  show_progress="hidden")
7318
  _chain_failed = _chain_step.failure(scene_abort, [scene_state], [scene_state, status_box, chain_btn], show_progress="hidden")
@@ -7404,6 +7670,8 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7404
  guidance_scale_input, frame_multi, safe_mode_checkbox,
7405
  chain_count, sound_auto, sound_engine, sound_steps,
7406
  scene_seconds,
 
 
7407
  ]
7408
  # Recalculated on demand only. An automatic readout means an event on every slider
7409
  # move, and a browser that never gets to rest.
@@ -7411,6 +7679,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7411
  fn=enhance_prompt,
7412
  inputs=[prompt_input, pb_use_model, pb_camera, pb_framing, pb_lighting, pb_pace, pb_quality],
7413
  outputs=[prompt_input, pb_status],
 
7414
  )
7415
 
7416
  # One press, one booking on the borrowed Space: the prompt comes back written from the
@@ -7423,6 +7692,8 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7423
  outputs=[prompt_input, pb_status] + _LORA_READ_OUT,
7424
  )
7425
 
 
 
7426
  # One selection shared by prompt preparation and the scene planner.
7427
  _BASIC_SLOTS = [my1_repo, my1_high, my1_hs, my1_low, my1_ls,
7428
  my2_repo, my2_high, my2_hs, my2_low, my2_ls]
@@ -7511,7 +7782,10 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7511
  )
7512
 
7513
  if __name__ == "__main__":
 
 
7514
  demo.queue().launch(
7515
  mcp_server=True,
 
7516
  show_error=True,
7517
  )
 
1
+ import os # Use the platform-installed spaces package; do not upgrade it on every boot.
2
  import spaces
3
  import shutil
4
  import subprocess
 
22
 
23
  import gradio as gr
24
 
25
+ # Bounded runtime diagnostics: no prompts, photo paths, credentials or LoRA URLs.
26
+ import atexit
27
+ import fcntl
28
+ import json
29
+
30
+ _BOOT_ID = uuid.uuid4().hex[:12]
31
+ _WEB_PID = os.getpid()
32
+
33
+
34
+ def _runtime_dir():
35
+ for root in ("/data", "/bucket", tempfile.gettempdir()):
36
+ if not os.path.isdir(root):
37
+ continue
38
+ try:
39
+ folder = os.path.join(root, "wan-runtime")
40
+ os.makedirs(folder, exist_ok=True)
41
+ with tempfile.TemporaryFile(dir=folder) as probe:
42
+ fcntl.flock(probe.fileno(), fcntl.LOCK_EX)
43
+ return folder
44
+ except OSError:
45
+ continue
46
+ return None
47
+
48
+
49
+ _RUNTIME_DIR = _runtime_dir()
50
+ _RUNTIME_LOG = os.path.join(_RUNTIME_DIR, "runtime.jsonl") if _RUNTIME_DIR else None
51
+
52
+
53
+ def _memory_snapshot():
54
+ result = {}
55
+ try:
56
+ with open("/proc/self/status") as handle:
57
+ for line in handle:
58
+ if line.startswith(("VmRSS:", "VmHWM:")):
59
+ key, value, _ = line.split()
60
+ result[key.rstrip(":") + "_MiB"] = round(int(value) / 1024, 1)
61
+ except (OSError, ValueError):
62
+ pass
63
+ for name in ("memory.current", "memory.peak", "memory.max", "memory.events"):
64
+ try:
65
+ with open("/sys/fs/cgroup/" + name) as handle:
66
+ value = handle.read(4096).strip()
67
+ if name == "memory.events":
68
+ result["cgroup_events"] = dict((k, int(v)) for k, v in
69
+ (line.split() for line in value.splitlines()))
70
+ else:
71
+ result[name + "_MiB"] = round(int(value) / 1048576, 1) if value.isdigit() else value
72
+ except (OSError, ValueError):
73
+ pass
74
+ return result
75
+
76
+
77
+ def _runtime_event(phase, **details):
78
+ record = {"utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
79
+ "boot": _BOOT_ID, "pid": os.getpid(), "web_pid": _WEB_PID,
80
+ "phase": phase, **_memory_snapshot(), **details}
81
+ line = json.dumps(record)
82
+ if phase != "heartbeat":
83
+ print("[runtime] " + line, flush=True)
84
+ if _RUNTIME_LOG:
85
+ try:
86
+ with open(_RUNTIME_LOG, "a+", encoding="utf-8") as handle:
87
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
88
+ if handle.tell() > 1024 * 1024:
89
+ handle.seek(0)
90
+ retained = handle.readlines()[-300:]
91
+ handle.seek(0)
92
+ handle.truncate()
93
+ handle.writelines(retained)
94
+ handle.write(line + "\n")
95
+ handle.flush()
96
+ except OSError:
97
+ pass
98
+
99
+
100
+ def runtime_report():
101
+ _runtime_event("diagnostics_requested")
102
+ history = ""
103
+ try:
104
+ with open(_RUNTIME_LOG, encoding="utf-8") as handle:
105
+ fcntl.flock(handle.fileno(), fcntl.LOCK_SH)
106
+ history = handle.read(2 * 1024 * 1024)
107
+ except (OSError, TypeError):
108
+ pass
109
+ with tempfile.NamedTemporaryFile(mode="w", prefix="wan-runtime-", suffix=".txt",
110
+ encoding="utf-8", delete=False) as handle:
111
+ handle.write("Wan runtime report\nBoot: " + _BOOT_ID +
112
+ "\nA changed boot ID indicates a new app process. GPU worker PIDs can change normally.\n"
113
+ "History survives container replacement only with persistent storage.\n"
114
+ "Cgroup OOM counters may reset when a container is replaced.\n\n" + history)
115
+ path = handle.name
116
+ return "Boot: " + _BOOT_ID + "\n" + json.dumps(_memory_snapshot(), indent=2), path
117
+
118
+
119
+ def _runtime_heartbeat():
120
+ while os.getpid() == _WEB_PID:
121
+ time.sleep(30)
122
+ _runtime_event("heartbeat")
123
+
124
+
125
+ def _runtime_shutdown():
126
+ if os.getpid() == _WEB_PID:
127
+ _runtime_event("normal_shutdown")
128
+
129
+
130
+ _runtime_event("boot")
131
+ atexit.register(_runtime_shutdown)
132
+
133
+
134
+ def _guard_missing_images():
135
+ original = gr.Image.preprocess
136
+ labels = {"wan-start-image": "Start frame", "wan-end-image": "End frame",
137
+ "wan-identity-image": "Identity Lock photo"}
138
+
139
+ def preprocess(self, payload):
140
+ try:
141
+ return original(self, payload)
142
+ except FileNotFoundError as error:
143
+ label = labels.get(getattr(self, "elem_id", None))
144
+ if label is None:
145
+ raise
146
+ _runtime_event("missing_upload", component=self.elem_id)
147
+ raise gr.Error(f"{label} is no longer on the server. The Space may have restarted "
148
+ "or the upload expired. Upload it again; clear it if optional.") from error
149
+ gr.Image.preprocess = preprocess
150
+
151
+
152
+ _guard_missing_images()
153
+
154
+
155
+ def _generation_failed():
156
+ _runtime_event("generation_event_failed")
157
+ return None, ("<div class='status-idle'><b>Generation did not complete.</b>"
158
+ "<span>See the error message. Re-upload any expired image. "
159
+ "Automatic audio and joining were not started.</span></div>")
160
+
161
+
162
+ def _frame_u8(frame):
163
+ frame = np.asarray(frame)[..., :3]
164
+ if frame.dtype != np.uint8:
165
+ frame = np.clip(frame * 255.0, 0, 255).astype(np.uint8)
166
+ return np.ascontiguousarray(frame)
167
+
168
+
169
+ def _stream_video(frames, video_path, fps, quality):
170
+ """One RGB frame at a time; no full interpolated float/uint8 clip copies."""
171
+ iterator, process, timer = iter(frames), None, None
172
+ try:
173
+ first = _frame_u8(next(iterator))
174
+ height, width = first.shape[:2]
175
+ crf = int((1 - min(10.0, max(1.0, float(quality))) / 10) * 51)
176
+ command = [_ffmpeg_exe(), "-hide_banner", "-loglevel", "error", "-y",
177
+ "-f", "rawvideo", "-vcodec", "rawvideo", "-s", f"{width}x{height}",
178
+ "-pix_fmt", "rgb24", "-r", str(fps), "-i", "pipe:0", "-an",
179
+ "-c:v", "libx264", "-threads", "2", "-crf", str(crf),
180
+ "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(video_path)]
181
+ with tempfile.TemporaryFile() as error_log:
182
+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
183
+ stderr=error_log)
184
+ def expire():
185
+ if process.poll() is None:
186
+ process.kill()
187
+ timer = threading.Timer(600, expire)
188
+ timer.daemon = True
189
+ timer.start()
190
+ process.stdin.write(first.tobytes())
191
+ tail = first
192
+ for frame in iterator:
193
+ tail = _frame_u8(frame)
194
+ if tail.shape != first.shape:
195
+ raise ValueError("Video frames must have the same dimensions.")
196
+ process.stdin.write(tail.tobytes())
197
+ process.stdin.close()
198
+ process.wait(timeout=30)
199
+ if process.returncode:
200
+ error_log.seek(0)
201
+ raise RuntimeError("Video encoding failed: " + error_log.read(2048).decode("utf-8", "replace"))
202
+ if not os.path.isfile(video_path) or os.path.getsize(video_path) == 0:
203
+ raise RuntimeError("Video encoding produced no output.")
204
+ return tail
205
+ except BaseException:
206
+ if os.path.isfile(video_path):
207
+ os.remove(video_path)
208
+ raise
209
+ finally:
210
+ if timer is not None:
211
+ timer.cancel()
212
+ if process is not None:
213
+ if process.poll() is None:
214
+ process.kill()
215
+ try:
216
+ if process.stdin and not process.stdin.closed:
217
+ process.stdin.close()
218
+ except OSError:
219
+ pass
220
+ process.wait(timeout=10)
221
+ if hasattr(iterator, "close"):
222
+ iterator.close()
223
+
224
+
225
+ def _concat_duration(path):
226
+ capture = cv2.VideoCapture(str(path))
227
+ try:
228
+ fps = float(capture.get(cv2.CAP_PROP_FPS) or 0)
229
+ frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
230
+ finally:
231
+ capture.release()
232
+ if fps <= 0 or frames <= 0:
233
+ raise ValueError("Could not read clip duration.")
234
+ return frames / fps
235
+
236
+
237
+ def _estimate_lora_groups(adapter_values):
238
+ values = list(adapter_values)
239
+ if len(values) < 37:
240
+ return []
241
+ groups = []
242
+ speed = (SPEED_PRESETS.get(values[0]) or {}).get("lora")
243
+ if speed:
244
+ source = _SPEED_CACHE.get(speed) or SPEED_LORA_SOURCES.get(speed) or {}
245
+ groups.append({"repo": source.get("repo", ""),
246
+ "file_high": source.get("file_high") or "unresolved-speed-high",
247
+ "file_low": source.get("file_low") or "unresolved-speed-low",
248
+ "high_scale": values[1], "low_scale": values[2]})
249
+ for index in range(3):
250
+ offset = 3 + index * 3
251
+ groups.append({"preset": values[offset], "high_scale": values[offset+1], "low_scale": values[offset+2]})
252
+ for index in range(5):
253
+ offset = 12 + index * 5
254
+ groups.append({"repo": values[offset], "file_high": values[offset+1], "high_scale": values[offset+2],
255
+ "file_low": values[offset+3], "low_scale": values[offset+4]})
256
+ return groups
257
+
258
+
259
+
260
 
261
  # A slider or number box that has been emptied arrives as None, and gradio compares that
262
  # against the component's minimum before any handler is called - so the event dies in
 
296
  DPMSolverSinglestepScheduler,
297
  )
298
  from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
 
299
 
300
  from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
301
  import aoti
 
377
  rife_model.eval()
378
 
379
 
 
380
  def interpolate_bits(frames_np, multiplier=2, scale=1.0):
381
+ with torch.no_grad():
382
+ if len(frames_np) == 0:
383
+ return
384
+ if isinstance(frames_np, list):
385
+ T = len(frames_np)
386
+ H, W, C = frames_np[0].shape
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  else:
388
+ T, H, W, C = frames_np.shape
389
+
390
+ if multiplier < 2:
391
+ yield from frames_np
392
+ return
393
+
394
+ n_interp = multiplier - 1
395
+
396
+ tmp = max(128, int(128 / scale))
397
+ ph = ((H - 1) // tmp + 1) * tmp
398
+ pw = ((W - 1) // tmp + 1) * tmp
399
+ padding = (0, pw - W, 0, ph - H)
400
+
401
+ def to_tensor(frame_np):
402
+ t = torch.from_numpy(frame_np).to(device)
403
+ t = t.permute(2, 0, 1).unsqueeze(0)
404
+ return F.pad(t, padding).half()
405
+
406
+ def from_tensor(tensor):
407
+ t = tensor[0, :, :H, :W]
408
+ t = t.permute(1, 2, 0)
409
+ return t.float().cpu().numpy()
410
+
411
+ def make_inference(I0, I1, n):
412
+ if rife_model.version >= 3.9:
413
+ res = []
414
+ for i in range(n):
415
+ res.append(rife_model.inference(I0, I1, (i+1) * 1. / (n+1), scale))
416
+ return res
417
  else:
418
+ middle = rife_model.inference(I0, I1, scale)
419
+ if n == 1:
420
+ return [middle]
421
+ first_half = make_inference(I0, middle, n=n//2)
422
+ second_half = make_inference(middle, I1, n=n//2)
423
+ if n % 2:
424
+ return [*first_half, middle, *second_half]
425
+ else:
426
+ return [*first_half, *second_half]
427
+
428
+ I1 = to_tensor(frames_np[0])
429
+ total_steps = T - 1
430
+
431
+ with tqdm(total=total_steps, desc="Interpolating", unit="frame") as pbar:
432
+ for i in range(total_steps):
433
+ I0 = I1
434
+ yield from_tensor(I0)
435
+ I1 = to_tensor(frames_np[i+1])
436
+ mid_tensors = make_inference(I0, I1, n_interp)
437
+ for mid in mid_tensors:
438
+ yield from_tensor(mid)
439
+ if (i + 1) % 50 == 0:
440
+ pbar.update(50)
441
+ pbar.update(total_steps % 50)
442
+ yield from_tensor(I1)
443
 
444
 
445
  # WAN
 
673
  `crop` takes the middle out, `pad` keeps the whole picture and fills the rest with black."""
674
  width, height = image.size
675
  if width == height:
676
+ side = min(SQUARE_DIM, max(MIN_DIM, round(width / MULTIPLE_OF) * MULTIPLE_OF))
677
+ return image.resize((side, side), Image.LANCZOS)
678
 
679
  aspect_ratio = width / height
680
  MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
 
705
  top = (height - crop_height) // 2
706
  image_to_resize = image.crop((0, top, width, top + crop_height))
707
  else:
708
+ # Keep already suitable images at their native size. Do not upscale a
709
+ # 512x768 upload to 560x832 and pay for pixels the user never supplied.
710
+ scale = min(MAX_DIM / max(width, height), max(1.0, MIN_DIM / min(width, height)))
711
+ target_w, target_h = int(round(width * scale)), int(round(height * scale))
 
 
712
 
713
  final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
714
  final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
 
1755
  lora_groups,
1756
  progress
1757
  ):
 
 
 
 
 
 
1758
  width, height = resized_image.size
1759
+ factor = num_frames * width * height / (81 * 832 * 624)
1760
+ denoise_seconds = int(steps) * 7.0 * factor ** 1.5
1761
+ if max(float(guidance_scale), float(guidance_scale_2)) > 1:
1762
+ denoise_seconds *= 2.4
1763
+ multiplier = max(1, int(frame_multiplier) // FIXED_FPS)
1764
+ extra_frames = (int(num_frames) - 1) * (multiplier - 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1765
  if safe_mode:
1766
+ output_frames = (int(num_frames) - 1) * multiplier + 1
1767
+ requested = (30 + denoise_seconds * 1.35 + extra_frames * 0.10
1768
+ + output_frames * 0.02 + _lora_booking_extra(lora_groups)) * 1.15
1769
+ else:
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
 
1777
  @spaces.GPU(duration=get_inference_duration, size='xlarge')
 
1794
  lora_groups=None,
1795
  progress=gr.Progress(track_tqdm=True),
1796
  ):
1797
+ gpu_clock = time.perf_counter()
1798
+ _runtime_event("gpu_begin", frames=int(num_frames), fps=int(frame_multiplier))
1799
+ try:
1800
+ scheduler_class = SCHEDULER_MAP.get(scheduler_name, type(original_scheduler))
1801
+ if scheduler_class.__name__ != pipe.scheduler.config._class_name or flow_shift != pipe.scheduler.config.get("flow_shift", "shift"):
1802
+ config = copy.deepcopy(original_scheduler.config)
1803
+ if scheduler_class == FlowMatchEulerDiscreteScheduler:
1804
+ config['shift'] = flow_shift
1805
+ else:
1806
+ config['flow_shift'] = flow_shift
1807
+ pipe.scheduler = scheduler_class.from_config(config)
1808
 
1809
+ clear_vram()
1810
 
1811
+ task_name = str(uuid.uuid4())[:8]
1812
 
1813
+ # Only the shape of the request: no prompt text, and adapters by name rather than by what the
1814
+ # visitor typed. Enough to read a report or spot a bad adapter, without recording anybody's words.
1815
+ active = []
1816
+ for group in lora_groups or []:
1817
+ if group.get("preset") and group["preset"] != "(None)":
1818
+ active.append(f"{group['preset']} @ {group.get('high_scale')}/{group.get('low_scale')}")
1819
+ continue
1820
+ for role in ("file_high", "file_low"):
1821
+ value = group.get(role)
1822
+ if value and value != "(None)":
1823
+ scale = group.get("high_scale" if role == "file_high" else "low_scale")
1824
+ active.append(f"{os.path.basename(str(value))[:60]} ({role[5:]}) @ {scale}")
1825
+
1826
+ print(f"[request {task_name}] {num_frames} frames, {duration_seconds}s, {resized_image.size}, "
1827
+ f"{int(steps)} steps, seed {current_seed}")
1828
+ if active:
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:
1836
+ try:
1837
+ # Newer loader: one bad file is skipped rather than taking the whole
1838
+ # request down with it, and it hands back a line explaining each skip.
1839
+ outcome = lora_loader.load_lora_slots(pipe, lora_groups)
1840
+ if isinstance(outcome, tuple):
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]]
1848
+ try:
1849
+ lora_loader.unload_lora(pipe)
1850
+ except Exception:
1851
+ pass
1852
 
1853
+ _runtime_event("denoise_and_decode")
1854
+ result = pipe(
1855
+ image=resized_image,
1856
+ last_image=processed_last_image,
1857
+ prompt=prompt,
1858
+ negative_prompt=negative_prompt,
1859
+ height=resized_image.height,
1860
+ width=resized_image.width,
1861
+ num_frames=num_frames,
1862
+ guidance_scale=float(guidance_scale),
1863
+ guidance_scale_2=float(guidance_scale_2),
1864
+ num_inference_steps=int(steps),
1865
+ generator=torch.Generator(device="cuda").manual_seed(current_seed),
1866
+ output_type="np"
1867
+ )
1868
 
1869
+ if lora_loaded:
1870
+ lora_loader.unload_lora(pipe)
1871
 
1872
+ print("gen time passed:", time.time() - start)
 
1873
 
1874
+ raw_frames_np = result.frames[0]
1875
+ pipe.scheduler = original_scheduler
 
 
 
 
 
 
 
 
1876
 
1877
+ frame_factor = max(1, int(frame_multiplier) // FIXED_FPS)
1878
+ if frame_factor > 1:
1879
+ start = time.time()
1880
+ print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")
1881
+ rife_model.device()
1882
+ rife_model.flownet = rife_model.flownet.half()
1883
+ final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
1884
+ # Interpolation executes lazily as the encoder requests each frame.
1885
+ else:
1886
+ final_frames = iter(raw_frames_np)
1887
 
1888
+ final_fps = FIXED_FPS * int(frame_factor)
 
1889
 
1890
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
1891
+ video_path = tmpfile.name
 
 
 
 
1892
 
1893
+ start = time.time()
1894
+ with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
1895
+ pbar.update(2)
1896
+ _runtime_event("rife_and_export" if frame_factor > 1 else "export")
1897
+ tail = _stream_video(final_frames, video_path, fps=final_fps, quality=quality)
1898
+ pbar.update(1)
1899
+ print(f"Export time passed, {final_fps} FPS:", time.time() - start)
1900
+
1901
+ # Keep the closing frame losslessly beside the clip. A chain that continues
1902
+ # from the h264 file re-encodes the same picture again at every link, and the
1903
+ # blocking and colour banding pile up clip after clip; continuing from this
1904
+ # png instead means the tenth shot starts from the same quality as the first.
1905
+ try:
1906
+ tail = np.asarray(tail)
1907
+ if tail.dtype != np.uint8:
1908
+ tail = (tail * 255.0 if float(tail.max()) <= 1.001 else tail)
1909
+ tail = tail.clip(0, 255).astype(np.uint8)
1910
+ Image.fromarray(tail[..., :3]).save(video_path + ".last.png")
1911
+ except Exception as error:
1912
+ print(f"[chain] could not keep the closing frame: {error}", flush=True)
1913
 
1914
+ _runtime_event("gpu_complete", elapsed_gpu_s=round(time.perf_counter() - gpu_clock, 3))
1915
+ return video_path, task_name, list(lora_problems)
1916
+ except BaseException as error:
1917
+ _runtime_event("gpu_failed", error_type=type(error).__name__,
1918
+ elapsed_gpu_s=round(time.perf_counter() - gpu_clock, 3))
1919
+ raise
1920
+ finally:
1921
+ try:
1922
+ if lora_groups:
1923
+ lora_loader.unload_lora(pipe)
1924
+ except Exception as error:
1925
+ _runtime_event("adapter_cleanup_failed", error_type=type(error).__name__)
1926
+ pipe.scheduler = original_scheduler
1927
+ result = raw_frames_np = final_frames = None
1928
+ clear_vram()
1929
 
1930
 
1931
  def generate_video(
 
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,
2034
+ guidance_scale, guidance_scale_2, current_seed, scheduler, flow_shift,
2035
+ frame_multiplier, quality, duration_seconds, safe_mode, lora_groups, progress,
2036
+ )
2037
+ _runtime_event("gpu_reservation", requested_gpu_s=int(requested_seconds),
2038
+ requested_quota_s=2 * int(requested_seconds), safe_mode=bool(safe_mode))
2039
  try:
2040
  inference = run_inference(
2041
  resized_image,
 
2062
  # ZeroGPU speaks in stack traces. Say what happened and what to do about it.
2063
  message = _scene_trouble(error)
2064
  fit = _what_would_fit(str(error), resized_image, steps, duration_seconds,
2065
+ guidance_scale, frame_multiplier, lora_groups=lora_groups)
2066
  raise gr.Error(message + fit) from error
2067
  video_path, task_n, lora_problems = inference
2068
  _record_wan_lora_failures(lora_groups, lora_problems)
 
2410
  total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
2411
  if total > tail:
2412
  capture.set(cv2.CAP_PROP_POS_FRAMES, max(0, total - tail))
2413
+ last, last_visible = None, None
2414
  while True:
2415
  ok, candidate = capture.read()
2416
  if not ok or candidate is None:
2417
  break
2418
+ last = candidate
 
 
 
 
2419
  if float(candidate.mean()) > 2.0:
2420
+ last_visible = candidate
2421
+ capture.release()
2422
+ return last_visible if last_visible is not None else last
2423
 
2424
 
2425
  def _last_frame_small(path):
 
2470
  return max(1.0, total / fps)
2471
 
2472
 
2473
+ def _normalise_clip(path, width, height, fps, out_path, trim_head=False, colour="", include_audio=True):
 
 
 
2474
  fps_str = f"{fps:.6f}".rstrip("0").rstrip(".")
2475
  video_chain = (f"{colour}scale={width}:{height}:force_original_aspect_ratio=decrease,"
2476
  f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps_str}")
 
2477
  if trim_head:
2478
+ video_chain += ",trim=start_frame=1"
2479
+ video_chain += ",setpts=PTS-STARTPTS"
2480
+ command = [_ffmpeg_exe(), "-hide_banner", "-loglevel", "error", "-y",
2481
+ "-threads", "2", "-filter_threads", "1", "-filter_complex_threads", "1", "-i", path]
2482
+ tail = ["-c:v", "libx264", "-threads", "2", "-preset", "fast", "-crf", "20",
2483
+ "-pix_fmt", "yuv420p", "-r", fps_str, "-fps_mode", "cfr", "-video_track_timescale", "90000"]
2484
+ if include_audio:
2485
+ output_frames = max(1, int(round(_concat_duration(path) * fps)) - int(bool(trim_head)))
2486
+ audio_chain = "aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo"
2487
+ if trim_head:
2488
+ audio_chain += f",atrim=start={1.0 / fps:.6f}"
2489
+ audio_chain += ",asetpts=PTS-STARTPTS,apad"
2490
+ audio_input = "0:a"
2491
+ if not _has_audio(path):
2492
+ command += ["-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo"]
2493
+ audio_input = "1:a"
2494
+ command += ["-filter_complex", f"[0:v]{video_chain}[v];[{audio_input}]{audio_chain}[a]",
2495
+ "-map", "[v]", "-map", "[a]", "-t", f"{output_frames / fps:.9f}", *tail,
2496
+ "-c:a", "aac", "-ar", "48000", "-ac", "2", "-b:a", "192k", out_path]
2497
  else:
2498
+ command += ["-vf", video_chain, "-map", "0:v:0", "-an", *tail, out_path]
 
 
 
2499
  subprocess.run(command, check=True, capture_output=True, timeout=600)
2500
  return out_path
2501
 
 
2589
 
2590
  colour_fixes = _colour_fix_filters(valid)
2591
 
2592
+ include_audio = any(_has_audio(p) for p in valid)
2593
+ _runtime_event("stitch_begin", clips=len(valid), audio=include_audio)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2594
  try:
2595
+ with tempfile.TemporaryDirectory(prefix="stitch-") as work_dir:
2596
+ parts = []
2597
+ for index, path in enumerate(valid):
2598
+ _runtime_event("stitch_normalise", clip=index+1, clips=len(valid))
2599
+ part = os.path.join(work_dir, f"part{index:04d}.mp4")
2600
+ _normalise_clip(path, width, height, fps, part, trim_head=bool(trims[index]),
2601
+ colour=colour_fixes[index], include_audio=include_audio)
2602
+ parts.append(part)
2603
+ manifest = os.path.join(work_dir, "parts.ffconcat")
2604
+ with open(manifest, "w", encoding="utf-8") as handle:
2605
+ handle.write("ffconcat version 1.0\n")
2606
+ for part in parts:
2607
+ handle.write("file '" + os.path.basename(part) + "'\n")
2608
+ handle.write(f"duration {_concat_duration(part):.9f}\n")
2609
+ _runtime_event("stitch_copy", clips=len(parts))
2610
+ subprocess.run([_ffmpeg_exe(), "-hide_banner", "-loglevel", "error", "-y",
2611
+ "-f", "concat", "-safe", "1", "-i", manifest,
2612
+ "-map", "0:v:0", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", out_path],
2613
+ check=True, capture_output=True, timeout=600)
2614
+ if not os.path.isfile(out_path) or os.path.getsize(out_path) == 0:
2615
+ raise RuntimeError("Joining produced no complete output.")
2616
+ except BaseException as error:
2617
  if os.path.exists(out_path):
2618
  os.remove(out_path)
2619
+ _runtime_event("stitch_failed", error_type=type(error).__name__)
2620
+ if not isinstance(error, Exception):
2621
+ raise
2622
  raise gr.Error("Joining failed; all original clips remain in the queue. Retry Join.") from error
2623
  _persist(out_path)
2624
+ _runtime_event("stitch_complete", clips=len(valid))
2625
  return out_path
2626
 
2627
 
 
3434
  raise gr.Error("Generate a video first — there is nothing to add sound to.")
3435
 
3436
  engine = FOLEY_ENGINES.get(engine_label, FOLEY_ENGINES[FOLEY_DEFAULT])
3437
+ _runtime_event("audio_prepare", engine=engine)
3438
  prompt = str(prompt or "").strip()
3439
  negative = FOLEY_NEGATIVE if negative is None else str(negative).strip()
3440
  out_path = os.path.join(tempfile.gettempdir(), f"{uuid.uuid4().hex[:4]}_sound.mp4")
 
3443
  try:
3444
  if engine == "hunyuan":
3445
  model_path, config_path = _hunyuan_paths()
3446
+ _runtime_event("audio_inference", engine=engine)
3447
  _hunyuan_run(str(video_path), prompt, negative, steps, guidance,
3448
  model_path, config_path, out_path)
3449
  else:
3450
  cfg = _mmaudio_config(engine)
3451
  seconds = _video_duration(video_path)
3452
+ _runtime_event("audio_inference", engine=engine, seconds=round(seconds, 2))
3453
  _mmaudio_run(str(video_path), prompt, negative, steps, guidance, seconds,
3454
  int(seed) or random.randint(0, 10_000), out_path,
3455
  engine=engine, model_path=str(cfg.model_path))
 
3458
  except gr.Error:
3459
  raise
3460
  except Exception as error:
3461
+ _runtime_event("audio_failed", error_type=type(error).__name__)
3462
  raise gr.Error(f"Sound failed: {error}")
3463
 
3464
+ _runtime_event("audio_returned", engine=engine)
3465
  if not os.path.exists(out_path):
3466
  raise gr.Error("The sound model produced nothing.")
3467
 
 
3615
  )
3616
 
3617
 
3618
+ def _release_enhancer_cpu():
3619
+ _ENHANCER.update(model=None, tokenizer=None, ready=False)
3620
+ gc.collect()
3621
+
3622
+
3623
  def _load_enhancer_cpu():
3624
  """Read the weights into CPU RAM. Deliberately outside the GPU call: 8 GB off disk is 30 s or
3625
  more, and a ZeroGPU booking that spends its whole allowance loading is a booking that times out
 
3693
 
3694
  try:
3695
  # Said out loud because the first press downloads ~8 GB and a bare spinner looks like a hang.
3696
+ # None of this is GPU time: downloaded files remain cached on disk; RAM is released after this request.
3697
  progress(0.05, desc="Fetching the model (first time only, no GPU time)...")
3698
  _fetch_enhancer_files()
3699
  progress(0.5, desc="Loading it into memory...")
3700
  _load_enhancer_cpu()
3701
  except Exception as error:
3702
+ _release_enhancer_cpu()
3703
  return built, (
3704
  "<div class='status-idle'>Model unavailable, so the built prompt is shown "
3705
  f"instead: {type(error).__name__}</div>"
 
3714
  f"instead: {error!r}</div>"
3715
  )
3716
 
3717
+ finally:
3718
+ _release_enhancer_cpu()
3719
+
3720
  if len(written) < 40:
3721
  return built, "<div class='status-idle'>The model returned too little; built prompt kept.</div>"
3722
  return written, (
 
3765
 
3766
 
3767
  def _make_remote_client(space_id):
3768
+ """Public writers are anonymous. Never reuse the model-download HF_TOKEN for visitors.
 
 
 
 
3769
 
3770
+ An owner may explicitly opt into authenticated writer calls using EXPANDER_HF_TOKEN.
3771
+ Those calls use that account's remote Space allowance/credits. False is intentional:
3772
+ token=None can silently pick up HF_TOKEN or a cached Hub login.
3773
+ """
3774
+ import inspect
3775
  from gradio_client import Client
3776
+ token = os.environ.get("EXPANDER_HF_TOKEN") or False
3777
+ parameters = inspect.signature(Client.__init__).parameters
3778
+ for name in ("hf_token", "token"):
3779
+ if name in parameters:
3780
+ return Client(space_id, **{name: token})
3781
+ raise RuntimeError("This gradio_client cannot explicitly control remote authentication.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3782
 
3783
 
3784
  def _remote_plan(client, payload, message, max_new_tokens=None):
 
3833
 
3834
 
3835
  def _remote_ask(space_id, message, image=None, temperature=0.7, max_new_tokens=None):
3836
+ """One submitted AI job per call. Never replay a timed-out/failed paid request."""
 
3837
  from gradio_client import handle_file
3838
+ from concurrent.futures import TimeoutError as FutureTimeout
3839
  client = _REMOTE_CLIENTS.get(space_id)
3840
  if client is None:
3841
  client = _make_remote_client(space_id)
3842
+ if len(_REMOTE_CLIENTS) >= 8:
3843
+ _REMOTE_CLIENTS.pop(next(iter(_REMOTE_CLIENTS)))
3844
  _REMOTE_CLIENTS[space_id] = client
3845
+ temporary_image = None
3846
+ job = None
3847
+ try:
3848
+ files = []
3849
+ if image is not None:
3850
  picture = image.convert("RGB")
3851
  picture.thumbnail((1024, 1024))
3852
+ fd, temporary_image = tempfile.mkstemp(suffix=".png")
3853
+ os.close(fd)
3854
+ picture.save(temporary_image, format="PNG")
3855
+ files.append(handle_file(temporary_image))
3856
+ payload = {"text": message, "files": files}
3857
+ plan, _ = _remote_plan(client, payload, message, max_new_tokens=int(max_new_tokens or 768))
3858
+ if not plan:
3859
+ raise RuntimeError("The writing Space did not expose a usable API. No AI job was submitted.")
3860
+ args, kwargs = plan[0]
3861
+ _runtime_event("remote_ai_submit", authenticated=bool(os.environ.get("EXPANDER_HF_TOKEN")))
3862
+ job = client.submit(*args, **kwargs)
3863
+ reply = _remote_reply_text(job.result(timeout=300))
3864
+ _runtime_event("remote_ai_complete")
3865
+ return reply
3866
+ except FutureTimeout as error:
3867
+ if job is not None:
3868
+ try:
3869
+ job.cancel()
3870
+ except Exception:
3871
+ pass
3872
+ _runtime_event("remote_ai_timeout")
3873
+ raise RuntimeError("The writing Space timed out. No automatic retry was submitted. "
3874
+ "A started job may still consume its own GPU allowance.") from error
3875
+ except Exception as error:
3876
+ _runtime_event("remote_ai_failed", error_type=type(error).__name__)
3877
+ raise
3878
+ finally:
3879
+ if temporary_image:
3880
+ try:
3881
+ os.remove(temporary_image)
3882
+ except OSError:
3883
+ pass
3884
 
3885
 
3886
  def _big_space_message(built, rows, has_image=False):
 
4726
 
4727
 
4728
  def _what_would_fit(text, image, steps, duration_seconds, guidance_scale, frame_multiplier,
4729
+ as_numbers=False, lora_groups=None):
4730
  """Given how many seconds ZeroGPU says are left, name a clip that would fit.
4731
 
4732
  "Make it shorter" is not much of an instruction when the numbers are doubled behind
 
4745
  seconds = get_inference_duration(
4746
  _SizeOnly(width, height), None, "", int(clip_steps), "", frames,
4747
  float(guidance_scale), 1.0, 0, "UniPCMultistep", 3.0,
4748
+ int(frame_multiplier), 5, float(clip_seconds), bool(safe), lora_groups, None,
4749
  )
4750
+ return 2 * int(seconds), frames # xlarge doubles the request
4751
 
4752
  attempts = []
4753
  for clip_steps in (int(steps), 4):
 
4797
  f"mode off, may bring it under what is left.")
4798
  except Exception:
4799
  extra = ""
4800
+ return ("ZeroGPU could not admit this request with the available allowance. " + text + extra)
4801
  if "token" in low and any(word in low for word in ("expire", "invalid", "not found",
4802
  "missing", "unauthor")):
4803
  return ("The page's GPU pass went stale while the tab sat open. Refresh the page and "
 
4959
  try:
4960
  retry = _what_would_fit(str(error), _SizeOnly(*_target_size(values[0])),
4961
  values[3], values[5], values[6], values[13],
4962
+ as_numbers=True,
4963
+ lora_groups=_estimate_lora_groups(values[16:53]))
4964
  except Exception:
4965
  retry = None
4966
  if retry:
 
5206
  return (832, 624)
5207
  width, height = image.size
5208
  if width == height:
5209
+ side = min(SQUARE_DIM, max(MIN_DIM, round(width / MULTIPLE_OF) * MULTIPLE_OF))
5210
+ return (side, side)
5211
 
5212
  aspect_ratio = width / height
5213
  MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
 
5218
  elif aspect_ratio < MIN_ASPECT_RATIO:
5219
  target_w, target_h = MIN_DIM, MAX_DIM
5220
  else:
5221
+ scale = min(MAX_DIM / max(width, height), max(1.0, MIN_DIM / min(width, height)))
5222
+ target_w, target_h = int(round(width * scale)), int(round(height * scale))
 
 
 
 
5223
 
5224
  final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
5225
  final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
 
5301
 
5302
  def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5303
  frame_multiplier, safe_mode, clip_count=1,
5304
+ sound_on=False, sound_engine=None, sound_steps=25, scene_seconds="", *adapter_values):
5305
  """Live ZeroGPU cost readout, using the exact same formula the
5306
  @spaces.GPU decorator asks for at generation time."""
5307
+ groups = _estimate_lora_groups(adapter_values)
5308
  try:
5309
+ guidance_low = float(adapter_values[37]) if len(adapter_values) > 37 else 1.0
5310
  num_frames = get_num_frames(float(duration_seconds))
5311
  w, h = _target_size(input_image)
5312
  secs = get_inference_duration(
5313
  _SizeOnly(w, h), None, "", steps, "", num_frames,
5314
+ float(guidance_scale), guidance_low, 0, "UniPCMultistep", 3.0,
5315
  int(frame_multiplier), 5, float(duration_seconds),
5316
+ bool(safe_mode), groups, None,
5317
  )
5318
  except Exception as exc: # never break the UI over a readout
5319
  return f"⏳ **ZeroGPU cost:** estimate unavailable ({exc})"
5320
 
5321
  note = "" if input_image is not None else " · upload an image for an exact number"
5322
  out_fps = int(frame_multiplier)
5323
+ out_frames = (num_frames - 1) * max(1, out_fps // FIXED_FPS) + 1
5324
 
5325
  # Sound is a second booking on top of every clip: model load plus the denoise.
5326
  sound_secs = 0.0
 
5331
  else:
5332
  sound_secs = min(200.0, 70.0 + float(sound_steps) * 0.9 + float(duration_seconds) * 2.0)
5333
 
5334
+ # SDK admission uses whole seconds and xlarge's 2x multiplier.
5335
+ video_cost = 2 * int(secs)
 
 
5336
  per_clip = video_cost + sound_secs
5337
  try:
5338
  clips = _scene_count(clip_count)
5339
  scene_durations = _scene_durations(scene_seconds, clips, duration_seconds)
5340
  except (TypeError, ValueError) as error:
5341
  return f"⏳ **ZeroGPU cost:** check the scene timing plan — {error}"
5342
+ lines = ["⏳ **ZeroGPU reservation estimate** "]
5343
  sound_bit = f" + ~{int(round(sound_secs))} s sound" if sound_secs else ""
5344
+ lines.append(f"one clip **~{int(round(per_clip))} s requested allowance**"
5345
  f" ({int(round(video_cost))} s video{sound_bit}) ")
5346
  # In a chain the sound is added once, to the joined scene, not to every clip.
5347
  scene_video_cost = sum(
5348
+ 2 * int(get_inference_duration(
5349
  _SizeOnly(w, h), None, "", steps, "", get_num_frames(seconds),
5350
+ float(guidance_scale), guidance_low, 0, "UniPCMultistep", 3.0,
5351
+ int(frame_multiplier), 5, seconds, bool(safe_mode), groups, None,
5352
+ )) for seconds in scene_durations
5353
  )
5354
  scene_sound_cost = sound_secs
5355
  if sound_on and engine != "hunyuan":
 
5357
  scene_total = scene_video_cost + scene_sound_cost
5358
  lines.append(f"🎬 whole scene, {clips} clips: **~{int(round(scene_total))} s**"
5359
  f"{' (sound is added once, to the finished scene)' if sound_secs and clips > 1 else ''} ")
5360
+ if video_cost > 300:
5361
+ lines.append("⚠️ This video reservation exceeds the free account's full 300 s daily allowance. ")
5362
  lines.append(
5363
+ f"<sub>{num_frames} model frames · {w}×{h} · {int(steps)} steps · "
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
 
 
5837
  for section in ("nsfw", "normal"):
5838
  for item in (data.get(section) or []):
5839
  if isinstance(item, dict) and item.get("url") and item.get("name"):
5840
+ pool.append({**item, "_picker_section": section})
5841
  return pool
5842
 
5843
 
 
5864
 
5865
  def _pick_label(index, item):
5866
  text = f"{index + 1}. {item.get('name', '')}"
5867
+ if _pick_all_in_one(item):
5868
+ text += " · always listed"
5869
  if item.get("builtin"):
5870
  text += " · built in"
5871
  elif not str(item.get("trigger") or "").strip():
 
5893
  "of them match. Write nothing else - no explanation, no names, only numbers."
5894
  )
5895
  try:
5896
+ reply = _remote_ask(space, message, max_new_tokens=64)
5897
  except Exception as error: # noqa: BLE001
5898
  print(f"[simple] the Space did not answer the pick question: {error}", flush=True)
5899
  return []
 
6127
  return result
6128
 
6129
 
6130
+ def _pick_all_in_one(item):
6131
+ name = str(item.get("name") or "").lower()
6132
+ compact = re.sub(r"[^a-z0-9]+", "", name)
6133
+ general = ("allinone" in compact or bool(re.search(r"\baio\b", name))
6134
+ or "generalnsfwbooster" in compact)
6135
+ nsfw = (item.get("_picker_section") == "nsfw" or item.get("nsfw") is True or "nsfw" in name)
6136
+ return general and nsfw
6137
+
6138
+
6139
  def _pick_page(basis, state, advance=False, keep=None):
6140
  from concurrent.futures import ThreadPoolExecutor
6141
+ pool = _library_pool()
6142
  ranked = _shortlist_loras(basis, pool, limit=len(pool))
6143
+ pins, pin_keys = [], set()
6144
+ for item in pool:
6145
+ key = _pick_key(item)
6146
+ if _pick_all_in_one(item) and key not in pin_keys:
6147
+ pin_keys.add(key)
6148
+ pins.append(item)
6149
+ rotating, seen = [], set(pin_keys)
6150
  for item in ranked:
6151
  key = _pick_key(item)
6152
  if key not in seen:
6153
  seen.add(key)
6154
+ rotating.append(item)
6155
+ count = len(rotating)
6156
+ state = state if isinstance(state, dict) else {}
6157
+ try:
6158
+ cursor = int(state.get("cursor", 0))
6159
+ except (TypeError, ValueError):
6160
+ cursor = 0
6161
+ start = cursor % count if count and advance and state.get("basis") == basis else 0
6162
+ page, page_keys, skipped = [], set(), 0
 
 
 
 
 
 
 
 
 
 
 
 
6163
  with ThreadPoolExecutor(max_workers=LORA_PICK_PAGE) as workers:
6164
+ # Pinned means visible, not enabled. Keep general options through transient
6165
+ # link failures, but exclude confirmed invalid/incompatible files.
6166
+ for item, status in zip(pins, workers.map(_pick_probe, pins)):
6167
+ if status == "bad":
6168
+ skipped += 1
6169
+ continue
6170
+ page.append(item)
6171
+ page_keys.add(_pick_key(item))
6172
+ for item in (keep or [])[:2]:
6173
+ key = _pick_key(item)
6174
+ if key in page_keys:
6175
+ continue
6176
+ if _pick_probe(item) == "bad":
6177
+ skipped += 1
6178
+ continue
6179
+ page.append(item)
6180
+ page_keys.add(key)
6181
+ # Cursor counts catalogue positions INCLUDING held entries, so selections cannot
6182
+ # skew it. Five rotating candidates remain available even with several pinned entries.
6183
+ positions = [(start + offset) % count for offset in range(min(count, 20))]
6184
+ checked, added = 0, 0
6185
+ for offset in range(0, len(positions), LORA_PICK_PAGE):
6186
+ batch = [rotating[i] for i in positions[offset:offset + LORA_PICK_PAGE]]
6187
  statuses = list(workers.map(_pick_probe, batch))
6188
  for item, status in zip(batch, statuses):
6189
  checked += 1
6190
+ key = _pick_key(item)
6191
+ if key in page_keys:
6192
+ continue
6193
  if status in ("bad", "unavailable"):
6194
  skipped += 1
6195
+ continue
6196
+ page.append(item)
6197
+ page_keys.add(key)
6198
+ added += 1
6199
+ if added >= LORA_PICK_PAGE:
6200
  break
6201
+ if added >= LORA_PICK_PAGE:
6202
  break
6203
+ return page, ((start + checked) % count if count else 0), skipped, count + len(pins)
6204
 
6205
 
6206
  def _pick_text(text, picks, sheet=False):
 
6247
  page, cursor, skipped, available = _pick_page(basis, state, advance, keep=held)
6248
  held_keys = {_pick_key(item) for item in held}
6249
  kept = [i for i, item in enumerate(page) if _pick_key(item) in held_keys]
6250
+ if advance or kept:
6251
+ chosen = kept # Refresh is local: never book the writing model.
6252
+ else:
6253
+ eligible = [(i, item) for i, item in enumerate(page) if not _pick_all_in_one(item)]
6254
+ judged = _ask_which_loras(space_id, basis, [item for _, item in eligible])
6255
+ chosen = [eligible[i][0] for i in judged if 0 <= i < len(eligible)]
6256
  state.update(basis=basis, cursor=cursor, page=page)
6257
  detail = f"{len(page)} suggestions shown; {skipped} unavailable entries skipped."
6258
  if kept:
6259
  detail += f" {len(kept)} kept ticked; only the unticked ones were replaced."
6260
+ detail += (" Refresh uses no AI/GPU call, loops through up to 5 relevant candidates and returns to the beginning. "
6261
+ "General NSFW all-in-one entries stay visible; select them explicitly when needed.")
6262
  else:
6263
  page = list(state.get("page") or [])
6264
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
 
6306
  delete_cache=(3600, 259200)) as demo:
6307
  gr.HTML("<style>" + CSS + "</style>")
6308
  gr.HTML(HERO)
6309
+ with gr.Accordion("Runtime diagnostics", open=False):
6310
+ gr.Markdown("If the Space restarts or gets stuck, download this report and attach it to your bug report.")
6311
+ runtime_button = gr.Button("Check runtime / download report", size="sm")
6312
+ runtime_status = gr.Textbox(label="Current process and memory", interactive=False, lines=5)
6313
+ runtime_file = gr.File(label="Runtime report", interactive=False)
6314
+ runtime_button.click(runtime_report, None, [runtime_status, runtime_file], queue=False, show_progress="hidden")
6315
 
6316
  with gr.Group(elem_classes="panel"):
6317
  ui_mode = gr.Radio(
 
6338
  with gr.Tabs():
6339
  with gr.Tab("🖼️ Start frame"):
6340
  input_image_component = gr.Image(
6341
+ type="pil", label=None, show_label=False, elem_id="wan-start-image",
6342
  sources=["upload", "clipboard"], height=300,
6343
  )
6344
  with gr.Tab("🏁 End frame (optional)"):
6345
  last_image_component = gr.Image(
6346
+ type="pil", label=None, show_label=False, elem_id="wan-end-image",
6347
  sources=["upload", "clipboard"], height=300,
6348
  )
6349
 
 
6360
  "otherwise the app uses alignment checks."
6361
  )
6362
  identity_ref_component = gr.Image(
6363
+ type="pil", label="Photo of the person", height=160, elem_id="wan-identity-image",
6364
  sources=["upload", "clipboard"],
6365
  )
6366
  identity_check = gr.HTML("")
 
6384
  "**Picture in, a few words above, one press.** The prompt is "
6385
  "rewritten from your photo, the library is searched for effects "
6386
  "that match it, and their strengths are set. Whatever it picks "
6387
+ "is shown underneath. NEW: Refresh loops through relevant LoRAs; general NSFW all-in-one entries stay visible."
6388
  )
6389
  basic_btn = gr.Button("✨ Prepare prompt & effects", variant="primary",
6390
  elem_id="enhance-btn")
 
6399
  )
6400
  basic_links = gr.Markdown("")
6401
  basic_shortlist = gr.State({})
6402
+ basic_refresh_btn = gr.Button("🔄 Refresh — next group ↻", variant="secondary")
6403
 
6404
  with gr.Accordion("✨ Prompt Assist — build your shot", open=False,
6405
  visible=False) as pro_promptbuilder:
 
6811
  gpu_estimate_btn = gr.Button("🔄", variant="secondary", scale=1, min_width=60,
6812
  elem_id="estimate-btn")
6813
  safe_mode_checkbox = gr.Checkbox(
6814
+ label="🛠️ Safe Mode — extra time for slow or cold runs",
6815
+ value=False,
6816
+ info="Off restores the smaller normal reservation. On adds conservative margins "
6817
+ "and an adapter-loading reserve, which can exceed free quota. Enable it "
6818
+ "if a run reaches its time limit. Neither mode changes HF quota rates.",
6819
  )
6820
  with gr.Group(elem_classes="panel"):
6821
  video_output = gr.Video(
 
6878
  "only to matching clip prompts.",
6879
  )
6880
  scene_links = gr.Markdown("")
6881
+ scene_refresh_btn = gr.Button("🔄 Refresh — next group ↻", variant="secondary")
6882
  with gr.Row():
6883
  chain_count = gr.Slider(
6884
  1, MAX_SCENE_CLIPS, value=3, step=1, label="How many clips in a row",
 
7200
  except Exception as error:
7201
  headline = (f"the model was not available ({type(error).__name__}), so these "
7202
  "are the instant figures")
7203
+ finally:
7204
+ _release_enhancer_cpu()
7205
 
7206
  return [render_lora_reading(rows, headline)] + _lora_updates(rows, entries)
7207
 
 
7296
 
7297
  lora_auto_btn.click(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7298
  lora_auto_chk.change(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7299
+ lora_ai_btn.click(_read_effects_model, _LORA_READ_IN, _LORA_READ_OUT, concurrency_id="wan-heavy", concurrency_limit=1)
7300
 
7301
  # A prompt is retyped far more often than an effect is picked, so the reading follows
7302
  # the text box as well - on leaving it, not on every keystroke.
 
7420
  fn=add_sound,
7421
  inputs=[file_output, *_SOUND_INPUTS],
7422
  outputs=[video_output, file_output, sound_status],
7423
+ concurrency_id="wan-heavy", concurrency_limit=1,
7424
  )
7425
 
7426
+ _gen_start = generate_button.click(
7427
+ fn=lambda: (None, None, mark_running()[1]), inputs=None,
7428
+ outputs=[video_output, file_output, status_box], show_progress="hidden",
7429
+ )
7430
+ _gen_video = _gen_start.success(
7431
+ fn=generate_video, inputs=ui_inputs,
 
 
7432
  outputs=[video_output, file_output, seed_input, status_box],
7433
+ concurrency_id="wan-heavy", concurrency_limit=1,
7434
+ )
7435
+ _gen_persist = _gen_video.success(
7436
+ fn=lambda path: (_persist(path), gr.update())[1], inputs=[file_output],
7437
+ outputs=[status_box], show_progress="hidden",
7438
+ )
7439
+ _gen_sound = _gen_persist.success(
7440
+ fn=maybe_sound, inputs=[file_output, sound_auto, *_SOUND_INPUTS],
 
 
7441
  outputs=[video_output, file_output, sound_status],
7442
+ concurrency_id="wan-heavy", concurrency_limit=1,
 
 
 
 
7443
  )
7444
+ _gen_join = _gen_sound.success(
7445
+ fn=auto_queue, inputs=[file_output, auto_merge, merge_queue, merge_name],
7446
+ outputs=[merged_video, merged_file, merge_queue, merge_status], show_progress="hidden",
7447
+ concurrency_id="wan-heavy", concurrency_limit=1,
7448
+ )
7449
+ _gen_failed = _gen_video.failure(_generation_failed, None, [file_output, status_box], show_progress="hidden")
7450
+ _gen_events = [_gen_start, _gen_video, _gen_persist, _gen_sound, _gen_join, _gen_failed]
7451
 
7452
  clear_button.click(
7453
  fn=_clear_all,
 
7487
  fn=lambda path: boomerang(path, "full"),
7488
  inputs=[file_output],
7489
  outputs=[video_output, file_output],
7490
+ concurrency_id="wan-heavy", concurrency_limit=1,
7491
  )
7492
  boomerang_end_btn.click(
7493
  fn=lambda path, tail: boomerang(path, "ending", tail),
7494
  inputs=[file_output, boomerang_tail],
7495
  outputs=[video_output, file_output],
7496
+ concurrency_id="wan-heavy", concurrency_limit=1,
7497
  )
7498
 
7499
  merge_add_btn.click(
7500
  fn=add_to_queue,
7501
  inputs=[file_output, merge_queue, merge_name],
7502
  outputs=[merged_video, merged_file, merge_queue, merge_status],
7503
+ concurrency_id="wan-heavy", concurrency_limit=1,
7504
  )
7505
  merge_retry_btn.click(join_queued_clips, [merge_queue, merge_name],
7506
+ [merged_video, merged_file, merge_status], show_progress="minimal", concurrency_id="wan-heavy", concurrency_limit=1)
7507
  merge_clear_btn.click(
7508
  fn=clear_queue,
7509
  inputs=None,
 
7514
  # finished clip in the queue and hand back its last frame, generate from that frame with the settings
7515
  # untouched, then join the new clip on. `ui_inputs` starts with the image box, so the second step reads
7516
  # the still the first step just put there.
7517
+ _extend_start = extend_btn.click(
7518
  fn=lambda: mark_running("Continuing the scene\u2026")[1], inputs=None,
7519
  outputs=[status_box], show_progress="hidden",
7520
+ )
7521
+ _extend_stage = _extend_start.success(
7522
  fn=stage_extension,
7523
  inputs=[file_output, merge_queue, merge_name,
7524
  input_image_component, identity_ref_component],
7525
  outputs=[input_image_component, last_image_component, video_output,
7526
  merged_video, merged_file,
7527
  merge_queue, merge_status, identity_ref_component],
7528
+ concurrency_id="wan-heavy", concurrency_limit=1,
7529
+ )
7530
+ _extend_video = _extend_stage.success(
7531
  fn=generate_video_continued,
7532
  inputs=ui_inputs + [merge_queue],
7533
  outputs=[video_output, file_output, seed_input, status_box],
7534
+ concurrency_id="wan-heavy", concurrency_limit=1,
7535
+ )
7536
+ _extend_sound = _extend_video.success(
7537
  fn=maybe_sound,
7538
  inputs=[file_output, sound_auto, *_SOUND_INPUTS],
7539
  outputs=[video_output, file_output, sound_status],
7540
+ concurrency_id="wan-heavy", concurrency_limit=1,
7541
+ )
7542
+ _extend_join = _extend_sound.success(
7543
  fn=add_to_queue,
7544
  inputs=[file_output, merge_queue, merge_name],
7545
  outputs=[merged_video, merged_file, merge_queue, merge_status],
7546
  show_progress="hidden",
7547
+ concurrency_id="wan-heavy", concurrency_limit=1,
7548
+ )
7549
+
7550
+ _extend_failed = _extend_video.failure(_generation_failed, None, [file_output, status_box], show_progress="hidden")
7551
+ _extend_stage_failed = _extend_stage.failure(_generation_failed, None, [file_output, status_box], show_progress="hidden")
7552
+ _extend_events = [_extend_start, _extend_stage, _extend_video, _extend_sound, _extend_join,
7553
+ _extend_failed, _extend_stage_failed]
7554
+ stop_button.click(
7555
+ fn=lambda: "<div class='status-idle'>Stop requested. An active step may finish before releasing resources.</div>",
7556
+ inputs=None, outputs=[status_box], cancels=_gen_events + _extend_events,
7557
+ queue=False, show_progress="hidden",
7558
  )
7559
 
7560
  # One button, a whole scene: N clips in a row, each starting where the last one ended,
 
7578
  _chain_first = _chain_begin.success(scene_kick, [scene_state], [scene_tick, chain_btn],
7579
  show_progress="hidden")
7580
  _chain_step = scene_tick.change(scene_step, _scene_inputs, _scene_outputs,
7581
+ show_progress="hidden", trigger_mode="always_last", concurrency_id="wan-heavy", concurrency_limit=1)
7582
  _chain_next = _chain_step.success(scene_kick, [scene_state], [scene_tick, chain_btn],
7583
  show_progress="hidden")
7584
  _chain_failed = _chain_step.failure(scene_abort, [scene_state], [scene_state, status_box, chain_btn], show_progress="hidden")
 
7670
  guidance_scale_input, frame_multi, safe_mode_checkbox,
7671
  chain_count, sound_auto, sound_engine, sound_steps,
7672
  scene_seconds,
7673
+ *ui_inputs[16:53],
7674
+ guidance_scale_2_input,
7675
  ]
7676
  # Recalculated on demand only. An automatic readout means an event on every slider
7677
  # move, and a browser that never gets to rest.
 
7679
  fn=enhance_prompt,
7680
  inputs=[prompt_input, pb_use_model, pb_camera, pb_framing, pb_lighting, pb_pace, pb_quality],
7681
  outputs=[prompt_input, pb_status],
7682
+ concurrency_id="wan-heavy", concurrency_limit=1,
7683
  )
7684
 
7685
  # One press, one booking on the borrowed Space: the prompt comes back written from the
 
7692
  outputs=[prompt_input, pb_status] + _LORA_READ_OUT,
7693
  )
7694
 
7695
+ # Authentication is configured by the Space owner, separately from model downloads.
7696
+ # Public writer calls never inherit HF_TOKEN.
7697
  # One selection shared by prompt preparation and the scene planner.
7698
  _BASIC_SLOTS = [my1_repo, my1_high, my1_hs, my1_low, my1_ls,
7699
  my2_repo, my2_high, my2_hs, my2_low, my2_ls]
 
7782
  )
7783
 
7784
  if __name__ == "__main__":
7785
+ _runtime_event("server_start")
7786
+ threading.Thread(target=_runtime_heartbeat, name="wan-memory-log", daemon=True).start()
7787
  demo.queue().launch(
7788
  mcp_server=True,
7789
+ ssr_mode=False,
7790
  show_error=True,
7791
  )