Spaces:
Paused
Paused
Initial Wan 2.2 I2V Extend Space (Generate + last-frame chain)
Browse files- .gitignore +9 -0
- README.md +53 -7
- app.py +601 -0
- requirements.txt +8 -0
.gitignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.venv/
|
| 4 |
+
.env
|
| 5 |
+
*.mp4
|
| 6 |
+
*.png
|
| 7 |
+
*.jpg
|
| 8 |
+
tmp/
|
| 9 |
+
.cache/
|
README.md
CHANGED
|
@@ -1,13 +1,59 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Wan 2.2 Extend
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.44.1
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
short_description: Wan 2.2 I2V + Extend chaining for ~10–20s clips
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Wan 2.2 Image → Video + Extend
|
| 15 |
+
|
| 16 |
+
Private helper Space for **Casey (Simzy)**: generate a short [Wan 2.2](https://huggingface.co/spaces/kulkas2pintu/wan222) image-to-video clip on **free ZeroGPU**, then **Extend** by chaining from the last frame until you reach roughly **10–20 seconds**.
|
| 17 |
+
|
| 18 |
+
This Space does **not** load the 14B Wan weights itself. It calls the public ZeroGPU Space `kulkas2pintu/wan222` via `gradio_client`, then stitches segments with ffmpeg.
|
| 19 |
+
|
| 20 |
+
## How to use
|
| 21 |
+
|
| 22 |
+
1. Upload a still image and write a motion prompt.
|
| 23 |
+
2. Click **Generate** — wait for ZeroGPU (often 1–3 minutes when busy).
|
| 24 |
+
3. Click **Extend** to continue from the last frame (same or updated prompt).
|
| 25 |
+
4. Or set a target length and use **Auto-extend** (capped at 6 segments).
|
| 26 |
+
5. Download the concatenated MP4.
|
| 27 |
+
|
| 28 |
+
### Length guide
|
| 29 |
+
|
| 30 |
+
| Segment length | Segments | Rough total |
|
| 31 |
+
|----------------|----------|-------------|
|
| 32 |
+
| ~3.5s | 3 | ~10s |
|
| 33 |
+
| ~3.5s | 4–5 | ~14–18s |
|
| 34 |
+
| ~4–5s | 4 | ~16–20s |
|
| 35 |
+
|
| 36 |
+
## Honesty about ZeroGPU
|
| 37 |
+
|
| 38 |
+
- ZeroGPU is **free** but **queued and quota-limited** — not unlimited.
|
| 39 |
+
- Each segment is a separate upstream call; longer videos = more waits.
|
| 40 |
+
- If the queue is full or quota exhausted, wait and retry.
|
| 41 |
+
|
| 42 |
+
## Architecture
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
[Your image] → Generate → clip1.mp4
|
| 46 |
+
↓ last frame
|
| 47 |
+
Extend → clip2.mp4 → ffmpeg concat → longer.mp4
|
| 48 |
+
↓ …
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Upstream API: `generate_video` on `kulkas2pintu/wan222` (same endpoint used by Command Center).
|
| 52 |
+
|
| 53 |
+
## Local files
|
| 54 |
+
|
| 55 |
+
Source also lives at `/workspace/wan22-extend/` on the agent box for re-push if needed.
|
| 56 |
+
|
| 57 |
+
## License / ToS
|
| 58 |
+
|
| 59 |
+
Apache-2.0 for this app code. Hugging Face Terms of Service apply to hosted Spaces and ZeroGPU usage.
|
app.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Wan 2.2 Image-to-Video with Extend chaining.
|
| 3 |
+
Calls a public ZeroGPU Wan 2.2 I2V Space per segment, extracts the last frame,
|
| 4 |
+
and concatenates clips for longer videos (~10–20s).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import shutil
|
| 11 |
+
import subprocess
|
| 12 |
+
import tempfile
|
| 13 |
+
import time
|
| 14 |
+
import uuid
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import cv2
|
| 19 |
+
import gradio as gr
|
| 20 |
+
import numpy as np
|
| 21 |
+
from gradio_client import Client, handle_file
|
| 22 |
+
from PIL import Image
|
| 23 |
+
|
| 24 |
+
# Upstream Wan 2.2 I2V (ZeroGPU) — same Space Command Center uses
|
| 25 |
+
UPSTREAM_SPACE = os.environ.get("WAN_UPSTREAM_SPACE", "kulkas2pintu/wan222")
|
| 26 |
+
UPSTREAM_API = "generate_video"
|
| 27 |
+
|
| 28 |
+
DEFAULT_PROMPT = "make this image come alive, cinematic motion, smooth animation"
|
| 29 |
+
DEFAULT_NEGATIVE = (
|
| 30 |
+
"色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, "
|
| 31 |
+
"整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, "
|
| 32 |
+
"画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, "
|
| 33 |
+
"静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
WORK = Path(tempfile.gettempdir()) / "wan22_extend"
|
| 37 |
+
WORK.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
|
| 39 |
+
_client: Client | None = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_client() -> Client:
|
| 43 |
+
global _client
|
| 44 |
+
if _client is None:
|
| 45 |
+
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 46 |
+
kwargs: dict[str, Any] = {}
|
| 47 |
+
if token:
|
| 48 |
+
kwargs["hf_token"] = token
|
| 49 |
+
_client = Client(UPSTREAM_SPACE, **kwargs)
|
| 50 |
+
return _client
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _session_dir() -> Path:
|
| 54 |
+
d = WORK / uuid.uuid4().hex[:12]
|
| 55 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
return d
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def save_image(img: Image.Image | np.ndarray | str | None, dest: Path) -> Path | None:
|
| 60 |
+
if img is None:
|
| 61 |
+
return None
|
| 62 |
+
if isinstance(img, str):
|
| 63 |
+
src = Path(img)
|
| 64 |
+
if not src.exists():
|
| 65 |
+
return None
|
| 66 |
+
out = dest.with_suffix(src.suffix or ".png")
|
| 67 |
+
shutil.copy2(src, out)
|
| 68 |
+
return out
|
| 69 |
+
if isinstance(img, np.ndarray):
|
| 70 |
+
img = Image.fromarray(img.astype("uint8"))
|
| 71 |
+
if not isinstance(img, Image.Image):
|
| 72 |
+
return None
|
| 73 |
+
out = dest.with_suffix(".png")
|
| 74 |
+
img.convert("RGB").save(out)
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def extract_last_frame(video_path: str | Path, out_path: Path) -> Path:
|
| 79 |
+
video_path = str(video_path)
|
| 80 |
+
cap = cv2.VideoCapture(video_path)
|
| 81 |
+
if not cap.isOpened():
|
| 82 |
+
raise RuntimeError(f"Could not open video: {video_path}")
|
| 83 |
+
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
| 84 |
+
frame = None
|
| 85 |
+
if total > 0:
|
| 86 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, total - 1))
|
| 87 |
+
ok, frame = cap.read()
|
| 88 |
+
if not ok or frame is None:
|
| 89 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 90 |
+
while True:
|
| 91 |
+
ok, f = cap.read()
|
| 92 |
+
if not ok:
|
| 93 |
+
break
|
| 94 |
+
frame = f
|
| 95 |
+
else:
|
| 96 |
+
while True:
|
| 97 |
+
ok, f = cap.read()
|
| 98 |
+
if not ok:
|
| 99 |
+
break
|
| 100 |
+
frame = f
|
| 101 |
+
cap.release()
|
| 102 |
+
if frame is None:
|
| 103 |
+
raise RuntimeError("No frames found in video.")
|
| 104 |
+
out_path = out_path.with_suffix(".png")
|
| 105 |
+
cv2.imwrite(str(out_path), frame)
|
| 106 |
+
return out_path
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def video_duration_seconds(video_path: str | Path) -> float:
|
| 110 |
+
video_path = str(video_path)
|
| 111 |
+
try:
|
| 112 |
+
out = subprocess.check_output(
|
| 113 |
+
[
|
| 114 |
+
"ffprobe",
|
| 115 |
+
"-v",
|
| 116 |
+
"error",
|
| 117 |
+
"-show_entries",
|
| 118 |
+
"format=duration",
|
| 119 |
+
"-of",
|
| 120 |
+
"default=noprint_wrappers=1:nokey=1",
|
| 121 |
+
video_path,
|
| 122 |
+
],
|
| 123 |
+
text=True,
|
| 124 |
+
stderr=subprocess.DEVNULL,
|
| 125 |
+
).strip()
|
| 126 |
+
return float(out)
|
| 127 |
+
except Exception:
|
| 128 |
+
cap = cv2.VideoCapture(video_path)
|
| 129 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 16.0
|
| 130 |
+
frames = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0
|
| 131 |
+
cap.release()
|
| 132 |
+
if fps > 0 and frames > 0:
|
| 133 |
+
return frames / fps
|
| 134 |
+
return 0.0
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def concat_videos(paths: list[Path], out_path: Path) -> Path:
|
| 138 |
+
if len(paths) == 1:
|
| 139 |
+
shutil.copy2(paths[0], out_path)
|
| 140 |
+
return out_path
|
| 141 |
+
# Re-encode to a common format so mismatched segments still join cleanly
|
| 142 |
+
list_file = out_path.parent / "concat_list.txt"
|
| 143 |
+
normalized: list[Path] = []
|
| 144 |
+
for i, p in enumerate(paths):
|
| 145 |
+
norm = out_path.parent / f"norm_{i:03d}.mp4"
|
| 146 |
+
subprocess.run(
|
| 147 |
+
[
|
| 148 |
+
"ffmpeg",
|
| 149 |
+
"-y",
|
| 150 |
+
"-i",
|
| 151 |
+
str(p),
|
| 152 |
+
"-vf",
|
| 153 |
+
"scale=trunc(iw/2)*2:trunc(ih/2)*2",
|
| 154 |
+
"-c:v",
|
| 155 |
+
"libx264",
|
| 156 |
+
"-pix_fmt",
|
| 157 |
+
"yuv420p",
|
| 158 |
+
"-an",
|
| 159 |
+
"-r",
|
| 160 |
+
"16",
|
| 161 |
+
str(norm),
|
| 162 |
+
],
|
| 163 |
+
check=True,
|
| 164 |
+
capture_output=True,
|
| 165 |
+
)
|
| 166 |
+
normalized.append(norm)
|
| 167 |
+
with list_file.open("w") as f:
|
| 168 |
+
for p in normalized:
|
| 169 |
+
f.write(f"file '{p.resolve()}'\n")
|
| 170 |
+
subprocess.run(
|
| 171 |
+
[
|
| 172 |
+
"ffmpeg",
|
| 173 |
+
"-y",
|
| 174 |
+
"-f",
|
| 175 |
+
"concat",
|
| 176 |
+
"-safe",
|
| 177 |
+
"0",
|
| 178 |
+
"-i",
|
| 179 |
+
str(list_file),
|
| 180 |
+
"-c",
|
| 181 |
+
"copy",
|
| 182 |
+
str(out_path),
|
| 183 |
+
],
|
| 184 |
+
check=True,
|
| 185 |
+
capture_output=True,
|
| 186 |
+
)
|
| 187 |
+
return out_path
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def call_wan_i2v(
|
| 191 |
+
image_path: Path,
|
| 192 |
+
prompt: str,
|
| 193 |
+
duration: float,
|
| 194 |
+
steps: int,
|
| 195 |
+
negative: str,
|
| 196 |
+
seed: int,
|
| 197 |
+
randomize: bool,
|
| 198 |
+
quality: int,
|
| 199 |
+
fps: int,
|
| 200 |
+
safe_mode: bool,
|
| 201 |
+
progress: gr.Progress | None = None,
|
| 202 |
+
) -> Path:
|
| 203 |
+
client = get_client()
|
| 204 |
+
if progress:
|
| 205 |
+
progress(0.1, desc=f"Calling {UPSTREAM_SPACE} (ZeroGPU queue)…")
|
| 206 |
+
|
| 207 |
+
# Match generate_video argument order from kulkas2pintu/wan222 /config
|
| 208 |
+
result = client.predict(
|
| 209 |
+
handle_file(str(image_path)), # input image
|
| 210 |
+
None, # last image (optional end-frame; we chain via last-frame start instead)
|
| 211 |
+
prompt or DEFAULT_PROMPT,
|
| 212 |
+
int(steps),
|
| 213 |
+
negative or DEFAULT_NEGATIVE,
|
| 214 |
+
float(duration),
|
| 215 |
+
1.0, # guidance high
|
| 216 |
+
1.0, # guidance low
|
| 217 |
+
int(seed),
|
| 218 |
+
bool(randomize),
|
| 219 |
+
int(quality),
|
| 220 |
+
"UniPCMultistep",
|
| 221 |
+
3.0, # flow shift
|
| 222 |
+
int(fps),
|
| 223 |
+
True, # display result
|
| 224 |
+
bool(safe_mode),
|
| 225 |
+
api_name=f"/{UPSTREAM_API}",
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Returns (video, download_file, seed) typically
|
| 229 |
+
video_ref = None
|
| 230 |
+
if isinstance(result, (list, tuple)):
|
| 231 |
+
video_ref = result[0]
|
| 232 |
+
else:
|
| 233 |
+
video_ref = result
|
| 234 |
+
|
| 235 |
+
if isinstance(video_ref, dict):
|
| 236 |
+
video_path = video_ref.get("video") or video_ref.get("path") or video_ref.get("url")
|
| 237 |
+
if isinstance(video_path, dict):
|
| 238 |
+
video_path = video_path.get("path") or video_path.get("url")
|
| 239 |
+
else:
|
| 240 |
+
video_path = video_ref
|
| 241 |
+
|
| 242 |
+
if not video_path or not Path(str(video_path)).exists():
|
| 243 |
+
raise RuntimeError(
|
| 244 |
+
f"Upstream did not return a local video path. Got: {type(result)} {str(result)[:300]}"
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
dest = image_path.parent / f"seg_{uuid.uuid4().hex[:8]}.mp4"
|
| 248 |
+
shutil.copy2(str(video_path), dest)
|
| 249 |
+
return dest
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def status_line(segments: list[str], duration_est: float) -> str:
|
| 253 |
+
n = len(segments)
|
| 254 |
+
return (
|
| 255 |
+
f"**Segments:** {n} · **Duration ≈ {duration_est:.1f}s** · "
|
| 256 |
+
f"Upstream: `{UPSTREAM_SPACE}` (ZeroGPU — free, queued/quota-limited)"
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def estimate_total(seg_duration: float, num_segments: int) -> float:
|
| 261 |
+
return float(seg_duration) * int(num_segments)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def do_generate(
|
| 265 |
+
image,
|
| 266 |
+
prompt,
|
| 267 |
+
seg_duration,
|
| 268 |
+
steps,
|
| 269 |
+
negative,
|
| 270 |
+
seed,
|
| 271 |
+
randomize,
|
| 272 |
+
quality,
|
| 273 |
+
fps,
|
| 274 |
+
safe_mode,
|
| 275 |
+
state: dict,
|
| 276 |
+
progress=gr.Progress(track_tqdm=False),
|
| 277 |
+
):
|
| 278 |
+
if image is None:
|
| 279 |
+
raise gr.Error("Upload a still image first.")
|
| 280 |
+
sess = Path(state.get("dir") or str(_session_dir()))
|
| 281 |
+
sess.mkdir(parents=True, exist_ok=True)
|
| 282 |
+
state["dir"] = str(sess)
|
| 283 |
+
|
| 284 |
+
img_path = save_image(image, sess / "input")
|
| 285 |
+
if img_path is None:
|
| 286 |
+
raise gr.Error("Could not read the uploaded image.")
|
| 287 |
+
|
| 288 |
+
progress(0.05, desc="Starting generation…")
|
| 289 |
+
try:
|
| 290 |
+
clip = call_wan_i2v(
|
| 291 |
+
img_path,
|
| 292 |
+
prompt,
|
| 293 |
+
float(seg_duration),
|
| 294 |
+
int(steps),
|
| 295 |
+
negative,
|
| 296 |
+
int(seed),
|
| 297 |
+
bool(randomize),
|
| 298 |
+
int(quality),
|
| 299 |
+
int(fps),
|
| 300 |
+
bool(safe_mode),
|
| 301 |
+
progress,
|
| 302 |
+
)
|
| 303 |
+
except Exception as e:
|
| 304 |
+
raise gr.Error(
|
| 305 |
+
f"Generation failed (ZeroGPU queue/quota or upstream error): {e}"
|
| 306 |
+
) from e
|
| 307 |
+
|
| 308 |
+
out = sess / "current.mp4"
|
| 309 |
+
shutil.copy2(clip, out)
|
| 310 |
+
last = extract_last_frame(out, sess / "last_frame")
|
| 311 |
+
dur = video_duration_seconds(out)
|
| 312 |
+
state["segments"] = [str(clip)]
|
| 313 |
+
state["video"] = str(out)
|
| 314 |
+
state["last_frame"] = str(last)
|
| 315 |
+
state["prompt"] = prompt
|
| 316 |
+
progress(1.0, desc="Done")
|
| 317 |
+
return (
|
| 318 |
+
str(out),
|
| 319 |
+
str(out),
|
| 320 |
+
status_line(state["segments"], dur),
|
| 321 |
+
str(last),
|
| 322 |
+
state,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def do_extend(
|
| 327 |
+
prompt,
|
| 328 |
+
seg_duration,
|
| 329 |
+
steps,
|
| 330 |
+
negative,
|
| 331 |
+
seed,
|
| 332 |
+
randomize,
|
| 333 |
+
quality,
|
| 334 |
+
fps,
|
| 335 |
+
safe_mode,
|
| 336 |
+
state: dict,
|
| 337 |
+
progress=gr.Progress(track_tqdm=False),
|
| 338 |
+
):
|
| 339 |
+
if not state or not state.get("video") or not state.get("last_frame"):
|
| 340 |
+
raise gr.Error("Generate a clip first, then use Extend.")
|
| 341 |
+
if len(state.get("segments", [])) >= 6:
|
| 342 |
+
raise gr.Error("Segment cap reached (6). Reset and start a new chain.")
|
| 343 |
+
|
| 344 |
+
sess = Path(state["dir"])
|
| 345 |
+
last = Path(state["last_frame"])
|
| 346 |
+
if not last.exists():
|
| 347 |
+
last = extract_last_frame(state["video"], sess / "last_frame")
|
| 348 |
+
state["last_frame"] = str(last)
|
| 349 |
+
|
| 350 |
+
use_prompt = prompt or state.get("prompt") or DEFAULT_PROMPT
|
| 351 |
+
progress(0.05, desc="Extending from last frame…")
|
| 352 |
+
try:
|
| 353 |
+
clip = call_wan_i2v(
|
| 354 |
+
last,
|
| 355 |
+
use_prompt,
|
| 356 |
+
float(seg_duration),
|
| 357 |
+
int(steps),
|
| 358 |
+
negative,
|
| 359 |
+
int(seed),
|
| 360 |
+
bool(randomize),
|
| 361 |
+
int(quality),
|
| 362 |
+
int(fps),
|
| 363 |
+
bool(safe_mode),
|
| 364 |
+
progress,
|
| 365 |
+
)
|
| 366 |
+
except Exception as e:
|
| 367 |
+
raise gr.Error(f"Extend failed: {e}") from e
|
| 368 |
+
|
| 369 |
+
segs = [Path(p) for p in state["segments"]] + [clip]
|
| 370 |
+
out = sess / f"current_{len(segs)}.mp4"
|
| 371 |
+
try:
|
| 372 |
+
concat_videos(segs, out)
|
| 373 |
+
except Exception as e:
|
| 374 |
+
raise gr.Error(f"Concat failed (ffmpeg): {e}") from e
|
| 375 |
+
|
| 376 |
+
last = extract_last_frame(out, sess / "last_frame")
|
| 377 |
+
dur = video_duration_seconds(out)
|
| 378 |
+
state["segments"] = [str(p) for p in segs]
|
| 379 |
+
state["video"] = str(out)
|
| 380 |
+
state["last_frame"] = str(last)
|
| 381 |
+
state["prompt"] = use_prompt
|
| 382 |
+
progress(1.0, desc="Extended")
|
| 383 |
+
return (
|
| 384 |
+
str(out),
|
| 385 |
+
str(out),
|
| 386 |
+
status_line(state["segments"], dur),
|
| 387 |
+
str(last),
|
| 388 |
+
state,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def do_auto_extend(
|
| 393 |
+
target_seconds,
|
| 394 |
+
prompt,
|
| 395 |
+
seg_duration,
|
| 396 |
+
steps,
|
| 397 |
+
negative,
|
| 398 |
+
seed,
|
| 399 |
+
randomize,
|
| 400 |
+
quality,
|
| 401 |
+
fps,
|
| 402 |
+
safe_mode,
|
| 403 |
+
state: dict,
|
| 404 |
+
progress=gr.Progress(track_tqdm=False),
|
| 405 |
+
):
|
| 406 |
+
if not state or not state.get("video"):
|
| 407 |
+
raise gr.Error("Generate a first clip, then Auto-extend.")
|
| 408 |
+
target = float(target_seconds)
|
| 409 |
+
max_segs = 6
|
| 410 |
+
video, download, status, last_preview, state = (
|
| 411 |
+
state.get("video"),
|
| 412 |
+
state.get("video"),
|
| 413 |
+
status_line(state.get("segments", []), video_duration_seconds(state["video"])),
|
| 414 |
+
state.get("last_frame"),
|
| 415 |
+
state,
|
| 416 |
+
)
|
| 417 |
+
while len(state.get("segments", [])) < max_segs:
|
| 418 |
+
dur = video_duration_seconds(state["video"])
|
| 419 |
+
if dur >= target:
|
| 420 |
+
break
|
| 421 |
+
progress(
|
| 422 |
+
len(state["segments"]) / max_segs,
|
| 423 |
+
desc=f"Auto-extend: {dur:.1f}s / {target:.0f}s…",
|
| 424 |
+
)
|
| 425 |
+
video, download, status, last_preview, state = do_extend(
|
| 426 |
+
prompt,
|
| 427 |
+
seg_duration,
|
| 428 |
+
steps,
|
| 429 |
+
negative,
|
| 430 |
+
seed,
|
| 431 |
+
randomize,
|
| 432 |
+
quality,
|
| 433 |
+
fps,
|
| 434 |
+
safe_mode,
|
| 435 |
+
state,
|
| 436 |
+
progress,
|
| 437 |
+
)
|
| 438 |
+
time.sleep(0.3)
|
| 439 |
+
return video, download, status, last_preview, state
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def do_reset(state: dict):
|
| 443 |
+
if state and state.get("dir"):
|
| 444 |
+
try:
|
| 445 |
+
shutil.rmtree(state["dir"], ignore_errors=True)
|
| 446 |
+
except Exception:
|
| 447 |
+
pass
|
| 448 |
+
return None, None, "**Segments:** 0 · **Duration ≈ 0s**", None, {}
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def update_estimate(seg_duration, num_planned):
|
| 452 |
+
total = estimate_total(seg_duration, num_planned)
|
| 453 |
+
return f"Planned length ≈ **{total:.1f}s** ({num_planned} × {seg_duration:.1f}s segments). Cap: 6 segments."
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
CSS = """
|
| 457 |
+
.big-btn button { font-size: 1.15rem !important; min-height: 3rem !important; }
|
| 458 |
+
#status-md { font-size: 1rem; }
|
| 459 |
+
footer { display: none !important; }
|
| 460 |
+
"""
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def build_ui():
|
| 464 |
+
with gr.Blocks(title="Wan 2.2 Extend — I2V", css=CSS, theme=gr.themes.Soft()) as demo:
|
| 465 |
+
gr.Markdown(
|
| 466 |
+
"""
|
| 467 |
+
# Wan 2.2 Image → Video + Extend
|
| 468 |
+
Upload a still, generate a short Wan 2.2 clip on **free ZeroGPU**, then **Extend** from the last frame to chain ~10–20s videos.
|
| 469 |
+
|
| 470 |
+
ZeroGPU is free but **queued and quota-limited** — each segment often takes 1–3 minutes when busy.
|
| 471 |
+
"""
|
| 472 |
+
)
|
| 473 |
+
state = gr.State({})
|
| 474 |
+
|
| 475 |
+
with gr.Row():
|
| 476 |
+
with gr.Column(scale=1):
|
| 477 |
+
image = gr.Image(label="Still image", type="pil", height=320)
|
| 478 |
+
prompt = gr.Textbox(
|
| 479 |
+
label="Prompt",
|
| 480 |
+
value=DEFAULT_PROMPT,
|
| 481 |
+
lines=3,
|
| 482 |
+
placeholder="Describe the motion you want…",
|
| 483 |
+
)
|
| 484 |
+
with gr.Row():
|
| 485 |
+
seg_duration = gr.Slider(
|
| 486 |
+
2.0,
|
| 487 |
+
5.0,
|
| 488 |
+
value=3.5,
|
| 489 |
+
step=0.5,
|
| 490 |
+
label="Segment length (seconds)",
|
| 491 |
+
info="Each Wan call; Extend adds another segment.",
|
| 492 |
+
)
|
| 493 |
+
num_planned = gr.Slider(
|
| 494 |
+
1,
|
| 495 |
+
6,
|
| 496 |
+
value=4,
|
| 497 |
+
step=1,
|
| 498 |
+
label="Target segments",
|
| 499 |
+
info="For estimate only (3–5 ≈ 10–20s).",
|
| 500 |
+
)
|
| 501 |
+
estimate = gr.Markdown(update_estimate(3.5, 4))
|
| 502 |
+
target_seconds = gr.Slider(
|
| 503 |
+
8,
|
| 504 |
+
22,
|
| 505 |
+
value=14,
|
| 506 |
+
step=1,
|
| 507 |
+
label="Auto-extend target (seconds)",
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
with gr.Accordion("Advanced", open=False):
|
| 511 |
+
steps = gr.Slider(1, 12, value=4, step=1, label="Inference steps")
|
| 512 |
+
quality = gr.Slider(1, 10, value=6, step=1, label="Video quality")
|
| 513 |
+
fps = gr.Dropdown(
|
| 514 |
+
choices=[16, 32, 64],
|
| 515 |
+
value=16,
|
| 516 |
+
label="Fluidity FPS",
|
| 517 |
+
)
|
| 518 |
+
seed = gr.Number(value=42, label="Seed", precision=0)
|
| 519 |
+
randomize = gr.Checkbox(value=True, label="Randomize seed")
|
| 520 |
+
safe_mode = gr.Checkbox(
|
| 521 |
+
value=True,
|
| 522 |
+
label="Upstream Safe Mode",
|
| 523 |
+
info="Extra ZeroGPU headroom on busy servers.",
|
| 524 |
+
)
|
| 525 |
+
negative = gr.Textbox(
|
| 526 |
+
label="Negative prompt",
|
| 527 |
+
value=DEFAULT_NEGATIVE,
|
| 528 |
+
lines=2,
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
with gr.Row(elem_classes=["big-btn"]):
|
| 532 |
+
btn_gen = gr.Button("Generate", variant="primary", size="lg")
|
| 533 |
+
btn_ext = gr.Button("Extend", variant="secondary", size="lg")
|
| 534 |
+
with gr.Row(elem_classes=["big-btn"]):
|
| 535 |
+
btn_auto = gr.Button("Auto-extend to target", size="lg")
|
| 536 |
+
btn_reset = gr.Button("Reset", size="lg")
|
| 537 |
+
|
| 538 |
+
with gr.Column(scale=1):
|
| 539 |
+
video = gr.Video(label="Preview", height=360, autoplay=True)
|
| 540 |
+
status = gr.Markdown("**Segments:** 0 · **Duration ≈ 0s**", elem_id="status-md")
|
| 541 |
+
last_preview = gr.Image(label="Last frame (next Extend start)", height=180)
|
| 542 |
+
download = gr.File(label="Download MP4")
|
| 543 |
+
|
| 544 |
+
seg_duration.change(update_estimate, [seg_duration, num_planned], estimate)
|
| 545 |
+
num_planned.change(update_estimate, [seg_duration, num_planned], estimate)
|
| 546 |
+
|
| 547 |
+
gen_inputs = [
|
| 548 |
+
image,
|
| 549 |
+
prompt,
|
| 550 |
+
seg_duration,
|
| 551 |
+
steps,
|
| 552 |
+
negative,
|
| 553 |
+
seed,
|
| 554 |
+
randomize,
|
| 555 |
+
quality,
|
| 556 |
+
fps,
|
| 557 |
+
safe_mode,
|
| 558 |
+
state,
|
| 559 |
+
]
|
| 560 |
+
ext_inputs = [
|
| 561 |
+
prompt,
|
| 562 |
+
seg_duration,
|
| 563 |
+
steps,
|
| 564 |
+
negative,
|
| 565 |
+
seed,
|
| 566 |
+
randomize,
|
| 567 |
+
quality,
|
| 568 |
+
fps,
|
| 569 |
+
safe_mode,
|
| 570 |
+
state,
|
| 571 |
+
]
|
| 572 |
+
outs = [video, download, status, last_preview, state]
|
| 573 |
+
|
| 574 |
+
btn_gen.click(do_generate, gen_inputs, outs)
|
| 575 |
+
btn_ext.click(do_extend, ext_inputs, outs)
|
| 576 |
+
btn_auto.click(
|
| 577 |
+
do_auto_extend,
|
| 578 |
+
[target_seconds] + ext_inputs,
|
| 579 |
+
outs,
|
| 580 |
+
)
|
| 581 |
+
btn_reset.click(do_reset, [state], outs)
|
| 582 |
+
|
| 583 |
+
gr.Markdown(
|
| 584 |
+
f"""
|
| 585 |
+
### How Extend works
|
| 586 |
+
1. **Generate** — still image + prompt → short Wan 2.2 I2V clip (~{3.5}s default).
|
| 587 |
+
2. **Extend** — take the **last frame**, run I2V again, **concatenate** onto the previous video.
|
| 588 |
+
3. Repeat until you hit ~10–20s (or use **Auto-extend**). Soft cap: **6 segments**.
|
| 589 |
+
|
| 590 |
+
### Limits
|
| 591 |
+
- Powered by public ZeroGPU Space `{UPSTREAM_SPACE}` — free, but **queued / quota-limited**, not unlimited.
|
| 592 |
+
- Single segments are typically a few seconds; longer clips = chained Extends.
|
| 593 |
+
- Hugging Face Terms of Service apply to hosted Spaces.
|
| 594 |
+
"""
|
| 595 |
+
)
|
| 596 |
+
return demo
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
if __name__ == "__main__":
|
| 600 |
+
demo = build_ui()
|
| 601 |
+
demo.queue(default_concurrency_limit=1).launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.0.0
|
| 2 |
+
gradio_client>=1.0.0
|
| 3 |
+
huggingface_hub>=0.26.0
|
| 4 |
+
opencv-python-headless>=4.8.0
|
| 5 |
+
numpy>=1.24.0
|
| 6 |
+
Pillow>=10.0.0
|
| 7 |
+
imageio>=2.31.0
|
| 8 |
+
imageio-ffmpeg>=0.4.9
|