Spaces:
Running on Zero
Running on Zero
Upload 13 files
Browse files- .gitattributes +1 -0
- PERFORMANCE_FIX_BG.md +58 -0
- app.py +189 -42
- extend-proof.jpg +3 -0
- gitattributes +35 -0
- lora_loader.py +33 -3
- stitch_cache.py +256 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
extend-proof.jpg filter=lfs diff=lfs merge=lfs -text
|
PERFORMANCE_FIX_BG.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Поправка на Wan 2.2 Studio — 17 октомври 2026
|
| 2 |
+
|
| 3 |
+
## Поставяне в Space
|
| 4 |
+
|
| 5 |
+
В `amisima/Wan_2.2_I2V_Studio` замени `app.py` и `lora_loader.py` и добави
|
| 6 |
+
`stitch_cache.py` в същата основна папка. Останалите оригинални файлове са
|
| 7 |
+
включени за пълнота. След обновяването Space трябва да се рестартира/изгради.
|
| 8 |
+
|
| 9 |
+
Тази версия НЕ е качена в работещия Space: настроеният Hugging Face вход е
|
| 10 |
+
`amisima2`, а проверката за запис в посочения Space върна HTTP 403.
|
| 11 |
+
Не е правен опит за запис след отказа.
|
| 12 |
+
|
| 13 |
+
## Какво е поправено
|
| 14 |
+
|
| 15 |
+
- Подготовката на Extend, съединяването и другата CPU видеообработка използват
|
| 16 |
+
отделна опашка. В оригинала чакаха зад GPU генерации на всички посетители.
|
| 17 |
+
- При изключен „Sound on every clip“ Generate и Extend преминават направо към
|
| 18 |
+
съединяване. Не влизат отново в GPU опашката за празна аудиооперация.
|
| 19 |
+
- Вече подготвените части се използват повторно при следващ stitch. Кешът
|
| 20 |
+
е ограничен до 2 GiB/128 части, с изтичане след 6 часа без използване.
|
| 21 |
+
Смяна на източник, размер, FPS, аудио или цветова корекция обновява частите.
|
| 22 |
+
- Ограничени са CPU нишките за видеообработка; добавени са измервания за
|
| 23 |
+
отделните етапи. Параметрите за качество на крайния файл са запазени.
|
| 24 |
+
- Всяка генерация получава отделен scheduler; изчистването на LoRA и VAE
|
| 25 |
+
обхваща и грешките. Неуспешно изчистване не допуска мълчаливо повторно
|
| 26 |
+
използване на останал адаптер.
|
| 27 |
+
|
| 28 |
+
Генерациите и включеното аудио остават последователни, защото споделят модела.
|
| 29 |
+
Поправката не премахва чакането за свободен GPU при натоварен публичен Space.
|
| 30 |
+
|
| 31 |
+
## Измерени резултати
|
| 32 |
+
|
| 33 |
+
Реалните тестове по-долу са върху ОРИГИНАЛНИЯ работещ Space, с неутрален
|
| 34 |
+
пейзаж, 640×480, 53 кадъра, 16 FPS, 6 стъпки, без LoRA и без звук.
|
| 35 |
+
|
| 36 |
+
| Тест | GPU обработка | CPU MP4 |
|
| 37 |
+
| --- | ---: | ---: |
|
| 38 |
+
| Generate 1 | 12,680 s | 0,640 s |
|
| 39 |
+
| Generate 2 | 12,943 s | 0,700 s |
|
| 40 |
+
| Extend 1 | 12,899 s | 0,770 s |
|
| 41 |
+
| Extend 2 | 12,911 s | 0,640 s |
|
| 42 |
+
|
| 43 |
+
Първият Extend чака около 80 секунди преди обработката, зад друга заявка.
|
| 44 |
+
Самата му генерация е 14,0 секунди; втората е 14,1 секунди. И двете удължавания
|
| 45 |
+
успяха и крайният резултат съдържа 3 клипа. В тези тестове не се повтори
|
| 46 |
+
забавяне само от факта, че генерацията е втора. Това не изключва проблем при
|
| 47 |
+
други размери, по-дълги клипове, други настройки или LoRA.
|
| 48 |
+
|
| 49 |
+
Локални CPU тестове на поправения код провериха съвпадение на декодираните
|
| 50 |
+
видео кадри и аудио, смесени размери/FPS, цветови корекции и изчистване при
|
| 51 |
+
грешка. На малките тестови клипове повторният stitch спадна от 0,941 на
|
| 52 |
+
0,061 секунди; добавянето на трети клип — от 1,403 на 0,410 секунди.
|
| 53 |
+
Тези числа не са измерване на скоростта на Hugging Face машината.
|
| 54 |
+
|
| 55 |
+
Преминаха и 23 проверки на LoRA изчистването, изолирането на състоянието при
|
| 56 |
+
генерация и новото разпределение на опашките. Поправената версия все още няма
|
| 57 |
+
реален GPU тест след качване. `extend-proof.jpg` показва успешния браузърен
|
| 58 |
+
Extend тест върху оригиналната версия.
|
app.py
CHANGED
|
@@ -12,8 +12,11 @@ import time
|
|
| 12 |
import gc
|
| 13 |
import uuid
|
| 14 |
import threading
|
|
|
|
|
|
|
| 15 |
from tqdm import tqdm
|
| 16 |
import cv2
|
|
|
|
| 17 |
import numpy as np
|
| 18 |
import torch
|
| 19 |
import torch._dynamo
|
|
@@ -32,6 +35,43 @@ _BOOT_ID = uuid.uuid4().hex[:12]
|
|
| 32 |
_WEB_PID = os.getpid()
|
| 33 |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def _runtime_dir():
|
| 36 |
for root in ("/data", "/bucket", tempfile.gettempdir()):
|
| 37 |
if not os.path.isdir(root):
|
|
@@ -61,13 +101,19 @@ def _memory_snapshot():
|
|
| 61 |
result[key.rstrip(":") + "_MiB"] = round(int(value) / 1024, 1)
|
| 62 |
except (OSError, ValueError):
|
| 63 |
pass
|
| 64 |
-
for name in ("memory.current", "memory.peak", "memory.max", "memory.events"
|
|
|
|
| 65 |
try:
|
| 66 |
with open("/sys/fs/cgroup/" + name) as handle:
|
| 67 |
value = handle.read(4096).strip()
|
| 68 |
if name == "memory.events":
|
| 69 |
result["cgroup_events"] = dict((k, int(v)) for k, v in
|
| 70 |
(line.split() for line in value.splitlines()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
else:
|
| 72 |
result[name + "_MiB"] = round(int(value) / 1048576, 1) if value.isdigit() else value
|
| 73 |
except (OSError, ValueError):
|
|
@@ -175,6 +221,7 @@ def _stream_video(frames, video_path, fps, quality):
|
|
| 175 |
height, width = first.shape[:2]
|
| 176 |
crf = int((1 - min(10.0, max(1.0, float(quality))) / 10) * 51)
|
| 177 |
command = [_ffmpeg_exe(), "-hide_banner", "-loglevel", "error", "-y",
|
|
|
|
| 178 |
"-f", "rawvideo", "-vcodec", "rawvideo", "-s", f"{width}x{height}",
|
| 179 |
"-pix_fmt", "rgb24", "-r", str(fps), "-i", "pipe:0", "-an",
|
| 180 |
"-c:v", "libx264", "-threads", "2", "-crf", str(crf),
|
|
@@ -223,8 +270,9 @@ def _stream_video(frames, video_path, fps, quality):
|
|
| 223 |
iterator.close()
|
| 224 |
|
| 225 |
|
|
|
|
| 226 |
def _concat_duration(path):
|
| 227 |
-
capture =
|
| 228 |
try:
|
| 229 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0)
|
| 230 |
frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
|
@@ -332,7 +380,7 @@ def extract_frame(video_path, timestamp):
|
|
| 332 |
|
| 333 |
print(f"Extracting frame at timestamp: {timestamp}")
|
| 334 |
|
| 335 |
-
cap =
|
| 336 |
|
| 337 |
if not cap.isOpened():
|
| 338 |
return None
|
|
@@ -2250,16 +2298,25 @@ def run_inference(
|
|
| 2250 |
timing={}
|
| 2251 |
completed=False
|
| 2252 |
if not render_dir:raise gr.Error('Missing CPU export directory.')
|
| 2253 |
-
_runtime_event("gpu_begin", frames=int(num_frames), fps=int(frame_multiplier)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2254 |
try:
|
|
|
|
|
|
|
| 2255 |
scheduler_class = SCHEDULER_MAP.get(scheduler_name, type(original_scheduler))
|
| 2256 |
-
|
| 2257 |
-
|
| 2258 |
-
|
| 2259 |
-
|
| 2260 |
-
|
| 2261 |
-
|
| 2262 |
-
|
|
|
|
|
|
|
|
|
|
| 2263 |
|
| 2264 |
clear_vram()
|
| 2265 |
|
|
@@ -2303,13 +2360,16 @@ def run_inference(
|
|
| 2303 |
print(f"lora warning: {e}")
|
| 2304 |
lora_problems = [str(e)[:200]]
|
| 2305 |
try:
|
| 2306 |
-
lora_loader.unload_lora(pipe)
|
| 2307 |
-
except Exception:
|
| 2308 |
-
|
|
|
|
|
|
|
| 2309 |
|
| 2310 |
_runtime_event("adapters_ready", load_wall_s=round(time.perf_counter() - adapter_start, 2),
|
| 2311 |
adapter_mib=round(sum(g.get("_load_bytes", 0) for g in lora_groups or []) / 1048576, 1))
|
| 2312 |
_runtime_event("denoise_and_decode")
|
|
|
|
| 2313 |
result = pipe(
|
| 2314 |
image=resized_image,
|
| 2315 |
last_image=processed_last_image,
|
|
@@ -2325,8 +2385,10 @@ def run_inference(
|
|
| 2325 |
output_type="np"
|
| 2326 |
)
|
| 2327 |
|
|
|
|
|
|
|
| 2328 |
if lora_loaded:
|
| 2329 |
-
lora_loader.unload_lora(pipe)
|
| 2330 |
|
| 2331 |
print("gen time passed:", time.time() - start)
|
| 2332 |
|
|
@@ -2348,7 +2410,9 @@ def run_inference(
|
|
| 2348 |
|
| 2349 |
output_count=(len(raw_frames_np)-1)*frame_factor+1
|
| 2350 |
_runtime_event('rife_and_handoff' if frame_factor>1 else 'cpu_handoff')
|
|
|
|
| 2351 |
frames_path=_spool_wan_frames(final_frames,render_dir,output_count,resized_image.width,resized_image.height)
|
|
|
|
| 2352 |
torch.cuda.synchronize()
|
| 2353 |
completed=True
|
| 2354 |
return dict(frames_path=frames_path,fps=final_fps),task_name,list(lora_problems),timing
|
|
@@ -2359,12 +2423,21 @@ def run_inference(
|
|
| 2359 |
finally:
|
| 2360 |
try:
|
| 2361 |
if lora_groups:
|
| 2362 |
-
lora_loader.unload_lora(pipe)
|
|
|
|
| 2363 |
except Exception as error:
|
|
|
|
| 2364 |
_runtime_event("adapter_cleanup_failed", error_type=type(error).__name__)
|
| 2365 |
pipe.scheduler = original_scheduler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2366 |
result = raw_frames_np = final_frames = None
|
| 2367 |
clear_vram()
|
|
|
|
| 2368 |
if completed:
|
| 2369 |
elapsed=time.perf_counter()-gpu_clock
|
| 2370 |
timing['gpu_seconds']=elapsed
|
|
@@ -2420,6 +2493,7 @@ def generate_video(
|
|
| 2420 |
raise gr.Error("Please upload an input image.")
|
| 2421 |
|
| 2422 |
wall_start = time.time()
|
|
|
|
| 2423 |
|
| 2424 |
num_frames = get_num_frames(duration_seconds)
|
| 2425 |
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
|
@@ -2473,7 +2547,10 @@ def generate_video(
|
|
| 2473 |
lora_groups.insert(0, speed_group)
|
| 2474 |
|
| 2475 |
# Resolve and validate every enabled adapter before booking the GPU.
|
|
|
|
| 2476 |
lora_groups = _prefetch_lora_files(lora_groups, progress=progress)
|
|
|
|
|
|
|
| 2477 |
|
| 2478 |
requested_seconds = get_inference_duration(
|
| 2479 |
resized_image, processed_last_image, prompt, steps, negative_prompt, num_frames,
|
|
@@ -2485,6 +2562,10 @@ def generate_video(
|
|
| 2485 |
render_dir=tempfile.mkdtemp(prefix='wan22-frames-')
|
| 2486 |
try:
|
| 2487 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2488 |
inference = run_inference(
|
| 2489 |
resized_image,
|
| 2490 |
processed_last_image,
|
|
@@ -2514,11 +2595,18 @@ def generate_video(
|
|
| 2514 |
guidance_scale, frame_multiplier, lora_groups=lora_groups)
|
| 2515 |
raise gr.Error(message + fit) from error
|
| 2516 |
bundle,task_n,lora_problems,timing=inference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2517 |
progress(.98,desc='Saving MP4 · GPU released')
|
|
|
|
| 2518 |
video_path,encode_seconds=_finish_wan_cpu(bundle,quality)
|
| 2519 |
_runtime_event('cpu_encode_complete',encode_seconds=round(encode_seconds,2))
|
| 2520 |
finally:
|
| 2521 |
shutil.rmtree(render_dir,ignore_errors=True)
|
|
|
|
| 2522 |
_record_wan_lora_failures(lora_groups, lora_problems)
|
| 2523 |
if not lora_problems:
|
| 2524 |
for _group in lora_groups:
|
|
@@ -2560,11 +2648,13 @@ def generate_video(
|
|
| 2560 |
f"<span>{num_frames} frames · {int(frame_multiplier)} fps</span>"
|
| 2561 |
f"<span>seed {current_seed}</span>"
|
| 2562 |
f"<span>{int(steps)} steps</span>"
|
|
|
|
| 2563 |
+ speed_info +
|
| 2564 |
identity_info +
|
| 2565 |
lora_info +
|
| 2566 |
f"<span>{elapsed:.1f} s total</span>"
|
| 2567 |
f"<span>GPU worker {timing['gpu_seconds']:.1f} s · CPU MP4 {encode_seconds:.1f} s</span>"
|
|
|
|
| 2568 |
"</div>"
|
| 2569 |
)
|
| 2570 |
|
|
@@ -2831,16 +2921,18 @@ def _ffmpeg_exe() -> str:
|
|
| 2831 |
return "ffmpeg"
|
| 2832 |
|
| 2833 |
|
|
|
|
| 2834 |
def _video_size(path):
|
| 2835 |
-
capture =
|
| 2836 |
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
|
| 2837 |
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
|
| 2838 |
capture.release()
|
| 2839 |
return (width or 832), (height or 624)
|
| 2840 |
|
| 2841 |
|
|
|
|
| 2842 |
def _video_fps(path):
|
| 2843 |
-
capture =
|
| 2844 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
|
| 2845 |
capture.release()
|
| 2846 |
if not fps or fps != fps or fps <= 0.5 or fps > 1000:
|
|
@@ -2848,8 +2940,9 @@ def _video_fps(path):
|
|
| 2848 |
return fps
|
| 2849 |
|
| 2850 |
|
|
|
|
| 2851 |
def _first_frame_small(path):
|
| 2852 |
-
capture =
|
| 2853 |
if not capture.isOpened():
|
| 2854 |
return None
|
| 2855 |
ok, frame = capture.read()
|
|
@@ -2862,7 +2955,7 @@ def _first_frame_small(path):
|
|
| 2862 |
def _last_frame_bgr(path, tail=40):
|
| 2863 |
"""The genuine final decoded frame. Seeking straight to total-1 is unreliable on
|
| 2864 |
some encodes, so it seeks a little short and decodes forward to the end."""
|
| 2865 |
-
capture =
|
| 2866 |
if not capture.isOpened():
|
| 2867 |
return None
|
| 2868 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
|
@@ -2880,6 +2973,7 @@ def _last_frame_bgr(path, tail=40):
|
|
| 2880 |
return last
|
| 2881 |
|
| 2882 |
|
|
|
|
| 2883 |
def _last_frame_small(path):
|
| 2884 |
frame = _last_frame_bgr(path)
|
| 2885 |
if frame is None:
|
|
@@ -2909,6 +3003,7 @@ def _persist(path):
|
|
| 2909 |
print(f"[storage] could not save: {error}")
|
| 2910 |
|
| 2911 |
|
|
|
|
| 2912 |
def _has_audio(path):
|
| 2913 |
"""Whether ffmpeg reports an audio stream on the file."""
|
| 2914 |
try:
|
|
@@ -2918,8 +3013,9 @@ def _has_audio(path):
|
|
| 2918 |
return False
|
| 2919 |
|
| 2920 |
|
|
|
|
| 2921 |
def _video_duration(path):
|
| 2922 |
-
capture =
|
| 2923 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
|
| 2924 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
| 2925 |
capture.release()
|
|
@@ -3033,10 +3129,13 @@ def concat_videos(paths, name_hint=""):
|
|
| 3033 |
if len(valid) == 1:
|
| 3034 |
return valid[0]
|
| 3035 |
|
|
|
|
|
|
|
|
|
|
| 3036 |
width, height = _extension_display_size(valid[0])
|
| 3037 |
fps = max(_video_fps(p) for p in valid)
|
| 3038 |
fps_str = f"{fps:.6f}".rstrip("0").rstrip(".")
|
| 3039 |
-
prefix = uuid.uuid4().hex[:
|
| 3040 |
clean = re.sub(r"[^\w.-]+", "_", str(name_hint).strip()).strip("._")[:80] or f"merged_{len(valid)}clips"
|
| 3041 |
if clean.lower().endswith(".mp4"):
|
| 3042 |
clean = clean[:-4]
|
|
@@ -3063,8 +3162,13 @@ def concat_videos(paths, name_hint=""):
|
|
| 3063 |
for index, path in enumerate(valid):
|
| 3064 |
_runtime_event("stitch_normalise", clip=index+1, clips=len(valid))
|
| 3065 |
part = os.path.join(work_dir, f"part{index:04d}.mp4")
|
| 3066 |
-
|
| 3067 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3068 |
parts.append(part)
|
| 3069 |
manifest = os.path.join(work_dir, "parts.ffconcat")
|
| 3070 |
with open(manifest, "w", encoding="utf-8") as handle:
|
|
@@ -3087,7 +3191,9 @@ def concat_videos(paths, name_hint=""):
|
|
| 3087 |
raise
|
| 3088 |
raise gr.Error("Joining failed; all original clips remain in the queue. Retry Join.") from error
|
| 3089 |
_persist(out_path)
|
| 3090 |
-
_runtime_event("stitch_complete", clips=len(valid)
|
|
|
|
|
|
|
| 3091 |
return out_path
|
| 3092 |
|
| 3093 |
|
|
@@ -3145,7 +3251,7 @@ def boomerang(video_path, mode, tail_seconds=2.0):
|
|
| 3145 |
with_audio = _has_audio(video_path)
|
| 3146 |
|
| 3147 |
if mode == "ending":
|
| 3148 |
-
capture =
|
| 3149 |
fps = capture.get(cv2.CAP_PROP_FPS) or 16
|
| 3150 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
| 3151 |
capture.release()
|
|
@@ -4932,7 +5038,7 @@ def last_frame_of(video_path):
|
|
| 4932 |
except Exception:
|
| 4933 |
pass
|
| 4934 |
|
| 4935 |
-
capture =
|
| 4936 |
if not capture.isOpened():
|
| 4937 |
raise gr.Error("That video cannot be read.")
|
| 4938 |
|
|
@@ -4943,7 +5049,7 @@ def last_frame_of(video_path):
|
|
| 4943 |
# then started from a moment the previous clip had already played past.
|
| 4944 |
frame = _last_frame_bgr(video_path)
|
| 4945 |
if frame is None:
|
| 4946 |
-
capture =
|
| 4947 |
while True:
|
| 4948 |
ok, candidate = capture.read()
|
| 4949 |
if not ok or candidate is None:
|
|
@@ -4961,6 +5067,7 @@ def _last_frame_pil(video_path):
|
|
| 4961 |
return Image.fromarray(last_frame_of(video_path))
|
| 4962 |
|
| 4963 |
|
|
|
|
| 4964 |
def _extension_signature(path):
|
| 4965 |
"""Recognize Gradio's byte-identical cache copy without confusing a new take."""
|
| 4966 |
import hashlib
|
|
@@ -4971,6 +5078,7 @@ def _extension_signature(path):
|
|
| 4971 |
return digest.hexdigest()
|
| 4972 |
|
| 4973 |
|
|
|
|
| 4974 |
def _extension_hdr_filter(path):
|
| 4975 |
"""Map tagged HDR to SDR for model keyframes and browser-compatible joins."""
|
| 4976 |
report = subprocess.run([_ffmpeg_exe(), "-nostdin", "-hide_banner", "-i", str(path)],
|
|
@@ -5040,6 +5148,7 @@ def _extension_tail_png(video_path, directory=None):
|
|
| 5040 |
raise gr.Error("This video could not be read. Try an MP4, MOV or WebM with a video track.") from error
|
| 5041 |
|
| 5042 |
|
|
|
|
| 5043 |
def _extension_display_size(path):
|
| 5044 |
"""Use displayed orientation, and even dimensions required by H.264."""
|
| 5045 |
import io
|
|
@@ -5057,6 +5166,7 @@ def _extension_display_size(path):
|
|
| 5057 |
raise gr.Error("A queued video could not be read. Re-upload it before stitching.") from error
|
| 5058 |
|
| 5059 |
|
|
|
|
| 5060 |
def _extension_video_origin(path):
|
| 5061 |
"""Read the video origin on FFmpeg's input timeline for audio alignment."""
|
| 5062 |
completed = subprocess.run(
|
|
@@ -8320,6 +8430,21 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8320 |
|
| 8321 |
_SOUND_INPUTS = [sound_engine, sound_prompt, sound_negative, sound_steps, sound_guidance]
|
| 8322 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8323 |
sound_btn.click(
|
| 8324 |
fn=add_sound,
|
| 8325 |
inputs=[file_output, *_SOUND_INPUTS],
|
|
@@ -8340,18 +8465,28 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8340 |
fn=lambda path: (_persist(path), gr.update())[1], inputs=[file_output],
|
| 8341 |
outputs=[status_box], show_progress="hidden",
|
| 8342 |
)
|
| 8343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8344 |
fn=maybe_sound, inputs=[file_output, sound_auto, *_SOUND_INPUTS],
|
| 8345 |
outputs=[video_output, file_output, sound_status],
|
| 8346 |
concurrency_id="wan-heavy", concurrency_limit=1,
|
| 8347 |
)
|
| 8348 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8349 |
fn=auto_queue, inputs=[file_output, auto_merge, merge_queue, merge_name],
|
| 8350 |
outputs=[merged_video, merged_file, merge_queue, merge_status], show_progress="hidden",
|
| 8351 |
-
concurrency_id="wan-
|
| 8352 |
)
|
| 8353 |
_gen_failed = _gen_video.failure(_generation_failed, None, [file_output, status_box], show_progress="hidden")
|
| 8354 |
-
_gen_events = [_gen_start, _gen_video, _gen_persist,
|
|
|
|
| 8355 |
|
| 8356 |
clear_button.click(
|
| 8357 |
fn=_clear_all,
|
|
@@ -8387,27 +8522,29 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8387 |
outputs=[last_image_component],
|
| 8388 |
)
|
| 8389 |
|
|
|
|
|
|
|
| 8390 |
boomerang_full_btn.click(
|
| 8391 |
fn=lambda path: boomerang(path, "full"),
|
| 8392 |
inputs=[file_output],
|
| 8393 |
outputs=[video_output, file_output],
|
| 8394 |
-
concurrency_id="wan-
|
| 8395 |
)
|
| 8396 |
boomerang_end_btn.click(
|
| 8397 |
fn=lambda path, tail: boomerang(path, "ending", tail),
|
| 8398 |
inputs=[file_output, boomerang_tail],
|
| 8399 |
outputs=[video_output, file_output],
|
| 8400 |
-
concurrency_id="wan-
|
| 8401 |
)
|
| 8402 |
|
| 8403 |
merge_add_btn.click(
|
| 8404 |
fn=add_to_queue,
|
| 8405 |
inputs=[file_output, merge_queue, merge_name],
|
| 8406 |
outputs=[merged_video, merged_file, merge_queue, merge_status],
|
| 8407 |
-
concurrency_id="wan-
|
| 8408 |
)
|
| 8409 |
merge_retry_btn.click(join_queued_clips, [merge_queue, merge_name],
|
| 8410 |
-
[merged_video, merged_file, merge_status], show_progress="minimal", concurrency_id="wan-
|
| 8411 |
merge_clear_btn.click(
|
| 8412 |
fn=clear_queue,
|
| 8413 |
inputs=None,
|
|
@@ -8440,28 +8577,38 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8440 |
outputs=[input_image_component, last_image_component, video_output, file_output,
|
| 8441 |
merged_video, merged_file, merge_queue, merge_status, identity_ref_component,
|
| 8442 |
extend_loaded, extension_status, prompt_input, duration_seconds_input, aspect_mode],
|
| 8443 |
-
concurrency_id="wan-
|
| 8444 |
)
|
| 8445 |
_extend_video = _extend_start.success(
|
| 8446 |
fn=generate_video_continued, inputs=ui_inputs + [merge_queue],
|
| 8447 |
outputs=[video_output, file_output, seed_input, status_box],
|
| 8448 |
concurrency_id="wan-heavy", concurrency_limit=1, api_name=False,
|
| 8449 |
)
|
| 8450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8451 |
fn=_extension_sound, inputs=[file_output, sound_auto, *_SOUND_INPUTS],
|
| 8452 |
outputs=[video_output, file_output, sound_status],
|
| 8453 |
concurrency_id="wan-heavy", concurrency_limit=1, api_name=False,
|
| 8454 |
)
|
| 8455 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8456 |
_queue_extension_clip, [file_output, merge_queue], [merge_queue, merge_status],
|
| 8457 |
-
concurrency_id="wan-
|
| 8458 |
)
|
| 8459 |
_extend_join = _extend_commit.success(
|
| 8460 |
_join_extension_queue, [merge_queue, merge_name],
|
| 8461 |
[merged_video, merged_file, merge_status, extension_status, stitch_panel],
|
| 8462 |
-
concurrency_id="wan-
|
| 8463 |
)
|
| 8464 |
-
_extend_events = [_extend_start, _extend_video,
|
|
|
|
| 8465 |
for _event in tuple(_extend_events):
|
| 8466 |
_extend_events.append(_event.failure(_extension_failed_note, None, extension_status,
|
| 8467 |
show_progress="hidden", api_name=False))
|
|
|
|
| 12 |
import gc
|
| 13 |
import uuid
|
| 14 |
import threading
|
| 15 |
+
import functools
|
| 16 |
+
from stitch_cache import stage_clip, memoize_file
|
| 17 |
from tqdm import tqdm
|
| 18 |
import cv2
|
| 19 |
+
cv2.setNumThreads(2)
|
| 20 |
import numpy as np
|
| 21 |
import torch
|
| 22 |
import torch._dynamo
|
|
|
|
| 35 |
_WEB_PID = os.getpid()
|
| 36 |
|
| 37 |
|
| 38 |
+
def _open_video(path):
|
| 39 |
+
"""Bound FFmpeg decoder threads on shared CPU hosts, including warm runs."""
|
| 40 |
+
if hasattr(cv2, "CAP_PROP_N_THREADS"):
|
| 41 |
+
capture = None
|
| 42 |
+
try:
|
| 43 |
+
capture = cv2.VideoCapture(str(path), cv2.CAP_FFMPEG,
|
| 44 |
+
[cv2.CAP_PROP_N_THREADS, 2])
|
| 45 |
+
if capture.isOpened():
|
| 46 |
+
return capture
|
| 47 |
+
except (cv2.error, TypeError):
|
| 48 |
+
pass
|
| 49 |
+
if capture is not None:
|
| 50 |
+
capture.release()
|
| 51 |
+
return cv2.VideoCapture(str(path))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _release_cpu_heap():
|
| 55 |
+
"""Return unused native buffers; live model weights remain allocated."""
|
| 56 |
+
if not sys.platform.startswith("linux"):
|
| 57 |
+
return
|
| 58 |
+
try:
|
| 59 |
+
import ctypes
|
| 60 |
+
trim = ctypes.CDLL(None).malloc_trim
|
| 61 |
+
trim.argtypes = [ctypes.c_size_t]
|
| 62 |
+
trim.restype = ctypes.c_int
|
| 63 |
+
trim(0)
|
| 64 |
+
except (AttributeError, OSError):
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _cached_video_probe(function):
|
| 69 |
+
@functools.wraps(function)
|
| 70 |
+
def cached(path):
|
| 71 |
+
return memoize_file(path, function.__name__, lambda: function(path))
|
| 72 |
+
return cached
|
| 73 |
+
|
| 74 |
+
|
| 75 |
def _runtime_dir():
|
| 76 |
for root in ("/data", "/bucket", tempfile.gettempdir()):
|
| 77 |
if not os.path.isdir(root):
|
|
|
|
| 101 |
result[key.rstrip(":") + "_MiB"] = round(int(value) / 1024, 1)
|
| 102 |
except (OSError, ValueError):
|
| 103 |
pass
|
| 104 |
+
for name in ("memory.current", "memory.peak", "memory.max", "memory.events",
|
| 105 |
+
"memory.stat", "cpu.stat"):
|
| 106 |
try:
|
| 107 |
with open("/sys/fs/cgroup/" + name) as handle:
|
| 108 |
value = handle.read(4096).strip()
|
| 109 |
if name == "memory.events":
|
| 110 |
result["cgroup_events"] = dict((k, int(v)) for k, v in
|
| 111 |
(line.split() for line in value.splitlines()))
|
| 112 |
+
elif name in ("memory.stat", "cpu.stat"):
|
| 113 |
+
selected = {"anon", "file", "shmem", "file_dirty", "file_writeback",
|
| 114 |
+
"usage_usec", "nr_throttled", "throttled_usec"}
|
| 115 |
+
result[name] = {k: int(v) for k, v in
|
| 116 |
+
(line.split() for line in value.splitlines()) if k in selected}
|
| 117 |
else:
|
| 118 |
result[name + "_MiB"] = round(int(value) / 1048576, 1) if value.isdigit() else value
|
| 119 |
except (OSError, ValueError):
|
|
|
|
| 221 |
height, width = first.shape[:2]
|
| 222 |
crf = int((1 - min(10.0, max(1.0, float(quality))) / 10) * 51)
|
| 223 |
command = [_ffmpeg_exe(), "-hide_banner", "-loglevel", "error", "-y",
|
| 224 |
+
"-filter_threads", "1", "-filter_complex_threads", "1",
|
| 225 |
"-f", "rawvideo", "-vcodec", "rawvideo", "-s", f"{width}x{height}",
|
| 226 |
"-pix_fmt", "rgb24", "-r", str(fps), "-i", "pipe:0", "-an",
|
| 227 |
"-c:v", "libx264", "-threads", "2", "-crf", str(crf),
|
|
|
|
| 270 |
iterator.close()
|
| 271 |
|
| 272 |
|
| 273 |
+
@_cached_video_probe
|
| 274 |
def _concat_duration(path):
|
| 275 |
+
capture = _open_video(path)
|
| 276 |
try:
|
| 277 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0)
|
| 278 |
frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
|
|
|
| 380 |
|
| 381 |
print(f"Extracting frame at timestamp: {timestamp}")
|
| 382 |
|
| 383 |
+
cap = _open_video(video_path)
|
| 384 |
|
| 385 |
if not cap.isOpened():
|
| 386 |
return None
|
|
|
|
| 2298 |
timing={}
|
| 2299 |
completed=False
|
| 2300 |
if not render_dir:raise gr.Error('Missing CPU export directory.')
|
| 2301 |
+
_runtime_event("gpu_begin", frames=int(num_frames), fps=int(frame_multiplier),
|
| 2302 |
+
width=int(resized_image.width), height=int(resized_image.height),
|
| 2303 |
+
steps=int(steps), guidance=float(guidance_scale),
|
| 2304 |
+
guidance_low=float(guidance_scale_2), scheduler=str(scheduler_name),
|
| 2305 |
+
flow_shift=float(flow_shift))
|
| 2306 |
try:
|
| 2307 |
+
# A scheduler holds latent history. Keep the template pristine and use a
|
| 2308 |
+
# fresh scheduler for every job, including a warm ZeroGPU worker.
|
| 2309 |
scheduler_class = SCHEDULER_MAP.get(scheduler_name, type(original_scheduler))
|
| 2310 |
+
config = copy.deepcopy(original_scheduler.config)
|
| 2311 |
+
if scheduler_class == FlowMatchEulerDiscreteScheduler:
|
| 2312 |
+
config['shift'] = flow_shift
|
| 2313 |
+
else:
|
| 2314 |
+
config['flow_shift'] = flow_shift
|
| 2315 |
+
pipe.scheduler = scheduler_class.from_config(config)
|
| 2316 |
+
|
| 2317 |
+
if getattr(pipe, "_wan_adapter_cleanup_failed", False):
|
| 2318 |
+
lora_loader.unload_lora(pipe, strict=True)
|
| 2319 |
+
pipe._wan_adapter_cleanup_failed = False
|
| 2320 |
|
| 2321 |
clear_vram()
|
| 2322 |
|
|
|
|
| 2360 |
print(f"lora warning: {e}")
|
| 2361 |
lora_problems = [str(e)[:200]]
|
| 2362 |
try:
|
| 2363 |
+
lora_loader.unload_lora(pipe, strict=True)
|
| 2364 |
+
except Exception as cleanup_error:
|
| 2365 |
+
pipe._wan_adapter_cleanup_failed = True
|
| 2366 |
+
raise gr.Error("LoRA cleanup failed. Generation stopped before using stale adapters; "
|
| 2367 |
+
"retry or restart the Space if it repeats.") from cleanup_error
|
| 2368 |
|
| 2369 |
_runtime_event("adapters_ready", load_wall_s=round(time.perf_counter() - adapter_start, 2),
|
| 2370 |
adapter_mib=round(sum(g.get("_load_bytes", 0) for g in lora_groups or []) / 1048576, 1))
|
| 2371 |
_runtime_event("denoise_and_decode")
|
| 2372 |
+
denoise_started = time.perf_counter()
|
| 2373 |
result = pipe(
|
| 2374 |
image=resized_image,
|
| 2375 |
last_image=processed_last_image,
|
|
|
|
| 2385 |
output_type="np"
|
| 2386 |
)
|
| 2387 |
|
| 2388 |
+
_runtime_event("denoise_and_decode_complete",
|
| 2389 |
+
seconds=round(time.perf_counter() - denoise_started, 3))
|
| 2390 |
if lora_loaded:
|
| 2391 |
+
lora_loader.unload_lora(pipe, strict=True)
|
| 2392 |
|
| 2393 |
print("gen time passed:", time.time() - start)
|
| 2394 |
|
|
|
|
| 2410 |
|
| 2411 |
output_count=(len(raw_frames_np)-1)*frame_factor+1
|
| 2412 |
_runtime_event('rife_and_handoff' if frame_factor>1 else 'cpu_handoff')
|
| 2413 |
+
handoff_started = time.perf_counter()
|
| 2414 |
frames_path=_spool_wan_frames(final_frames,render_dir,output_count,resized_image.width,resized_image.height)
|
| 2415 |
+
_runtime_event("handoff_complete", seconds=round(time.perf_counter() - handoff_started, 3))
|
| 2416 |
torch.cuda.synchronize()
|
| 2417 |
completed=True
|
| 2418 |
return dict(frames_path=frames_path,fps=final_fps),task_name,list(lora_problems),timing
|
|
|
|
| 2423 |
finally:
|
| 2424 |
try:
|
| 2425 |
if lora_groups:
|
| 2426 |
+
lora_loader.unload_lora(pipe, strict=True)
|
| 2427 |
+
pipe._wan_adapter_cleanup_failed = False
|
| 2428 |
except Exception as error:
|
| 2429 |
+
pipe._wan_adapter_cleanup_failed = True
|
| 2430 |
_runtime_event("adapter_cleanup_failed", error_type=type(error).__name__)
|
| 2431 |
pipe.scheduler = original_scheduler
|
| 2432 |
+
try:
|
| 2433 |
+
clear_vae_cache = getattr(pipe.vae, "clear_cache", None)
|
| 2434 |
+
if callable(clear_vae_cache):
|
| 2435 |
+
clear_vae_cache()
|
| 2436 |
+
except Exception as error:
|
| 2437 |
+
_runtime_event("vae_cleanup_failed", error_type=type(error).__name__)
|
| 2438 |
result = raw_frames_np = final_frames = None
|
| 2439 |
clear_vram()
|
| 2440 |
+
_release_cpu_heap()
|
| 2441 |
if completed:
|
| 2442 |
elapsed=time.perf_counter()-gpu_clock
|
| 2443 |
timing['gpu_seconds']=elapsed
|
|
|
|
| 2493 |
raise gr.Error("Please upload an input image.")
|
| 2494 |
|
| 2495 |
wall_start = time.time()
|
| 2496 |
+
_runtime_event("generation_begin")
|
| 2497 |
|
| 2498 |
num_frames = get_num_frames(duration_seconds)
|
| 2499 |
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
|
|
|
| 2547 |
lora_groups.insert(0, speed_group)
|
| 2548 |
|
| 2549 |
# Resolve and validate every enabled adapter before booking the GPU.
|
| 2550 |
+
preparation_started = time.perf_counter()
|
| 2551 |
lora_groups = _prefetch_lora_files(lora_groups, progress=progress)
|
| 2552 |
+
_runtime_event("lora_preparation_complete",
|
| 2553 |
+
seconds=round(time.perf_counter() - preparation_started, 3))
|
| 2554 |
|
| 2555 |
requested_seconds = get_inference_duration(
|
| 2556 |
resized_image, processed_last_image, prompt, steps, negative_prompt, num_frames,
|
|
|
|
| 2562 |
render_dir=tempfile.mkdtemp(prefix='wan22-frames-')
|
| 2563 |
try:
|
| 2564 |
try:
|
| 2565 |
+
gpu_call_started = time.perf_counter()
|
| 2566 |
+
progress(0, desc=(f'Waiting for GPU / generating: {resized_image.width}x{resized_image.height}, '
|
| 2567 |
+
f'{int(steps)} steps, {float(guidance_scale):g}/{float(guidance_scale_2):g} CFG, '
|
| 2568 |
+
f'{float(duration_seconds):g}s, {int(frame_multiplier)} fps'))
|
| 2569 |
inference = run_inference(
|
| 2570 |
resized_image,
|
| 2571 |
processed_last_image,
|
|
|
|
| 2595 |
guidance_scale, frame_multiplier, lora_groups=lora_groups)
|
| 2596 |
raise gr.Error(message + fit) from error
|
| 2597 |
bundle,task_n,lora_problems,timing=inference
|
| 2598 |
+
gpu_call_seconds = time.perf_counter() - gpu_call_started
|
| 2599 |
+
# Includes allocation/startup and RPC overhead, not just queue time.
|
| 2600 |
+
outside_worker_seconds = max(0.0, gpu_call_seconds - timing['gpu_seconds'])
|
| 2601 |
+
_runtime_event('gpu_call_returned', total_call_s=round(gpu_call_seconds, 3),
|
| 2602 |
+
outside_worker_s=round(outside_worker_seconds, 3))
|
| 2603 |
progress(.98,desc='Saving MP4 · GPU released')
|
| 2604 |
+
_runtime_event('cpu_encode_begin')
|
| 2605 |
video_path,encode_seconds=_finish_wan_cpu(bundle,quality)
|
| 2606 |
_runtime_event('cpu_encode_complete',encode_seconds=round(encode_seconds,2))
|
| 2607 |
finally:
|
| 2608 |
shutil.rmtree(render_dir,ignore_errors=True)
|
| 2609 |
+
_release_cpu_heap()
|
| 2610 |
_record_wan_lora_failures(lora_groups, lora_problems)
|
| 2611 |
if not lora_problems:
|
| 2612 |
for _group in lora_groups:
|
|
|
|
| 2648 |
f"<span>{num_frames} frames · {int(frame_multiplier)} fps</span>"
|
| 2649 |
f"<span>seed {current_seed}</span>"
|
| 2650 |
f"<span>{int(steps)} steps</span>"
|
| 2651 |
+
f"<span>CFG {float(guidance_scale):g}/{float(guidance_scale_2):g}</span>"
|
| 2652 |
+ speed_info +
|
| 2653 |
identity_info +
|
| 2654 |
lora_info +
|
| 2655 |
f"<span>{elapsed:.1f} s total</span>"
|
| 2656 |
f"<span>GPU worker {timing['gpu_seconds']:.1f} s · CPU MP4 {encode_seconds:.1f} s</span>"
|
| 2657 |
+
f"<span>GPU allocation / startup / transfer {outside_worker_seconds:.1f} s</span>"
|
| 2658 |
"</div>"
|
| 2659 |
)
|
| 2660 |
|
|
|
|
| 2921 |
return "ffmpeg"
|
| 2922 |
|
| 2923 |
|
| 2924 |
+
@_cached_video_probe
|
| 2925 |
def _video_size(path):
|
| 2926 |
+
capture = _open_video(path)
|
| 2927 |
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
|
| 2928 |
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
|
| 2929 |
capture.release()
|
| 2930 |
return (width or 832), (height or 624)
|
| 2931 |
|
| 2932 |
|
| 2933 |
+
@_cached_video_probe
|
| 2934 |
def _video_fps(path):
|
| 2935 |
+
capture = _open_video(path)
|
| 2936 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
|
| 2937 |
capture.release()
|
| 2938 |
if not fps or fps != fps or fps <= 0.5 or fps > 1000:
|
|
|
|
| 2940 |
return fps
|
| 2941 |
|
| 2942 |
|
| 2943 |
+
@_cached_video_probe
|
| 2944 |
def _first_frame_small(path):
|
| 2945 |
+
capture = _open_video(path)
|
| 2946 |
if not capture.isOpened():
|
| 2947 |
return None
|
| 2948 |
ok, frame = capture.read()
|
|
|
|
| 2955 |
def _last_frame_bgr(path, tail=40):
|
| 2956 |
"""The genuine final decoded frame. Seeking straight to total-1 is unreliable on
|
| 2957 |
some encodes, so it seeks a little short and decodes forward to the end."""
|
| 2958 |
+
capture = _open_video(path)
|
| 2959 |
if not capture.isOpened():
|
| 2960 |
return None
|
| 2961 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
|
|
|
| 2973 |
return last
|
| 2974 |
|
| 2975 |
|
| 2976 |
+
@_cached_video_probe
|
| 2977 |
def _last_frame_small(path):
|
| 2978 |
frame = _last_frame_bgr(path)
|
| 2979 |
if frame is None:
|
|
|
|
| 3003 |
print(f"[storage] could not save: {error}")
|
| 3004 |
|
| 3005 |
|
| 3006 |
+
@_cached_video_probe
|
| 3007 |
def _has_audio(path):
|
| 3008 |
"""Whether ffmpeg reports an audio stream on the file."""
|
| 3009 |
try:
|
|
|
|
| 3013 |
return False
|
| 3014 |
|
| 3015 |
|
| 3016 |
+
@_cached_video_probe
|
| 3017 |
def _video_duration(path):
|
| 3018 |
+
capture = _open_video(path)
|
| 3019 |
fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
|
| 3020 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
| 3021 |
capture.release()
|
|
|
|
| 3129 |
if len(valid) == 1:
|
| 3130 |
return valid[0]
|
| 3131 |
|
| 3132 |
+
stitch_started = time.perf_counter()
|
| 3133 |
+
cache_hits = 0
|
| 3134 |
+
_runtime_event("stitch_prepare", clips=len(valid))
|
| 3135 |
width, height = _extension_display_size(valid[0])
|
| 3136 |
fps = max(_video_fps(p) for p in valid)
|
| 3137 |
fps_str = f"{fps:.6f}".rstrip("0").rstrip(".")
|
| 3138 |
+
prefix = uuid.uuid4().hex[:12]
|
| 3139 |
clean = re.sub(r"[^\w.-]+", "_", str(name_hint).strip()).strip("._")[:80] or f"merged_{len(valid)}clips"
|
| 3140 |
if clean.lower().endswith(".mp4"):
|
| 3141 |
clean = clean[:-4]
|
|
|
|
| 3162 |
for index, path in enumerate(valid):
|
| 3163 |
_runtime_event("stitch_normalise", clip=index+1, clips=len(valid))
|
| 3164 |
part = os.path.join(work_dir, f"part{index:04d}.mp4")
|
| 3165 |
+
part_started = time.perf_counter()
|
| 3166 |
+
cache_hit = stage_clip(path, width, height, fps, part, normalise=_normalise_clip,
|
| 3167 |
+
trim_head=bool(trims[index]), colour=colour_fixes[index],
|
| 3168 |
+
include_audio=include_audio)
|
| 3169 |
+
cache_hits += int(cache_hit)
|
| 3170 |
+
_runtime_event("stitch_part_ready", clip=index+1, clips=len(valid),
|
| 3171 |
+
reused=cache_hit, seconds=round(time.perf_counter() - part_started, 3))
|
| 3172 |
parts.append(part)
|
| 3173 |
manifest = os.path.join(work_dir, "parts.ffconcat")
|
| 3174 |
with open(manifest, "w", encoding="utf-8") as handle:
|
|
|
|
| 3191 |
raise
|
| 3192 |
raise gr.Error("Joining failed; all original clips remain in the queue. Retry Join.") from error
|
| 3193 |
_persist(out_path)
|
| 3194 |
+
_runtime_event("stitch_complete", clips=len(valid), reused=cache_hits,
|
| 3195 |
+
seconds=round(time.perf_counter() - stitch_started, 3))
|
| 3196 |
+
_release_cpu_heap()
|
| 3197 |
return out_path
|
| 3198 |
|
| 3199 |
|
|
|
|
| 3251 |
with_audio = _has_audio(video_path)
|
| 3252 |
|
| 3253 |
if mode == "ending":
|
| 3254 |
+
capture = _open_video(video_path)
|
| 3255 |
fps = capture.get(cv2.CAP_PROP_FPS) or 16
|
| 3256 |
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
| 3257 |
capture.release()
|
|
|
|
| 5038 |
except Exception:
|
| 5039 |
pass
|
| 5040 |
|
| 5041 |
+
capture = _open_video(video_path)
|
| 5042 |
if not capture.isOpened():
|
| 5043 |
raise gr.Error("That video cannot be read.")
|
| 5044 |
|
|
|
|
| 5049 |
# then started from a moment the previous clip had already played past.
|
| 5050 |
frame = _last_frame_bgr(video_path)
|
| 5051 |
if frame is None:
|
| 5052 |
+
capture = _open_video(video_path)
|
| 5053 |
while True:
|
| 5054 |
ok, candidate = capture.read()
|
| 5055 |
if not ok or candidate is None:
|
|
|
|
| 5067 |
return Image.fromarray(last_frame_of(video_path))
|
| 5068 |
|
| 5069 |
|
| 5070 |
+
@_cached_video_probe
|
| 5071 |
def _extension_signature(path):
|
| 5072 |
"""Recognize Gradio's byte-identical cache copy without confusing a new take."""
|
| 5073 |
import hashlib
|
|
|
|
| 5078 |
return digest.hexdigest()
|
| 5079 |
|
| 5080 |
|
| 5081 |
+
@_cached_video_probe
|
| 5082 |
def _extension_hdr_filter(path):
|
| 5083 |
"""Map tagged HDR to SDR for model keyframes and browser-compatible joins."""
|
| 5084 |
report = subprocess.run([_ffmpeg_exe(), "-nostdin", "-hide_banner", "-i", str(path)],
|
|
|
|
| 5148 |
raise gr.Error("This video could not be read. Try an MP4, MOV or WebM with a video track.") from error
|
| 5149 |
|
| 5150 |
|
| 5151 |
+
@_cached_video_probe
|
| 5152 |
def _extension_display_size(path):
|
| 5153 |
"""Use displayed orientation, and even dimensions required by H.264."""
|
| 5154 |
import io
|
|
|
|
| 5166 |
raise gr.Error("A queued video could not be read. Re-upload it before stitching.") from error
|
| 5167 |
|
| 5168 |
|
| 5169 |
+
@_cached_video_probe
|
| 5170 |
def _extension_video_origin(path):
|
| 5171 |
"""Read the video origin on FFmpeg's input timeline for audio alignment."""
|
| 5172 |
completed = subprocess.run(
|
|
|
|
| 8430 |
|
| 8431 |
_SOUND_INPUTS = [sound_engine, sound_prompt, sound_negative, sound_steps, sound_guidance]
|
| 8432 |
|
| 8433 |
+
def _next_media_tick():
|
| 8434 |
+
return uuid.uuid4().hex
|
| 8435 |
+
|
| 8436 |
+
def _route_optional_sound(wanted):
|
| 8437 |
+
# Leave the unused token unchanged: only the chosen branch fires.
|
| 8438 |
+
tick = _next_media_tick()
|
| 8439 |
+
return (tick, gr.update()) if wanted else (gr.update(), tick)
|
| 8440 |
+
|
| 8441 |
+
# Disabled automatic sound must not reacquire the shared GPU queue before
|
| 8442 |
+
# joining. Tokens keep audio in its own request when it is enabled.
|
| 8443 |
+
gen_sound_tick = gr.Textbox(value="", visible=False)
|
| 8444 |
+
gen_join_tick = gr.Textbox(value="", visible=False)
|
| 8445 |
+
extend_sound_tick = gr.Textbox(value="", visible=False)
|
| 8446 |
+
extend_join_tick = gr.Textbox(value="", visible=False)
|
| 8447 |
+
|
| 8448 |
sound_btn.click(
|
| 8449 |
fn=add_sound,
|
| 8450 |
inputs=[file_output, *_SOUND_INPUTS],
|
|
|
|
| 8465 |
fn=lambda path: (_persist(path), gr.update())[1], inputs=[file_output],
|
| 8466 |
outputs=[status_box], show_progress="hidden",
|
| 8467 |
)
|
| 8468 |
+
_gen_route = _gen_persist.success(
|
| 8469 |
+
fn=_route_optional_sound, inputs=[sound_auto],
|
| 8470 |
+
outputs=[gen_sound_tick, gen_join_tick],
|
| 8471 |
+
queue=False, show_progress="hidden", api_name=False,
|
| 8472 |
+
)
|
| 8473 |
+
_gen_sound = gen_sound_tick.change(
|
| 8474 |
fn=maybe_sound, inputs=[file_output, sound_auto, *_SOUND_INPUTS],
|
| 8475 |
outputs=[video_output, file_output, sound_status],
|
| 8476 |
concurrency_id="wan-heavy", concurrency_limit=1,
|
| 8477 |
)
|
| 8478 |
+
_gen_sound_done = _gen_sound.success(
|
| 8479 |
+
fn=_next_media_tick, inputs=None, outputs=[gen_join_tick],
|
| 8480 |
+
queue=False, show_progress="hidden", api_name=False,
|
| 8481 |
+
)
|
| 8482 |
+
_gen_join = gen_join_tick.change(
|
| 8483 |
fn=auto_queue, inputs=[file_output, auto_merge, merge_queue, merge_name],
|
| 8484 |
outputs=[merged_video, merged_file, merge_queue, merge_status], show_progress="hidden",
|
| 8485 |
+
concurrency_id="wan-media", concurrency_limit=1,
|
| 8486 |
)
|
| 8487 |
_gen_failed = _gen_video.failure(_generation_failed, None, [file_output, status_box], show_progress="hidden")
|
| 8488 |
+
_gen_events = [_gen_start, _gen_video, _gen_persist, _gen_route,
|
| 8489 |
+
_gen_sound, _gen_sound_done, _gen_join, _gen_failed]
|
| 8490 |
|
| 8491 |
clear_button.click(
|
| 8492 |
fn=_clear_all,
|
|
|
|
| 8522 |
outputs=[last_image_component],
|
| 8523 |
)
|
| 8524 |
|
| 8525 |
+
# CPU media work has its own bounded queue, so Join and Loop do not wait
|
| 8526 |
+
# behind another visitor's long GPU generation. Success chains keep order.
|
| 8527 |
boomerang_full_btn.click(
|
| 8528 |
fn=lambda path: boomerang(path, "full"),
|
| 8529 |
inputs=[file_output],
|
| 8530 |
outputs=[video_output, file_output],
|
| 8531 |
+
concurrency_id="wan-media", concurrency_limit=1,
|
| 8532 |
)
|
| 8533 |
boomerang_end_btn.click(
|
| 8534 |
fn=lambda path, tail: boomerang(path, "ending", tail),
|
| 8535 |
inputs=[file_output, boomerang_tail],
|
| 8536 |
outputs=[video_output, file_output],
|
| 8537 |
+
concurrency_id="wan-media", concurrency_limit=1,
|
| 8538 |
)
|
| 8539 |
|
| 8540 |
merge_add_btn.click(
|
| 8541 |
fn=add_to_queue,
|
| 8542 |
inputs=[file_output, merge_queue, merge_name],
|
| 8543 |
outputs=[merged_video, merged_file, merge_queue, merge_status],
|
| 8544 |
+
concurrency_id="wan-media", concurrency_limit=1,
|
| 8545 |
)
|
| 8546 |
merge_retry_btn.click(join_queued_clips, [merge_queue, merge_name],
|
| 8547 |
+
[merged_video, merged_file, merge_status], show_progress="minimal", concurrency_id="wan-media", concurrency_limit=1)
|
| 8548 |
merge_clear_btn.click(
|
| 8549 |
fn=clear_queue,
|
| 8550 |
inputs=None,
|
|
|
|
| 8577 |
outputs=[input_image_component, last_image_component, video_output, file_output,
|
| 8578 |
merged_video, merged_file, merge_queue, merge_status, identity_ref_component,
|
| 8579 |
extend_loaded, extension_status, prompt_input, duration_seconds_input, aspect_mode],
|
| 8580 |
+
concurrency_id="wan-media", concurrency_limit=1, api_name=False,
|
| 8581 |
)
|
| 8582 |
_extend_video = _extend_start.success(
|
| 8583 |
fn=generate_video_continued, inputs=ui_inputs + [merge_queue],
|
| 8584 |
outputs=[video_output, file_output, seed_input, status_box],
|
| 8585 |
concurrency_id="wan-heavy", concurrency_limit=1, api_name=False,
|
| 8586 |
)
|
| 8587 |
+
_extend_route = _extend_video.success(
|
| 8588 |
+
fn=_route_optional_sound, inputs=[sound_auto],
|
| 8589 |
+
outputs=[extend_sound_tick, extend_join_tick],
|
| 8590 |
+
queue=False, show_progress="hidden", api_name=False,
|
| 8591 |
+
)
|
| 8592 |
+
_extend_sound = extend_sound_tick.change(
|
| 8593 |
fn=_extension_sound, inputs=[file_output, sound_auto, *_SOUND_INPUTS],
|
| 8594 |
outputs=[video_output, file_output, sound_status],
|
| 8595 |
concurrency_id="wan-heavy", concurrency_limit=1, api_name=False,
|
| 8596 |
)
|
| 8597 |
+
_extend_sound_done = _extend_sound.success(
|
| 8598 |
+
fn=_next_media_tick, inputs=None, outputs=[extend_join_tick],
|
| 8599 |
+
queue=False, show_progress="hidden", api_name=False,
|
| 8600 |
+
)
|
| 8601 |
+
_extend_commit = extend_join_tick.change(
|
| 8602 |
_queue_extension_clip, [file_output, merge_queue], [merge_queue, merge_status],
|
| 8603 |
+
concurrency_id="wan-media", concurrency_limit=1, api_name=False,
|
| 8604 |
)
|
| 8605 |
_extend_join = _extend_commit.success(
|
| 8606 |
_join_extension_queue, [merge_queue, merge_name],
|
| 8607 |
[merged_video, merged_file, merge_status, extension_status, stitch_panel],
|
| 8608 |
+
concurrency_id="wan-media", concurrency_limit=1, api_name=False,
|
| 8609 |
)
|
| 8610 |
+
_extend_events = [_extend_start, _extend_video, _extend_route, _extend_sound,
|
| 8611 |
+
_extend_sound_done, _extend_commit, _extend_join]
|
| 8612 |
for _event in tuple(_extend_events):
|
| 8613 |
_extend_events.append(_event.failure(_extension_failed_note, None, extension_status,
|
| 8614 |
show_progress="hidden", api_name=False))
|
extend-proof.jpg
ADDED
|
Git LFS Details
|
gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
lora_loader.py
CHANGED
|
@@ -444,6 +444,22 @@ def load_lora_to_pipe(pipe, group_name, adapter_name="lora", high_scale=1.0, low
|
|
| 444 |
|
| 445 |
|
| 446 |
def load_lora_slots(pipe, slots):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
"""Load every slot that can be loaded.
|
| 448 |
|
| 449 |
Each file is handled on its own. One bad file - a lora for another model family, a
|
|
@@ -522,8 +538,22 @@ def load_lora_slots(pipe, slots):
|
|
| 522 |
return False, problems
|
| 523 |
|
| 524 |
|
| 525 |
-
def unload_lora(pipe):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
try:
|
| 527 |
pipe.unload_lora_weights()
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
|
| 446 |
def load_lora_slots(pipe, slots):
|
| 447 |
+
"""Load adapters only into a clean pipeline; clean partial loads on failure."""
|
| 448 |
+
# A reused ZeroGPU worker can still own adapters if the previous request's
|
| 449 |
+
# cleanup failed. Do not add another set or continue with stale effects.
|
| 450 |
+
unload_lora(pipe, strict=True)
|
| 451 |
+
try:
|
| 452 |
+
loaded, problems = _load_lora_slots(pipe, slots)
|
| 453 |
+
if not loaded:
|
| 454 |
+
# Activation can fail after every weight has already been loaded.
|
| 455 |
+
unload_lora(pipe, strict=True)
|
| 456 |
+
return loaded, problems
|
| 457 |
+
except BaseException:
|
| 458 |
+
unload_lora(pipe, strict=True)
|
| 459 |
+
raise
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _load_lora_slots(pipe, slots):
|
| 463 |
"""Load every slot that can be loaded.
|
| 464 |
|
| 465 |
Each file is handled on its own. One bad file - a lora for another model family, a
|
|
|
|
| 538 |
return False, problems
|
| 539 |
|
| 540 |
|
| 541 |
+
def unload_lora(pipe, strict=False):
|
| 542 |
+
"""Release adapter weights, optionally refusing a partially cleaned model.
|
| 543 |
+
|
| 544 |
+
Legacy callers remain best-effort. Generation uses strict=True so a failed
|
| 545 |
+
unload cannot silently carry adapter weights into a warm worker's next run.
|
| 546 |
+
"""
|
| 547 |
try:
|
| 548 |
pipe.unload_lora_weights()
|
| 549 |
+
components = set(getattr(pipe, "_lora_loadable_modules", ()) or ())
|
| 550 |
+
components.update(("transformer", "transformer_2"))
|
| 551 |
+
remaining = [name for name in sorted(components)
|
| 552 |
+
if getattr(getattr(pipe, name, None), "peft_config", None)]
|
| 553 |
+
if remaining:
|
| 554 |
+
raise RuntimeError("LoRA adapters remain registered in " + ", ".join(remaining))
|
| 555 |
+
except Exception as error:
|
| 556 |
+
if strict:
|
| 557 |
+
raise RuntimeError("LoRA cleanup failed; the pipeline cannot be reused safely.") from error
|
| 558 |
+
return False
|
| 559 |
+
return True
|
stitch_cache.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded, process-local caches for CPU clip preparation.
|
| 2 |
+
|
| 3 |
+
Keep the existing normalizer: this module caches its output, not a cheaper
|
| 4 |
+
approximation. Each join stages its own hardlinks (or copies), so eviction and
|
| 5 |
+
another session cannot remove the files currently being concatenated.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from collections import OrderedDict
|
| 9 |
+
import atexit
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
import stat
|
| 16 |
+
import tempfile
|
| 17 |
+
import threading
|
| 18 |
+
import time
|
| 19 |
+
import uuid
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_CACHE_VERSION = "normalise-h264-fast-crf20-aac-v1"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def file_signature(path):
|
| 26 |
+
"""Invalidate when a source is replaced or edited, including same-size edits."""
|
| 27 |
+
resolved = os.path.normcase(os.path.realpath(os.fspath(path)))
|
| 28 |
+
info = os.stat(resolved)
|
| 29 |
+
if not stat.S_ISREG(info.st_mode):
|
| 30 |
+
raise ValueError("A queued clip is not a regular file.")
|
| 31 |
+
return (resolved, info.st_dev, info.st_ino, info.st_size,
|
| 32 |
+
info.st_mtime_ns, info.st_ctime_ns)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _link_or_copy(source, destination):
|
| 36 |
+
# Cache entries and staged parts are immutable. Both names remain valid if
|
| 37 |
+
# the other is unlinked; copy is the fallback for different filesystems.
|
| 38 |
+
try:
|
| 39 |
+
os.link(source, destination)
|
| 40 |
+
except OSError:
|
| 41 |
+
shutil.copyfile(source, destination)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class NormalizedClipCache:
|
| 45 |
+
"""An LRU bounded by both bytes and entries, isolated from other workers.
|
| 46 |
+
|
| 47 |
+
Only one cache miss is encoded at a time per worker. Hits remain available
|
| 48 |
+
while that happens, and simultaneous joins of the same clip share the
|
| 49 |
+
completed encode. No cache path is returned to a caller for later use.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, max_bytes=2 * 1024 ** 3, max_entries=128,
|
| 53 |
+
max_age_seconds=6 * 60 * 60):
|
| 54 |
+
self.max_bytes = max(0, int(max_bytes))
|
| 55 |
+
self.max_entries = max(0, int(max_entries))
|
| 56 |
+
self.max_age_seconds = max(0.0, float(max_age_seconds))
|
| 57 |
+
self._entries = OrderedDict()
|
| 58 |
+
self._bytes = 0
|
| 59 |
+
self._lock = threading.RLock()
|
| 60 |
+
self._build_lock = threading.Lock()
|
| 61 |
+
self._directory = None
|
| 62 |
+
atexit.register(self.close)
|
| 63 |
+
|
| 64 |
+
def _discard(self, key):
|
| 65 |
+
entry = self._entries.get(key)
|
| 66 |
+
if entry is None:
|
| 67 |
+
return True
|
| 68 |
+
try:
|
| 69 |
+
os.unlink(entry[0])
|
| 70 |
+
except FileNotFoundError:
|
| 71 |
+
pass
|
| 72 |
+
except OSError:
|
| 73 |
+
# For example, an OS may briefly deny unlinking an open file. Keep
|
| 74 |
+
# accounting for it and retry later rather than exceed the limit.
|
| 75 |
+
return False
|
| 76 |
+
del self._entries[key]
|
| 77 |
+
self._bytes -= entry[1]
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
def _expire(self):
|
| 81 |
+
cutoff = time.monotonic() - self.max_age_seconds
|
| 82 |
+
for key, entry in list(self._entries.items()):
|
| 83 |
+
if entry[2] <= cutoff:
|
| 84 |
+
self._discard(key)
|
| 85 |
+
|
| 86 |
+
def _reserve(self, size):
|
| 87 |
+
self._expire()
|
| 88 |
+
for key in list(self._entries):
|
| 89 |
+
if self._bytes + size <= self.max_bytes and len(self._entries) < self.max_entries:
|
| 90 |
+
break
|
| 91 |
+
self._discard(key)
|
| 92 |
+
return (self._bytes + size <= self.max_bytes and
|
| 93 |
+
len(self._entries) < self.max_entries)
|
| 94 |
+
|
| 95 |
+
def _hit(self, key, output_path):
|
| 96 |
+
with self._lock:
|
| 97 |
+
self._expire()
|
| 98 |
+
entry = self._entries.get(key)
|
| 99 |
+
if entry is None:
|
| 100 |
+
return False
|
| 101 |
+
try:
|
| 102 |
+
if os.path.getsize(entry[0]) != entry[1]:
|
| 103 |
+
self._discard(key)
|
| 104 |
+
return False
|
| 105 |
+
# Hold the lock until the caller has its own file. Eviction
|
| 106 |
+
# cannot race the link/copy, including on Windows.
|
| 107 |
+
_link_or_copy(entry[0], output_path)
|
| 108 |
+
except (FileNotFoundError, PermissionError):
|
| 109 |
+
self._discard(key)
|
| 110 |
+
return False
|
| 111 |
+
self._entries[key] = (entry[0], entry[1], time.monotonic())
|
| 112 |
+
self._entries.move_to_end(key)
|
| 113 |
+
return True
|
| 114 |
+
|
| 115 |
+
def _publish(self, key, output_path):
|
| 116 |
+
size = os.path.getsize(output_path)
|
| 117 |
+
if size <= 0:
|
| 118 |
+
raise RuntimeError("Normalizing a clip produced no complete output.")
|
| 119 |
+
if not self.max_entries or size > self.max_bytes or not self.max_age_seconds:
|
| 120 |
+
return
|
| 121 |
+
with self._lock:
|
| 122 |
+
# A stale entry whose unlink was denied must remain accounted for;
|
| 123 |
+
# do not overwrite its record and orphan its bytes on disk.
|
| 124 |
+
if key in self._entries and not self._discard(key):
|
| 125 |
+
return
|
| 126 |
+
if not self._reserve(size):
|
| 127 |
+
return
|
| 128 |
+
cache_path = None
|
| 129 |
+
try:
|
| 130 |
+
if self._directory is None:
|
| 131 |
+
# Never share cache filenames with a different process.
|
| 132 |
+
self._directory = tempfile.TemporaryDirectory(prefix="wan-stitch-cache-")
|
| 133 |
+
cache_path = os.path.join(self._directory.name, uuid.uuid4().hex + ".mp4")
|
| 134 |
+
_link_or_copy(output_path, cache_path)
|
| 135 |
+
self._entries[key] = (cache_path, size, time.monotonic())
|
| 136 |
+
self._bytes += size
|
| 137 |
+
except OSError as error:
|
| 138 |
+
# Caching is optional; a fully prepared join can still finish
|
| 139 |
+
# on a disk without room for an additional cached copy.
|
| 140 |
+
if cache_path is not None:
|
| 141 |
+
try:
|
| 142 |
+
os.unlink(cache_path)
|
| 143 |
+
except FileNotFoundError:
|
| 144 |
+
pass
|
| 145 |
+
except OSError:
|
| 146 |
+
# A failed cross-filesystem copy may leave a partial
|
| 147 |
+
# file. Account for its reserved upper bound until it
|
| 148 |
+
# can be removed, under a key that can never be a hit.
|
| 149 |
+
orphan_key = "incomplete:" + os.path.basename(cache_path)
|
| 150 |
+
self._entries[orphan_key] = (cache_path, size, 0.0)
|
| 151 |
+
self._bytes += size
|
| 152 |
+
print(f"[stitch-cache] could not retain part: {type(error).__name__}", flush=True)
|
| 153 |
+
|
| 154 |
+
def stage_clip(self, path, width, height, fps, output_path, *, normalise,
|
| 155 |
+
trim_head=False, colour="", include_audio=True):
|
| 156 |
+
"""Write one join-owned part; return True when an encode was reused.
|
| 157 |
+
|
| 158 |
+
`normalise` has the app's _normalise_clip signature. Its HDR mapping,
|
| 159 |
+
audio alignment/silence, geometry, frame rate and seam trim stay intact.
|
| 160 |
+
Bump _CACHE_VERSION if the normalization settings change at runtime.
|
| 161 |
+
"""
|
| 162 |
+
path, output_path = os.fspath(path), os.fspath(output_path)
|
| 163 |
+
if os.path.normcase(os.path.realpath(path)) == os.path.normcase(os.path.realpath(output_path)):
|
| 164 |
+
raise ValueError("A normalized part must not overwrite its source.")
|
| 165 |
+
fps = float(fps)
|
| 166 |
+
if not math.isfinite(fps) or fps <= 0:
|
| 167 |
+
raise ValueError("The stitching frame rate must be positive and finite.")
|
| 168 |
+
transform = (_CACHE_VERSION, int(width), int(height), fps.hex(),
|
| 169 |
+
bool(trim_head), str(colour), bool(include_audio))
|
| 170 |
+
|
| 171 |
+
def signature_and_key():
|
| 172 |
+
signature = file_signature(path)
|
| 173 |
+
payload = json.dumps((signature, transform), ensure_ascii=True, separators=(",", ":"))
|
| 174 |
+
return signature, hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 175 |
+
|
| 176 |
+
before, key = signature_and_key()
|
| 177 |
+
if self._hit(key, output_path):
|
| 178 |
+
if file_signature(path) != before:
|
| 179 |
+
raise RuntimeError("A queued clip changed while stitching. Retry Join.")
|
| 180 |
+
return True
|
| 181 |
+
with self._build_lock:
|
| 182 |
+
# A previous join may have completed this exact part while we
|
| 183 |
+
# waited. Re-read source metadata as well before doing any work.
|
| 184 |
+
before, key = signature_and_key()
|
| 185 |
+
if self._hit(key, output_path):
|
| 186 |
+
if file_signature(path) != before:
|
| 187 |
+
raise RuntimeError("A queued clip changed while stitching. Retry Join.")
|
| 188 |
+
return True
|
| 189 |
+
normalise(path, width, height, fps, output_path,
|
| 190 |
+
trim_head=trim_head, colour=colour, include_audio=include_audio)
|
| 191 |
+
if file_signature(path) != before:
|
| 192 |
+
raise RuntimeError("A queued clip changed while stitching. Retry Join.")
|
| 193 |
+
self._publish(key, output_path)
|
| 194 |
+
return False
|
| 195 |
+
|
| 196 |
+
def close(self):
|
| 197 |
+
"""Release only this worker's private cache, never original clips."""
|
| 198 |
+
with self._build_lock:
|
| 199 |
+
with self._lock:
|
| 200 |
+
if self._directory is not None:
|
| 201 |
+
try:
|
| 202 |
+
self._directory.cleanup()
|
| 203 |
+
except OSError:
|
| 204 |
+
return
|
| 205 |
+
self._directory = None
|
| 206 |
+
self._entries.clear()
|
| 207 |
+
self._bytes = 0
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class FileMemo:
|
| 211 |
+
"""Small metadata/frame cache; loaders must return values callers do not mutate."""
|
| 212 |
+
|
| 213 |
+
def __init__(self, max_entries=512, max_age_seconds=6 * 60 * 60):
|
| 214 |
+
self.max_entries = max(0, int(max_entries))
|
| 215 |
+
self.max_age_seconds = max(0.0, float(max_age_seconds))
|
| 216 |
+
self._entries = OrderedDict()
|
| 217 |
+
self._lock = threading.RLock()
|
| 218 |
+
|
| 219 |
+
def get(self, path, probe_name, loader):
|
| 220 |
+
# Separate from the encoding lock: cheap metadata hits never wait for
|
| 221 |
+
# an H.264 encode. RLock also permits loaders to consult another probe.
|
| 222 |
+
with self._lock:
|
| 223 |
+
signature = file_signature(path)
|
| 224 |
+
key = (str(probe_name), signature)
|
| 225 |
+
now = time.monotonic()
|
| 226 |
+
for old_key, entry in list(self._entries.items()):
|
| 227 |
+
if now - entry[1] >= self.max_age_seconds:
|
| 228 |
+
del self._entries[old_key]
|
| 229 |
+
if key in self._entries:
|
| 230 |
+
value, _ = self._entries[key]
|
| 231 |
+
self._entries[key] = (value, now)
|
| 232 |
+
self._entries.move_to_end(key)
|
| 233 |
+
return value
|
| 234 |
+
value = loader()
|
| 235 |
+
if file_signature(path) != signature:
|
| 236 |
+
raise RuntimeError("A queued clip changed while reading its metadata.")
|
| 237 |
+
if value is not None and self.max_entries and self.max_age_seconds:
|
| 238 |
+
self._entries[key] = (value, time.monotonic())
|
| 239 |
+
while len(self._entries) > self.max_entries:
|
| 240 |
+
self._entries.popitem(last=False)
|
| 241 |
+
return value
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
_normalised = NormalizedClipCache()
|
| 245 |
+
_metadata = FileMemo()
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def stage_clip(path, width, height, fps, output_path, *, normalise,
|
| 249 |
+
trim_head=False, colour="", include_audio=True):
|
| 250 |
+
return _normalised.stage_clip(path, width, height, fps, output_path,
|
| 251 |
+
normalise=normalise, trim_head=trim_head,
|
| 252 |
+
colour=colour, include_audio=include_audio)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def memoize_file(path, probe_name, loader):
|
| 256 |
+
return _metadata.get(path, probe_name, loader)
|