diff --git "a/app.py" "b/app.py"
--- "a/app.py"
+++ "b/app.py"
@@ -44,7 +44,7 @@ IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))
get_timestamp_js = """
function() {
const video = document.querySelector('#generated-video video');
-
+
if (video) {
console.log("Video found! Time: " + video.currentTime);
return video.currentTime;
@@ -56,31 +56,34 @@ function() {
"""
+get_timestamp_js_last = get_timestamp_js
+
+
def extract_frame(video_path, timestamp):
if not video_path:
return None
-
- print(f"Extracting frame at timestamp: {timestamp}")
-
+
+ print(f"Extracting frame at timestamp: {timestamp}")
+
cap = cv2.VideoCapture(video_path)
-
+
if not cap.isOpened():
return None
fps = cap.get(cv2.CAP_PROP_FPS)
target_frame_num = int(float(timestamp) * fps)
-
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if target_frame_num >= total_frames:
target_frame_num = total_frames - 1
-
+
cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_num)
ret, frame = cap.read()
cap.release()
-
+
if ret:
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
-
+
return None
# --- END FRAME EXTRACTION LOGIC ---
@@ -122,7 +125,7 @@ def interpolate_bits(frames_np, multiplier=2, scale=1.0):
return frames_np
n_interp = multiplier - 1
-
+
tmp = max(128, int(128 / scale))
ph = ((H - 1) // tmp + 1) * tmp
pw = ((W - 1) // tmp + 1) * tmp
@@ -171,7 +174,7 @@ def interpolate_bits(frames_np, multiplier=2, scale=1.0):
pbar.update(50)
pbar.update(total_steps % 50)
output_frames.append(from_tensor(I1))
-
+
del I0, I1, mid_tensors
torch.cuda.empty_cache()
return output_frames
@@ -215,14 +218,14 @@ original_scheduler = copy.deepcopy(pipe.scheduler)
for i, lora in enumerate(LORA_MODELS):
name_high_tr = lora["high_tr"].split(".")[0].split("/")[-1] + "Hh"
name_low_tr = lora["low_tr"].split(".")[0].split("/")[-1] + "Ll"
-
- try:
+
+ try:
pipe.load_lora_weights(
lora["repo_id"],
weight_name=lora["high_tr"],
adapter_name=name_high_tr
)
-
+
kwargs_lora = {"load_into_transformer_2": True}
pipe.load_lora_weights(
lora["repo_id"],
@@ -230,18 +233,18 @@ for i, lora in enumerate(LORA_MODELS):
adapter_name=name_low_tr,
**kwargs_lora
)
-
+
pipe.set_adapters([name_high_tr, name_low_tr], adapter_weights=[1.0, 1.0])
-
+
pipe.fuse_lora(adapter_names=[name_high_tr], lora_scale=lora["high_scale"], components=["transformer"])
pipe.fuse_lora(adapter_names=[name_low_tr], lora_scale=lora["low_scale"], components=["transformer_2"])
-
+
pipe.unload_lora_weights()
- print(f"Applied: {lora['high_tr']}, hs={lora['high_scale']}/ls={lora['low_scale']}, {i+1}/{len(LORA_MODELS)}")
+ print(f"Applied: {lora['high_tr']}, hs={lora['high_scale']}/ls={lora['low_scale']}, {i+1}/{len(LORA_MODELS)}")
except Exception as e:
print("Error:", str(e))
- print("Failed LoRA:", name_high_tr)
+ print("Failed lora:", name_high_tr)
pipe.unload_lora_weights()
quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
@@ -265,31 +268,136 @@ default_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字
LORA_CHOICES = lora_loader.get_lora_choices()
+# ---------- Speed / step presets ----------
+
+SPEED_LORA_SOURCES = {
+ "seko_v1": {
+ "repo": "lightx2v/Wan2.2-Lightning",
+ "file_high": "Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors",
+ "file_low": "Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors",
+ },
+ "distill": {
+ "repo": "lightx2v/Wan2.2-Distill-Loras",
+ "match_high": ["i2v", "high", "4step"],
+ "match_low": ["i2v", "low", "4step"],
+ },
+}
+
+SPEED_NONE = "Built-in Lightning · 6 steps (balanced)"
+
+SPEED_PRESETS = {
+ "Built-in Lightning · 4 steps (fastest)":
+ {"steps": 4, "flow_shift": 3.0, "scheduler": "UniPCMultistep", "lora": None},
+ SPEED_NONE:
+ {"steps": 6, "flow_shift": 3.0, "scheduler": "UniPCMultistep", "lora": None},
+ "Built-in Lightning · 8 steps (best motion)":
+ {"steps": 8, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": None},
+ "Lightning lora (lightx2v Seko V1) · 4 steps":
+ {"steps": 4, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": "seko_v1"},
+ "Lightning lora (lightx2v Seko V1) · 6 steps":
+ {"steps": 6, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": "seko_v1"},
+ "Lightning lora (lightx2v Seko V1) · 8 steps":
+ {"steps": 8, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": "seko_v1"},
+ "Distill lora (lightx2v 4step) · 4 steps":
+ {"steps": 4, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": "distill"},
+ "Distill lora (lightx2v 4step) · 8 steps":
+ {"steps": 8, "flow_shift": 5.0, "scheduler": "UniPCMultistep", "lora": "distill"},
+}
+
+_SPEED_CACHE = {}
+
+
+def _match_all(name, keys):
+ n = str(name).lower()
+ return all(k in n for k in keys)
+
+
+def resolve_speed_lora(key):
+ if not key:
+ return None
+ if key in _SPEED_CACHE:
+ return _SPEED_CACHE[key]
+
+ src = SPEED_LORA_SOURCES.get(key)
+ if not src:
+ return None
+
+ if "file_high" in src:
+ out = {"repo": src["repo"], "file_high": src["file_high"], "file_low": src["file_low"]}
+ _SPEED_CACHE[key] = out
+ return out
+
+ try:
+ files = list(lora_loader.list_loras_from_repo(src["repo"]))
+ except Exception as e:
+ print("Speed lora listing failed:", e)
+ return None
+
+ highs = [f for f in files if f and f != "(None)" and _match_all(f, src["match_high"])]
+ lows = [f for f in files if f and f != "(None)" and _match_all(f, src["match_low"])]
+ if not highs or not lows:
+ print("Speed lora files not found in", src["repo"])
+ return None
+
+ out = {"repo": src["repo"], "file_high": sorted(highs)[-1], "file_low": sorted(lows)[-1]}
+ _SPEED_CACHE[key] = out
+ return out
+
+
+PROMPT_CHIPS = [
+ "cinematic motion",
+ "slow camera zoom in",
+ "camera orbit around subject",
+ "slow dolly forward",
+ "gentle handheld camera",
+ "wind blowing, hair and cloth moving",
+ "soft natural light, shallow depth of field",
+ "subject slowly turns head and smiles",
+ "rain falling, wet reflections",
+ "smoke and dust particles in the air",
+]
+
def model_title():
return "## Wan 2.2 I2V 14B Custom Lora"
-def resize_image(image: Image.Image) -> Image.Image:
+def resize_image(image: Image.Image, aspect_mode: str = "crop") -> Image.Image:
+ """Fit an image into the model's frame. The checkpoint accepts 480 to 832 on a side, so anything
+ taller than 832:480 (1.73:1) cannot be represented as it is - a 487x1056 phone shot is 2.17:1.
+ `crop` takes the middle out, `pad` keeps the whole picture and fills the rest with black."""
width, height = image.size
if width == height:
return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)
-
+
aspect_ratio = width / height
MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
MIN_ASPECT_RATIO = MIN_DIM / MAX_DIM
image_to_resize = image
- if aspect_ratio > MAX_ASPECT_RATIO:
- target_w, target_h = MAX_DIM, MIN_DIM
- crop_width = int(round(height * MAX_ASPECT_RATIO))
- left = (width - crop_width) // 2
- image_to_resize = image.crop((left, 0, left + crop_width, height))
- elif aspect_ratio < MIN_ASPECT_RATIO:
- target_w, target_h = MIN_DIM, MAX_DIM
- crop_height = int(round(width / MIN_ASPECT_RATIO))
- top = (height - crop_height) // 2
- image_to_resize = image.crop((0, top, width, top + crop_height))
+ if aspect_ratio > MAX_ASPECT_RATIO or aspect_ratio < MIN_ASPECT_RATIO:
+ wide = aspect_ratio > MAX_ASPECT_RATIO
+ target_w, target_h = (MAX_DIM, MIN_DIM) if wide else (MIN_DIM, MAX_DIM)
+
+ if str(aspect_mode).startswith("pad"):
+ # The whole picture, scaled to fit inside the frame, centred on black. Nothing is lost;
+ # the bars are.
+ final_w = max(MIN_DIM, min(MAX_DIM, round(target_w / MULTIPLE_OF) * MULTIPLE_OF))
+ final_h = max(MIN_DIM, min(MAX_DIM, round(target_h / MULTIPLE_OF) * MULTIPLE_OF))
+ scale = min(final_w / width, final_h / height)
+ inner = image.resize((max(1, int(width * scale)), max(1, int(height * scale))), Image.LANCZOS)
+ canvas = Image.new("RGB", (final_w, final_h), (0, 0, 0))
+ canvas.paste(inner, ((final_w - inner.width) // 2, (final_h - inner.height) // 2))
+ return canvas
+
+ if wide:
+ crop_width = int(round(height * MAX_ASPECT_RATIO))
+ left = (width - crop_width) // 2
+ image_to_resize = image.crop((left, 0, left + crop_width, height))
+ else:
+ crop_height = int(round(width / MIN_ASPECT_RATIO))
+ top = (height - crop_height) // 2
+ image_to_resize = image.crop((0, top, width, top + crop_height))
else:
if width > height:
target_w = MAX_DIM
@@ -340,8 +448,12 @@ def get_inference_duration(
lora_groups,
progress
):
+ # Recalibrated after a report of an 8 s clip at 128 fps fluidity being killed mid-interpolation.
+ # Two numbers were optimistic: the per-step cost, and above all the 0.02 s per interpolated frame -
+ # at 128 fps RIFE produces eight frames for every one the model made, so a 129-frame clip becomes
+ # over a thousand, and the error compounds there rather than in the diffusion.
BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624
- BASE_STEP_DURATION = 5.
+ BASE_STEP_DURATION = 7.
width, height = resized_image.size
factor = num_frames * width * height / BASE_FRAMES_HEIGHT_WIDTH
step_duration = BASE_STEP_DURATION * factor ** 1.5
@@ -353,14 +465,15 @@ def get_inference_duration(
frame_factor = frame_multiplier // FIXED_FPS
if frame_factor > 1:
total_out_frames = (num_frames * frame_factor) - num_frames
- inter_time = (total_out_frames * 0.02)
- gen_time += inter_time
+ gen_time += total_out_frames * 0.06
- total_time = 15 + gen_time
+ total_time = 20 + gen_time
if safe_mode:
total_time = total_time * 1.30
- return total_time
+ # ZeroGPU refuses a booking above its own ceiling outright, and `size="xlarge"` doubles what is
+ # asked for, so a runaway estimate fails before it starts.
+ return min(total_time, 600)
@spaces.GPU(duration=get_inference_duration, size='xlarge')
@@ -395,16 +508,33 @@ def run_inference(
clear_vram()
task_name = str(uuid.uuid4())[:8]
- print(f"Generating {num_frames} frames, task: {task_name}, {duration_seconds}, {resized_image.size}, lora={lora_groups}")
+
+ # Only the shape of the request: no prompt text, and adapters by name rather than by what the
+ # visitor typed. Enough to read a report or spot a bad adapter, without recording anybody's words.
+ active = []
+ for group in lora_groups or []:
+ if group.get("preset") and group["preset"] != "(None)":
+ active.append(f"{group['preset']} @ {group.get('high_scale')}/{group.get('low_scale')}")
+ continue
+ for role in ("file_high", "file_low"):
+ value = group.get(role)
+ if value and value != "(None)":
+ scale = group.get("high_scale" if role == "file_high" else "low_scale")
+ active.append(f"{os.path.basename(str(value))[:60]} ({role[5:]}) @ {scale}")
+
+ print(f"[request {task_name}] {num_frames} frames, {duration_seconds}s, {resized_image.size}, "
+ f"{int(steps)} steps, seed {current_seed}")
+ if active:
+ print(f"[request {task_name}] lora: {', '.join(active)}")
start = time.time()
lora_loaded = False
if lora_groups:
try:
lora_loaded = lora_loader.load_lora_slots(pipe, lora_groups)
- print(f"LoRA loaded: {lora_groups}")
+ print(f"lora loaded: {lora_groups}")
except Exception as e:
- print(f"LoRA warning: {e}")
+ print(f"lora warning: {e}")
try:
lora_loader.unload_lora(pipe)
except Exception:
@@ -475,6 +605,10 @@ def generate_video(
flow_shift=6.0,
frame_multiplier=16,
safe_mode=False,
+ aspect_mode="crop",
+ speed_preset=SPEED_NONE,
+ speed_high_scale=1.0,
+ speed_low_scale=1.0,
# original 3
lora1_preset="(None)",
lora1_high_scale=1.0,
@@ -497,14 +631,33 @@ def generate_video(
if input_image is None:
raise gr.Error("Please upload an input image.")
+ wall_start = time.time()
+
num_frames = get_num_frames(duration_seconds)
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
- resized_image = resize_image(input_image)
+ resized_image = resize_image(input_image, aspect_mode)
processed_last_image = None
if last_image:
processed_last_image = resize_and_crop_to_match(last_image, resized_image)
+ preset_cfg = SPEED_PRESETS.get(speed_preset) or {}
+ speed_info = ""
+ speed_group = None
+ if preset_cfg.get("lora"):
+ resolved = resolve_speed_lora(preset_cfg["lora"])
+ if resolved:
+ speed_group = {
+ "repo": resolved["repo"],
+ "file_high": resolved["file_high"],
+ "file_low": resolved["file_low"],
+ "high_scale": speed_high_scale,
+ "low_scale": speed_low_scale,
+ }
+ speed_info = f"speed lora on"
+ else:
+ speed_info = "speed lora not found — skipped"
+
lora_groups = [
{"preset": lora1_preset, "high_scale": lora1_high_scale, "low_scale": lora1_low_scale},
{"preset": lora2_preset, "high_scale": lora2_high_scale, "low_scale": lora2_low_scale},
@@ -516,6 +669,9 @@ def generate_video(
{"repo": my5_repo, "file_high": my5_high, "file_low": my5_low, "high_scale": my5_hs, "low_scale": my5_ls},
]
+ if speed_group:
+ lora_groups.insert(0, speed_group)
+
video_path, task_n = run_inference(
resized_image,
processed_last_image,
@@ -537,18 +693,941 @@ def generate_video(
)
print(f"GPU complete: {task_n}")
- return (video_path if video_component else None), video_path, current_seed
+ elapsed = time.time() - wall_start
+ w, h = resized_image.size
+ status = (
+ "
"
+ "✓ Ready"
+ f"{w}×{h}"
+ f"{num_frames} frames · {int(frame_multiplier)} fps"
+ f"seed {current_seed}"
+ f"{int(steps)} steps"
+ + speed_info +
+ f"{elapsed:.1f} s"
+ "
"
+ )
+
+ return (video_path if video_component else None), video_path, current_seed, status
+
+
+def _pick_file(files, *keys):
+ for key in keys:
+ for f in files:
+ if f and f != "(None)" and key in str(f).lower():
+ return f
+ return "(None)"
def _load_repo_files(repo_link):
- files = lora_loader.list_loras_from_repo(repo_link)
+ if not repo_link or not str(repo_link).strip():
+ return (
+ gr.update(choices=["(None)"], value="(None)"),
+ gr.update(choices=["(None)"], value="(None)"),
+ )
+
+ # A CivitAI (or any other) download link is a single file, not a repo to list: put it in the
+ # High box and leave Low empty, since a Wan adapter ships its two halves as two separate files.
+ link = str(repo_link).strip()
+ if getattr(lora_loader, "is_direct_link", lambda _: False)(link):
+ return (
+ gr.update(choices=["(None)", link], value=link),
+ gr.update(choices=["(None)", link], value="(None)"),
+ )
+ try:
+ files = lora_loader.list_loras_from_repo(repo_link)
+ except Exception as e:
+ raise gr.Error(f"Cannot read repo: {e}")
+
+ files = list(files) if files else []
+ if "(None)" not in files:
+ files = ["(None)"] + files
+
+ auto_high = _pick_file(files, "high", "_h.", "-h.", "hn")
+ auto_low = _pick_file(files, "low", "_l.", "-l.", "ln")
+
return (
- gr.update(choices=files, value="(None)"),
- gr.update(choices=files, value="(None)"),
+ gr.update(choices=files, value=auto_high),
+ gr.update(choices=files, value=auto_low),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Named profiles
+# ---------------------------------------------------------------------------
+# Everything typed rather than uploaded, stored under a name inside the Space.
+# `/data` is used when the Space has persistent storage attached, so profiles
+# survive a restart; otherwise they live for as long as the Space runs.
+
+import json
+import re
+import tempfile
+import time
+
+if os.path.isdir("/data") and os.access("/data", os.W_OK):
+ PROFILES_DIR = os.path.join("/data", "wan22-profiles")
+else:
+ PROFILES_DIR = os.path.join(tempfile.gettempdir(), "wan22-profiles")
+os.makedirs(PROFILES_DIR, exist_ok=True)
+
+NO_PROFILE = "\u2014 no saved profile \u2014"
+
+SETTINGS_KEYS = [
+ "prompt", "negative_prompt", "duration", "steps", "quality",
+ "seed", "randomize_seed", "scheduler", "flow_shift", "fps", "safe_mode",
+ "speed_preset", "speed_high_scale", "speed_low_scale",
+ "lora1_preset", "lora1_high", "lora1_low",
+ "lora2_preset", "lora2_high", "lora2_low",
+ "lora3_preset", "lora3_high", "lora3_low",
+]
+for _slot in range(1, 6):
+ SETTINGS_KEYS += [
+ f"my{_slot}_repo", f"my{_slot}_high_file", f"my{_slot}_high_scale",
+ f"my{_slot}_low_file", f"my{_slot}_low_scale",
+ ]
+
+# The per-repo file dropdowns are populated only after a repo has been read, so a restored value
+# would not be among the choices. These keys get their choice list rebuilt around the stored value.
+_FILE_DROPDOWN_KEYS = {f"my{slot}_{end}_file" for slot in range(1, 6) for end in ("high", "low")}
+
+
+def _profile_path(name):
+ safe = re.sub(r"[^A-Za-z0-9 ._-]", "_", str(name or "").strip())[:64].strip() or "profile"
+ return os.path.join(PROFILES_DIR, f"{safe}.json")
+
+
+def list_profiles():
+ if not os.path.isdir(PROFILES_DIR):
+ return []
+ return [entry[:-5] for entry in sorted(os.listdir(PROFILES_DIR)) if entry.endswith(".json")]
+
+
+def refresh_profiles(current=None):
+ """Re-read the folder. The dropdown's choices are built once at start-up, so a profile saved in
+ another tab (or after this page was opened) would otherwise stay invisible until a restart."""
+ names = list_profiles()
+ value = current if current in names else NO_PROFILE
+ return gr.update(choices=[NO_PROFILE, *names], value=value)
+
+
+def save_profile(name, *values):
+ if not str(name or "").strip():
+ return gr.update(), "Give the profile a name first."
+ payload = {"saved": time.strftime("%Y-%m-%d %H:%M:%S")}
+ payload.update(dict(zip(SETTINGS_KEYS, values)))
+ try:
+ with open(_profile_path(name), "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, ensure_ascii=False, indent=2, default=str)
+ except Exception as error:
+ return gr.update(), f"Could not save: `{type(error).__name__}: {error}`"
+ saved = os.path.basename(_profile_path(name))[:-5]
+ return gr.update(choices=[NO_PROFILE, *list_profiles()], value=saved), f"Saved **{saved}**."
+
+
+def load_profile(name):
+ blank = [gr.update() for _ in SETTINGS_KEYS]
+ if not name or name == NO_PROFILE:
+ return [*blank, gr.update(), ""]
+ path = _profile_path(name)
+ if not os.path.exists(path):
+ return [*blank, gr.update(), f"No profile named **{name}**."]
+ try:
+ with open(path, encoding="utf-8") as handle:
+ payload = json.load(handle)
+ except Exception as error:
+ return [*blank, gr.update(), f"Could not read it: `{type(error).__name__}: {error}`"]
+
+ updates = []
+ for key in SETTINGS_KEYS:
+ value = payload.get(key)
+ if value is None:
+ updates.append(gr.update())
+ elif key in _FILE_DROPDOWN_KEYS:
+ choices = ["(None)"] if value == "(None)" else ["(None)", value]
+ updates.append(gr.update(choices=choices, value=value))
+ else:
+ updates.append(gr.update(value=value))
+ stamp = payload.get("saved", "")
+ return [*updates, gr.update(value=name), f"Loaded **{name}**{f' (saved {stamp})' if stamp else ''}."]
+
+
+def delete_profile(name):
+ if not name or name == NO_PROFILE:
+ return gr.update(), "Pick a profile first."
+ try:
+ os.remove(_profile_path(name))
+ except FileNotFoundError:
+ return gr.update(choices=[NO_PROFILE, *list_profiles()], value=NO_PROFILE), f"No profile named **{name}**."
+ except Exception as error:
+ return gr.update(), f"Could not delete: `{type(error).__name__}: {error}`"
+ return gr.update(choices=[NO_PROFILE, *list_profiles()], value=NO_PROFILE), f"Deleted **{name}**."
+
+
+def export_settings(*values):
+ payload = {"saved": time.strftime("%Y-%m-%d %H:%M:%S")}
+ payload.update(dict(zip(SETTINGS_KEYS, values)))
+ directory = os.path.join(tempfile.gettempdir(), "wan22-settings")
+ os.makedirs(directory, exist_ok=True)
+ path = os.path.join(directory, f"wan22-settings-{int(time.time())}.json")
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, ensure_ascii=False, indent=2, default=str)
+ return gr.update(value=path, visible=True)
+
+
+def import_settings(path):
+ if not path:
+ return [gr.update() for _ in SETTINGS_KEYS]
+ try:
+ with open(path, encoding="utf-8") as handle:
+ payload = json.load(handle)
+ except Exception as error:
+ raise gr.Error(f"That settings file cannot be read: `{type(error).__name__}: {error}`")
+ updates = []
+ for key in SETTINGS_KEYS:
+ value = payload.get(key)
+ if value is None:
+ updates.append(gr.update())
+ elif key in _FILE_DROPDOWN_KEYS:
+ choices = ["(None)"] if value == "(None)" else ["(None)", value]
+ updates.append(gr.update(choices=choices, value=value))
+ else:
+ updates.append(gr.update(value=value))
+ return updates
+
+
+# ---------------------------------------------------------------------------
+# Clip stitching, boomerang, and persistent saving - all CPU, zero GPU quota
+# ---------------------------------------------------------------------------
+# Every one of these runs after the video already exists, so none of them touch
+# the card or the ZeroGPU allowance. Chaining three 3.5 s clips into a 10 s one
+# costs nothing extra.
+
+def _ffmpeg_exe() -> str:
+ """imageio-ffmpeg ships a binary, so this works even when the image has no
+ system ffmpeg."""
+ try:
+ import imageio_ffmpeg
+ return imageio_ffmpeg.get_ffmpeg_exe()
+ except Exception:
+ return "ffmpeg"
+
+
+def _video_size(path):
+ capture = cv2.VideoCapture(path)
+ width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
+ height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
+ capture.release()
+ return (width or 832), (height or 624)
+
+
+def _persist(path):
+ """Copy to /data/videos when the Space has persistent storage attached, so a
+ restart does not take the clip with it."""
+ if not path or not os.path.isdir("/data") or not os.access("/data", os.W_OK):
+ return
+ try:
+ target_dir = os.path.join("/data", "videos")
+ os.makedirs(target_dir, exist_ok=True)
+ shutil.copy(path, os.path.join(target_dir, os.path.basename(path)))
+ print(f"[storage] saved to /data/videos/{os.path.basename(path)}")
+ except Exception as error:
+ print(f"[storage] could not save: {error}")
+
+
+def concat_videos(paths, name_hint=""):
+ """Stitch clips into one file. Everything is scaled and padded to the first
+ clip's frame so a mixed-aspect queue still concatenates cleanly."""
+ valid = [p for p in (paths or []) if p and os.path.exists(p)]
+ if not valid:
+ return None
+ if len(valid) == 1:
+ return valid[0]
+
+ width, height = _video_size(valid[0])
+ prefix = uuid.uuid4().hex[:4]
+ clean = (str(name_hint).strip().replace(" ", "_") or f"merged_{len(valid)}clips")
+ if clean.lower().endswith(".mp4"):
+ clean = clean[:-4]
+ out_path = os.path.join(tempfile.gettempdir(), f"{prefix}_{clean}.mp4")
+
+ inputs, chains = [], []
+ for index, path in enumerate(valid):
+ inputs += ["-i", path]
+ chains.append(
+ f"[{index}:v]scale={width}:{height}:force_original_aspect_ratio=decrease,"
+ f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1[v{index}];"
+ )
+ joined = "".join(f"[v{i}]" for i in range(len(valid)))
+ filter_str = "".join(chains) + f"{joined}concat=n={len(valid)}:v=1:a=0[outv]"
+
+ command = [_ffmpeg_exe(), "-y", *inputs, "-filter_complex", filter_str,
+ "-map", "[outv]", "-c:v", "libx264", "-preset", "fast", "-crf", "20",
+ "-movflags", "+faststart", out_path]
+ try:
+ subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ except Exception as error:
+ print(f"[merge] filter_complex failed ({error}); trying the concat demuxer")
+ list_file = os.path.join(tempfile.gettempdir(), f"concat_{prefix}.txt")
+ with open(list_file, "w", encoding="utf-8") as handle:
+ for path in valid:
+ handle.write(f"file '{path}'\n")
+ subprocess.run([_ffmpeg_exe(), "-y", "-f", "concat", "-safe", "0", "-i", list_file,
+ "-c", "copy", "-movflags", "+faststart", out_path], check=False)
+ if os.path.exists(out_path):
+ _persist(out_path)
+ return out_path
+ return valid[-1]
+
+
+def _queue_status(count, path=None):
+ if not count:
+ return "Merge queue: empty
"
+ name = f" → {os.path.basename(path)}" if path else ""
+ return f"{count} clip(s) in the queue{name}
"
+
+
+def add_to_queue(video_path, queue, name_hint):
+ queue = list(queue or [])
+ if video_path and os.path.exists(video_path):
+ queue.append(video_path)
+ if not queue:
+ return None, None, [], _queue_status(0)
+ merged = concat_videos(queue, name_hint)
+ return merged, merged, queue, _queue_status(len(queue), merged)
+
+
+def clear_queue():
+ return None, None, [], _queue_status(0)
+
+
+def auto_queue(video_path, auto_on, queue, name_hint):
+ """Runs after every generation; only appends when the box is ticked."""
+ if not auto_on:
+ queue = list(queue or [])
+ if not queue:
+ return gr.update(), gr.update(), queue, _queue_status(0)
+ return gr.update(), gr.update(), queue, _queue_status(len(queue))
+ return add_to_queue(video_path, queue, name_hint)
+
+
+def boomerang(video_path, mode, tail_seconds=2.0):
+ """`full` plays forward then backward. `ending` keeps the clip as it is and
+ boomerangs only its tail, which loops without the whole thing rewinding."""
+ if not video_path or not os.path.exists(video_path):
+ raise gr.Error("Generate a video first.")
+
+ prefix = uuid.uuid4().hex[:4]
+ out_path = os.path.join(tempfile.gettempdir(), f"{prefix}_boomerang.mp4")
+
+ if mode == "ending":
+ capture = cv2.VideoCapture(video_path)
+ fps = capture.get(cv2.CAP_PROP_FPS) or 16
+ total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
+ capture.release()
+ duration = total / fps if fps else 0
+ start = max(0.0, duration - float(tail_seconds))
+ filter_str = (
+ f"[0:v]split=2[base][tail];"
+ f"[tail]trim=start={start:.3f},setpts=PTS-STARTPTS,reverse[rev];"
+ f"[base][rev]concat=n=2:v=1[outv]"
+ )
+ else:
+ filter_str = "[0:v]split=2[a][b];[b]reverse[r];[a][r]concat=n=2:v=1[outv]"
+
+ command = [_ffmpeg_exe(), "-y", "-i", video_path, "-filter_complex", filter_str,
+ "-map", "[outv]", "-c:v", "libx264", "-preset", "fast", "-crf", "20",
+ "-movflags", "+faststart", out_path]
+ try:
+ subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ except Exception as error:
+ raise gr.Error(f"Loop failed: {error}")
+ _persist(out_path)
+ return out_path, out_path
+
+
+# ---------------------------------------------------------------------------
+# Prompt building and enhancement
+# ---------------------------------------------------------------------------
+# Two paths. The builder is pure string work: it takes what you typed and wraps
+# it in the camera, framing, light and pacing language Wan responds to. It is
+# instant, costs nothing, and cannot fail or refuse.
+#
+# The model path runs an abliterated Qwen3-4B - a small instruct model with its
+# refusal directions removed - so it writes the paragraph for you whatever the
+# subject is. The weights are fetched on the CPU, outside GPU time; only the
+# generation itself books the card, and it books ~45 s.
+
+ENHANCER_MODEL = os.environ.get(
+ "ENHANCER_MODEL", "huihui-ai/Huihui-Qwen3-4B-Instruct-2507-abliterated"
+)
+
+CAMERA_MOVES = {
+ "(keep as written)": "",
+ "static shot": "the camera holds still",
+ "slow push in": "the camera pushes in slowly",
+ "slow pull back": "the camera pulls back slowly",
+ "orbit around the subject": "the camera orbits around the subject",
+ "tracking alongside": "the camera tracks alongside the subject",
+ "handheld, subtle shake": "handheld camera with a subtle shake",
+ "tilt up": "the camera tilts up",
+ "tilt down": "the camera tilts down",
+ "crane up and back": "the camera cranes up and back",
+}
+
+FRAMINGS = {
+ "(keep as written)": "",
+ "extreme close-up": "extreme close-up",
+ "close-up": "close-up",
+ "medium shot": "medium shot",
+ "medium wide": "medium wide shot",
+ "wide shot": "wide shot",
+ "low angle": "low angle shot",
+ "high angle": "high angle shot",
+ "over the shoulder": "over-the-shoulder shot",
+ "point of view": "point-of-view shot",
+}
+
+LIGHTING = {
+ "(keep as written)": "",
+ "soft natural light": "soft natural light, gentle falloff",
+ "golden hour": "warm golden-hour light with a soft rim",
+ "hard key light": "a hard key light with deep shadows",
+ "candle / firelight": "flickering warm candlelight",
+ "neon night": "neon light, wet reflections, night",
+ "overcast daylight": "flat overcast daylight",
+ "studio softbox": "clean studio softbox lighting on a plain backdrop",
+ "single lamp in a dark room": "one warm lamp in an otherwise dark room",
+ "moonlight": "cool moonlight through a window",
+}
+
+PACING = {
+ "(keep as written)": "",
+ "slow and deliberate": "slow, deliberate movement",
+ "steady": "steady, even movement",
+ "building": "movement that builds through the shot",
+ "fast and urgent": "fast, urgent movement",
+ "loose and languid": "loose, languid movement",
+}
+
+QUALITY_TAIL = (
+ "photorealistic, natural skin texture, shallow depth of field, "
+ "consistent anatomy, smooth motion, no morphing"
+)
+
+
+def _strip_built(text):
+ """Remove sentences a previous Build added, so pressing it again rewrites rather than stacks."""
+ known = {QUALITY_TAIL.lower().rstrip(".")}
+ for table in (LIGHTING, PACING):
+ for value in table.values():
+ if value:
+ known.add(value.lower().rstrip("."))
+ for framing in FRAMINGS.values():
+ for camera in CAMERA_MOVES.values():
+ joined = ", ".join(part for part in (framing, camera) if part)
+ if joined:
+ known.add(joined.lower().rstrip("."))
+
+ kept = []
+ for sentence in re.split(r"(?<=\.)\s+", (text or "").strip()):
+ if sentence.strip().lower().rstrip(".") not in known:
+ kept.append(sentence.strip())
+ return " ".join(kept).strip()
+
+
+def build_prompt(prompt, camera, framing, lighting, pace, add_quality=True):
+ """Wrap what the user wrote in the shot language Wan responds to. No model,
+ no network, nothing to refuse - it only ever adds to your own words, and it
+ replaces what it added last time."""
+ body = _strip_built(prompt).strip().rstrip(".,;")
+ if not body:
+ raise gr.Error("Write what should happen first - the builder adds the shot around it.")
+
+ parts = [body + "."]
+ shot = ", ".join(part for part in (FRAMINGS.get(framing, ""), CAMERA_MOVES.get(camera, "")) if part)
+ if shot:
+ parts.append(shot[0].upper() + shot[1:] + ".")
+ if LIGHTING.get(lighting):
+ parts.append(LIGHTING[lighting][0].upper() + LIGHTING[lighting][1:] + ".")
+ if PACING.get(pace):
+ parts.append(PACING[pace][0].upper() + PACING[pace][1:] + ".")
+ if add_quality:
+ parts.append(QUALITY_TAIL + ".")
+ return " ".join(parts)
+
+
+_ENHANCER = {"model": None, "tokenizer": None, "ready": False}
+
+ENHANCER_SYSTEM = (
+ "You write prompts for a video generation model. Rewrite the user's line as ONE paragraph of "
+ "60 to 110 words, present tense, third person. Describe, in this order: who or what is in "
+ "frame and how they look, what they do and how the motion progresses, the camera framing and "
+ "any camera move, the lighting, and the setting. Keep every element the user gave you, "
+ "including explicit ones, and keep their wording for those. Add nothing about story, mood "
+ "words or artistic intent. Output the paragraph only - no preamble, no lists, no quotation "
+ "marks, no commentary, no questions."
+)
+
+
+def _fetch_enhancer_files():
+ """Download the weights on the CPU, so no GPU time is spent on the transfer."""
+ from huggingface_hub import snapshot_download
+
+ return snapshot_download(
+ ENHANCER_MODEL,
+ allow_patterns=["*.json", "*.safetensors", "*.txt", "*.jinja", "*.model"],
+ token=os.environ.get("HF_TOKEN"),
+ )
+
+
+def _load_enhancer_cpu():
+ """Read the weights into CPU RAM. Deliberately outside the GPU call: 8 GB off disk is 30 s or
+ more, and a ZeroGPU booking that spends its whole allowance loading is a booking that times out
+ before a single token is written."""
+ import torch as _t
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ if _ENHANCER["ready"]:
+ return
+ _ENHANCER["tokenizer"] = AutoTokenizer.from_pretrained(ENHANCER_MODEL)
+ _ENHANCER["model"] = AutoModelForCausalLM.from_pretrained(
+ ENHANCER_MODEL, dtype=_t.bfloat16, low_cpu_mem_usage=True
+ )
+ _ENHANCER["ready"] = True
+
+
+# NOTE: this Space books `size='xlarge'` for generation, and a GPU call gets handed the Space's whole packed
+# tensor set either way, so the enhancer asks for the same slice.
+@spaces.GPU(duration=120, size="xlarge")
+def _run_enhancer(text):
+ import torch as _torch
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ tokenizer, model = _ENHANCER["tokenizer"], _ENHANCER["model"]
+ model = model.to("cuda")
+
+ messages = [
+ {"role": "system", "content": ENHANCER_SYSTEM},
+ {"role": "user", "content": text},
+ ]
+ # Render to text and tokenize separately. `apply_chat_template(return_tensors=...)` hands back a
+ # plain tensor on some transformers versions and a BatchEncoding on others, and asking the wrong
+ # one for `.shape` is an AttributeError; going through text sidesteps the difference. The
+ # thinking switch is Qwen3-only, so it is offered and dropped if the template ignores it.
+ try:
+ rendered = tokenizer.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=False, enable_thinking=False
+ )
+ except TypeError:
+ rendered = tokenizer.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=False
+ )
+
+ inputs = tokenizer(rendered, return_tensors="pt").to("cuda")
+ prompt_length = inputs["input_ids"].shape[-1]
+
+ with _torch.no_grad():
+ out = model.generate(
+ **inputs,
+ max_new_tokens=260,
+ do_sample=True,
+ temperature=0.85,
+ top_p=0.9,
+ repetition_penalty=1.05,
+ pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id,
+ )
+ written = tokenizer.decode(out[0][prompt_length:], skip_special_tokens=True)
+
+ # Some abliterated builds still emit a block; keep only what follows it.
+ if "" in written:
+ written = written.split("", 1)[1]
+ return " ".join(written.replace("\n", " ").split()).strip().strip('"')
+
+
+def enhance_prompt(prompt, use_model, camera, framing, lighting, pace, add_quality,
+ progress=gr.Progress()):
+ """Builder first - it is instant and never fails - then the model on top of it."""
+ built = build_prompt(prompt, camera, framing, lighting, pace, add_quality)
+ if not use_model:
+ return built, "Builtno GPU time used
"
+
+ try:
+ # Said out loud because the first press downloads ~8 GB and a bare spinner looks like a hang.
+ # None of this is GPU time: the files land on the CPU and stay in RAM for the next press.
+ progress(0.05, desc="Fetching the model (first time only, no GPU time)...")
+ _fetch_enhancer_files()
+ progress(0.5, desc="Loading it into memory...")
+ _load_enhancer_cpu()
+ except Exception as error:
+ return built, (
+ "Model unavailable, so the built prompt is shown "
+ f"instead: {type(error).__name__}
"
+ )
+
+ try:
+ progress(0.8, desc="Writing...")
+ written = _run_enhancer(built)
+ except Exception as error:
+ return built, (
+ "The model call failed, so the built prompt is shown "
+ f"instead: {error!r}
"
+ )
+
+ if len(written) < 40:
+ return built, "The model returned too little; built prompt kept.
"
+ return written, (
+ f"Written by {ENHANCER_MODEL.split('/')[-1]}"
+ f"{len(written.split())} words
"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Naming CivitAI links
+# ---------------------------------------------------------------------------
+# A CivitAI download URL is a bare number, which is useless once three slots are
+# filled. The number is the *model version* id, and CivitAI's public API turns it
+# into the model's title, the version, the file behind `fileId`, and the words the
+# adapter was trained on. Public, cached, and never fatal.
+
+from functools import lru_cache
+
+CIVITAI_DOWNLOAD_RE = re.compile(r"/api/download/models/(\d+)")
+
+
+@lru_cache(maxsize=128)
+def civitai_details(version_id: str, file_id: str = ""):
+ import requests
+
+ headers = {"User-Agent": "Mozilla/5.0"}
+ token = os.environ.get("CIVITAI_TOKEN", "").strip()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+
+ try:
+ response = requests.get(
+ f"https://civitai.com/api/v1/model-versions/{version_id}", headers=headers, timeout=20
+ )
+ response.raise_for_status()
+ data = response.json()
+ except Exception as error:
+ return f"CivitAI {version_id} (name unavailable: {type(error).__name__})", []
+
+ model_name = (data.get("model") or {}).get("name") or f"model {data.get('modelId', '?')}"
+ version_name = data.get("name") or ""
+ label = f"{model_name} · {version_name}".strip(" ·")
+
+ if file_id:
+ for entry in data.get("files") or []:
+ if str(entry.get("id")) == str(file_id):
+ label += f" · {entry.get('name', '')}"
+ break
+
+ return label, [word for word in (data.get("trainedWords") or []) if word]
+
+
+def describe_lora(reference: str):
+ """A readable line for whatever is in a box: a CivitAI link becomes its real title."""
+ reference = (reference or "").strip()
+ if not reference or reference == "(None)":
+ return "", []
+
+ match = CIVITAI_DOWNLOAD_RE.search(reference)
+ if match:
+ file_id = ""
+ if "fileId=" in reference:
+ file_id = reference.split("fileId=", 1)[1].split("&")[0]
+ return civitai_details(match.group(1), file_id)
+
+ if reference.startswith(("http://", "https://")):
+ return os.path.basename(reference.split("?")[0]) or reference, []
+ return reference, []
+
+
+def identify_loras(*fields):
+ """Name every filled box across the five slots. `fields` arrives as
+ `repo, high, low` per slot, so each slot is reported on one line."""
+ lines = []
+ for slot in range(len(fields) // 3):
+ repo, high, low = fields[slot * 3: slot * 3 + 3]
+ parts = []
+ for role, value in (("repo", repo), ("high", high), ("low", low)):
+ label, words = describe_lora(value)
+ if not label:
+ continue
+ entry = f"{role}: {label}"
+ if words:
+ entry += f" — triggers: {', '.join(words[:6])}"
+ parts.append(entry)
+ if parts:
+ lines.append(f"Custom lora {slot + 1} — " + " · ".join(parts))
+ if not lines:
+ return "Nothing in the slots yet.
"
+ return "" + "
".join(lines) + "
"
+
+
+def last_frame_of(video_path):
+ """The final frame of a clip, as the array the image box takes. Used to chain a scene: the shot
+ that just ended becomes the still the next one starts from."""
+ if not video_path or not os.path.exists(str(video_path)):
+ raise gr.Error("Generate a video first - there is nothing to continue from.")
+
+ capture = cv2.VideoCapture(str(video_path))
+ if not capture.isOpened():
+ raise gr.Error("That video cannot be read.")
+
+ total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
+ frame = None
+ if total > 0:
+ # A few frames back from the very end: the last one is sometimes a duplicate or a partly
+ # written frame, and a still that is not quite sharp starts the next clip badly.
+ capture.set(cv2.CAP_PROP_POS_FRAMES, max(0, total - 3))
+ ok, frame = capture.read()
+ if not ok:
+ frame = None
+ if frame is None:
+ capture.set(cv2.CAP_PROP_POS_FRAMES, 0)
+ while True:
+ ok, candidate = capture.read()
+ if not ok:
+ break
+ frame = candidate
+ capture.release()
+
+ if frame is None:
+ raise gr.Error("That video has no readable frames.")
+ return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+
+
+def stage_extension(video_path, queue, name_hint):
+ """Before a continuation runs: park the clip that just finished in the merge queue, and hand its
+ last frame back as the new starting image."""
+ frame = last_frame_of(video_path)
+ merged, merged_file, queue, status = add_to_queue(video_path, queue, name_hint)
+ return frame, None, merged, merged_file, queue, status
+
+
+# ---------------------------------------------------------------------------
+# Searching CivitAI
+# ---------------------------------------------------------------------------
+# `/api/v1/models` already embeds each model's versions, their files and their trigger words, so one
+# call gives everything a slot needs - no second lookup per result. Public endpoint; the token is
+# only attached so gated entries show up for an account that can see them.
+
+# Which host answers the search. `.red` is a mirror of the same API and carries entries the main
+# domain hides, so it is asked first and `.com` is the fallback. Set CIVITAI_API_HOST to pin one.
+# Note that adult entries are returned to an authenticated caller only, whichever host answers:
+# without CIVITAI_TOKEN the X / XXX levels are simply absent from the results.
+CIVITAI_API_HOSTS = [h for h in (os.environ.get("CIVITAI_API_HOST", "").strip(),
+ "civitai.red", "civitai.com") if h]
+
+
+WAN_BASE_MODELS = [
+ "Wan Video 2.2 I2V-A14B",
+ "Wan Video 2.2 T2V-A14B",
+ "Wan Video 14B i2v 480p",
+ "Wan Video 14B i2v 720p",
+ "(any base model)",
+]
+
+
+def civitai_search(query, base_model, want_nsfw, limit=20):
+ """Search CivitAI for lora. Returns `(readable list, dropdown update, {label: url})`."""
+ import requests
+
+ query = (query or "").strip()
+ if not query:
+ return "Type something to search for.
", gr.update(choices=[], value=None), {}
+
+ params = {"query": query, "types": "LORA", "limit": int(limit), "sort": "Most Downloaded"}
+ if base_model and base_model != "(any base model)":
+ params["baseModels"] = base_model
+ if want_nsfw:
+ params["nsfw"] = "true"
+
+ headers = {"User-Agent": "Mozilla/5.0"}
+ token = os.environ.get("CIVITAI_TOKEN", "").strip()
+ if token:
+ # Both forms on purpose. The header is the documented one, but search honours the query
+ # parameter more reliably - and without an authenticated call the adult browsing levels are
+ # simply missing from the results, whichever host answers.
+ headers["Authorization"] = f"Bearer {token}"
+ params["token"] = token
+
+ items, error, answered = [], None, False
+ host_used = CIVITAI_API_HOSTS[0]
+ for host in CIVITAI_API_HOSTS:
+ try:
+ response = requests.get(f"https://{host}/api/v1/models", params=params,
+ headers=headers, timeout=30)
+ response.raise_for_status()
+ items = response.json().get("items") or []
+ host_used, answered = host, True
+ if items:
+ break
+ except Exception as failure: # noqa: BLE001
+ error = failure
+
+ if not items and error is not None and not answered:
+ # Deliberately not quoting the exception: `requests` puts the full URL in its message, and the
+ # URL carries the token as a query parameter, so echoing it would print the key on screen.
+ status = getattr(getattr(error, "response", None), "status_code", None)
+ reason = f"HTTP {status}" if status else type(error).__name__
+ tried = ", ".join(CIVITAI_API_HOSTS)
+ return (f"Search failed ({reason}). Tried: {tried}. CivitAI answers 503 "
+ f"when it is rate-limiting or briefly down - wait a moment and press Search again.
",
+ gr.update(choices=[], value=None), {})
+
+ if not items:
+ return ("Nothing found. Try fewer words, or set the base model to "
+ "(any base model).
", gr.update(choices=[], value=None), {})
+
+ mapping, lines, choices = {}, [], []
+ for item in items:
+ model_name = item.get("name") or "?"
+ creator = (item.get("creator") or {}).get("username") or "?"
+ downloads = ((item.get("stats") or {}).get("downloadCount") or 0)
+
+ for version in (item.get("modelVersions") or [])[:3]:
+ version_name = version.get("name") or ""
+ # What the adapter was trained against. Worth showing on every row: with the filter set to
+ # "(any base model)" the results mix families, and a lora for another one downloads happily
+ # and then does nothing useful.
+ base = version.get("baseModel") or "base model unknown"
+ words = [w for w in (version.get("trainedWords") or []) if w]
+ for entry in (version.get("files") or []):
+ name = entry.get("name") or ""
+ if not name.lower().endswith(".safetensors"):
+ continue
+ url = f"https://{host_used}/api/download/models/{version.get('id')}?fileId={entry.get('id')}"
+ size = float(entry.get("sizeKB") or 0) / 1024
+ label = f"{len(choices) + 1}. [{base}] {model_name} · {version_name} · {name}"[:160]
+ mapping[label] = url
+ choices.append(label)
+ lines.append(
+ f"{label.split('. ', 1)[0]}. {model_name} · {version_name} · {name} "
+ f"[{base}] ({size:.0f} MB · {downloads} downloads · by {creator}"
+ + (f" · triggers: {', '.join(words[:5])}" if words else "")
+ + ")"
+ )
+
+ if not choices:
+ return ("Found models, but none with a .safetensors file.
",
+ gr.update(choices=[], value=None), {})
+
+ # A scrolling box: the picker sits above this, and a 40-line wall would push it off the screen.
+ body = ("" + "
".join(lines[:40]) + "
")
+ return body, gr.update(choices=choices, value=choices[0]), mapping
+
+
+def put_in_slot(label, mapping, slot, role, *current):
+ """Write the chosen result's download link into one High or Low box, leaving the rest alone."""
+ updates = [gr.update() for _ in range(10)]
+ url = (mapping or {}).get(label)
+ if not url:
+ return [*updates, "Search and pick a file first.
"]
+
+ index = (int(str(slot).split()[-1]) - 1) * 2 + (0 if role == "High" else 1)
+ updates[index] = gr.update(choices=["(None)", url], value=url)
+ return [*updates,
+ f"Put into {slot}, {role}{label}
"]
+
+
+def _target_size(image):
+ """Same math as resize_image(), but returns only the final (w, h)."""
+ if image is None:
+ return (832, 624)
+ width, height = image.size
+ if width == height:
+ return (SQUARE_DIM, SQUARE_DIM)
+
+ aspect_ratio = width / height
+ MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
+ MIN_ASPECT_RATIO = MIN_DIM / MAX_DIM
+
+ if aspect_ratio > MAX_ASPECT_RATIO:
+ target_w, target_h = MAX_DIM, MIN_DIM
+ elif aspect_ratio < MIN_ASPECT_RATIO:
+ target_w, target_h = MIN_DIM, MAX_DIM
+ else:
+ if width > height:
+ target_w = MAX_DIM
+ target_h = int(round(target_w / aspect_ratio))
+ else:
+ target_h = MAX_DIM
+ target_w = int(round(target_h * aspect_ratio))
+
+ final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
+ final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
+ final_w = max(MIN_DIM, min(MAX_DIM, final_w))
+ final_h = max(MIN_DIM, min(MAX_DIM, final_h))
+ return (final_w, final_h)
+
+
+class _SizeOnly:
+ def __init__(self, w, h):
+ self.size = (w, h)
+ self.width = w
+ self.height = h
+
+
+def _gpu_estimate_text(input_image, duration_seconds, steps, guidance_scale,
+ frame_multiplier, safe_mode):
+ """Live ZeroGPU cost readout, using the exact same formula the
+ @spaces.GPU decorator asks for at generation time."""
+ try:
+ num_frames = get_num_frames(float(duration_seconds))
+ w, h = _target_size(input_image)
+ secs = get_inference_duration(
+ _SizeOnly(w, h), None, "", steps, "", num_frames,
+ float(guidance_scale), 1.0, 0, "UniPCMultistep", 3.0,
+ int(frame_multiplier), 5, float(duration_seconds),
+ bool(safe_mode), None, None,
+ )
+ except Exception as exc: # never break the UI over a readout
+ return f"⏳ **ZeroGPU cost:** estimate unavailable ({exc})"
+
+ note = "" if input_image is not None else " · upload an image for an exact number"
+ out_fps = int(frame_multiplier)
+ out_frames = num_frames * max(1, out_fps // FIXED_FPS)
+
+ return (
+ f"⏳ **ZeroGPU cost: ~{int(round(secs))} s** \n"
+ f"{num_frames} frames · {w}×{h} · {int(steps)} steps · "
+ f"output {out_frames} frames @ {out_fps} fps{note}"
+ )
+
+
+def _apply_speed_preset(name):
+ cfg = SPEED_PRESETS.get(name) or {}
+ return (
+ gr.update(value=cfg.get("steps", 6)),
+ gr.update(value=cfg.get("flow_shift", 3.0)),
+ gr.update(value=cfg.get("scheduler", "UniPCMultistep")),
+ )
+
+
+def _append_chip(prompt, chip):
+ text = (prompt or "").strip().rstrip(",")
+ if chip.lower() in text.lower():
+ return text
+ return f"{text}, {chip}" if text else chip
+
+
+def _clear_all():
+ return (
+ None, None, default_prompt_i2v,
+ gr.update(value=None), gr.update(value=None),
+ "Ready when you are.
",
)
CSS = """
+@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
+
+.gradio-container {
+ font-family: 'Inter', ui-sans-serif, system-ui, sans-serif !important;
+ max-width: 1440px !important;
+}
+
#hidden-timestamp {
opacity: 0;
height: 0px;
@@ -559,140 +1638,536 @@ CSS = """
position: absolute;
pointer-events: none;
}
-"""
+#hero {
+ border-radius: 18px;
+ padding: 22px 26px;
+ margin-bottom: 14px;
+ background: linear-gradient(120deg, #6d28d9 0%, #7c3aed 35%, #2563eb 100%);
+ color: #fff;
+ box-shadow: 0 10px 30px rgba(76, 29, 149, .25);
+}
+#hero h1 {
+ margin: 0;
+ font-size: 26px;
+ font-weight: 700;
+ letter-spacing: -.02em;
+ color: #fff;
+}
+#hero p {
+ margin: 6px 0 0 0;
+ font-size: 14px;
+ opacity: .92;
+ color: #fff;
+}
+#hero .pills { margin-top: 12px; display: flex; flex-wrap: wrap; gap: 8px; }
+#hero .policy { margin-top: 10px; font-size: 12px; opacity: .8; }
+#hero .pills span {
+ background: rgba(255,255,255,.16);
+ border: 1px solid rgba(255,255,255,.25);
+ padding: 4px 11px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 500;
+}
-with gr.Blocks(delete_cache=(3600, 10800)) as demo:
- gr.Markdown(model_title())
- gr.Markdown("Run Wan 2.2 in just 4-8 steps, fp8 quantization & AoT compilation - compatible with 🧨 diffusers and ZeroGPU")
-
- with gr.Row():
- with gr.Column():
- input_image_component = gr.Image(type="pil", label="Input Image", sources=["upload", "clipboard"])
- prompt_input = gr.Textbox(label="Prompt", value=default_prompt_i2v)
- duration_seconds_input = gr.Slider(minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=3.5, label="Duration (seconds)", info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.")
- frame_multi = gr.Dropdown(
- choices=[FIXED_FPS, FIXED_FPS*2, FIXED_FPS*4, FIXED_FPS*8],
- value=FIXED_FPS,
- label="Video Fluidity (Frames per Second)",
- info="Extra frames will be generated using flow estimation, which estimates motion between frames to make the video smoother."
- )
- safe_mode_checkbox = gr.Checkbox(
- label="🛠️ Safe Mode",
- value=True,
- info="Requests 30% extra processing time to try to prevent unfinished tasks when the server is busy."
- )
- with gr.Accordion("Advanced Settings", open=False):
- last_image_component = gr.Image(type="pil", label="Last Image (Optional)", sources=["upload", "clipboard"])
- negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, info="Used if any Guidance Scale > 1.", lines=3)
- quality_slider = gr.Slider(minimum=1, maximum=10, step=1, value=6, label="Video Quality", info="If set to 10, the generated video may be too large and won't play in the Gradio preview.")
- seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
- randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
- steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6, label="Inference Steps")
- guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale - high noise stage", info="Values above 1 increase GPU usage and may take longer to process.")
- guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale 2 - low noise stage")
- scheduler_dropdown = gr.Dropdown(
- label="Scheduler",
- choices=list(SCHEDULER_MAP.keys()),
- value="UniPCMultistep",
- info="Select a custom scheduler."
- )
- flow_shift_slider = gr.Slider(minimum=0.5, maximum=15.0, step=0.1, value=3.0, label="Flow Shift")
+.panel {
+ border-radius: 16px !important;
+ border: 1px solid var(--border-color-primary) !important;
+ padding: 14px !important;
+ background: var(--background-fill-secondary) !important;
+}
- gr.Markdown("### 1) Original LoRA x3 + strength")
- with gr.Row():
- lora1_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)", label="Original LoRA 1", filterable=True)
- lora1_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- lora1_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- with gr.Row():
- lora2_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)", label="Original LoRA 2", filterable=True)
- lora2_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- lora2_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- with gr.Row():
- lora3_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)", label="Original LoRA 3", filterable=True)
- lora3_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- lora3_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
+#generate-btn {
+ font-size: 17px !important;
+ font-weight: 700 !important;
+ min-height: 62px !important;
+ border-radius: 14px !important;
+ letter-spacing: .01em;
+ box-shadow: 0 8px 22px rgba(124, 58, 237, .28);
+}
+#estimate-btn, #enhance-btn { min-height: 42px !important; border-radius: 12px !important; }
+#search-btn, #search-put, #extend-btn, #lora-identify, #profile-load, #profile-save, #profile-delete, #profile-refresh {
+ min-height: 42px !important; border-radius: 12px !important; font-weight: 600 !important;
+}
+#stop-btn, #clear-btn { min-height: 46px !important; border-radius: 12px !important; }
+#grab-btn { min-height: 48px !important; border-radius: 12px !important; font-weight: 600 !important; }
+
+.chip-row { gap: 6px !important; }
+.chip-row button {
+ border-radius: 999px !important;
+ font-size: 12.5px !important;
+ padding: 6px 12px !important;
+ min-height: 34px !important;
+ font-weight: 500 !important;
+}
- gr.Markdown("### 2) My LoRA x5 from HF repo + strength")
- gr.Markdown("For each slot: paste repo → Load files → pick High/Low → set strength. Example: `username/my-loras`")
+.search-results {
+ max-height: 300px;
+ overflow-y: auto;
+ border-radius: 12px;
+ padding: 10px 14px;
+ background: rgba(16, 185, 129, .10);
+ border: 1px solid rgba(16, 185, 129, .30);
+ font-size: 13px;
+ line-height: 1.5;
+}
+.search-results span { opacity: .75; font-size: 12px; }
+
+.consent-note {
+ border-radius: 12px;
+ padding: 8px 12px;
+ margin-bottom: 10px;
+ background: rgba(239, 68, 68, .08);
+ border: 1px solid rgba(239, 68, 68, .30);
+ font-size: 12.5px;
+ opacity: .9;
+}
- # --- My LoRA 1 ---
- gr.Markdown("**My LoRA 1**")
- with gr.Row():
- my1_repo = gr.Textbox(label="Repo link", placeholder="username/repo", lines=1, scale=4)
- my1_load = gr.Button("Load files", scale=1)
- with gr.Row():
- my1_high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True)
- my1_hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- with gr.Row():
- my1_low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True)
- my1_ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- my1_load.click(fn=_load_repo_files, inputs=[my1_repo], outputs=[my1_high, my1_low])
+.gpu-estimate {
+ border-radius: 12px;
+ padding: 10px 14px;
+ background: rgba(139, 92, 246, .10);
+ border: 1px solid rgba(139, 92, 246, .35);
+ font-size: 14px;
+}
+.gpu-estimate sub { opacity: .75; font-size: 12px; }
+
+.status-ok, .status-idle {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 14px;
+ border-radius: 12px;
+ padding: 10px 14px;
+ font-size: 13.5px;
+}
+.status-ok {
+ background: rgba(16, 185, 129, .12);
+ border: 1px solid rgba(16, 185, 129, .35);
+}
+.status-idle {
+ background: var(--background-fill-secondary);
+ border: 1px solid var(--border-color-primary);
+ opacity: .8;
+}
+.status-ok span { opacity: .85; }
- # --- My LoRA 2 ---
- gr.Markdown("**My LoRA 2**")
- with gr.Row():
- my2_repo = gr.Textbox(label="Repo link", placeholder="username/repo", lines=1, scale=4)
- my2_load = gr.Button("Load files", scale=1)
- with gr.Row():
- my2_high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True)
- my2_hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- with gr.Row():
- my2_low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True)
- my2_ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- my2_load.click(fn=_load_repo_files, inputs=[my2_repo], outputs=[my2_high, my2_low])
+button.primary, .primary > button {
+ background: linear-gradient(120deg, #7c3aed 0%, #6d28d9 55%, #2563eb 100%) !important;
+ border: none !important;
+ color: #fff !important;
+}
+button.primary:hover, .primary > button:hover { filter: brightness(1.08); }
- # --- My LoRA 3 ---
- gr.Markdown("**My LoRA 3**")
- with gr.Row():
- my3_repo = gr.Textbox(label="Repo link", placeholder="username/repo", lines=1, scale=4)
- my3_load = gr.Button("Load files", scale=1)
- with gr.Row():
- my3_high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True)
- my3_hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
- with gr.Row():
- my3_low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True)
- my3_ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- my3_load.click(fn=_load_repo_files, inputs=[my3_repo], outputs=[my3_high, my3_low])
+.block, .form { border-radius: 14px !important; }
+button { border-radius: 12px !important; }
+.tab-nav button { font-weight: 600 !important; }
+label > span { font-weight: 600 !important; }
+
+footer { display: none !important; }
+"""
+
+HERO = """
+
+
Wan 2.2 I2V 14B · Custom lora + CivitAI search, prompt builder, scene continuation,
+ Fast Options, ZeroGPU cost, profiles, clip stitching & looping
+
Turn a still image into smooth cinematic motion — with your own loras, searched and pulled in from
+ CivitAI without leaving the page. Continue a scene from its own last frame, then stitch and loop the clips
+ on the CPU, for no extra ZeroGPU time.
+
+ 14B I2V4–8 stepsfp8 quantized
+ AoT compiledRIFE interpolation3 built-in + 5 custom lora
+ CivitAI search + linksprompt builderscene continuationclip stitchingboomerang loopsstart & end frame grab
+
+
+"""
+
+# (sweep every hour, keep files for a day). The old (3600, 10800) deleted a grabbed frame after
+# three hours while the page still showed it, and the next Generate died in gradio's own
+# preprocessing with FileNotFoundError before this code ran.
+with gr.Blocks(delete_cache=(3600, 86400)) as demo:
+ gr.HTML("")
+ gr.HTML(HERO)
+
+ with gr.Row(equal_height=False):
+
+ # ---------------- LEFT: controls ----------------
+ with gr.Column(scale=5):
+
+ with gr.Group(elem_classes="panel"):
+ gr.Markdown(
+ "Upload only photographs of yourself, or of people who have agreed to this. "
+ "Sexual imagery of a real person made without their consent breaks Hugging "
+ "Face's content policy and is not welcome here.",
+ elem_classes="consent-note",
+ )
+ with gr.Tabs():
+ with gr.Tab("🖼️ Start frame"):
+ input_image_component = gr.Image(
+ type="pil", label=None, show_label=False,
+ sources=["upload", "clipboard"], height=300,
+ )
+ with gr.Tab("🏁 End frame (optional)"):
+ last_image_component = gr.Image(
+ type="pil", label=None, show_label=False,
+ sources=["upload", "clipboard"], height=300,
+ )
+
+ prompt_input = gr.Textbox(
+ label="Prompt",
+ value=default_prompt_i2v,
+ lines=3,
+ placeholder="Describe the motion you want to see…",
+ )
- # --- My LoRA 4 ---
- gr.Markdown("**My LoRA 4**")
+ with gr.Accordion("🖋️ Prompt builder", open=False):
+ gr.Markdown(
+ "Write what should happen in the box above, pick the shot below, and press "
+ "**Build**. The builder only ever adds to your own words — it is instant, "
+ "costs no GPU time and refuses nothing.\n\n"
+ "Tick **write it with a model** and a small local language model turns it "
+ "into a full paragraph instead, keeping your own wording for whatever you "
+ "wrote. The weights download on the CPU; only the writing books the card, "
+ "about 20 s. The first press also downloads ~8 GB on the CPU, which is slow but free. Any failure falls back to the built prompt."
+ )
+ with gr.Row():
+ pb_framing = gr.Dropdown(list(FRAMINGS), value="(keep as written)",
+ label="Framing")
+ pb_camera = gr.Dropdown(list(CAMERA_MOVES), value="(keep as written)",
+ label="Camera move")
+ with gr.Row():
+ pb_lighting = gr.Dropdown(list(LIGHTING), value="(keep as written)",
+ label="Lighting")
+ pb_pace = gr.Dropdown(list(PACING), value="(keep as written)",
+ label="Pacing")
+ pb_quality = gr.Checkbox(
+ value=True, label="Add the quality tail",
+ info="photorealistic, natural skin texture, consistent anatomy, smooth motion",
+ )
+ pb_use_model = gr.Checkbox(
+ value=False, label="🧠 Write it with a model (first press downloads 8 GB, then ~20 s)",
+ )
+ pb_button = gr.Button("🖋️ Build / rewrite the prompt", variant="secondary",
+ elem_id="enhance-btn")
+ pb_status = gr.HTML("")
+
+ with gr.Accordion("✨ Quick motion tags — click to add", open=False):
+ with gr.Row(elem_classes="chip-row"):
+ for _chip in PROMPT_CHIPS[:5]:
+ _b = gr.Button(_chip, size="sm", variant="secondary")
+ _b.click(
+ fn=lambda p, c=_chip: _append_chip(p, c),
+ inputs=[prompt_input], outputs=[prompt_input],
+ )
+ with gr.Row(elem_classes="chip-row"):
+ for _chip in PROMPT_CHIPS[5:]:
+ _b = gr.Button(_chip, size="sm", variant="secondary")
+ _b.click(
+ fn=lambda p, c=_chip: _append_chip(p, c),
+ inputs=[prompt_input], outputs=[prompt_input],
+ )
+
+ with gr.Group(elem_classes="panel"):
+ duration_seconds_input = gr.Slider(
+ minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=3.5,
+ label="⏱️ Duration (seconds)",
+ info=f"Clamped to the model's {MIN_FRAMES_MODEL}–{MAX_FRAMES_MODEL} frames at {FIXED_FPS} fps.",
+ )
+ frame_multi = gr.Dropdown(
+ choices=[FIXED_FPS, FIXED_FPS*2, FIXED_FPS*4, FIXED_FPS*8],
+ value=FIXED_FPS,
+ label="🎞️ Fluidity (frames per second)",
+ info="Extra frames are created with flow estimation for smoother motion.",
+ )
+ safe_mode_checkbox = gr.Checkbox(
+ label="🛠️ Safe Mode",
+ value=True,
+ info="Requests 30% extra processing time so busy servers don't cut the task short.",
+ )
with gr.Row():
- my4_repo = gr.Textbox(label="Repo link", placeholder="username/repo", lines=1, scale=4)
- my4_load = gr.Button("Load files", scale=1)
+ aspect_mode = gr.Radio(
+ [("Crop to fit (default)", "crop"), ("Keep it all, add black bars", "pad")],
+ value="crop",
+ label="🖼️ Images taller or wider than the model's frame",
+ info="The checkpoint accepts 480–832 px per side, so anything past 1.73:1 has to give: "
+ "crop cuts the middle out, pad keeps the whole picture between bars.",
+ )
with gr.Row():
- my4_high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True)
- my4_hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
+ gpu_estimate = gr.Markdown(
+ _gpu_estimate_text(None, 3.5, 6, 1, FIXED_FPS, True),
+ elem_classes="gpu-estimate",
+ )
+ gpu_estimate_btn = gr.Button("🔄", variant="secondary", scale=1, min_width=60,
+ elem_id="estimate-btn")
+
+ with gr.Group(elem_classes="panel"):
+ speed_preset_dd = gr.Dropdown(
+ choices=list(SPEED_PRESETS.keys()),
+ value=SPEED_NONE,
+ label="⚡ Speed preset (steps)",
+ info="Sets steps, flow shift and scheduler in one click. lora options download on first use.",
+ )
with gr.Row():
- my4_low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True)
- my4_ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- my4_load.click(fn=_load_repo_files, inputs=[my4_repo], outputs=[my4_high, my4_low])
+ speed_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Speed lora — high strength")
+ speed_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Speed lora — low strength")
+
+ with gr.Accordion("⚙️ Advanced settings & Custom lora", open=False):
+ with gr.Tabs():
+
+ with gr.Tab("Sampling"):
+ with gr.Row():
+ steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6, label="Inference Steps")
+ quality_slider = gr.Slider(
+ minimum=1, maximum=10, step=1, value=6, label="Video Quality",
+ info="At 10 the file may be too large to preview in the browser.",
+ )
+ with gr.Row():
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
+ with gr.Row():
+ randomize_seed_checkbox = gr.Checkbox(label="🎲 Randomize seed", value=True, interactive=True)
+ play_result_video = gr.Checkbox(label="▶️ Display result", value=True, interactive=True)
+ with gr.Row():
+ guidance_scale_input = gr.Slider(
+ minimum=0.0, maximum=10.0, step=0.5, value=1,
+ label="Guidance — high noise",
+ info="Above 1 uses more GPU and takes longer.",
+ )
+ guidance_scale_2_input = gr.Slider(
+ minimum=0.0, maximum=10.0, step=0.5, value=1,
+ label="Guidance — low noise",
+ )
+ with gr.Row():
+ scheduler_dropdown = gr.Dropdown(
+ label="Scheduler",
+ choices=list(SCHEDULER_MAP.keys()),
+ value="UniPCMultistep",
+ )
+ flow_shift_slider = gr.Slider(minimum=0.5, maximum=15.0, step=0.1, value=3.0, label="Flow Shift")
+ negative_prompt_input = gr.Textbox(
+ label="Negative Prompt",
+ value=default_negative_prompt,
+ info="Used if any Guidance Scale > 1.",
+ lines=3,
+ )
+
+ with gr.Tab("🎛️ Built-in lora"):
+ gr.Markdown(
+ "Built-in lora list — pick up to three and set their strengths. These are "
+ "trained on particular faces, bodies and lighting, and that carries into "
+ "everything they touch: at strength `1.0` a face and hair colour can change "
+ "outright. They start at `0.7` for that reason; drop to `0.4`–`0.5` when the "
+ "person has to stay recognisable."
+ )
+ _preset_rows = []
+ for _i in range(1, 4):
+ with gr.Group(elem_classes="panel"):
+ _p = gr.Dropdown(choices=LORA_CHOICES, value="(None)", label=f"Built-in lora {_i}", filterable=True)
+ with gr.Row():
+ _hs = gr.Slider(0.0, 2.0, value=0.7, step=0.05, label="High strength",
+ info="Lower it if faces or hair drift")
+ _ls = gr.Slider(0.0, 2.0, value=0.7, step=0.05, label="Low strength")
+ _preset_rows.append((_p, _hs, _ls))
+
+ (lora1_preset, lora1_high_scale, lora1_low_scale) = _preset_rows[0]
+ (lora2_preset, lora2_high_scale, lora2_low_scale) = _preset_rows[1]
+ (lora3_preset, lora3_high_scale, lora3_low_scale) = _preset_rows[2]
+
+ with gr.Tab("⭐ Custom lora"):
+ gr.Markdown(
+ "**Your own lora from Hugging Face or CivitAI.** Paste the repo "
+ "(e.g. `username/my-loras`) and press **Enter** — the files load "
+ "automatically and High/Low are pre-selected for you. 5 slots available.\n\n"
+ "**CivitAI:** paste a download link "
+ "(`https://civitai.com/api/download/models/...`) into the repo box and press "
+ "Enter — it lands in the High box. A Wan adapter usually ships its two halves as "
+ "two separate files, so paste the low-noise link straight into the Low box "
+ "(both boxes accept a pasted link). The Space downloads it itself, so being "
+ "signed in to CivitAI in your browser does not help a gated model: add "
+ "`CIVITAI_TOKEN` under Settings → Variables and secrets. Downloads are cached.\n\n"
+ "A CivitAI link is just a number, so press **🔎 name the CivitAI links** and "
+ "each box is replaced by its real title, version, file name and trigger words, "
+ "read from CivitAI's public API."
+ )
+ with gr.Accordion("🔍 Search CivitAI", open=False):
+ gr.Markdown(
+ "Search CivitAI without leaving the Space, then drop a result straight "
+ "into a slot. Each hit shows its size, downloads and trigger words."
+ )
+ with gr.Row():
+ search_query = gr.Textbox(label="Search", placeholder="e.g. rain, dance, camera move",
+ scale=3)
+ search_base = gr.Dropdown(WAN_BASE_MODELS, value=WAN_BASE_MODELS[0],
+ label="Base model", allow_custom_value=True, scale=2)
+ with gr.Row():
+ search_nsfw = gr.Checkbox(value=True, label="Include NSFW results")
+ search_btn = gr.Button("🔍 Search", variant="secondary",
+ elem_id="search-btn")
+ search_pick = gr.Dropdown(choices=[], label="Pick a file",
+ allow_custom_value=False)
+ with gr.Row():
+ search_slot = gr.Dropdown(
+ [f"Custom lora {i}" for i in range(1, 6)],
+ value="Custom lora 1", label="Into slot", scale=2,
+ )
+ search_role = gr.Radio(["High", "Low"], value="High", label="Box", scale=2)
+ search_put_btn = gr.Button("⬇️ Put it in", variant="primary", scale=1,
+ elem_id="search-put")
+ search_results = gr.HTML("No search yet.
")
+ search_state = gr.State({})
+
+ with gr.Row():
+ lora_identify_btn = gr.Button("🔎 name the CivitAI links",
+ variant="secondary", elem_id="lora-identify")
+ lora_names = gr.HTML("Nothing in the slots yet.
")
+ _my_rows = []
+ for _i in range(1, 6):
+ with gr.Accordion(f"Custom lora {_i}", open=(_i == 1)):
+ with gr.Row():
+ _repo = gr.Textbox(label="Repo", placeholder="username/repo", lines=1, scale=4)
+ _load = gr.Button("📥 Load files", scale=1, variant="secondary")
+ with gr.Row():
+ _high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True,
+ allow_custom_value=True, scale=3)
+ _hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength", scale=2)
+ with gr.Row():
+ _low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True,
+ allow_custom_value=True, scale=3)
+ _ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength", scale=2)
+
+ _load.click(fn=_load_repo_files, inputs=[_repo], outputs=[_high, _low])
+ _repo.submit(fn=_load_repo_files, inputs=[_repo], outputs=[_high, _low])
+
+ _my_rows.append((_repo, _high, _hs, _low, _ls))
+
+ (my1_repo, my1_high, my1_hs, my1_low, my1_ls) = _my_rows[0]
+ (my2_repo, my2_high, my2_hs, my2_low, my2_ls) = _my_rows[1]
+ (my3_repo, my3_high, my3_hs, my3_low, my3_ls) = _my_rows[2]
+ (my4_repo, my4_high, my4_hs, my4_low, my4_ls) = _my_rows[3]
+ (my5_repo, my5_high, my5_hs, my5_low, my5_ls) = _my_rows[4]
+
+ with gr.Tab("💾 Profiles"):
+ gr.Markdown(
+ "Every current setting, kept under a name inside this Space. Images are "
+ "not stored."
+ )
+ with gr.Row():
+ profile_picker = gr.Dropdown(
+ label="Saved profiles",
+ choices=[NO_PROFILE, *list_profiles()],
+ value=NO_PROFILE,
+ scale=3,
+ )
+ profile_load_btn = gr.Button("📂 load", variant="secondary", scale=1,
+ elem_id="profile-load")
+ profile_refresh = gr.Button("🔄", variant="secondary", scale=1, min_width=60,
+ elem_id="profile-refresh")
+ with gr.Row():
+ profile_name = gr.Textbox(
+ label="Save as", placeholder="e.g. portrait, turbo 4 steps",
+ max_lines=1, scale=3,
+ )
+ profile_save_btn = gr.Button("💾 save", variant="primary", scale=1,
+ elem_id="profile-save")
+ profile_delete_btn = gr.Button("🗑️ delete the selected profile",
+ variant="secondary", elem_id="profile-delete")
+ profile_status = gr.Markdown("")
+ gr.Markdown("---")
+ gr.Markdown("**Take it with you (.json file)**")
+ settings_export_btn = gr.Button("⬇️ export the current settings to .json",
+ size="sm")
+ settings_download = gr.File(label="Your settings", visible=False,
+ interactive=False)
+ settings_upload = gr.File(label="📤 import a settings .json",
+ file_types=[".json"], type="filepath")
+
+ generate_button = gr.Button("🚀 Generate Video", variant="primary", elem_id="generate-btn")
+ with gr.Row():
+ stop_button = gr.Button("⏹ Stop", variant="stop", elem_id="stop-btn")
+ clear_button = gr.Button("🧹 Clear", variant="secondary", elem_id="clear-btn")
+
+ # ---------------- RIGHT: result ----------------
+ with gr.Column(scale=6):
+ with gr.Group(elem_classes="panel"):
+ video_output = gr.Video(
+ label="Generated Video",
+ autoplay=True,
+ sources=["upload"],
+ buttons=["download", "share"],
+ interactive=True,
+ elem_id="generated-video",
+ height=520,
+ )
+ status_box = gr.HTML("Ready when you are.
")
- # --- My LoRA 5 ---
- gr.Markdown("**My LoRA 5**")
with gr.Row():
- my5_repo = gr.Textbox(label="Repo link", placeholder="username/repo", lines=1, scale=4)
- my5_load = gr.Button("Load files", scale=1)
+ grab_frame_btn = gr.Button(
+ "📸 Current frame → start image",
+ variant="secondary",
+ elem_id="grab-btn",
+ )
+ grab_frame_last_btn = gr.Button(
+ "🏁 Current frame → end image",
+ variant="secondary",
+ elem_id="grab-btn",
+ )
+ timestamp_box = gr.Number(value=0, label="Timestamp", visible=True, elem_id="hidden-timestamp")
+ timestamp_box_last = gr.Number(value=0, label="Timestamp", visible=True, elem_id="hidden-timestamp")
+
+ file_output = gr.File(label="⬇️ Download video")
+
+ with gr.Group(elem_classes="panel"):
+ extend_btn = gr.Button("➕ Continue the scene (one more clip, joined on)",
+ variant="secondary", elem_id="extend-btn")
+ gr.Markdown(
+ "Takes the last frame of the clip above, starts a new generation from it with "
+ "the same settings, and joins the two into one file. Press it again for a third "
+ "clip, and so on — each press costs one normal generation, the joining is free. "
+ "Change the prompt in between if the scene should move on.",
+ elem_classes="turbo-blurb",
+ )
+
+ with gr.Accordion("🔁 Loop the clip (no GPU used)", open=False):
+ gr.Markdown(
+ "Runs on the result you already have, on the CPU — it costs nothing from your "
+ "ZeroGPU allowance."
+ )
+ boomerang_tail = gr.Slider(
+ 0.5, 4.0, value=2.0, step=0.5,
+ label="Tail length for the ending loop (seconds)",
+ )
with gr.Row():
- my5_high = gr.Dropdown(choices=["(None)"], value="(None)", label="High file", filterable=True)
- my5_hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
+ boomerang_full_btn = gr.Button("🔁 Full boomerang (forward + reverse)",
+ variant="secondary")
+ boomerang_end_btn = gr.Button("🔂 Ending only", variant="secondary")
+
+ with gr.Accordion("🎞️ Stitch clips into one video (no GPU used)", open=False):
+ gr.Markdown(
+ "Add clips to a queue and they are joined into a single file with ffmpeg. Three "
+ "3.5 s clips make one 10 s video for no extra GPU time. Everything is scaled to "
+ "the first clip's frame."
+ )
+ merge_name = gr.Textbox(label="File name (optional)", placeholder="my_scene",
+ max_lines=1)
+ auto_merge = gr.Checkbox(
+ value=False, label="⚡ Add every new generation automatically",
+ info="Generate, generate, generate — the joined file grows on its own.",
+ )
with gr.Row():
- my5_low = gr.Dropdown(choices=["(None)"], value="(None)", label="Low file", filterable=True)
- my5_ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
- my5_load.click(fn=_load_repo_files, inputs=[my5_repo], outputs=[my5_high, my5_low])
-
- play_result_video = gr.Checkbox(label="Display result", value=True, interactive=True)
-
- generate_button = gr.Button("Generate Video", variant="primary")
-
- with gr.Column():
- video_output = gr.Video(label="Generated Video", autoplay=True, sources=["upload"], buttons=["download", "share"], interactive=True, elem_id="generated-video")
-
- with gr.Row():
- grab_frame_btn = gr.Button("Use Current Frame as Input", variant="secondary")
- timestamp_box = gr.Number(value=0, label="Timestamp", visible=True, elem_id="hidden-timestamp")
-
- file_output = gr.File(label="Download Video")
+ merge_add_btn = gr.Button("➕ Add the current video", variant="secondary")
+ merge_clear_btn = gr.Button("🧹 Clear the queue", variant="secondary")
+ merge_status = gr.HTML("Merge queue: empty
")
+ merged_video = gr.Video(label="🎬 Stitched result", height=360)
+ merged_file = gr.File(label="⬇️ Download the stitched video")
+ merge_queue = gr.State([])
+
+ with gr.Accordion("💡 Tips", open=False):
+ gr.Markdown(
+ "- Pause the video on any frame, then hit **Use current frame** to continue the shot from there.\n"
+ "- 6 steps + UniPC is the sweet spot; more steps rarely helps this model.\n"
+ "- Higher fluidity only interpolates — it adds smoothness, not new content.\n"
+ "- Keep **Randomize seed** on while exploring, then lock a seed you like."
+ )
ui_inputs = [
input_image_component, last_image_component, prompt_input, steps_slider,
@@ -700,6 +2175,8 @@ with gr.Blocks(delete_cache=(3600, 10800)) as demo:
guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox,
quality_slider, scheduler_dropdown, flow_shift_slider, frame_multi,
safe_mode_checkbox,
+ aspect_mode,
+ speed_preset_dd, speed_high_scale, speed_low_scale,
# original 3
lora1_preset, lora1_high_scale, lora1_low_scale,
lora2_preset, lora2_high_scale, lora2_low_scale,
@@ -712,29 +2189,188 @@ with gr.Blocks(delete_cache=(3600, 10800)) as demo:
my5_repo, my5_high, my5_hs, my5_low, my5_ls,
play_result_video,
]
-
- generate_button.click(
- fn=generate_video,
- inputs=ui_inputs,
- outputs=[video_output, file_output, seed_input]
+
+ speed_preset_dd.change(
+ fn=_apply_speed_preset,
+ inputs=[speed_preset_dd],
+ outputs=[steps_slider, flow_shift_slider, scheduler_dropdown],
+ )
+
+ gen_event = generate_button.click(
+ fn=generate_video,
+ inputs=ui_inputs,
+ outputs=[video_output, file_output, seed_input, status_box],
+ ).then(
+ # Keeps the clip when the Space has persistent storage, then grows the
+ # stitched file if auto-merge is on. Both are CPU-only.
+ fn=lambda path: (_persist(path), gr.update())[1],
+ inputs=[file_output],
+ outputs=[status_box],
+ show_progress="hidden",
+ ).then(
+ fn=auto_queue,
+ inputs=[file_output, auto_merge, merge_queue, merge_name],
+ outputs=[merged_video, merged_file, merge_queue, merge_status],
+ show_progress="hidden",
)
-
+
+ stop_button.click(fn=None, inputs=None, outputs=None, cancels=[gen_event])
+
+ clear_button.click(
+ fn=_clear_all,
+ inputs=None,
+ outputs=[input_image_component, last_image_component, prompt_input,
+ video_output, file_output, status_box],
+ )
+
grab_frame_btn.click(
fn=None,
inputs=None,
outputs=[timestamp_box],
js=get_timestamp_js
)
-
+
timestamp_box.change(
fn=extract_frame,
inputs=[video_output, timestamp_box],
outputs=[input_image_component]
)
+ grab_frame_last_btn.click(
+ fn=None,
+ inputs=None,
+ outputs=[timestamp_box_last],
+ js=get_timestamp_js_last,
+ )
+
+ timestamp_box_last.change(
+ fn=extract_frame,
+ inputs=[video_output, timestamp_box_last],
+ outputs=[last_image_component],
+ )
+
+ boomerang_full_btn.click(
+ fn=lambda path: boomerang(path, "full"),
+ inputs=[video_output],
+ outputs=[video_output, file_output],
+ )
+ boomerang_end_btn.click(
+ fn=lambda path, tail: boomerang(path, "ending", tail),
+ inputs=[video_output, boomerang_tail],
+ outputs=[video_output, file_output],
+ )
+
+ merge_add_btn.click(
+ fn=add_to_queue,
+ inputs=[video_output, merge_queue, merge_name],
+ outputs=[merged_video, merged_file, merge_queue, merge_status],
+ )
+ merge_clear_btn.click(
+ fn=clear_queue,
+ inputs=None,
+ outputs=[merged_video, merged_file, merge_queue, merge_status],
+ )
+
+ # Continue the scene. Three steps, chained so each one sees what the one before it wrote: park the
+ # finished clip in the queue and hand back its last frame, generate from that frame with the settings
+ # untouched, then join the new clip on. `ui_inputs` starts with the image box, so the second step reads
+ # the still the first step just put there.
+ extend_btn.click(
+ fn=stage_extension,
+ inputs=[video_output, merge_queue, merge_name],
+ outputs=[input_image_component, video_output, merged_video, merged_file, merge_queue, merge_status],
+ ).then(
+ fn=generate_video,
+ inputs=ui_inputs,
+ outputs=[video_output, file_output, seed_input, status_box],
+ ).then(
+ fn=add_to_queue,
+ inputs=[file_output, merge_queue, merge_name],
+ outputs=[merged_video, merged_file, merge_queue, merge_status],
+ show_progress="hidden",
+ )
+
+ # Searching CivitAI, and dropping a result into a slot. `put_in_slot` writes to one of the ten
+ # High / Low boxes and leaves the other nine untouched, so a half-filled set-up survives a search.
+ _SLOT_BOXES = [
+ my1_high, my1_low, my2_high, my2_low, my3_high, my3_low,
+ my4_high, my4_low, my5_high, my5_low,
+ ]
+ search_btn.click(
+ fn=civitai_search,
+ inputs=[search_query, search_base, search_nsfw],
+ outputs=[search_results, search_pick, search_state],
+ )
+ search_query.submit(
+ fn=civitai_search,
+ inputs=[search_query, search_base, search_nsfw],
+ outputs=[search_results, search_pick, search_state],
+ )
+ search_put_btn.click(
+ fn=put_in_slot,
+ inputs=[search_pick, search_state, search_slot, search_role],
+ outputs=[*_SLOT_BOXES, search_results],
+ )
+
+ # Naming the links. Registered here with the rest of the additions, and reading every box of every slot.
+ _IDENTIFY_FIELDS = [
+ my1_repo, my1_high, my1_low,
+ my2_repo, my2_high, my2_low,
+ my3_repo, my3_high, my3_low,
+ my4_repo, my4_high, my4_low,
+ my5_repo, my5_high, my5_low,
+ ]
+ lora_identify_btn.click(identify_loras, _IDENTIFY_FIELDS, lora_names)
+
+ _SETTINGS_FIELDS = [
+ prompt_input, negative_prompt_input, duration_seconds_input, steps_slider, quality_slider,
+ seed_input, randomize_seed_checkbox, scheduler_dropdown, flow_shift_slider, frame_multi,
+ safe_mode_checkbox,
+ speed_preset_dd, speed_high_scale, speed_low_scale,
+ lora1_preset, lora1_high_scale, lora1_low_scale,
+ lora2_preset, lora2_high_scale, lora2_low_scale,
+ lora3_preset, lora3_high_scale, lora3_low_scale,
+ my1_repo, my1_high, my1_hs, my1_low, my1_ls,
+ my2_repo, my2_high, my2_hs, my2_low, my2_ls,
+ my3_repo, my3_high, my3_hs, my3_low, my3_ls,
+ my4_repo, my4_high, my4_hs, my4_low, my4_ls,
+ my5_repo, my5_high, my5_hs, my5_low, my5_ls,
+ ]
+
+ profile_save_btn.click(
+ save_profile, [profile_name, *_SETTINGS_FIELDS], [profile_picker, profile_status]
+ )
+ profile_load_btn.click(
+ load_profile, profile_picker, [*_SETTINGS_FIELDS, profile_name, profile_status]
+ )
+ profile_delete_btn.click(delete_profile, profile_picker, [profile_picker, profile_status])
+ profile_refresh.click(refresh_profiles, profile_picker, profile_picker)
+ settings_export_btn.click(export_settings, _SETTINGS_FIELDS, settings_download)
+ settings_upload.upload(import_settings, settings_upload, _SETTINGS_FIELDS)
+ # Repopulate on every page open, so profiles saved elsewhere show up without a restart.
+ demo.load(refresh_profiles, profile_picker, profile_picker)
+
+ _ESTIMATE_INPUTS = [
+ input_image_component, duration_seconds_input, steps_slider,
+ guidance_scale_input, frame_multi, safe_mode_checkbox,
+ ]
+ # Recalculated on demand only. An automatic readout means an event on every slider
+ # move, and a browser that never gets to rest.
+ pb_button.click(
+ fn=enhance_prompt,
+ inputs=[prompt_input, pb_use_model, pb_camera, pb_framing, pb_lighting, pb_pace, pb_quality],
+ outputs=[prompt_input, pb_status],
+ )
+
+ gpu_estimate_btn.click(
+ fn=_gpu_estimate_text,
+ inputs=_ESTIMATE_INPUTS,
+ outputs=[gpu_estimate],
+ show_progress="hidden",
+ )
+
if __name__ == "__main__":
demo.queue().launch(
mcp_server=True,
- css=CSS,
show_error=True,
- )
\ No newline at end of file
+ )