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

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +306 -75
app.py CHANGED
@@ -2089,6 +2089,94 @@ def _require_local_lora_slots(groups):
2089
 
2090
 
2091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2092
  def get_inference_duration(
2093
  resized_image,
2094
  processed_last_image,
@@ -2106,7 +2194,8 @@ def get_inference_duration(
2106
  duration_seconds,
2107
  safe_mode,
2108
  lora_groups,
2109
- progress
 
2110
  ):
2111
  width, height = resized_image.size
2112
  factor = num_frames * width * height / (81 * 832 * 624)
@@ -2124,10 +2213,12 @@ def get_inference_duration(
2124
  # more RIFE time. No unconditional 60 s floor, 35/120 s adapter surcharge or 35% margin.
2125
  rife_seconds = extra_frames * (0.06 if multiplier <= 2 else 0.10)
2126
  requested = 10 + denoise_seconds + rife_seconds + _lora_loading_seconds(lora_groups)
2127
- return min(max(requested, 10.0), 600.0)
 
 
2128
 
2129
 
2130
- @spaces.GPU(duration=get_inference_duration, size='xlarge')
2131
  def run_inference(
2132
  resized_image,
2133
  processed_last_image,
@@ -2146,8 +2237,12 @@ def run_inference(
2146
  safe_mode=False,
2147
  lora_groups=None,
2148
  progress=gr.Progress(track_tqdm=True),
 
2149
  ):
2150
  gpu_clock = time.perf_counter()
 
 
 
2151
  _runtime_event("gpu_begin", frames=int(num_frames), fps=int(frame_multiplier))
2152
  try:
2153
  scheduler_class = SCHEDULER_MAP.get(scheduler_name, type(original_scheduler))
@@ -2238,38 +2333,18 @@ def run_inference(
2238
  rife_model.device()
2239
  rife_model.flownet = rife_model.flownet.half()
2240
  final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
2241
- # Interpolation executes lazily as the encoder requests each frame.
2242
  else:
2243
  final_frames = iter(raw_frames_np)
2244
 
2245
  final_fps = FIXED_FPS * int(frame_factor)
2246
 
2247
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
2248
- video_path = tmpfile.name
2249
-
2250
- start = time.time()
2251
- with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
2252
- pbar.update(2)
2253
- _runtime_event("rife_and_export" if frame_factor > 1 else "export")
2254
- tail = _stream_video(final_frames, video_path, fps=final_fps, quality=quality)
2255
- pbar.update(1)
2256
- print(f"Export time passed, {final_fps} FPS:", time.time() - start)
2257
-
2258
- # Keep the closing frame losslessly beside the clip. A chain that continues
2259
- # from the h264 file re-encodes the same picture again at every link, and the
2260
- # blocking and colour banding pile up clip after clip; continuing from this
2261
- # png instead means the tenth shot starts from the same quality as the first.
2262
- try:
2263
- tail = np.asarray(tail)
2264
- if tail.dtype != np.uint8:
2265
- tail = (tail * 255.0 if float(tail.max()) <= 1.001 else tail)
2266
- tail = tail.clip(0, 255).astype(np.uint8)
2267
- Image.fromarray(tail[..., :3]).save(video_path + ".last.png")
2268
- except Exception as error:
2269
- print(f"[chain] could not keep the closing frame: {error}", flush=True)
2270
-
2271
- _runtime_event("gpu_complete", elapsed_gpu_s=round(time.perf_counter() - gpu_clock, 3))
2272
- return video_path, task_name, list(lora_problems)
2273
  except BaseException as error:
2274
  _runtime_event("gpu_failed", error_type=type(error).__name__,
2275
  elapsed_gpu_s=round(time.perf_counter() - gpu_clock, 3))
@@ -2283,6 +2358,13 @@ def run_inference(
2283
  pipe.scheduler = original_scheduler
2284
  result = raw_frames_np = final_frames = None
2285
  clear_vram()
 
 
 
 
 
 
 
2286
 
2287
 
2288
  def generate_video(
@@ -2393,35 +2475,43 @@ def generate_video(
2393
  )
2394
  _runtime_event("gpu_reservation", requested_gpu_s=int(requested_seconds),
2395
  requested_quota_s=2 * int(requested_seconds), safe_mode=bool(safe_mode))
 
2396
  try:
2397
- inference = run_inference(
2398
- resized_image,
2399
- processed_last_image,
2400
- prompt,
2401
- steps,
2402
- negative_prompt,
2403
- num_frames,
2404
- guidance_scale,
2405
- guidance_scale_2,
2406
- current_seed,
2407
- scheduler,
2408
- flow_shift,
2409
- frame_multiplier,
2410
- quality,
2411
- duration_seconds,
2412
- safe_mode,
2413
- lora_groups,
2414
- progress,
2415
- )
2416
- except gr.Error:
2417
- raise
2418
- except Exception as error: # noqa: BLE001
2419
- # ZeroGPU speaks in stack traces. Say what happened and what to do about it.
2420
- message = _scene_trouble(error)
2421
- fit = _what_would_fit(str(error), resized_image, steps, duration_seconds,
2422
- guidance_scale, frame_multiplier, lora_groups=lora_groups)
2423
- raise gr.Error(message + fit) from error
2424
- video_path, task_n, lora_problems = inference
 
 
 
 
 
 
 
2425
  _record_wan_lora_failures(lora_groups, lora_problems)
2426
  if not lora_problems:
2427
  for _group in lora_groups:
@@ -2466,7 +2556,8 @@ def generate_video(
2466
  + speed_info +
2467
  identity_info +
2468
  lora_info +
2469
- f"<span>{elapsed:.1f} s</span>"
 
2470
  "</div>"
2471
  )
2472
 
@@ -5664,11 +5755,14 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5664
  groups = _estimate_lora_groups(adapter_values)
5665
  try:
5666
  guidance_low = float(adapter_values[37]) if len(adapter_values) > 37 else 1.0
 
 
 
5667
  num_frames = get_num_frames(float(duration_seconds))
5668
  w, h = _target_size(input_image)
5669
  secs = get_inference_duration(
5670
- _SizeOnly(w, h), None, "", steps, "", num_frames,
5671
- float(guidance_scale), guidance_low, 0, "UniPCMultistep", 3.0,
5672
  int(frame_multiplier), 5, float(duration_seconds),
5673
  bool(safe_mode), groups, None,
5674
  )
@@ -5703,8 +5797,8 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5703
  # In a chain the sound is added once, to the joined scene, not to every clip.
5704
  scene_video_cost = sum(
5705
  2 * int(get_inference_duration(
5706
- _SizeOnly(w, h), None, "", steps, "", get_num_frames(seconds),
5707
- float(guidance_scale), guidance_low, 0, "UniPCMultistep", 3.0,
5708
  int(frame_multiplier), 5, seconds, bool(safe_mode), groups, None,
5709
  )) for seconds in scene_durations
5710
  )
@@ -5722,7 +5816,7 @@ def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
5722
  "xlarge uses a 2× quota multiplier. Requested allowance is checked before generation; "
5723
  "this is not a receipt for actual GPU usage. Normal mode restores smaller reservations; "
5724
  "LoRA downloads finish on CPU before the GPU request; a size-based loading reserve is then added. "
5725
- "Unknown adapter sizes are checked before generation. Safe Mode adds extra runtime margin. Joining and looping do not book a GPU.</sub>"
5726
  )
5727
  return "\n".join(lines)
5728
 
@@ -6627,12 +6721,50 @@ def _pick_clean(text, records):
6627
  return "\n".join(lines)
6628
 
6629
 
6630
- def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6631
  import copy
6632
  state = copy.deepcopy(state) if isinstance(state, dict) else {}
6633
  prompt_text = _pick_clean(prompt_text, state.get("prompt_added"))
6634
  sheet_text = _pick_clean(sheet_text, state.get("sheet_added"))
6635
  old_picks = list(state.get("applied") or [])
 
 
 
6636
  if ticked is None:
6637
  basis = prompt_text if mode == "prompt" else (str(idea_text or "").strip() + "\n" + sheet_text).strip()
6638
  held = old_picks if advance else []
@@ -7783,7 +7915,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
7783
  if _event is not None:
7784
  _event(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7785
 
7786
- _simple_lora_event = simple_lora.change(
7787
  _apply_simple_loras, [simple_lora, simple_lora_strength], _SIMPLE_LORA_OUT
7788
  ).then(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7789
  # One button back to nothing selected. Without it the only way out is to pick the
@@ -8151,7 +8283,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8151
  chain_count, sound_auto, sound_engine, sound_steps,
8152
  scene_seconds,
8153
  *ui_inputs[16:53],
8154
- guidance_scale_2_input,
8155
  ]
8156
  # Recalculated on demand only. An automatic readout means an event on every slider
8157
  # move, and a browser that never gets to rest.
@@ -8177,9 +8309,9 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8177
  # One selection shared by prompt preparation and the scene planner.
8178
  _BASIC_SLOTS = [my1_repo, my1_high, my1_hs, my1_low, my1_ls,
8179
  my2_repo, my2_high, my2_hs, my2_low, my2_ls]
8180
- def _pick_ui(mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=None):
8181
  state, page, selected, note, prompt_text, sheet_text, picks, old_picks = _pick_result(
8182
- mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=ticked)
8183
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
8184
  link_rows = _pick_links(page, picks)
8185
 
@@ -8198,7 +8330,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8198
  built, linked = _split_picks(picks)
8199
  return [_choices_update(), _choices_update(), status, status,
8200
  _links_update(), _links_update(), state, prompt_text, sheet_text,
8201
- gr.update(value=list(built))] + _slot_updates(linked)
8202
 
8203
  def _pick_prompt(prompt_text, sheet_text, idea_text, space_id, state):
8204
  return _pick_ui("prompt", False, prompt_text, sheet_text, idea_text, space_id, state)
@@ -8215,17 +8347,115 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8215
  def _swap_pick(ticked, prompt_text, sheet_text, idea_text, space_id, state):
8216
  return _pick_ui("prompt", False, prompt_text, sheet_text, idea_text, space_id, state, ticked=ticked)
8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8218
  _PICK_INPUTS = [prompt_input, scene_prompts, scene_idea, pb_space, basic_shortlist]
8219
  _PICK_OUTPUTS = [basic_pick, scene_pick, basic_status, scene_pick_status, basic_links,
8220
- scene_links, basic_shortlist, prompt_input, scene_prompts] + [simple_lora] + _BASIC_SLOTS
 
8221
  _basic_prepared = basic_btn.click(
8222
- fn=_big_space_run,
8223
  inputs=([prompt_input, pb_space, input_image_component,
8224
- pb_camera, pb_framing, pb_lighting, pb_pace, pb_quality] + _LORA_READ_IN[1:]),
8225
- outputs=[prompt_input, basic_status] + _LORA_READ_OUT,
 
8226
  )
8227
  _pick_events = [
8228
- _basic_prepared.success(_pick_prompt, _PICK_INPUTS, _PICK_OUTPUTS, show_progress="hidden", concurrency_id="lora-picker"),
8229
  basic_refresh_btn.click(_refresh_prompt, _PICK_INPUTS, _PICK_OUTPUTS, show_progress="minimal", concurrency_id="lora-picker"),
8230
  scene_refresh_btn.click(_refresh_scene, _PICK_INPUTS, _PICK_OUTPUTS, show_progress="minimal", concurrency_id="lora-picker"),
8231
  basic_pick.input(_swap_pick, [basic_pick, *_PICK_INPUTS], _PICK_OUTPUTS, show_progress="hidden", concurrency_id="lora-picker", trigger_mode="always_last"),
@@ -8263,6 +8493,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
8263
  outputs=[gpu_estimate],
8264
  show_progress="hidden",
8265
  )
 
8266
  # Sitting under the numbers it changes, so the saving has to show without a second press.
8267
  safe_mode_checkbox.change(
8268
  fn=_gpu_estimate_text,
 
2089
 
2090
 
2091
 
2092
+
2093
+ def _timing_history(record=None):
2094
+ """Persist bounded, anonymous worker timings; never store prompts or media."""
2095
+ import fcntl
2096
+ path = os.path.join(globals().get('_RUNTIME_DIR') or tempfile.gettempdir(), 'wan22-timings-v1.json')
2097
+ try:
2098
+ with open(path, 'a+', encoding='utf-8') as stream:
2099
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX if record is not None else fcntl.LOCK_SH)
2100
+ stream.seek(0)
2101
+ try:
2102
+ rows=json.load(stream)
2103
+ if not isinstance(rows,list):rows=[]
2104
+ except (ValueError,TypeError):rows=[]
2105
+ if record is not None:
2106
+ rows=(rows+[record])[-200:]
2107
+ stream.seek(0);stream.truncate();json.dump(rows,stream);stream.flush()
2108
+ return rows
2109
+ except OSError:
2110
+ return []
2111
+
2112
+
2113
+ def _timing_estimate(key, work, fallback, minimum, maximum, margin=1.20):
2114
+ """Calibrate only from >=3 comparable successful runs of this exact path."""
2115
+ import math
2116
+ samples=[]
2117
+ for row in _timing_history():
2118
+ try:
2119
+ ratio=float(work)/float(row['work'])
2120
+ seconds=float(row['seconds'])
2121
+ if row['key']==key and .75<=ratio<=1.33 and math.isfinite(seconds) and seconds>0:
2122
+ samples.append(seconds*max(1.,ratio))
2123
+ except (KeyError,ValueError,TypeError,ZeroDivisionError):continue
2124
+ if len(samples)>=3:
2125
+ samples=sorted(samples[-20:])
2126
+ fallback=samples[math.ceil(.9*len(samples))-1]*margin+8
2127
+ return max(minimum,min(maximum,math.ceil(fallback)))
2128
+
2129
+
2130
+ def _timing_record(key,work,seconds):
2131
+ import math
2132
+ if math.isfinite(float(seconds)) and float(seconds)>0:
2133
+ _timing_history(dict(key=key,work=float(work),seconds=float(seconds)))
2134
+
2135
+
2136
+
2137
+ def _wan_timing_key(image,last_image,steps,guidance,guidance_low,scheduler,flow_shift,fps,loras):
2138
+ active=[g for g in (loras or ()) if _lora_slot_key(g)
2139
+ and any(float(g.get(role+'_scale',1.) or 0)!=0 for role in ('high','low'))]
2140
+ loaded_bytes=sum(g.get('_load_bytes') or _LORA_LOAD_INFO.get(_lora_slot_key(g),(0,0))[0] for g in active)
2141
+ return ['wan22-v1',int(image.width),int(image.height),bool(last_image is not None),int(steps),
2142
+ float(guidance),float(guidance_low),str(scheduler),float(flow_shift),int(fps),
2143
+ len(active),round(loaded_bytes/1048576)]
2144
+
2145
+
2146
+ def _spool_wan_frames(frames,directory,count,width,height):
2147
+ """Consume RIFE on GPU, preserving exactly the RGB bytes the old encoder saw."""
2148
+ path=os.path.join(directory,'frames.npy')
2149
+ mapped=np.lib.format.open_memmap(path,mode='w+',dtype=np.uint8,shape=(count,height,width,3))
2150
+ seen=0
2151
+ try:
2152
+ for frame in frames:
2153
+ rgb=_frame_u8(frame)
2154
+ if seen>=count or rgb.shape!=(height,width,3):raise ValueError('Unexpected interpolated frame shape/count.')
2155
+ mapped[seen]=rgb;seen+=1
2156
+ if seen!=count:raise ValueError('The interpolator returned an incomplete clip.')
2157
+ mapped.flush()
2158
+ finally:
2159
+ mapped._mmap.close()
2160
+ return path
2161
+
2162
+
2163
+ def _finish_wan_cpu(bundle,quality):
2164
+ """Encode after GPU release, retaining CRF/FPS and the lossless stitch tail."""
2165
+ started=time.perf_counter()
2166
+ frames=np.load(bundle['frames_path'],mmap_mode='r',allow_pickle=False)
2167
+ fd,path=tempfile.mkstemp(prefix='wan22-',suffix='.mp4');os.close(fd)
2168
+ try:
2169
+ tail=_stream_video(frames,path,fps=bundle['fps'],quality=quality)
2170
+ Image.fromarray(_frame_u8(tail)).save(path+'.last.png')
2171
+ return path,time.perf_counter()-started
2172
+ except BaseException:
2173
+ for part in (path,path+'.last.png'):
2174
+ if os.path.isfile(part):os.remove(part)
2175
+ raise
2176
+ finally:
2177
+ frames._mmap.close()
2178
+
2179
+
2180
  def get_inference_duration(
2181
  resized_image,
2182
  processed_last_image,
 
2194
  duration_seconds,
2195
  safe_mode,
2196
  lora_groups,
2197
+ progress,
2198
+ render_dir=None,
2199
  ):
2200
  width, height = resized_image.size
2201
  factor = num_frames * width * height / (81 * 832 * 624)
 
2213
  # more RIFE time. No unconditional 60 s floor, 35/120 s adapter surcharge or 35% margin.
2214
  rife_seconds = extra_frames * (0.06 if multiplier <= 2 else 0.10)
2215
  requested = 10 + denoise_seconds + rife_seconds + _lora_loading_seconds(lora_groups)
2216
+ return _timing_estimate(_wan_timing_key(resized_image,processed_last_image,steps,guidance_scale,guidance_scale_2,
2217
+ scheduler_name,flow_shift,frame_multiplier,lora_groups),num_frames,requested,10,600,
2218
+ margin=1.35 if safe_mode else 1.20)
2219
 
2220
 
2221
+ @spaces.GPU(duration=get_inference_duration, size="xlarge")
2222
  def run_inference(
2223
  resized_image,
2224
  processed_last_image,
 
2237
  safe_mode=False,
2238
  lora_groups=None,
2239
  progress=gr.Progress(track_tqdm=True),
2240
+ render_dir=None,
2241
  ):
2242
  gpu_clock = time.perf_counter()
2243
+ timing={}
2244
+ completed=False
2245
+ if not render_dir:raise gr.Error('Missing CPU export directory.')
2246
  _runtime_event("gpu_begin", frames=int(num_frames), fps=int(frame_multiplier))
2247
  try:
2248
  scheduler_class = SCHEDULER_MAP.get(scheduler_name, type(original_scheduler))
 
2333
  rife_model.device()
2334
  rife_model.flownet = rife_model.flownet.half()
2335
  final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
2336
+ # Interpolation is consumed into a raw disk buffer before GPU release.
2337
  else:
2338
  final_frames = iter(raw_frames_np)
2339
 
2340
  final_fps = FIXED_FPS * int(frame_factor)
2341
 
2342
+ output_count=(len(raw_frames_np)-1)*frame_factor+1
2343
+ _runtime_event('rife_and_handoff' if frame_factor>1 else 'cpu_handoff')
2344
+ frames_path=_spool_wan_frames(final_frames,render_dir,output_count,resized_image.width,resized_image.height)
2345
+ torch.cuda.synchronize()
2346
+ completed=True
2347
+ return dict(frames_path=frames_path,fps=final_fps),task_name,list(lora_problems),timing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2348
  except BaseException as error:
2349
  _runtime_event("gpu_failed", error_type=type(error).__name__,
2350
  elapsed_gpu_s=round(time.perf_counter() - gpu_clock, 3))
 
2358
  pipe.scheduler = original_scheduler
2359
  result = raw_frames_np = final_frames = None
2360
  clear_vram()
2361
+ if completed:
2362
+ elapsed=time.perf_counter()-gpu_clock
2363
+ timing['gpu_seconds']=elapsed
2364
+ if not lora_problems:
2365
+ _timing_record(_wan_timing_key(resized_image,processed_last_image,steps,guidance_scale,guidance_scale_2,
2366
+ scheduler_name,flow_shift,frame_multiplier,lora_groups),num_frames,elapsed)
2367
+ _runtime_event('gpu_complete',elapsed_gpu_s=round(elapsed,3))
2368
 
2369
 
2370
  def generate_video(
 
2475
  )
2476
  _runtime_event("gpu_reservation", requested_gpu_s=int(requested_seconds),
2477
  requested_quota_s=2 * int(requested_seconds), safe_mode=bool(safe_mode))
2478
+ render_dir=tempfile.mkdtemp(prefix='wan22-frames-')
2479
  try:
2480
+ try:
2481
+ inference = run_inference(
2482
+ resized_image,
2483
+ processed_last_image,
2484
+ prompt,
2485
+ steps,
2486
+ negative_prompt,
2487
+ num_frames,
2488
+ guidance_scale,
2489
+ guidance_scale_2,
2490
+ current_seed,
2491
+ scheduler,
2492
+ flow_shift,
2493
+ frame_multiplier,
2494
+ quality,
2495
+ duration_seconds,
2496
+ safe_mode,
2497
+ lora_groups,
2498
+ progress,
2499
+ render_dir=render_dir,
2500
+ )
2501
+ except gr.Error:
2502
+ raise
2503
+ except Exception as error: # noqa: BLE001
2504
+ # ZeroGPU speaks in stack traces. Say what happened and what to do about it.
2505
+ message = _scene_trouble(error)
2506
+ fit = _what_would_fit(str(error), resized_image, steps, duration_seconds,
2507
+ guidance_scale, frame_multiplier, lora_groups=lora_groups)
2508
+ raise gr.Error(message + fit) from error
2509
+ bundle,task_n,lora_problems,timing=inference
2510
+ progress(.98,desc='Saving MP4 · GPU released')
2511
+ video_path,encode_seconds=_finish_wan_cpu(bundle,quality)
2512
+ _runtime_event('cpu_encode_complete',encode_seconds=round(encode_seconds,2))
2513
+ finally:
2514
+ shutil.rmtree(render_dir,ignore_errors=True)
2515
  _record_wan_lora_failures(lora_groups, lora_problems)
2516
  if not lora_problems:
2517
  for _group in lora_groups:
 
2556
  + speed_info +
2557
  identity_info +
2558
  lora_info +
2559
+ f"<span>{elapsed:.1f} s total</span>"
2560
+ f"<span>GPU worker {timing['gpu_seconds']:.1f} s · CPU MP4 {encode_seconds:.1f} s</span>"
2561
  "</div>"
2562
  )
2563
 
 
5755
  groups = _estimate_lora_groups(adapter_values)
5756
  try:
5757
  guidance_low = float(adapter_values[37]) if len(adapter_values) > 37 else 1.0
5758
+ scheduler_name = str(adapter_values[38]) if len(adapter_values) > 38 else "UniPCMultistep"
5759
+ flow_shift_value = float(adapter_values[39]) if len(adapter_values) > 39 else 6.0
5760
+ ending_image = adapter_values[40] if len(adapter_values) > 40 else None
5761
  num_frames = get_num_frames(float(duration_seconds))
5762
  w, h = _target_size(input_image)
5763
  secs = get_inference_duration(
5764
+ _SizeOnly(w, h), ending_image, "", steps, "", num_frames,
5765
+ float(guidance_scale), guidance_low, 0, scheduler_name, flow_shift_value,
5766
  int(frame_multiplier), 5, float(duration_seconds),
5767
  bool(safe_mode), groups, None,
5768
  )
 
5797
  # In a chain the sound is added once, to the joined scene, not to every clip.
5798
  scene_video_cost = sum(
5799
  2 * int(get_inference_duration(
5800
+ _SizeOnly(w, h), ending_image, "", steps, "", get_num_frames(seconds),
5801
+ float(guidance_scale), guidance_low, 0, scheduler_name, flow_shift_value,
5802
  int(frame_multiplier), 5, seconds, bool(safe_mode), groups, None,
5803
  )) for seconds in scene_durations
5804
  )
 
5816
  "xlarge uses a 2× quota multiplier. Requested allowance is checked before generation; "
5817
  "this is not a receipt for actual GPU usage. Normal mode restores smaller reservations; "
5818
  "LoRA downloads finish on CPU before the GPU request; a size-based loading reserve is then added. "
5819
+ "Unknown adapter sizes are checked before generation. Safe Mode adds extra runtime margin. MP4 encoding runs after GPU release; RIFE remains on GPU. Limits calibrate from 3 comparable completed runs. Joining and looping do not book a GPU.</sub>"
5820
  )
5821
  return "\n".join(lines)
5822
 
 
6721
  return "\n".join(lines)
6722
 
6723
 
6724
+
6725
+ def _prepare_reply_parts(reply):
6726
+ text=re.sub(r'<think>.*?</think>','',str(reply or ''),flags=re.S).strip()
6727
+ if '</think>' in text:text=text.split('</think>',1)[-1].strip()
6728
+ matches=list(re.finditer(r'(?im)^\s*(?:\*\*)?(PROMPT|STRENGTHS|PICKS)(?:\*\*)?\s*:\s*',text))
6729
+ return {m.group(1).upper():text[m.end():matches[i+1].start() if i+1<len(matches) else len(text)].strip().strip('`\n ')
6730
+ for i,m in enumerate(matches)}
6731
+
6732
+
6733
+ def _prepare_numbers(text,count,fields=('strength',)):
6734
+ import math
6735
+ try:
6736
+ start=text.index('[');data,_=json.JSONDecoder().raw_decode(text[start:])
6737
+ if not isinstance(data,list):return None
6738
+ except (TypeError,ValueError):return None
6739
+ result={}
6740
+ for item in data:
6741
+ try:
6742
+ if not isinstance(item,dict):continue
6743
+ n=item.get('n')
6744
+ values={field:float(item[field]) for field in fields}
6745
+ if type(n) is int and 1<=n<=count and all(math.isfinite(v) and .2<=v<=1.3 for v in values.values()):
6746
+ result[n-1]={**values,'why':str(item.get('why',''))[:120]}
6747
+ except (KeyError,ValueError,TypeError):continue
6748
+ return result if result or not data else None
6749
+
6750
+
6751
+ def _prepare_choice(page,state,picked,basis,cursor):
6752
+ old={_pick_key(item) for item in (state or {}).get('applied',[])}
6753
+ held=[i for i,item in enumerate(page) if _pick_key(item) in old]
6754
+ chosen=held if picked is None else [i for i in held if _pick_all_in_one(page[i])]
6755
+ if picked is not None:chosen += [i for i in picked if not _pick_all_in_one(page[i]) and i not in chosen]
6756
+ return dict(page=page,chosen=chosen[:2],basis=basis,cursor=cursor)
6757
+
6758
+
6759
+ def _pick_result(mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=None, prepared=None):
6760
  import copy
6761
  state = copy.deepcopy(state) if isinstance(state, dict) else {}
6762
  prompt_text = _pick_clean(prompt_text, state.get("prompt_added"))
6763
  sheet_text = _pick_clean(sheet_text, state.get("sheet_added"))
6764
  old_picks = list(state.get("applied") or [])
6765
+ if prepared is not None:
6766
+ state.update(page=prepared['page'],cursor=prepared['cursor'],basis=prepared['basis'])
6767
+ ticked=[_pick_label(i,prepared['page'][i]) for i in prepared['chosen']]
6768
  if ticked is None:
6769
  basis = prompt_text if mode == "prompt" else (str(idea_text or "").strip() + "\n" + sheet_text).strip()
6770
  held = old_picks if advance else []
 
7915
  if _event is not None:
7916
  _event(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7917
 
7918
+ _simple_lora_event = simple_lora.input(
7919
  _apply_simple_loras, [simple_lora, simple_lora_strength], _SIMPLE_LORA_OUT
7920
  ).then(_read_effects, _LORA_READ_IN, _LORA_READ_OUT)
7921
  # One button back to nothing selected. Without it the only way out is to pick the
 
8283
  chain_count, sound_auto, sound_engine, sound_steps,
8284
  scene_seconds,
8285
  *ui_inputs[16:53],
8286
+ guidance_scale_2_input, scheduler_dropdown, flow_shift_slider, last_image_component,
8287
  ]
8288
  # Recalculated on demand only. An automatic readout means an event on every slider
8289
  # move, and a browser that never gets to rest.
 
8309
  # One selection shared by prompt preparation and the scene planner.
8310
  _BASIC_SLOTS = [my1_repo, my1_high, my1_hs, my1_low, my1_ls,
8311
  my2_repo, my2_high, my2_hs, my2_low, my2_ls]
8312
+ def _pick_ui(mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=None, prepared=None):
8313
  state, page, selected, note, prompt_text, sheet_text, picks, old_picks = _pick_result(
8314
+ mode, advance, prompt_text, sheet_text, idea_text, space_id, state, ticked=ticked, prepared=prepared)
8315
  labels = [_pick_label(i, item) for i, item in enumerate(page)]
8316
  link_rows = _pick_links(page, picks)
8317
 
 
8330
  built, linked = _split_picks(picks)
8331
  return [_choices_update(), _choices_update(), status, status,
8332
  _links_update(), _links_update(), state, prompt_text, sheet_text,
8333
+ gr.update(value=list(built))] + _slot_updates(linked) + [gr.update(value=name) for name in (built + ["(None)"] * 3)[:3]]
8334
 
8335
  def _pick_prompt(prompt_text, sheet_text, idea_text, space_id, state):
8336
  return _pick_ui("prompt", False, prompt_text, sheet_text, idea_text, space_id, state)
 
8347
  def _swap_pick(ticked, prompt_text, sheet_text, idea_text, space_id, state):
8348
  return _pick_ui("prompt", False, prompt_text, sheet_text, idea_text, space_id, state, ticked=ticked)
8349
 
8350
+ def _prepare_wan(prompt, space_id, image, camera, framing, lighting, pace, add_quality,
8351
+ picked, preset1, preset2, preset3, auto_on, base_strength, identity_at,
8352
+ c1r, c1h, c1l, c2r, c2h, c2l, c3r, c3h, c3l,
8353
+ c4r, c4h, c4l, c5r, c5h, c5l, sheet, idea, state, *scales,
8354
+ progress=gr.Progress()):
8355
+ """One writer submission; invalid sections never trigger another AI request."""
8356
+ import copy
8357
+ from html import escape
8358
+ space = str(space_id or '').strip()
8359
+ if not space:
8360
+ raise gr.Error('Put your chat Space in the writer box first: owner/space-name.')
8361
+ state = copy.deepcopy(state or {})
8362
+ clean = _pick_clean(prompt, state.get('prompt_added'))
8363
+ built = build_prompt(clean, camera, framing, lighting, pace, add_quality)
8364
+ customs = [(c1r,c1h,c1l),(c2r,c2h,c2l),(c3r,c3h,c3l),(c4r,c4h,c4l),(c5r,c5h,c5l)]
8365
+ entries = _lora_entries(picked,preset1,preset2,preset3,customs)
8366
+ rows = score_lora_rows(_lora_rows(entries),clean,identity_at,base=base_strength)
8367
+ page,cursor,_,_ = _pick_page(clean,state,False,keep=state.get('applied',[]))
8368
+ page = copy.deepcopy(page)
8369
+ # Keep file references separate from the numeric high/low figures in the reply.
8370
+ candidates = [{'n':i+1,'name':item.get('name',''),
8371
+ 'description':str(item.get('desc') or item.get('description') or '')[:250],
8372
+ 'eligible':not _pick_all_in_one(item)} for i,item in enumerate(page)]
8373
+ message = _big_space_message(built,rows,image is not None)
8374
+ message = message.replace('You have two jobs. Answer with the two labelled parts below and nothing else.',
8375
+ 'Write the prompt, tune existing adapters and choose relevant adapters in one response.')
8376
+ message += ('\nJOB 3 - SELECT UP TO TWO CANDIDATES. Return [] if none helps. '
8377
+ 'Never select an entry with eligible=false. Choose complementary adapters; avoid duplicates. '
8378
+ 'For each choice provide high and low strengths in 0.2–1.3.\nCANDIDATES\n'
8379
+ + json.dumps(candidates,ensure_ascii=False)
8380
+ + '\nReturn exactly three sections: PROMPT: <paragraph>\n'
8381
+ 'STRENGTHS: [{"n":1,"high":0.9,"low":0.6,"why":"brief reason"}]\n'
8382
+ 'PICKS: [{"n":1,"high":0.8,"low":0.5,"why":"brief reason"}]\n'
8383
+ 'STRENGTHS numbers refer to existing ADAPTERS; PICKS numbers refer to CANDIDATES. '
8384
+ 'Use [] for an empty section. Preserve requested actions and exact dialogue.')
8385
+ updates = {component:gr.update() for component in _PREPARE_OUTPUTS}
8386
+ try:
8387
+ progress(.1,desc=f'Preparing prompt and LoRAs with {space}...')
8388
+ reply = _remote_ask(space,message,image,max_new_tokens=2304)
8389
+ except Exception as error:
8390
+ note = "<div class='status-idle'>Preparation failed; your settings were kept. " + escape(str(error)[:240]) + '</div>'
8391
+ updates[basic_status]=updates[scene_pick_status]=note
8392
+ return [updates[c] for c in _PREPARE_OUTPUTS]
8393
+ parts = _prepare_reply_parts(reply)
8394
+ paragraph = parts.get('PROMPT','')
8395
+ valid_prompt = len(paragraph) >= 40
8396
+ written = paragraph if valid_prompt else clean
8397
+ strengths = _prepare_numbers(parts.get('STRENGTHS',''),len(rows),('high','low'))
8398
+ choices = _prepare_numbers(parts.get('PICKS',''),len(page),('high','low'))
8399
+ if choices is not None:
8400
+ for i,values in choices.items():
8401
+ if not _pick_all_in_one(page[i]):
8402
+ page[i].update(strength=_round_step(values['high']),low_strength=_round_step(values['low']))
8403
+ prepared = _prepare_choice(page,state,choices,clean,cursor)
8404
+ state['prompt_added']=[]
8405
+ result = _pick_ui('prompt',False,written,sheet,idea,space,state,prepared=prepared)
8406
+ updates.update(zip(_PICK_OUTPUTS,result))
8407
+ active = result[6].get('applied',[])
8408
+ builtin,linked = _split_picks(active)
8409
+ new_customs = [(p.get('url',''),p.get('high') or p.get('url',''),p.get('low','')) for p in linked]
8410
+ new_customs += [('','','')] * (2-len(new_customs))
8411
+ final_entries = _lora_entries(builtin,*(builtin+['(None)']*3)[:3],new_customs+customs[2:])
8412
+ final_rows = _lora_rows(final_entries)
8413
+ picked_by_ref = {p.get('name') if p.get('builtin') else p.get('url'):p for p in active}
8414
+ else:
8415
+ # A missing or malformed PICKS section preserves every manual and selected slot.
8416
+ active = list(state.get('applied',[])) + list(state.get('extra_picks',[]))
8417
+ written,added = _pick_text(written,active)
8418
+ state['prompt_added']=added
8419
+ updates[prompt_input]=written
8420
+ updates[basic_shortlist]=state
8421
+ final_entries,final_rows=entries,rows
8422
+ picked_by_ref={}
8423
+ existing = {entry['ref']:(i,entry) for i,entry in enumerate(entries)}
8424
+ for row,entry in zip(final_rows,final_entries):
8425
+ row['high']=row['low']=None
8426
+ row['why']='existing strength kept'
8427
+ old = existing.get(entry['ref'])
8428
+ chosen = picked_by_ref.get(entry['ref'])
8429
+ values = (strengths or {}).get(old[0]) if old and auto_on else None
8430
+ if values is None and chosen and any(not _pick_all_in_one(page[i]) and _pick_key(chosen)==_pick_key(page[i]) for i in (choices or {})):
8431
+ values={'high':chosen['strength'],'low':chosen['low_strength'],'why':'chosen in the same AI request'}
8432
+ if values is not None:
8433
+ row.update(high=_round_step(values['high']),low=_round_step(values['low']),why=values.get('why',''))
8434
+ updates[_LORA_READ_OUT[1+entry['out']]]=gr.update(value=row['high'])
8435
+ updates[_LORA_READ_OUT[2+entry['out']]]=gr.update(value=row['low'])
8436
+ elif old and len(scales)==16:
8437
+ # Moving an existing adapter to another slot must not reset its manual scales.
8438
+ updates[_LORA_READ_OUT[1+entry['out']]]=gr.update(value=scales[old[1]['out']])
8439
+ updates[_LORA_READ_OUT[2+entry['out']]]=gr.update(value=scales[old[1]['out']+1])
8440
+ note = ('Prepared with one AI request. ' if valid_prompt else 'Prompt section was invalid; your wording was kept. ')
8441
+ if choices is None: note += 'LoRA selection was kept because PICKS was missing or invalid. '
8442
+ if strengths is None: note += 'Existing LoRA strengths were kept. '
8443
+ updates[basic_status]=updates[scene_pick_status]="<div class='status-ok'><span>"+escape(note)+'</span></div>'
8444
+ updates[simple_lora_about]=render_lora_reading(final_rows,'one request to '+space)
8445
+ return [updates[c] for c in _PREPARE_OUTPUTS]
8446
+
8447
  _PICK_INPUTS = [prompt_input, scene_prompts, scene_idea, pb_space, basic_shortlist]
8448
  _PICK_OUTPUTS = [basic_pick, scene_pick, basic_status, scene_pick_status, basic_links,
8449
+ scene_links, basic_shortlist, prompt_input, scene_prompts] + [simple_lora] + _BASIC_SLOTS + [lora1_preset, lora2_preset, lora3_preset]
8450
+ _PREPARE_OUTPUTS = list(dict.fromkeys(_PICK_OUTPUTS + _LORA_READ_OUT))
8451
  _basic_prepared = basic_btn.click(
8452
+ fn=_prepare_wan,
8453
  inputs=([prompt_input, pb_space, input_image_component,
8454
+ pb_camera, pb_framing, pb_lighting, pb_pace, pb_quality] + _LORA_READ_IN[1:]
8455
+ + [scene_prompts, scene_idea, basic_shortlist] + _LORA_READ_OUT[1:]),
8456
+ outputs=_PREPARE_OUTPUTS, concurrency_id="lora-picker", concurrency_limit=1,
8457
  )
8458
  _pick_events = [
 
8459
  basic_refresh_btn.click(_refresh_prompt, _PICK_INPUTS, _PICK_OUTPUTS, show_progress="minimal", concurrency_id="lora-picker"),
8460
  scene_refresh_btn.click(_refresh_scene, _PICK_INPUTS, _PICK_OUTPUTS, show_progress="minimal", concurrency_id="lora-picker"),
8461
  basic_pick.input(_swap_pick, [basic_pick, *_PICK_INPUTS], _PICK_OUTPUTS, show_progress="hidden", concurrency_id="lora-picker", trigger_mode="always_last"),
 
8493
  outputs=[gpu_estimate],
8494
  show_progress="hidden",
8495
  )
8496
+ _basic_prepared.success(_gpu_estimate_text, _ESTIMATE_INPUTS, gpu_estimate, show_progress="hidden")
8497
  # Sitting under the numbers it changes, so the saving has to show without a second press.
8498
  safe_mode_checkbox.change(
8499
  fn=_gpu_estimate_text,