Spaces:
Paused
Paused
Restore pre-Runpod ZeroGPU Extend (match extend-current-20260923 / GitHub main)
Browse files- .gitignore +0 -9
- README.md +15 -65
- app.py +35 -213
- runpod_i2v.py +0 -666
- tests/test_runpod_i2v.py +0 -809
.gitignore
DELETED
|
@@ -1,9 +0,0 @@
|
|
| 1 |
-
__pycache__/
|
| 2 |
-
*.py[cod]
|
| 3 |
-
.venv/
|
| 4 |
-
.env
|
| 5 |
-
*.mp4
|
| 6 |
-
*.png
|
| 7 |
-
*.jpg
|
| 8 |
-
tmp/
|
| 9 |
-
.cache/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -13,94 +13,44 @@ short_description: Wan 2.2 I2V + Extend chaining for ~10–20s clips
|
|
| 13 |
|
| 14 |
# Wan 2.2 Image → Video + Extend
|
| 15 |
|
| 16 |
-
Private helper Space for **Casey (Simzy)**:
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
## Space secrets
|
| 21 |
-
|
| 22 |
-
Set these in the Hugging Face Space (**Settings → Secrets**), then **rebuild** the Space. Do not commit them, and do not put them in this repo.
|
| 23 |
-
|
| 24 |
-
| Secret | Value |
|
| 25 |
-
| --- | --- |
|
| 26 |
-
| `RUNPOD_API_KEY` | Runpod API key. Sent only as `Authorization: Bearer …`. |
|
| 27 |
-
| `RUNPOD_ENDPOINT_ID` | `kyujeqw2gt779h` |
|
| 28 |
-
|
| 29 |
-
The endpoint id defaults to `kyujeqw2gt779h` (`wan22-extend-i2v`) when `RUNPOD_ENDPOINT_ID` is unset, so the API key alone turns Runpod on. Set the id explicitly anyway so the Space stays pinned to that endpoint.
|
| 30 |
-
|
| 31 |
-
Optional:
|
| 32 |
-
|
| 33 |
-
| Variable | Purpose |
|
| 34 |
-
| --- | --- |
|
| 35 |
-
| `RUNPOD_ENDPOINT_URL` | Override the base URL. A `/run` or `/runsync` URL is accepted and normalized. Default: `https://api.runpod.ai/v2/kyujeqw2gt779h`. |
|
| 36 |
-
| `WAN_BACKEND=zerogpu` | Force the free ZeroGPU fallback even when `RUNPOD_API_KEY` is set. `USE_ZERGPU=1` does the same. |
|
| 37 |
-
| `RUNPOD_TIMEOUT_SECONDS` | How long to wait for one segment (default 2700). Cold start is allowed. |
|
| 38 |
-
| `RUNPOD_CFG` | Classifier-free guidance sent to the worker (default `2.0`). |
|
| 39 |
-
|
| 40 |
-
If `RUNPOD_API_KEY` is missing and `WAN_BACKEND` is not `runpod`, segments fall back to the public ZeroGPU Space `kulkas2pintu/wan222`.
|
| 41 |
|
| 42 |
## How to use
|
| 43 |
|
| 44 |
1. Upload a still image and write a **Generate prompt**.
|
| 45 |
-
2. Click **Generate**
|
| 46 |
-
3. Optionally set an **Extend prompt** (leave blank to reuse
|
| 47 |
-
- **Last frame from video** (default)
|
| 48 |
-
- **Upload custom image** —
|
| 49 |
-
4. Click **Extend**, or set a target length and use **Auto-extend** (capped at 6 segments).
|
| 50 |
5. Download the concatenated MP4.
|
| 51 |
|
| 52 |
### Length guide
|
| 53 |
|
| 54 |
-
Segment length is turned into Wan frames at 16 fps (`4n+1`, max 81 frames ≈ 5s). Extend adds another segment of that length.
|
| 55 |
-
|
| 56 |
| Segment length | Segments | Rough total |
|
| 57 |
|----------------|----------|-------------|
|
| 58 |
| ~3.5s | 3 | ~10s |
|
| 59 |
| ~3.5s | 4–5 | ~14–18s |
|
| 60 |
| ~4–5s | 4 | ~16–20s |
|
| 61 |
|
| 62 |
-
##
|
| 63 |
-
|
| 64 |
-
- Endpoint id: `kyujeqw2gt779h`
|
| 65 |
-
- Name: `wan22-extend-i2v`
|
| 66 |
-
- `POST /run`, then poll `GET /status/{id}` (async, so a cold start can finish)
|
| 67 |
-
- Auth: `Authorization: Bearer $RUNPOD_API_KEY`
|
| 68 |
-
- `workersMin: 0` — idle workers shut down; the first Generate after that is slow
|
| 69 |
-
|
| 70 |
-
Worker input for every segment:
|
| 71 |
-
|
| 72 |
-
```json
|
| 73 |
-
{
|
| 74 |
-
"input": {
|
| 75 |
-
"prompt": "...",
|
| 76 |
-
"negative_prompt": "...",
|
| 77 |
-
"image_base64": "<raw jpeg base64>",
|
| 78 |
-
"width": 480,
|
| 79 |
-
"height": 832,
|
| 80 |
-
"length": 81,
|
| 81 |
-
"steps": 10,
|
| 82 |
-
"cfg": 2.0,
|
| 83 |
-
"seed": 42
|
| 84 |
-
}
|
| 85 |
-
}
|
| 86 |
-
```
|
| 87 |
-
|
| 88 |
-
`image_base64` is raw base64 (no `data:` prefix) because the worker decodes it directly. Width and height follow the still: portrait photos use 480×832, landscape photos use 832×480. The response video is read from `output.video` (raw base64 or `data:video/mp4;base64,…`) or from a video URL.
|
| 89 |
-
|
| 90 |
-
Failures (HTTP 401/404, job `FAILED` / `TIMED_OUT` / `CANCELLED`, a completed job with no MP4, or our own wait expiring) are shown on the Generate / Extend error. The API key is not included in that message.
|
| 91 |
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
## Architecture
|
| 95 |
|
| 96 |
```
|
| 97 |
-
[Your image] → Generate →
|
| 98 |
↓ last frame (or custom upload)
|
| 99 |
-
Extend →
|
| 100 |
↓ …
|
| 101 |
```
|
| 102 |
|
| 103 |
-
|
| 104 |
|
| 105 |
## Local files
|
| 106 |
|
|
@@ -110,4 +60,4 @@ HF branch `backup-v1-working` is frozen and should not be overwritten.
|
|
| 110 |
|
| 111 |
## License / ToS
|
| 112 |
|
| 113 |
-
Apache-2.0 for this app code. Hugging Face Terms of Service apply to hosted Spaces
|
|
|
|
| 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 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 **Generate prompt**.
|
| 23 |
+
2. Click **Generate** — wait for ZeroGPU (often 1–3 minutes when busy).
|
| 24 |
+
3. Optionally set an **Extend prompt** (leave blank to reuse Generate prompt) and choose **Extend start**:
|
| 25 |
+
- **Last frame from video** (default) — current behavior
|
| 26 |
+
- **Upload custom image** — use a different image as the I2V start for the next segment
|
| 27 |
+
4. Click **Extend** to continue, or set a target length and use **Auto-extend** (capped at 6 segments).
|
| 28 |
5. Download the concatenated MP4.
|
| 29 |
|
| 30 |
### Length guide
|
| 31 |
|
|
|
|
|
|
|
| 32 |
| Segment length | Segments | Rough total |
|
| 33 |
|----------------|----------|-------------|
|
| 34 |
| ~3.5s | 3 | ~10s |
|
| 35 |
| ~3.5s | 4–5 | ~14–18s |
|
| 36 |
| ~4–5s | 4 | ~16–20s |
|
| 37 |
|
| 38 |
+
## Honesty about ZeroGPU
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
- ZeroGPU is **free** but **queued and quota-limited** — not unlimited.
|
| 41 |
+
- Each segment is a separate upstream call; longer videos = more waits.
|
| 42 |
+
- If the queue is full or quota exhausted, wait and retry.
|
| 43 |
|
| 44 |
## Architecture
|
| 45 |
|
| 46 |
```
|
| 47 |
+
[Your image] → Generate → clip1.mp4
|
| 48 |
↓ last frame (or custom upload)
|
| 49 |
+
Extend → clip2.mp4 → ffmpeg concat → longer.mp4
|
| 50 |
↓ …
|
| 51 |
```
|
| 52 |
|
| 53 |
+
Upstream API: `generate_video` on `kulkas2pintu/wan222` (same endpoint used by Command Center).
|
| 54 |
|
| 55 |
## Local files
|
| 56 |
|
|
|
|
| 60 |
|
| 61 |
## License / ToS
|
| 62 |
|
| 63 |
+
Apache-2.0 for this app code. Hugging Face Terms of Service apply to hosted Spaces and ZeroGPU usage.
|
app.py
CHANGED
|
@@ -1,10 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
Wan 2.2 Image-to-Video with Extend chaining.
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
is set (endpoint id defaults to kyujeqw2gt779h). If that secret is missing,
|
| 6 |
-
or WAN_BACKEND=zerogpu, segments fall back to the public ZeroGPU Space.
|
| 7 |
-
Clips are stitched with ffmpeg for ~10–20s videos.
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
|
@@ -21,7 +18,6 @@ from typing import Any
|
|
| 21 |
import cv2
|
| 22 |
import gradio as gr
|
| 23 |
import numpy as np
|
| 24 |
-
import runpod_i2v
|
| 25 |
from gradio_client import Client, handle_file
|
| 26 |
from PIL import Image, ImageOps
|
| 27 |
|
|
@@ -336,70 +332,7 @@ def concat_videos(paths: list[Path], out_path: Path) -> Path:
|
|
| 336 |
return out_path
|
| 337 |
|
| 338 |
|
| 339 |
-
def
|
| 340 |
-
"""Surface Runpod failures directly. ``action`` is Generation or Extend."""
|
| 341 |
-
if isinstance(exc, gr.Error):
|
| 342 |
-
raise exc
|
| 343 |
-
if isinstance(exc, runpod_i2v.RunpodError):
|
| 344 |
-
raise gr.Error(f"{action} failed: {exc}") from exc
|
| 345 |
-
if runpod_i2v.active_backend() == "runpod":
|
| 346 |
-
raise gr.Error(f"{action} failed (Runpod): {exc}") from exc
|
| 347 |
-
if action == "Generation":
|
| 348 |
-
raise gr.Error(
|
| 349 |
-
f"Generation failed (ZeroGPU queue/quota or upstream error): {exc}"
|
| 350 |
-
) from exc
|
| 351 |
-
raise gr.Error(f"Extend failed: {exc}") from exc
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
def _runpod_progress(progress, phase: str, elapsed: float) -> None:
|
| 355 |
-
if not progress:
|
| 356 |
-
return
|
| 357 |
-
if phase == "submit":
|
| 358 |
-
progress(0.12, desc="Sending this segment to Runpod…")
|
| 359 |
-
return
|
| 360 |
-
if phase == "IN_QUEUE":
|
| 361 |
-
progress(
|
| 362 |
-
0.25,
|
| 363 |
-
desc=(
|
| 364 |
-
"Waiting for a Runpod worker "
|
| 365 |
-
f"(cold start + model download can take several minutes)… {int(elapsed)}s"
|
| 366 |
-
),
|
| 367 |
-
)
|
| 368 |
-
return
|
| 369 |
-
if phase == "IN_PROGRESS":
|
| 370 |
-
progress(0.6, desc=f"Runpod is generating this segment… {int(elapsed)}s")
|
| 371 |
-
return
|
| 372 |
-
if phase == "save":
|
| 373 |
-
progress(0.92, desc="Saving video…")
|
| 374 |
-
return
|
| 375 |
-
if phase:
|
| 376 |
-
progress(0.4, desc=f"Runpod status: {phase}… {int(elapsed)}s")
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
def call_runpod_i2v(
|
| 380 |
-
image_path: Path,
|
| 381 |
-
prompt: str,
|
| 382 |
-
duration: float,
|
| 383 |
-
steps: int,
|
| 384 |
-
negative: str,
|
| 385 |
-
seed: int,
|
| 386 |
-
randomize: bool,
|
| 387 |
-
progress: gr.Progress | None = None,
|
| 388 |
-
) -> Path:
|
| 389 |
-
dest = image_path.parent / f"seg_{uuid.uuid4().hex[:8]}.mp4"
|
| 390 |
-
return runpod_i2v.generate_i2v(
|
| 391 |
-
image_path,
|
| 392 |
-
dest,
|
| 393 |
-
prompt=prompt or DEFAULT_PROMPT,
|
| 394 |
-
negative_prompt=negative or DEFAULT_NEGATIVE,
|
| 395 |
-
duration_seconds=float(duration),
|
| 396 |
-
steps=int(steps),
|
| 397 |
-
seed=runpod_i2v.resolve_seed(int(seed), bool(randomize)),
|
| 398 |
-
on_progress=lambda phase, elapsed: _runpod_progress(progress, phase, elapsed),
|
| 399 |
-
)
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
def call_zerogpu_i2v(
|
| 403 |
image_path: Path,
|
| 404 |
prompt: str,
|
| 405 |
duration: float,
|
|
@@ -461,54 +394,11 @@ def call_zerogpu_i2v(
|
|
| 461 |
return dest
|
| 462 |
|
| 463 |
|
| 464 |
-
def call_wan_i2v(
|
| 465 |
-
image_path: Path,
|
| 466 |
-
prompt: str,
|
| 467 |
-
duration: float,
|
| 468 |
-
steps: int,
|
| 469 |
-
negative: str,
|
| 470 |
-
seed: int,
|
| 471 |
-
randomize: bool,
|
| 472 |
-
quality: int,
|
| 473 |
-
fps: int,
|
| 474 |
-
safe_mode: bool,
|
| 475 |
-
progress: gr.Progress | None = None,
|
| 476 |
-
) -> Path:
|
| 477 |
-
"""One I2V segment. Runpod when secrets are set, otherwise ZeroGPU."""
|
| 478 |
-
if runpod_i2v.active_backend() == "runpod":
|
| 479 |
-
return call_runpod_i2v(
|
| 480 |
-
image_path,
|
| 481 |
-
prompt,
|
| 482 |
-
duration,
|
| 483 |
-
steps,
|
| 484 |
-
negative,
|
| 485 |
-
seed,
|
| 486 |
-
randomize,
|
| 487 |
-
progress,
|
| 488 |
-
)
|
| 489 |
-
return call_zerogpu_i2v(
|
| 490 |
-
image_path,
|
| 491 |
-
prompt,
|
| 492 |
-
duration,
|
| 493 |
-
steps,
|
| 494 |
-
negative,
|
| 495 |
-
seed,
|
| 496 |
-
randomize,
|
| 497 |
-
quality,
|
| 498 |
-
fps,
|
| 499 |
-
safe_mode,
|
| 500 |
-
progress,
|
| 501 |
-
)
|
| 502 |
-
|
| 503 |
-
|
| 504 |
def status_line(segments: list[str], duration_est: float) -> str:
|
| 505 |
n = len(segments)
|
| 506 |
-
if runpod_i2v.active_backend() == "runpod":
|
| 507 |
-
backend = f"Runpod `{runpod_i2v.endpoint_base_url().split('?', 1)[0]}`"
|
| 508 |
-
else:
|
| 509 |
-
backend = f"ZeroGPU `{UPSTREAM_SPACE}` (fallback — queued/quota-limited)"
|
| 510 |
return (
|
| 511 |
-
f"**Segments:** {n} · **Duration ≈ {duration_est:.1f}s** ·
|
|
|
|
| 512 |
)
|
| 513 |
|
| 514 |
|
|
@@ -606,7 +496,9 @@ def do_generate(
|
|
| 606 |
progress,
|
| 607 |
)
|
| 608 |
except Exception as e:
|
| 609 |
-
|
|
|
|
|
|
|
| 610 |
|
| 611 |
out = sess / "current.mp4"
|
| 612 |
shutil.copy2(clip, out)
|
|
@@ -668,7 +560,7 @@ def do_extend(
|
|
| 668 |
progress,
|
| 669 |
)
|
| 670 |
except Exception as e:
|
| 671 |
-
|
| 672 |
|
| 673 |
segs = [Path(p) for p in state["segments"]] + [clip]
|
| 674 |
out = sess / f"current_{len(segs)}.mp4"
|
|
@@ -763,7 +655,7 @@ def do_reset(state: dict):
|
|
| 763 |
shutil.rmtree(state["dir"], ignore_errors=True)
|
| 764 |
except Exception:
|
| 765 |
pass
|
| 766 |
-
return None, None,
|
| 767 |
|
| 768 |
|
| 769 |
def update_estimate(seg_duration, num_planned):
|
|
@@ -776,68 +668,6 @@ def toggle_custom_extend_image(mode: str):
|
|
| 776 |
return gr.update(visible=visible)
|
| 777 |
|
| 778 |
|
| 779 |
-
def default_steps() -> int:
|
| 780 |
-
"""Runpod's usual setting is 10. ZeroGPU stays on the faster default of 4."""
|
| 781 |
-
return 10 if runpod_i2v.active_backend() == "runpod" else 4
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
def intro_markdown() -> str:
|
| 785 |
-
if runpod_i2v.active_backend() == "runpod":
|
| 786 |
-
endpoint = runpod_i2v.endpoint_id()
|
| 787 |
-
return f"""
|
| 788 |
-
# Wan 2.2 Image → Video + Extend
|
| 789 |
-
Upload a still, **Generate** a short Wan 2.2 clip, then **Extend** from the last frame (or a custom start image) to chain ~10–20s videos.
|
| 790 |
-
|
| 791 |
-
Each segment runs on **Runpod** endpoint `{endpoint}` (`wan22-extend-i2v`). **The first Generate may take several minutes** — the worker scales from zero (cold start) and may download the model before it starts. Extend and Auto-extend call Runpod again for every segment.
|
| 792 |
-
"""
|
| 793 |
-
return f"""
|
| 794 |
-
# Wan 2.2 Image → Video + Extend
|
| 795 |
-
Upload a still, generate a short Wan 2.2 clip on **free ZeroGPU**, then **Extend** from the last frame (or a custom start image) to chain ~10–20s videos.
|
| 796 |
-
|
| 797 |
-
ZeroGPU is the fallback while `RUNPOD_API_KEY` is unset. It is free but **queued and quota-limited** — each segment often takes 1–3 minutes when busy. Upstream: `{UPSTREAM_SPACE}`.
|
| 798 |
-
"""
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
def cold_start_note() -> str:
|
| 802 |
-
if runpod_i2v.active_backend() != "runpod":
|
| 803 |
-
return ""
|
| 804 |
-
return (
|
| 805 |
-
"> **First Generate may take several minutes** (cold start + model download). "
|
| 806 |
-
"The Runpod worker is scaled to zero when idle. Leave this tab open — "
|
| 807 |
-
"the clip shows up here when the segment finishes. Later segments are faster "
|
| 808 |
-
"while a worker stays warm."
|
| 809 |
-
)
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
def limits_markdown() -> str:
|
| 813 |
-
if runpod_i2v.active_backend() == "runpod":
|
| 814 |
-
endpoint = runpod_i2v.endpoint_id()
|
| 815 |
-
return f"""
|
| 816 |
-
### How Extend works
|
| 817 |
-
1. **Generate** — still image + Generate prompt → short Wan 2.2 I2V clip (~3.5s default).
|
| 818 |
-
2. **Extend** — start from the **last frame** (or a **custom uploaded image**), optional separate **Extend prompt**, run I2V again, **concatenate**.
|
| 819 |
-
3. Repeat until you hit ~10–20s (or use **Auto-extend**). Soft cap: **6 segments**.
|
| 820 |
-
|
| 821 |
-
### Limits
|
| 822 |
-
- Every segment calls Runpod `{endpoint}`. The first call after idle can take several minutes (cold start + model download).
|
| 823 |
-
- If Runpod fails, the error is shown here and earlier clips are left as they are.
|
| 824 |
-
- Steps, seed, and the negative prompt are sent to Runpod. Clips are 16 fps. Segment length becomes Wan frames (4n+1, up to 81 / ~5s).
|
| 825 |
-
- Fluidity FPS, video quality, and Safe Mode apply to the ZeroGPU fallback only.
|
| 826 |
-
"""
|
| 827 |
-
return f"""
|
| 828 |
-
### How Extend works
|
| 829 |
-
1. **Generate** — still image + Generate prompt → short Wan 2.2 I2V clip (~3.5s default).
|
| 830 |
-
2. **Extend** — start from the **last frame** (or a **custom uploaded image**), optional separate **Extend prompt**, run I2V again, **concatenate**.
|
| 831 |
-
3. Repeat until you hit ~10–20s (or use **Auto-extend**). Soft cap: **6 segments**.
|
| 832 |
-
|
| 833 |
-
### Limits
|
| 834 |
-
- Fallback path: public ZeroGPU Space `{UPSTREAM_SPACE}` — free, but **queued / quota-limited**.
|
| 835 |
-
- Set Space secrets `RUNPOD_API_KEY` and `RUNPOD_ENDPOINT_ID=kyujeqw2gt779h` to use Runpod instead.
|
| 836 |
-
- Single segments are typically a few seconds; longer clips = chained Extends.
|
| 837 |
-
- Hugging Face Terms of Service apply to hosted Spaces.
|
| 838 |
-
"""
|
| 839 |
-
|
| 840 |
-
|
| 841 |
CSS = """
|
| 842 |
.big-btn button { font-size: 1.15rem !important; min-height: 3rem !important; }
|
| 843 |
#status-md { font-size: 1rem; }
|
|
@@ -846,9 +676,15 @@ footer { display: none !important; }
|
|
| 846 |
|
| 847 |
|
| 848 |
def build_ui():
|
| 849 |
-
runpod = runpod_i2v.active_backend() == "runpod"
|
| 850 |
with gr.Blocks(title="Wan 2.2 Extend — I2V", css=CSS, theme=gr.themes.Soft()) as demo:
|
| 851 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 852 |
state = gr.State({})
|
| 853 |
|
| 854 |
with gr.Row():
|
|
@@ -909,42 +745,19 @@ def build_ui():
|
|
| 909 |
)
|
| 910 |
|
| 911 |
with gr.Accordion("Advanced", open=False):
|
| 912 |
-
steps = gr.Slider(
|
| 913 |
-
|
| 914 |
-
12,
|
| 915 |
-
value=default_steps(),
|
| 916 |
-
step=1,
|
| 917 |
-
label="Inference steps",
|
| 918 |
-
info=(
|
| 919 |
-
"Sent to Runpod. 10 is the usual setting for this endpoint."
|
| 920 |
-
if runpod
|
| 921 |
-
else None
|
| 922 |
-
),
|
| 923 |
-
)
|
| 924 |
-
quality = gr.Slider(
|
| 925 |
-
1,
|
| 926 |
-
10,
|
| 927 |
-
value=6,
|
| 928 |
-
step=1,
|
| 929 |
-
label="Video quality",
|
| 930 |
-
info="ZeroGPU fallback only." if runpod else None,
|
| 931 |
-
)
|
| 932 |
fps = gr.Dropdown(
|
| 933 |
choices=[16, 32, 64],
|
| 934 |
value=16,
|
| 935 |
label="Fluidity FPS",
|
| 936 |
-
info="ZeroGPU fallback only. Runpod generates at 16 fps." if runpod else None,
|
| 937 |
)
|
| 938 |
seed = gr.Number(value=42, label="Seed", precision=0)
|
| 939 |
randomize = gr.Checkbox(value=True, label="Randomize seed")
|
| 940 |
safe_mode = gr.Checkbox(
|
| 941 |
value=True,
|
| 942 |
label="Upstream Safe Mode",
|
| 943 |
-
info=
|
| 944 |
-
"ZeroGPU fallback only."
|
| 945 |
-
if runpod
|
| 946 |
-
else "Extra ZeroGPU headroom on busy servers."
|
| 947 |
-
),
|
| 948 |
)
|
| 949 |
negative = gr.Textbox(
|
| 950 |
label="Negative prompt",
|
|
@@ -952,9 +765,6 @@ def build_ui():
|
|
| 952 |
lines=2,
|
| 953 |
)
|
| 954 |
|
| 955 |
-
cold_note = cold_start_note()
|
| 956 |
-
if cold_note:
|
| 957 |
-
gr.Markdown(cold_note)
|
| 958 |
with gr.Row(elem_classes=["big-btn"]):
|
| 959 |
btn_gen = gr.Button("Generate", variant="primary", size="lg")
|
| 960 |
btn_ext = gr.Button("Extend", variant="secondary", size="lg")
|
|
@@ -964,7 +774,7 @@ def build_ui():
|
|
| 964 |
|
| 965 |
with gr.Column(scale=1):
|
| 966 |
video = gr.Video(label="Preview", height=360, autoplay=True)
|
| 967 |
-
status = gr.Markdown(
|
| 968 |
last_preview = gr.Image(label="Last frame (next Extend start)", height=180)
|
| 969 |
download = gr.File(label="Download MP4")
|
| 970 |
|
|
@@ -1011,7 +821,19 @@ def build_ui():
|
|
| 1011 |
)
|
| 1012 |
btn_reset.click(do_reset, [state], outs)
|
| 1013 |
|
| 1014 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1015 |
return demo
|
| 1016 |
|
| 1017 |
|
|
|
|
| 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
|
|
|
|
| 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, ImageOps
|
| 23 |
|
|
|
|
| 332 |
return out_path
|
| 333 |
|
| 334 |
|
| 335 |
+
def call_wan_i2v(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
image_path: Path,
|
| 337 |
prompt: str,
|
| 338 |
duration: float,
|
|
|
|
| 394 |
return dest
|
| 395 |
|
| 396 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
def status_line(segments: list[str], duration_est: float) -> str:
|
| 398 |
n = len(segments)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
return (
|
| 400 |
+
f"**Segments:** {n} · **Duration ≈ {duration_est:.1f}s** · "
|
| 401 |
+
f"Upstream: `{UPSTREAM_SPACE}` (ZeroGPU — free, queued/quota-limited)"
|
| 402 |
)
|
| 403 |
|
| 404 |
|
|
|
|
| 496 |
progress,
|
| 497 |
)
|
| 498 |
except Exception as e:
|
| 499 |
+
raise gr.Error(
|
| 500 |
+
f"Generation failed (ZeroGPU queue/quota or upstream error): {e}"
|
| 501 |
+
) from e
|
| 502 |
|
| 503 |
out = sess / "current.mp4"
|
| 504 |
shutil.copy2(clip, out)
|
|
|
|
| 560 |
progress,
|
| 561 |
)
|
| 562 |
except Exception as e:
|
| 563 |
+
raise gr.Error(f"Extend failed: {e}") from e
|
| 564 |
|
| 565 |
segs = [Path(p) for p in state["segments"]] + [clip]
|
| 566 |
out = sess / f"current_{len(segs)}.mp4"
|
|
|
|
| 655 |
shutil.rmtree(state["dir"], ignore_errors=True)
|
| 656 |
except Exception:
|
| 657 |
pass
|
| 658 |
+
return None, None, "**Segments:** 0 · **Duration ≈ 0s**", None, {}
|
| 659 |
|
| 660 |
|
| 661 |
def update_estimate(seg_duration, num_planned):
|
|
|
|
| 668 |
return gr.update(visible=visible)
|
| 669 |
|
| 670 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
CSS = """
|
| 672 |
.big-btn button { font-size: 1.15rem !important; min-height: 3rem !important; }
|
| 673 |
#status-md { font-size: 1rem; }
|
|
|
|
| 676 |
|
| 677 |
|
| 678 |
def build_ui():
|
|
|
|
| 679 |
with gr.Blocks(title="Wan 2.2 Extend — I2V", css=CSS, theme=gr.themes.Soft()) as demo:
|
| 680 |
+
gr.Markdown(
|
| 681 |
+
"""
|
| 682 |
+
# Wan 2.2 Image → Video + Extend
|
| 683 |
+
Upload a still, generate a short Wan 2.2 clip on **free ZeroGPU**, then **Extend** from the last frame (or a custom start image) to chain ~10–20s videos.
|
| 684 |
+
|
| 685 |
+
ZeroGPU is free but **queued and quota-limited** — each segment often takes 1–3 minutes when busy.
|
| 686 |
+
"""
|
| 687 |
+
)
|
| 688 |
state = gr.State({})
|
| 689 |
|
| 690 |
with gr.Row():
|
|
|
|
| 745 |
)
|
| 746 |
|
| 747 |
with gr.Accordion("Advanced", open=False):
|
| 748 |
+
steps = gr.Slider(1, 12, value=4, step=1, label="Inference steps")
|
| 749 |
+
quality = gr.Slider(1, 10, value=6, step=1, label="Video quality")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 750 |
fps = gr.Dropdown(
|
| 751 |
choices=[16, 32, 64],
|
| 752 |
value=16,
|
| 753 |
label="Fluidity FPS",
|
|
|
|
| 754 |
)
|
| 755 |
seed = gr.Number(value=42, label="Seed", precision=0)
|
| 756 |
randomize = gr.Checkbox(value=True, label="Randomize seed")
|
| 757 |
safe_mode = gr.Checkbox(
|
| 758 |
value=True,
|
| 759 |
label="Upstream Safe Mode",
|
| 760 |
+
info="Extra ZeroGPU headroom on busy servers.",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 761 |
)
|
| 762 |
negative = gr.Textbox(
|
| 763 |
label="Negative prompt",
|
|
|
|
| 765 |
lines=2,
|
| 766 |
)
|
| 767 |
|
|
|
|
|
|
|
|
|
|
| 768 |
with gr.Row(elem_classes=["big-btn"]):
|
| 769 |
btn_gen = gr.Button("Generate", variant="primary", size="lg")
|
| 770 |
btn_ext = gr.Button("Extend", variant="secondary", size="lg")
|
|
|
|
| 774 |
|
| 775 |
with gr.Column(scale=1):
|
| 776 |
video = gr.Video(label="Preview", height=360, autoplay=True)
|
| 777 |
+
status = gr.Markdown("**Segments:** 0 · **Duration ≈ 0s**", elem_id="status-md")
|
| 778 |
last_preview = gr.Image(label="Last frame (next Extend start)", height=180)
|
| 779 |
download = gr.File(label="Download MP4")
|
| 780 |
|
|
|
|
| 821 |
)
|
| 822 |
btn_reset.click(do_reset, [state], outs)
|
| 823 |
|
| 824 |
+
gr.Markdown(
|
| 825 |
+
f"""
|
| 826 |
+
### How Extend works
|
| 827 |
+
1. **Generate** — still image + Generate prompt → short Wan 2.2 I2V clip (~{3.5}s default).
|
| 828 |
+
2. **Extend** — start from the **last frame** (or a **custom uploaded image**), optional separate **Extend prompt**, run I2V again, **concatenate**.
|
| 829 |
+
3. Repeat until you hit ~10–20s (or use **Auto-extend**). Soft cap: **6 segments**.
|
| 830 |
+
|
| 831 |
+
### Limits
|
| 832 |
+
- Powered by public ZeroGPU Space `{UPSTREAM_SPACE}` — free, but **queued / quota-limited**, not unlimited.
|
| 833 |
+
- Single segments are typically a few seconds; longer clips = chained Extends.
|
| 834 |
+
- Hugging Face Terms of Service apply to hosted Spaces.
|
| 835 |
+
"""
|
| 836 |
+
)
|
| 837 |
return demo
|
| 838 |
|
| 839 |
|
runpod_i2v.py
DELETED
|
@@ -1,666 +0,0 @@
|
|
| 1 |
-
"""Runpod serverless client for Wan 2.2 TI2V segments.
|
| 2 |
-
|
| 3 |
-
Calls the already-deployed endpoint (default ``kyujeqw2gt779h``) with the
|
| 4 |
-
worker input contract: prompt, negative_prompt, image_base64, width, height,
|
| 5 |
-
length, steps, cfg, seed. Jobs are submitted to ``/run`` and polled on
|
| 6 |
-
``/status/{id}`` because a cold worker (workersMin=0) plus model download
|
| 7 |
-
can take several minutes.
|
| 8 |
-
|
| 9 |
-
The API key is read from the environment only and is never written into
|
| 10 |
-
errors, logs, or the job body.
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
from __future__ import annotations
|
| 14 |
-
|
| 15 |
-
import base64
|
| 16 |
-
import io
|
| 17 |
-
import json
|
| 18 |
-
import math
|
| 19 |
-
import os
|
| 20 |
-
import time
|
| 21 |
-
import urllib.error
|
| 22 |
-
import urllib.parse
|
| 23 |
-
import urllib.request
|
| 24 |
-
from pathlib import Path
|
| 25 |
-
from typing import Any, Callable
|
| 26 |
-
|
| 27 |
-
from PIL import Image, ImageOps
|
| 28 |
-
|
| 29 |
-
# Casey's deployed Wan 2.2 TI2V serverless endpoint. Do not swap this for
|
| 30 |
-
# another GPU endpoint; override only via RUNPOD_ENDPOINT_ID / RUNPOD_ENDPOINT_URL.
|
| 31 |
-
DEFAULT_ENDPOINT_ID = "kyujeqw2gt779h"
|
| 32 |
-
DEFAULT_CFG = 2.0
|
| 33 |
-
DEFAULT_TIMEOUT_S = 45 * 60
|
| 34 |
-
DEFAULT_POLL_S = 5.0
|
| 35 |
-
WAN_FPS = 16
|
| 36 |
-
MIN_LENGTH = 17
|
| 37 |
-
MAX_LENGTH = 81
|
| 38 |
-
MAX_VIDEO_BYTES = 80 * 1024 * 1024
|
| 39 |
-
|
| 40 |
-
# 480p buckets, multiples of 16, area near the worker example 480×832.
|
| 41 |
-
# Phone stills land on 480×832; landscape stills land on 832×480.
|
| 42 |
-
RESOLUTION_BUCKETS: tuple[tuple[int, int], ...] = (
|
| 43 |
-
(832, 480),
|
| 44 |
-
(768, 512),
|
| 45 |
-
(704, 544),
|
| 46 |
-
(640, 640),
|
| 47 |
-
(544, 704),
|
| 48 |
-
(512, 768),
|
| 49 |
-
(480, 832),
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
_ZERO_BACKENDS = frozenset({"zerogpu", "zero", "hf", "gradio"})
|
| 53 |
-
_RUNPOD_BACKENDS = frozenset({"runpod", "runpod-i2v"})
|
| 54 |
-
_TRUE = frozenset({"1", "true", "yes", "on"})
|
| 55 |
-
|
| 56 |
-
ProgressFn = Callable[[str, float], None]
|
| 57 |
-
UrlOpenFn = Callable[..., Any]
|
| 58 |
-
SleepFn = Callable[[float], None]
|
| 59 |
-
NowFn = Callable[[], float]
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
class RunpodError(Exception):
|
| 63 |
-
"""User-facing Runpod failure. The message must not contain the API key."""
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def _env(env: dict[str, str] | None) -> dict[str, str]:
|
| 67 |
-
if env is None:
|
| 68 |
-
return dict(os.environ)
|
| 69 |
-
return env
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def active_backend(env: dict[str, str] | None = None) -> str:
|
| 73 |
-
"""``runpod`` when a key is set, unless an explicit ZeroGPU flag is on.
|
| 74 |
-
|
| 75 |
-
``WAN_BACKEND=runpod`` without a key still selects Runpod so the call
|
| 76 |
-
fails with a clear missing-secret error instead of silently using ZeroGPU.
|
| 77 |
-
"""
|
| 78 |
-
env = _env(env)
|
| 79 |
-
backend = (env.get("WAN_BACKEND") or "").strip().lower()
|
| 80 |
-
force_zero = (env.get("USE_ZERGPU") or "").strip().lower() in _TRUE
|
| 81 |
-
if backend in _ZERO_BACKENDS or force_zero:
|
| 82 |
-
return "zerogpu"
|
| 83 |
-
if (env.get("RUNPOD_API_KEY") or "").strip():
|
| 84 |
-
return "runpod"
|
| 85 |
-
if backend in _RUNPOD_BACKENDS:
|
| 86 |
-
return "runpod"
|
| 87 |
-
return "zerogpu"
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def endpoint_id(env: dict[str, str] | None = None) -> str:
|
| 91 |
-
env = _env(env)
|
| 92 |
-
return (env.get("RUNPOD_ENDPOINT_ID") or "").strip() or DEFAULT_ENDPOINT_ID
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def normalize_base_url(url: str) -> str:
|
| 96 |
-
"""Accept a base URL or the documented ``/run`` / ``/runsync`` URLs.
|
| 97 |
-
|
| 98 |
-
Query strings and fragments are dropped so a token pasted into
|
| 99 |
-
``RUNPOD_ENDPOINT_URL`` is not stored on the client or written to logs.
|
| 100 |
-
"""
|
| 101 |
-
parts = urllib.parse.urlsplit(url.strip())
|
| 102 |
-
path = parts.path.rstrip("/")
|
| 103 |
-
for suffix in ("/runsync", "/run"):
|
| 104 |
-
if path.endswith(suffix):
|
| 105 |
-
path = path[: -len(suffix)]
|
| 106 |
-
break
|
| 107 |
-
return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path.rstrip("/"), "", ""))
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def endpoint_base_url(env: dict[str, str] | None = None) -> str:
|
| 111 |
-
env = _env(env)
|
| 112 |
-
override = (env.get("RUNPOD_ENDPOINT_URL") or "").strip()
|
| 113 |
-
if override:
|
| 114 |
-
return normalize_base_url(override)
|
| 115 |
-
return f"https://api.runpod.ai/v2/{endpoint_id(env)}"
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def _env_float(env: dict[str, str], name: str, default: float, minimum: float) -> float:
|
| 119 |
-
raw = (env.get(name) or "").strip()
|
| 120 |
-
if not raw:
|
| 121 |
-
return default
|
| 122 |
-
try:
|
| 123 |
-
value = float(raw)
|
| 124 |
-
except ValueError:
|
| 125 |
-
return default
|
| 126 |
-
if value < minimum:
|
| 127 |
-
return default
|
| 128 |
-
return value
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def configured_cfg(env: dict[str, str] | None = None) -> float:
|
| 132 |
-
env = _env(env)
|
| 133 |
-
raw = (env.get("RUNPOD_CFG") or "").strip()
|
| 134 |
-
if not raw:
|
| 135 |
-
return DEFAULT_CFG
|
| 136 |
-
try:
|
| 137 |
-
value = float(raw)
|
| 138 |
-
except ValueError:
|
| 139 |
-
return DEFAULT_CFG
|
| 140 |
-
if value <= 0:
|
| 141 |
-
return DEFAULT_CFG
|
| 142 |
-
return value
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
def require_api_key(env: dict[str, str] | None = None) -> str:
|
| 146 |
-
env = _env(env)
|
| 147 |
-
key = (env.get("RUNPOD_API_KEY") or "").strip()
|
| 148 |
-
if not key:
|
| 149 |
-
raise RunpodError(
|
| 150 |
-
"Runpod is selected but RUNPOD_API_KEY is not set. "
|
| 151 |
-
"Add RUNPOD_API_KEY and RUNPOD_ENDPOINT_ID=kyujeqw2gt779h "
|
| 152 |
-
"as Hugging Face Space secrets, then rebuild the Space. "
|
| 153 |
-
"Leave the key unset to use the ZeroGPU fallback, or set "
|
| 154 |
-
"WAN_BACKEND=zerogpu to force that fallback."
|
| 155 |
-
)
|
| 156 |
-
return key
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
def duration_to_length(duration_seconds: float, fps: int = WAN_FPS) -> int:
|
| 160 |
-
"""Map a segment length in seconds to Wan frame count (4n+1) at 16 fps."""
|
| 161 |
-
duration_seconds = max(0.0, float(duration_seconds))
|
| 162 |
-
raw = int(round(duration_seconds * int(fps)))
|
| 163 |
-
# Nearest 4n+1. Half steps round away from zero via the +2 bias.
|
| 164 |
-
n = (raw - 1 + 2) // 4
|
| 165 |
-
length = 4 * n + 1
|
| 166 |
-
if length < MIN_LENGTH:
|
| 167 |
-
length = MIN_LENGTH
|
| 168 |
-
if length > MAX_LENGTH:
|
| 169 |
-
length = MAX_LENGTH
|
| 170 |
-
if (length - 1) % 4 != 0:
|
| 171 |
-
length = max(MIN_LENGTH, ((length - 1) // 4) * 4 + 1)
|
| 172 |
-
return length
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
def resolution_for_size(src_w: int, src_h: int) -> tuple[int, int]:
|
| 176 |
-
"""Pick a 480p bucket whose aspect is closest to the still."""
|
| 177 |
-
if src_w < 1 or src_h < 1:
|
| 178 |
-
return 480, 832
|
| 179 |
-
aspect = src_w / src_h
|
| 180 |
-
|
| 181 |
-
def distance(bucket: tuple[int, int]) -> float:
|
| 182 |
-
bw, bh = bucket
|
| 183 |
-
return abs(math.log(aspect / (bw / bh)))
|
| 184 |
-
|
| 185 |
-
return min(RESOLUTION_BUCKETS, key=distance)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def cover_resize(image: Image.Image, width: int, height: int) -> Image.Image:
|
| 189 |
-
"""Scale-and-center-crop so ``image`` fills width×height."""
|
| 190 |
-
image = image.convert("RGB")
|
| 191 |
-
src_w, src_h = image.size
|
| 192 |
-
if src_w < 1 or src_h < 1:
|
| 193 |
-
raise RunpodError("Input image has no pixels.")
|
| 194 |
-
if src_w == width and src_h == height:
|
| 195 |
-
return image
|
| 196 |
-
scale = max(width / src_w, height / src_h)
|
| 197 |
-
new_w = max(1, int(round(src_w * scale)))
|
| 198 |
-
new_h = max(1, int(round(src_h * scale)))
|
| 199 |
-
resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
| 200 |
-
left = max(0, (new_w - width) // 2)
|
| 201 |
-
top = max(0, (new_h - height) // 2)
|
| 202 |
-
cropped = resized.crop((left, top, left + width, top + height))
|
| 203 |
-
if cropped.size != (width, height):
|
| 204 |
-
cropped = cropped.resize((width, height), Image.Resampling.LANCZOS)
|
| 205 |
-
return cropped
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
def resolve_seed(seed: int, randomize: bool) -> int:
|
| 209 |
-
if randomize:
|
| 210 |
-
return int.from_bytes(os.urandom(4), "big") % (2**31 - 1)
|
| 211 |
-
return int(seed)
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
def _redact(text: str, secret: str) -> str:
|
| 215 |
-
if secret and secret in text:
|
| 216 |
-
return text.replace(secret, "[redacted]")
|
| 217 |
-
return text
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
def _short(text: str, secret: str = "", limit: int = 500) -> str:
|
| 221 |
-
text = _redact(text or "", secret)
|
| 222 |
-
# Drop embedded base64 blobs so a failed payload cannot flood the UI.
|
| 223 |
-
cleaned: list[str] = []
|
| 224 |
-
for token in text.split():
|
| 225 |
-
if len(token) > 80 and all(c.isalnum() or c in "+/=" for c in token):
|
| 226 |
-
cleaned.append("[omitted]")
|
| 227 |
-
else:
|
| 228 |
-
cleaned.append(token)
|
| 229 |
-
text = " ".join(cleaned).strip()
|
| 230 |
-
if len(text) > limit:
|
| 231 |
-
return text[:limit] + "…"
|
| 232 |
-
return text
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def _looks_like_mp4(data: bytes) -> bool:
|
| 236 |
-
return len(data) >= 12 and b"ftyp" in data[:64]
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
def _is_video_key(key: str) -> bool:
|
| 240 |
-
lowered = key.lower().replace("-", "_")
|
| 241 |
-
return lowered in {
|
| 242 |
-
"video",
|
| 243 |
-
"video_base64",
|
| 244 |
-
"video_url",
|
| 245 |
-
"mp4",
|
| 246 |
-
"output_video",
|
| 247 |
-
"result",
|
| 248 |
-
}
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def _decode_video_text(text: str) -> bytes | None:
|
| 252 |
-
raw = text.strip()
|
| 253 |
-
if raw.startswith("data:"):
|
| 254 |
-
if "," not in raw:
|
| 255 |
-
return None
|
| 256 |
-
raw = raw.split(",", 1)[1]
|
| 257 |
-
if raw.startswith("http://") or raw.startswith("https://"):
|
| 258 |
-
return None
|
| 259 |
-
try:
|
| 260 |
-
return base64.b64decode(raw, validate=False)
|
| 261 |
-
except Exception:
|
| 262 |
-
return None
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
def _iter_video_candidates(obj: Any, keyed: bool = False, depth: int = 0):
|
| 266 |
-
if depth > 8 or obj is None:
|
| 267 |
-
return
|
| 268 |
-
if isinstance(obj, str):
|
| 269 |
-
if keyed or obj.startswith("data:video") or obj.startswith(("http://", "https://")):
|
| 270 |
-
yield obj
|
| 271 |
-
return
|
| 272 |
-
if isinstance(obj, dict):
|
| 273 |
-
for key, value in obj.items():
|
| 274 |
-
if _is_video_key(str(key)):
|
| 275 |
-
yield from _iter_video_candidates(value, True, depth + 1)
|
| 276 |
-
for key, value in obj.items():
|
| 277 |
-
if not _is_video_key(str(key)):
|
| 278 |
-
yield from _iter_video_candidates(value, keyed, depth + 1)
|
| 279 |
-
return
|
| 280 |
-
if isinstance(obj, (list, tuple)):
|
| 281 |
-
for item in obj[:12]:
|
| 282 |
-
yield from _iter_video_candidates(item, keyed, depth + 1)
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
def _output_has_video(payload: Any) -> bool:
|
| 286 |
-
output = payload.get("output") if isinstance(payload, dict) else payload
|
| 287 |
-
for candidate in _iter_video_candidates(output, isinstance(output, str)):
|
| 288 |
-
if isinstance(candidate, str) and (
|
| 289 |
-
candidate.startswith(("http://", "https://", "data:video"))
|
| 290 |
-
or (_decode_video_text(candidate) and _looks_like_mp4(_decode_video_text(candidate) or b""))
|
| 291 |
-
):
|
| 292 |
-
return True
|
| 293 |
-
return False
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
def _failure_message(job_id: str, body: dict[str, Any], secret: str) -> str:
|
| 297 |
-
status = str(body.get("status") or "FAILED")
|
| 298 |
-
err: Any = body.get("error")
|
| 299 |
-
output = body.get("output")
|
| 300 |
-
if not err and isinstance(output, dict):
|
| 301 |
-
err = output.get("error") or output.get("errors")
|
| 302 |
-
if not err and isinstance(output, str) and not output.startswith("data:"):
|
| 303 |
-
err = output
|
| 304 |
-
detail = _short(str(err), secret) if err else "no error details returned"
|
| 305 |
-
return f"Runpod job {job_id} failed ({status}): {detail}"
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
def _load_rgb(image_path: Path) -> Image.Image:
|
| 309 |
-
try:
|
| 310 |
-
with Image.open(image_path) as opened:
|
| 311 |
-
image = ImageOps.exif_transpose(opened)
|
| 312 |
-
if image is None:
|
| 313 |
-
raise RunpodError(f"Could not read the still image ({image_path.name}).")
|
| 314 |
-
image.load()
|
| 315 |
-
return image.copy().convert("RGB")
|
| 316 |
-
except RunpodError:
|
| 317 |
-
raise
|
| 318 |
-
except Exception as exc:
|
| 319 |
-
raise RunpodError(
|
| 320 |
-
f"Could not read the still image ({image_path.name}): {exc}"
|
| 321 |
-
) from exc
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
def _jpeg_base64(image_path: Path, width: int, height: int) -> str:
|
| 325 |
-
fitted = cover_resize(_load_rgb(image_path), width, height)
|
| 326 |
-
buf = io.BytesIO()
|
| 327 |
-
fitted.save(buf, format="JPEG", quality=90, optimize=True)
|
| 328 |
-
# Raw base64, not a data: URI. The worker decodes with b64decode, and a
|
| 329 |
-
# data-URI prefix is not valid base64 alphabet-only input.
|
| 330 |
-
return base64.b64encode(buf.getvalue()).decode("ascii")
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
def _image_size(image_path: Path) -> tuple[int, int]:
|
| 334 |
-
return _load_rgb(image_path).size
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
class RunpodClient:
|
| 338 |
-
def __init__(
|
| 339 |
-
self,
|
| 340 |
-
api_key: str,
|
| 341 |
-
base_url: str,
|
| 342 |
-
*,
|
| 343 |
-
timeout_s: float = DEFAULT_TIMEOUT_S,
|
| 344 |
-
poll_interval_s: float = DEFAULT_POLL_S,
|
| 345 |
-
urlopen: UrlOpenFn | None = None,
|
| 346 |
-
sleep: SleepFn | None = None,
|
| 347 |
-
now: NowFn | None = None,
|
| 348 |
-
) -> None:
|
| 349 |
-
self.api_key = api_key
|
| 350 |
-
self.base_url = base_url.rstrip("/")
|
| 351 |
-
self.timeout_s = timeout_s
|
| 352 |
-
self.poll_interval_s = poll_interval_s
|
| 353 |
-
self._urlopen = urlopen or urllib.request.urlopen
|
| 354 |
-
self._sleep = sleep or time.sleep
|
| 355 |
-
self._now = now or time.monotonic
|
| 356 |
-
|
| 357 |
-
def generate(
|
| 358 |
-
self,
|
| 359 |
-
image_path: Path,
|
| 360 |
-
dest: Path,
|
| 361 |
-
*,
|
| 362 |
-
prompt: str,
|
| 363 |
-
negative_prompt: str,
|
| 364 |
-
duration_seconds: float,
|
| 365 |
-
steps: int,
|
| 366 |
-
seed: int,
|
| 367 |
-
cfg: float,
|
| 368 |
-
width: int | None = None,
|
| 369 |
-
height: int | None = None,
|
| 370 |
-
on_progress: ProgressFn | None = None,
|
| 371 |
-
) -> Path:
|
| 372 |
-
if width is None or height is None:
|
| 373 |
-
src_w, src_h = _image_size(image_path)
|
| 374 |
-
width, height = resolution_for_size(src_w, src_h)
|
| 375 |
-
length = duration_to_length(duration_seconds)
|
| 376 |
-
steps = max(1, int(steps))
|
| 377 |
-
image_b64 = _jpeg_base64(image_path, width, height)
|
| 378 |
-
payload = {
|
| 379 |
-
"prompt": prompt,
|
| 380 |
-
"negative_prompt": negative_prompt,
|
| 381 |
-
"image_base64": image_b64,
|
| 382 |
-
"width": int(width),
|
| 383 |
-
"height": int(height),
|
| 384 |
-
"length": int(length),
|
| 385 |
-
"steps": steps,
|
| 386 |
-
"cfg": float(cfg),
|
| 387 |
-
"seed": int(seed),
|
| 388 |
-
}
|
| 389 |
-
if on_progress:
|
| 390 |
-
on_progress("submit", 0.0)
|
| 391 |
-
print(
|
| 392 |
-
f"[runpod] submit {self.base_url}/run {width}x{height} "
|
| 393 |
-
f"frames={length} steps={steps} cfg={cfg} seed={seed}",
|
| 394 |
-
flush=True,
|
| 395 |
-
)
|
| 396 |
-
submitted = self._request_json(
|
| 397 |
-
"POST",
|
| 398 |
-
f"{self.base_url}/run",
|
| 399 |
-
{"input": payload},
|
| 400 |
-
timeout=120,
|
| 401 |
-
retry_transient=False,
|
| 402 |
-
)
|
| 403 |
-
if not isinstance(submitted, dict):
|
| 404 |
-
raise RunpodError("Runpod /run did not return a job object.")
|
| 405 |
-
if submitted.get("error") and not submitted.get("id"):
|
| 406 |
-
raise RunpodError(
|
| 407 |
-
f"Runpod rejected the job: {_short(str(submitted.get('error')), self.api_key)}"
|
| 408 |
-
)
|
| 409 |
-
job_id = str(submitted.get("id") or "").strip()
|
| 410 |
-
if not job_id:
|
| 411 |
-
raise RunpodError(
|
| 412 |
-
f"Runpod did not return a job id: {_short(json.dumps(submitted), self.api_key)}"
|
| 413 |
-
)
|
| 414 |
-
status = str(submitted.get("status") or "").upper()
|
| 415 |
-
if status == "COMPLETED":
|
| 416 |
-
body = submitted
|
| 417 |
-
elif status in {"FAILED", "CANCELLED", "TIMED_OUT"}:
|
| 418 |
-
raise RunpodError(_failure_message(job_id, submitted, self.api_key))
|
| 419 |
-
else:
|
| 420 |
-
body = self._poll(job_id, on_progress)
|
| 421 |
-
video = self._extract_video(body)
|
| 422 |
-
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 423 |
-
dest.write_bytes(video)
|
| 424 |
-
if on_progress:
|
| 425 |
-
on_progress("save", 0.0)
|
| 426 |
-
print(f"[runpod] job {job_id} saved {dest.name} ({len(video)} bytes)", flush=True)
|
| 427 |
-
return dest
|
| 428 |
-
|
| 429 |
-
def _poll(self, job_id: str, on_progress: ProgressFn | None) -> dict[str, Any]:
|
| 430 |
-
start = self._now()
|
| 431 |
-
last = "IN_QUEUE"
|
| 432 |
-
while True:
|
| 433 |
-
body = self._request_json(
|
| 434 |
-
"GET",
|
| 435 |
-
f"{self.base_url}/status/{job_id}",
|
| 436 |
-
None,
|
| 437 |
-
timeout=60,
|
| 438 |
-
retry_transient=True,
|
| 439 |
-
)
|
| 440 |
-
if not isinstance(body, dict):
|
| 441 |
-
raise RunpodError(f"Runpod status for job {job_id} was not a JSON object.")
|
| 442 |
-
status = str(body.get("status") or "").upper() or last
|
| 443 |
-
last = status
|
| 444 |
-
elapsed = self._now() - start
|
| 445 |
-
print(f"[runpod] job {job_id} {status} ({int(elapsed)}s)", flush=True)
|
| 446 |
-
if on_progress:
|
| 447 |
-
on_progress(status, elapsed)
|
| 448 |
-
if status == "COMPLETED":
|
| 449 |
-
output = body.get("output")
|
| 450 |
-
if isinstance(output, dict) and output.get("error") and not _output_has_video(body):
|
| 451 |
-
raise RunpodError(
|
| 452 |
-
f"Runpod job {job_id} completed with an error: "
|
| 453 |
-
f"{_short(str(output.get('error')), self.api_key)}"
|
| 454 |
-
)
|
| 455 |
-
return body
|
| 456 |
-
if status in {"FAILED", "CANCELLED", "TIMED_OUT", "ERROR"}:
|
| 457 |
-
raise RunpodError(_failure_message(job_id, body, self.api_key))
|
| 458 |
-
if self._now() - start >= self.timeout_s:
|
| 459 |
-
self._cancel(job_id)
|
| 460 |
-
raise RunpodError(
|
| 461 |
-
f"Runpod job {job_id} did not finish within {int(self.timeout_s)}s "
|
| 462 |
-
f"(last status: {last}). The worker may still be cold-starting "
|
| 463 |
-
f"or downloading the model. Try Generate again in a few minutes."
|
| 464 |
-
)
|
| 465 |
-
self._sleep(self.poll_interval_s)
|
| 466 |
-
|
| 467 |
-
def _cancel(self, job_id: str) -> None:
|
| 468 |
-
try:
|
| 469 |
-
self._request_json(
|
| 470 |
-
"POST",
|
| 471 |
-
f"{self.base_url}/cancel/{job_id}",
|
| 472 |
-
{},
|
| 473 |
-
timeout=30,
|
| 474 |
-
retry_transient=False,
|
| 475 |
-
)
|
| 476 |
-
print(f"[runpod] cancelled job {job_id} after client timeout", flush=True)
|
| 477 |
-
except RunpodError as exc:
|
| 478 |
-
print(f"[runpod] cancel {job_id} failed: {_short(str(exc), self.api_key)}", flush=True)
|
| 479 |
-
|
| 480 |
-
def _extract_video(self, body: dict[str, Any]) -> bytes:
|
| 481 |
-
output = body.get("output")
|
| 482 |
-
secret = self.api_key
|
| 483 |
-
for candidate in _iter_video_candidates(output, isinstance(output, str)):
|
| 484 |
-
if not isinstance(candidate, str):
|
| 485 |
-
continue
|
| 486 |
-
text = candidate.strip()
|
| 487 |
-
if text.startswith(("http://", "https://")):
|
| 488 |
-
downloaded = self._download(text)
|
| 489 |
-
if _looks_like_mp4(downloaded):
|
| 490 |
-
return downloaded
|
| 491 |
-
continue
|
| 492 |
-
decoded = _decode_video_text(text)
|
| 493 |
-
if decoded and _looks_like_mp4(decoded):
|
| 494 |
-
if len(decoded) > MAX_VIDEO_BYTES:
|
| 495 |
-
raise RunpodError("Runpod returned a video larger than 80MB.")
|
| 496 |
-
return decoded
|
| 497 |
-
raise RunpodError(
|
| 498 |
-
"Runpod finished the job but did not return a playable MP4 "
|
| 499 |
-
f"(status payload: {_short(json.dumps(body)[:400], secret)})."
|
| 500 |
-
)
|
| 501 |
-
|
| 502 |
-
def _download(self, url: str) -> bytes:
|
| 503 |
-
headers = {"Accept": "video/mp4,application/octet-stream,*/*"}
|
| 504 |
-
# Only attach the key to Runpod's own API. Signed output URLs do not need it,
|
| 505 |
-
# and sending it to an arbitrary host would leak the secret.
|
| 506 |
-
host = (urllib.parse.urlparse(url).hostname or "").lower()
|
| 507 |
-
if host == "api.runpod.ai" or host.endswith(".api.runpod.ai"):
|
| 508 |
-
headers["Authorization"] = f"Bearer {self.api_key}"
|
| 509 |
-
request = urllib.request.Request(url, headers=headers, method="GET")
|
| 510 |
-
try:
|
| 511 |
-
with self._urlopen(request, timeout=120) as response:
|
| 512 |
-
data = response.read(MAX_VIDEO_BYTES + 1)
|
| 513 |
-
except urllib.error.HTTPError as exc:
|
| 514 |
-
detail = _read_http_error(exc, self.api_key)
|
| 515 |
-
raise RunpodError(f"Runpod video download failed (HTTP {exc.code}): {detail}") from exc
|
| 516 |
-
except urllib.error.URLError as exc:
|
| 517 |
-
raise RunpodError(
|
| 518 |
-
f"Could not download the Runpod video ({_short(str(exc.reason), self.api_key)})."
|
| 519 |
-
) from exc
|
| 520 |
-
if len(data) > MAX_VIDEO_BYTES:
|
| 521 |
-
raise RunpodError("Runpod returned a video larger than 80MB.")
|
| 522 |
-
return data
|
| 523 |
-
|
| 524 |
-
def _request_json(
|
| 525 |
-
self,
|
| 526 |
-
method: str,
|
| 527 |
-
url: str,
|
| 528 |
-
body: dict[str, Any] | None,
|
| 529 |
-
*,
|
| 530 |
-
timeout: float,
|
| 531 |
-
retry_transient: bool,
|
| 532 |
-
) -> Any:
|
| 533 |
-
attempts = 4 if retry_transient else 1
|
| 534 |
-
last_error: RunpodError | None = None
|
| 535 |
-
for attempt in range(attempts):
|
| 536 |
-
try:
|
| 537 |
-
return self._request_once(method, url, body, timeout)
|
| 538 |
-
except RunpodError as exc:
|
| 539 |
-
last_error = exc
|
| 540 |
-
if not retry_transient or attempt == attempts - 1 or not _is_transient(str(exc)):
|
| 541 |
-
raise
|
| 542 |
-
self._sleep(min(2**attempt, 8))
|
| 543 |
-
assert last_error is not None
|
| 544 |
-
raise last_error
|
| 545 |
-
|
| 546 |
-
def _request_once(self, method: str, url: str, body: dict[str, Any] | None, timeout: float) -> Any:
|
| 547 |
-
data = None
|
| 548 |
-
headers = {
|
| 549 |
-
"Authorization": f"Bearer {self.api_key}",
|
| 550 |
-
"Accept": "application/json",
|
| 551 |
-
}
|
| 552 |
-
if body is not None:
|
| 553 |
-
data = json.dumps(body).encode("utf-8")
|
| 554 |
-
headers["Content-Type"] = "application/json"
|
| 555 |
-
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
| 556 |
-
try:
|
| 557 |
-
with self._urlopen(request, timeout=timeout) as response:
|
| 558 |
-
raw = response.read()
|
| 559 |
-
except urllib.error.HTTPError as exc:
|
| 560 |
-
detail = _read_http_error(exc, self.api_key)
|
| 561 |
-
if exc.code == 401:
|
| 562 |
-
raise RunpodError(
|
| 563 |
-
"Runpod rejected the API key (HTTP 401). "
|
| 564 |
-
"Check the RUNPOD_API_KEY Space secret and rebuild."
|
| 565 |
-
) from exc
|
| 566 |
-
if exc.code == 404:
|
| 567 |
-
raise RunpodError(
|
| 568 |
-
"Runpod endpoint was not found (HTTP 404). "
|
| 569 |
-
f"Check RUNPOD_ENDPOINT_ID (expected {DEFAULT_ENDPOINT_ID}). {detail}"
|
| 570 |
-
) from exc
|
| 571 |
-
raise RunpodError(f"Runpod request failed (HTTP {exc.code}): {detail}") from exc
|
| 572 |
-
except urllib.error.URLError as exc:
|
| 573 |
-
raise RunpodError(
|
| 574 |
-
"Could not reach Runpod "
|
| 575 |
-
f"({_short(str(getattr(exc, 'reason', exc)), self.api_key)}). "
|
| 576 |
-
"Check the Space network and RUNPOD_ENDPOINT_URL."
|
| 577 |
-
) from exc
|
| 578 |
-
if not raw:
|
| 579 |
-
raise RunpodError("Runpod returned an empty response.")
|
| 580 |
-
try:
|
| 581 |
-
return json.loads(raw.decode("utf-8"))
|
| 582 |
-
except Exception as exc:
|
| 583 |
-
raise RunpodError(
|
| 584 |
-
f"Runpod returned non-JSON: {_short(raw.decode('utf-8', errors='replace'), self.api_key)}"
|
| 585 |
-
) from exc
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
def _is_transient(message: str) -> bool:
|
| 589 |
-
lowered = message.lower()
|
| 590 |
-
return any(
|
| 591 |
-
token in lowered
|
| 592 |
-
for token in (
|
| 593 |
-
"http 502",
|
| 594 |
-
"http 503",
|
| 595 |
-
"http 504",
|
| 596 |
-
"could not reach runpod",
|
| 597 |
-
"timed out",
|
| 598 |
-
)
|
| 599 |
-
)
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
def _read_http_error(exc: urllib.error.HTTPError, secret: str) -> str:
|
| 603 |
-
try:
|
| 604 |
-
raw = exc.read().decode("utf-8", errors="replace")
|
| 605 |
-
except Exception:
|
| 606 |
-
raw = str(exc)
|
| 607 |
-
try:
|
| 608 |
-
parsed = json.loads(raw)
|
| 609 |
-
except Exception:
|
| 610 |
-
parsed = None
|
| 611 |
-
if isinstance(parsed, dict) and parsed.get("error"):
|
| 612 |
-
return _short(str(parsed["error"]), secret)
|
| 613 |
-
return _short(raw, secret)
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
def generate_i2v(
|
| 617 |
-
image_path: Path,
|
| 618 |
-
dest: Path,
|
| 619 |
-
*,
|
| 620 |
-
prompt: str,
|
| 621 |
-
negative_prompt: str,
|
| 622 |
-
duration_seconds: float,
|
| 623 |
-
steps: int,
|
| 624 |
-
seed: int,
|
| 625 |
-
cfg: float | None = None,
|
| 626 |
-
width: int | None = None,
|
| 627 |
-
height: int | None = None,
|
| 628 |
-
env: dict[str, str] | None = None,
|
| 629 |
-
on_progress: ProgressFn | None = None,
|
| 630 |
-
urlopen: UrlOpenFn | None = None,
|
| 631 |
-
sleep: SleepFn | None = None,
|
| 632 |
-
now: NowFn | None = None,
|
| 633 |
-
timeout_s: float | None = None,
|
| 634 |
-
poll_interval_s: float | None = None,
|
| 635 |
-
) -> Path:
|
| 636 |
-
"""Submit one I2V segment and write an MP4 to ``dest``."""
|
| 637 |
-
env_map = _env(env)
|
| 638 |
-
api_key = require_api_key(env_map)
|
| 639 |
-
if timeout_s is None:
|
| 640 |
-
timeout_s = _env_float(env_map, "RUNPOD_TIMEOUT_SECONDS", DEFAULT_TIMEOUT_S, 1.0)
|
| 641 |
-
if poll_interval_s is None:
|
| 642 |
-
poll_interval_s = _env_float(env_map, "RUNPOD_POLL_INTERVAL_SECONDS", DEFAULT_POLL_S, 1.0)
|
| 643 |
-
if cfg is None:
|
| 644 |
-
cfg = configured_cfg(env_map)
|
| 645 |
-
client = RunpodClient(
|
| 646 |
-
api_key,
|
| 647 |
-
endpoint_base_url(env_map),
|
| 648 |
-
timeout_s=timeout_s,
|
| 649 |
-
poll_interval_s=poll_interval_s,
|
| 650 |
-
urlopen=urlopen,
|
| 651 |
-
sleep=sleep,
|
| 652 |
-
now=now,
|
| 653 |
-
)
|
| 654 |
-
return client.generate(
|
| 655 |
-
Path(image_path),
|
| 656 |
-
Path(dest),
|
| 657 |
-
prompt=prompt,
|
| 658 |
-
negative_prompt=negative_prompt,
|
| 659 |
-
duration_seconds=duration_seconds,
|
| 660 |
-
steps=steps,
|
| 661 |
-
seed=seed,
|
| 662 |
-
cfg=cfg,
|
| 663 |
-
width=width,
|
| 664 |
-
height=height,
|
| 665 |
-
on_progress=on_progress,
|
| 666 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_runpod_i2v.py
DELETED
|
@@ -1,809 +0,0 @@
|
|
| 1 |
-
"""Runpod Wan 2.2 TI2V client and Generate / Extend / Auto-extend wiring.
|
| 2 |
-
|
| 3 |
-
No live Runpod calls. HTTP is faked, and the returned bytes are a real MP4
|
| 4 |
-
so the stitch path can play the clip back.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from __future__ import annotations
|
| 8 |
-
|
| 9 |
-
import base64
|
| 10 |
-
import io
|
| 11 |
-
import json
|
| 12 |
-
import os
|
| 13 |
-
import subprocess
|
| 14 |
-
import sys
|
| 15 |
-
import tempfile
|
| 16 |
-
import types
|
| 17 |
-
import unittest
|
| 18 |
-
import urllib.error
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
from unittest.mock import patch
|
| 21 |
-
|
| 22 |
-
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
-
if str(ROOT) not in sys.path:
|
| 24 |
-
sys.path.insert(0, str(ROOT))
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def _install_import_stubs() -> None:
|
| 28 |
-
if "gradio" not in sys.modules:
|
| 29 |
-
gr = types.ModuleType("gradio")
|
| 30 |
-
|
| 31 |
-
class Error(Exception):
|
| 32 |
-
pass
|
| 33 |
-
|
| 34 |
-
class _Progress:
|
| 35 |
-
def __init__(self, *args, **kwargs):
|
| 36 |
-
pass
|
| 37 |
-
|
| 38 |
-
def __call__(self, *args, **kwargs):
|
| 39 |
-
return None
|
| 40 |
-
|
| 41 |
-
gr.Error = Error
|
| 42 |
-
gr.Progress = _Progress
|
| 43 |
-
gr.Blocks = object
|
| 44 |
-
gr.State = lambda *a, **k: None
|
| 45 |
-
gr.Image = lambda *a, **k: None
|
| 46 |
-
gr.Video = lambda *a, **k: None
|
| 47 |
-
gr.Textbox = lambda *a, **k: None
|
| 48 |
-
gr.Slider = lambda *a, **k: None
|
| 49 |
-
gr.Dropdown = lambda *a, **k: None
|
| 50 |
-
gr.Number = lambda *a, **k: None
|
| 51 |
-
gr.Checkbox = lambda *a, **k: None
|
| 52 |
-
gr.Button = lambda *a, **k: None
|
| 53 |
-
gr.Markdown = lambda *a, **k: None
|
| 54 |
-
gr.File = lambda *a, **k: None
|
| 55 |
-
gr.Accordion = object
|
| 56 |
-
gr.Row = object
|
| 57 |
-
gr.Column = object
|
| 58 |
-
|
| 59 |
-
def _update(*_a, **_k):
|
| 60 |
-
return None
|
| 61 |
-
|
| 62 |
-
gr.update = _update
|
| 63 |
-
themes = types.ModuleType("gradio.themes")
|
| 64 |
-
themes.Soft = lambda *a, **k: None
|
| 65 |
-
gr.themes = themes
|
| 66 |
-
sys.modules["gradio"] = gr
|
| 67 |
-
sys.modules["gradio.themes"] = themes
|
| 68 |
-
|
| 69 |
-
if "gradio_client" not in sys.modules:
|
| 70 |
-
client = types.ModuleType("gradio_client")
|
| 71 |
-
client.Client = object
|
| 72 |
-
client.handle_file = lambda p: p
|
| 73 |
-
sys.modules["gradio_client"] = client
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
_install_import_stubs()
|
| 77 |
-
|
| 78 |
-
import app # noqa: E402
|
| 79 |
-
import runpod_i2v # noqa: E402
|
| 80 |
-
|
| 81 |
-
API_KEY = "rpa_test_key_not_real"
|
| 82 |
-
ENDPOINT = "kyujeqw2gt779h"
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _run(cmd: list[str]) -> None:
|
| 86 |
-
subprocess.run(cmd, check=True, capture_output=True)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def _make_clip(path: Path, size: str = "320x240", duration: float = 1.0) -> None:
|
| 90 |
-
_run(
|
| 91 |
-
[
|
| 92 |
-
"ffmpeg",
|
| 93 |
-
"-y",
|
| 94 |
-
"-f",
|
| 95 |
-
"lavfi",
|
| 96 |
-
"-i",
|
| 97 |
-
f"color=c=black:s={size}:r=16:d={duration},format=rgb24,"
|
| 98 |
-
"geq=r='128+100*sin(2*PI*T)':g=40:b=40",
|
| 99 |
-
"-pix_fmt",
|
| 100 |
-
"yuv420p",
|
| 101 |
-
str(path),
|
| 102 |
-
]
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
class _Body:
|
| 107 |
-
def __init__(self, raw: bytes):
|
| 108 |
-
self._raw = raw
|
| 109 |
-
|
| 110 |
-
def read(self, n: int = -1) -> bytes:
|
| 111 |
-
if n is None or n < 0 or n >= len(self._raw):
|
| 112 |
-
data = self._raw
|
| 113 |
-
self._raw = b""
|
| 114 |
-
return data
|
| 115 |
-
data = self._raw[:n]
|
| 116 |
-
self._raw = self._raw[n:]
|
| 117 |
-
return data
|
| 118 |
-
|
| 119 |
-
def __enter__(self):
|
| 120 |
-
return self
|
| 121 |
-
|
| 122 |
-
def __exit__(self, *_args):
|
| 123 |
-
return False
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def _json_response(payload: dict) -> _Body:
|
| 127 |
-
return _Body(json.dumps(payload).encode())
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def _headers(req) -> dict[str, str]:
|
| 131 |
-
return {key.lower(): value for key, value in req.header_items()}
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
class _Clock:
|
| 135 |
-
def __init__(self) -> None:
|
| 136 |
-
self.t = 0.0
|
| 137 |
-
|
| 138 |
-
def now(self) -> float:
|
| 139 |
-
return self.t
|
| 140 |
-
|
| 141 |
-
def sleep(self, seconds: float) -> None:
|
| 142 |
-
self.t += float(seconds)
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
class EnvCase(unittest.TestCase):
|
| 146 |
-
def setUp(self) -> None:
|
| 147 |
-
self._old = os.environ.copy()
|
| 148 |
-
for name in (
|
| 149 |
-
"RUNPOD_API_KEY",
|
| 150 |
-
"RUNPOD_ENDPOINT_ID",
|
| 151 |
-
"RUNPOD_ENDPOINT_URL",
|
| 152 |
-
"WAN_BACKEND",
|
| 153 |
-
"USE_ZERGPU",
|
| 154 |
-
"RUNPOD_CFG",
|
| 155 |
-
"RUNPOD_TIMEOUT_SECONDS",
|
| 156 |
-
"RUNPOD_POLL_INTERVAL_SECONDS",
|
| 157 |
-
):
|
| 158 |
-
os.environ.pop(name, None)
|
| 159 |
-
|
| 160 |
-
def tearDown(self) -> None:
|
| 161 |
-
os.environ.clear()
|
| 162 |
-
os.environ.update(self._old)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
class ConfigTests(EnvCase):
|
| 166 |
-
def test_key_selects_runpod_and_default_endpoint(self):
|
| 167 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 168 |
-
self.assertEqual(runpod_i2v.active_backend(), "runpod")
|
| 169 |
-
self.assertEqual(runpod_i2v.endpoint_id(), ENDPOINT)
|
| 170 |
-
self.assertEqual(
|
| 171 |
-
runpod_i2v.endpoint_base_url(),
|
| 172 |
-
f"https://api.runpod.ai/v2/{ENDPOINT}",
|
| 173 |
-
)
|
| 174 |
-
self.assertEqual(app.default_steps(), 10)
|
| 175 |
-
text = app.intro_markdown() + app.cold_start_note() + app.limits_markdown()
|
| 176 |
-
self.assertIn("several minutes", text.lower())
|
| 177 |
-
self.assertIn("cold start", text.lower())
|
| 178 |
-
self.assertIn("model download", text.lower())
|
| 179 |
-
self.assertIn(ENDPOINT, text)
|
| 180 |
-
self.assertNotIn(API_KEY, text)
|
| 181 |
-
status = app.status_line([], 0)
|
| 182 |
-
self.assertIn(ENDPOINT, status)
|
| 183 |
-
self.assertNotIn("ZeroGPU", status)
|
| 184 |
-
|
| 185 |
-
def test_missing_key_falls_back_to_zerogpu(self):
|
| 186 |
-
self.assertEqual(runpod_i2v.active_backend(), "zerogpu")
|
| 187 |
-
self.assertEqual(app.default_steps(), 4)
|
| 188 |
-
self.assertEqual(app.cold_start_note(), "")
|
| 189 |
-
self.assertIn("ZeroGPU", app.intro_markdown())
|
| 190 |
-
self.assertIn("ZeroGPU", app.status_line(["a"], 3.5))
|
| 191 |
-
|
| 192 |
-
def test_explicit_zerogpu_flag_wins_over_key(self):
|
| 193 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 194 |
-
os.environ["WAN_BACKEND"] = "zerogpu"
|
| 195 |
-
self.assertEqual(runpod_i2v.active_backend(), "zerogpu")
|
| 196 |
-
os.environ["WAN_BACKEND"] = "runpod"
|
| 197 |
-
os.environ["USE_ZERGPU"] = "1"
|
| 198 |
-
self.assertEqual(runpod_i2v.active_backend(), "zerogpu")
|
| 199 |
-
|
| 200 |
-
def test_explicit_runpod_without_key_does_not_silently_fall_back(self):
|
| 201 |
-
os.environ["WAN_BACKEND"] = "runpod"
|
| 202 |
-
self.assertEqual(runpod_i2v.active_backend(), "runpod")
|
| 203 |
-
with self.assertRaises(runpod_i2v.RunpodError) as caught:
|
| 204 |
-
runpod_i2v.require_api_key()
|
| 205 |
-
self.assertIn("RUNPOD_API_KEY", str(caught.exception))
|
| 206 |
-
self.assertNotIn("rpa_", str(caught.exception))
|
| 207 |
-
|
| 208 |
-
def test_endpoint_url_accepts_run_and_runsync(self):
|
| 209 |
-
base = f"https://api.runpod.ai/v2/{ENDPOINT}"
|
| 210 |
-
self.assertEqual(runpod_i2v.normalize_base_url(base + "/run"), base)
|
| 211 |
-
self.assertEqual(runpod_i2v.normalize_base_url(base + "/runsync/"), base)
|
| 212 |
-
self.assertEqual(runpod_i2v.normalize_base_url(base + "/run?token=secret"), base)
|
| 213 |
-
self.assertNotIn("secret", runpod_i2v.normalize_base_url(base + "/run?token=secret"))
|
| 214 |
-
os.environ["RUNPOD_ENDPOINT_URL"] = base + "/run"
|
| 215 |
-
os.environ["RUNPOD_ENDPOINT_ID"] = "some-other-endpoint"
|
| 216 |
-
self.assertEqual(runpod_i2v.endpoint_base_url(), base)
|
| 217 |
-
|
| 218 |
-
def test_sources_do_not_embed_api_keys(self):
|
| 219 |
-
for name in ("app.py", "runpod_i2v.py", "README.md", "requirements.txt"):
|
| 220 |
-
text = (ROOT / name).read_text()
|
| 221 |
-
self.assertNotIn("rpa_", text)
|
| 222 |
-
self.assertNotRegex(text, r"Bearer [A-Za-z0-9]{8,}")
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
class FrameAndResolutionTests(unittest.TestCase):
|
| 226 |
-
def test_duration_maps_to_wan_frame_counts(self):
|
| 227 |
-
self.assertEqual(runpod_i2v.duration_to_length(5.0), 81)
|
| 228 |
-
self.assertEqual(runpod_i2v.duration_to_length(4.5), 73)
|
| 229 |
-
self.assertEqual(runpod_i2v.duration_to_length(4.0), 65)
|
| 230 |
-
self.assertEqual(runpod_i2v.duration_to_length(3.5), 57)
|
| 231 |
-
self.assertEqual(runpod_i2v.duration_to_length(3.0), 49)
|
| 232 |
-
self.assertEqual(runpod_i2v.duration_to_length(2.5), 41)
|
| 233 |
-
self.assertEqual(runpod_i2v.duration_to_length(2.0), 33)
|
| 234 |
-
self.assertEqual(runpod_i2v.duration_to_length(0.2), 17)
|
| 235 |
-
for seconds in (2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0):
|
| 236 |
-
length = runpod_i2v.duration_to_length(seconds)
|
| 237 |
-
self.assertEqual((length - 1) % 4, 0)
|
| 238 |
-
self.assertLessEqual(length, 81)
|
| 239 |
-
|
| 240 |
-
def test_aspect_buckets_match_the_worker_examples(self):
|
| 241 |
-
self.assertEqual(runpod_i2v.resolution_for_size(1080, 1920), (480, 832))
|
| 242 |
-
self.assertEqual(runpod_i2v.resolution_for_size(1920, 1080), (832, 480))
|
| 243 |
-
self.assertEqual(runpod_i2v.resolution_for_size(1000, 1000), (640, 640))
|
| 244 |
-
|
| 245 |
-
def test_seed_randomize(self):
|
| 246 |
-
self.assertEqual(runpod_i2v.resolve_seed(42, False), 42)
|
| 247 |
-
rolled = runpod_i2v.resolve_seed(42, True)
|
| 248 |
-
self.assertIsInstance(rolled, int)
|
| 249 |
-
self.assertGreaterEqual(rolled, 0)
|
| 250 |
-
self.assertLess(rolled, 2**31 - 1)
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
class ClientTests(EnvCase):
|
| 254 |
-
@classmethod
|
| 255 |
-
def setUpClass(cls):
|
| 256 |
-
cls._tmp = tempfile.TemporaryDirectory()
|
| 257 |
-
cls.video_path = Path(cls._tmp.name) / "clip.mp4"
|
| 258 |
-
_make_clip(cls.video_path, size="480x832", duration=1.0)
|
| 259 |
-
cls.video_bytes = cls.video_path.read_bytes()
|
| 260 |
-
cls.video_b64 = base64.b64encode(cls.video_bytes).decode("ascii")
|
| 261 |
-
|
| 262 |
-
@classmethod
|
| 263 |
-
def tearDownClass(cls):
|
| 264 |
-
cls._tmp.cleanup()
|
| 265 |
-
|
| 266 |
-
def _still(self, directory: Path, size=(400, 900)) -> Path:
|
| 267 |
-
from PIL import Image
|
| 268 |
-
|
| 269 |
-
path = directory / "still.png"
|
| 270 |
-
Image.new("RGB", size, (20, 40, 200)).save(path)
|
| 271 |
-
return path
|
| 272 |
-
|
| 273 |
-
def test_poll_then_data_uri_video_and_request_contract(self):
|
| 274 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 275 |
-
clock = _Clock()
|
| 276 |
-
calls: list[tuple[str, str]] = []
|
| 277 |
-
|
| 278 |
-
def urlopen(req, timeout=None):
|
| 279 |
-
calls.append((req.get_method(), req.full_url))
|
| 280 |
-
headers = _headers(req)
|
| 281 |
-
self.assertEqual(headers.get("authorization"), f"Bearer {API_KEY}")
|
| 282 |
-
self.assertNotIn(API_KEY, req.full_url)
|
| 283 |
-
if req.full_url.endswith("/run"):
|
| 284 |
-
body = json.loads(req.data.decode())
|
| 285 |
-
self.assertNotIn(API_KEY, req.data.decode())
|
| 286 |
-
payload = body["input"]
|
| 287 |
-
for key in (
|
| 288 |
-
"prompt",
|
| 289 |
-
"negative_prompt",
|
| 290 |
-
"image_base64",
|
| 291 |
-
"width",
|
| 292 |
-
"height",
|
| 293 |
-
"length",
|
| 294 |
-
"steps",
|
| 295 |
-
"cfg",
|
| 296 |
-
"seed",
|
| 297 |
-
):
|
| 298 |
-
self.assertIn(key, payload)
|
| 299 |
-
self.assertFalse(str(payload["image_base64"]).startswith("data:"))
|
| 300 |
-
self.assertEqual(payload["width"], 480)
|
| 301 |
-
self.assertEqual(payload["height"], 832)
|
| 302 |
-
self.assertEqual(payload["length"], 57)
|
| 303 |
-
self.assertEqual(payload["steps"], 10)
|
| 304 |
-
self.assertEqual(payload["cfg"], 2.0)
|
| 305 |
-
self.assertEqual(payload["seed"], 42)
|
| 306 |
-
self.assertEqual(payload["prompt"], "a cat walks")
|
| 307 |
-
from PIL import Image
|
| 308 |
-
|
| 309 |
-
decoded = base64.b64decode(payload["image_base64"])
|
| 310 |
-
with Image.open(io.BytesIO(decoded)) as image:
|
| 311 |
-
self.assertEqual(image.size, (480, 832))
|
| 312 |
-
self.assertEqual(image.format, "JPEG")
|
| 313 |
-
return _json_response({"id": "job-1", "status": "IN_QUEUE"})
|
| 314 |
-
if req.full_url.endswith("/status/job-1"):
|
| 315 |
-
if sum(1 for method, url in calls if url.endswith("/status/job-1")) == 1:
|
| 316 |
-
return _json_response({"id": "job-1", "status": "IN_QUEUE"})
|
| 317 |
-
if sum(1 for method, url in calls if url.endswith("/status/job-1")) == 2:
|
| 318 |
-
return _json_response({"id": "job-1", "status": "IN_PROGRESS"})
|
| 319 |
-
return _json_response(
|
| 320 |
-
{
|
| 321 |
-
"id": "job-1",
|
| 322 |
-
"status": "COMPLETED",
|
| 323 |
-
"output": {"video": f"data:video/mp4;base64,{self.video_b64}"},
|
| 324 |
-
}
|
| 325 |
-
)
|
| 326 |
-
raise AssertionError(req.full_url)
|
| 327 |
-
|
| 328 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 329 |
-
tmp_path = Path(tmp)
|
| 330 |
-
dest = tmp_path / "out.mp4"
|
| 331 |
-
runpod_i2v.generate_i2v(
|
| 332 |
-
self._still(tmp_path),
|
| 333 |
-
dest,
|
| 334 |
-
prompt="a cat walks",
|
| 335 |
-
negative_prompt="blurry",
|
| 336 |
-
duration_seconds=3.5,
|
| 337 |
-
steps=10,
|
| 338 |
-
seed=42,
|
| 339 |
-
urlopen=urlopen,
|
| 340 |
-
sleep=clock.sleep,
|
| 341 |
-
now=clock.now,
|
| 342 |
-
poll_interval_s=5,
|
| 343 |
-
)
|
| 344 |
-
self.assertTrue(dest.exists())
|
| 345 |
-
self.assertEqual(dest.read_bytes(), self.video_bytes)
|
| 346 |
-
self.assertLess(app.video_duration_seconds(dest), 1.2)
|
| 347 |
-
self.assertGreater(app.video_duration_seconds(dest), 0.8)
|
| 348 |
-
|
| 349 |
-
run_calls = [url for method, url in calls if method == "POST" and url.endswith("/run")]
|
| 350 |
-
self.assertEqual(run_calls, [f"https://api.runpod.ai/v2/{ENDPOINT}/run"])
|
| 351 |
-
self.assertGreaterEqual(clock.t, 10)
|
| 352 |
-
|
| 353 |
-
def test_raw_base64_video(self):
|
| 354 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 355 |
-
|
| 356 |
-
def urlopen(req, timeout=None):
|
| 357 |
-
if req.full_url.endswith("/run"):
|
| 358 |
-
return _json_response({"id": "job-raw", "status": "IN_QUEUE"})
|
| 359 |
-
return _json_response(
|
| 360 |
-
{"id": "job-raw", "status": "COMPLETED", "output": {"video": self.video_b64}}
|
| 361 |
-
)
|
| 362 |
-
|
| 363 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 364 |
-
dest = Path(tmp) / "out.mp4"
|
| 365 |
-
runpod_i2v.generate_i2v(
|
| 366 |
-
self._still(Path(tmp), (900, 400)),
|
| 367 |
-
dest,
|
| 368 |
-
prompt="pan",
|
| 369 |
-
negative_prompt="blurry",
|
| 370 |
-
duration_seconds=5,
|
| 371 |
-
steps=8,
|
| 372 |
-
seed=7,
|
| 373 |
-
urlopen=urlopen,
|
| 374 |
-
sleep=lambda _s: None,
|
| 375 |
-
now=lambda: 0.0,
|
| 376 |
-
)
|
| 377 |
-
self.assertEqual(dest.read_bytes(), self.video_bytes)
|
| 378 |
-
|
| 379 |
-
def test_landscape_still_uses_832x480(self):
|
| 380 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 381 |
-
seen: dict = {}
|
| 382 |
-
|
| 383 |
-
def urlopen(req, timeout=None):
|
| 384 |
-
if req.full_url.endswith("/run"):
|
| 385 |
-
seen.update(json.loads(req.data.decode())["input"])
|
| 386 |
-
return _json_response({"id": "job-l", "status": "IN_QUEUE"})
|
| 387 |
-
return _json_response(
|
| 388 |
-
{
|
| 389 |
-
"id": "job-l",
|
| 390 |
-
"status": "COMPLETED",
|
| 391 |
-
"output": {"video": self.video_b64},
|
| 392 |
-
}
|
| 393 |
-
)
|
| 394 |
-
|
| 395 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 396 |
-
runpod_i2v.generate_i2v(
|
| 397 |
-
self._still(Path(tmp), (900, 400)),
|
| 398 |
-
Path(tmp) / "out.mp4",
|
| 399 |
-
prompt="pan",
|
| 400 |
-
negative_prompt="blurry",
|
| 401 |
-
duration_seconds=2,
|
| 402 |
-
steps=4,
|
| 403 |
-
seed=1,
|
| 404 |
-
urlopen=urlopen,
|
| 405 |
-
sleep=lambda _s: None,
|
| 406 |
-
now=lambda: 0.0,
|
| 407 |
-
)
|
| 408 |
-
self.assertEqual((seen["width"], seen["height"], seen["length"]), (832, 480, 33))
|
| 409 |
-
|
| 410 |
-
def test_exif_orientation_picks_portrait_bucket(self):
|
| 411 |
-
from PIL import Image
|
| 412 |
-
|
| 413 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 414 |
-
seen: dict = {}
|
| 415 |
-
|
| 416 |
-
def urlopen(req, timeout=None):
|
| 417 |
-
if req.full_url.endswith("/run"):
|
| 418 |
-
seen.update(json.loads(req.data.decode())["input"])
|
| 419 |
-
return _json_response({"id": "job-exif", "status": "IN_QUEUE"})
|
| 420 |
-
return _json_response(
|
| 421 |
-
{"id": "job-exif", "status": "COMPLETED", "output": {"video": self.video_b64}}
|
| 422 |
-
)
|
| 423 |
-
|
| 424 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 425 |
-
path = Path(tmp) / "iphone.jpg"
|
| 426 |
-
image = Image.new("RGB", (300, 100), (255, 0, 0))
|
| 427 |
-
exif = image.getexif()
|
| 428 |
-
exif[274] = 6
|
| 429 |
-
image.save(path, exif=exif)
|
| 430 |
-
runpod_i2v.generate_i2v(
|
| 431 |
-
path,
|
| 432 |
-
Path(tmp) / "out.mp4",
|
| 433 |
-
prompt="look",
|
| 434 |
-
negative_prompt="blurry",
|
| 435 |
-
duration_seconds=2,
|
| 436 |
-
steps=4,
|
| 437 |
-
seed=1,
|
| 438 |
-
urlopen=urlopen,
|
| 439 |
-
sleep=lambda _s: None,
|
| 440 |
-
now=lambda: 0.0,
|
| 441 |
-
)
|
| 442 |
-
self.assertEqual((seen["width"], seen["height"]), (480, 832))
|
| 443 |
-
|
| 444 |
-
def test_video_url_download_does_not_send_the_key(self):
|
| 445 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 446 |
-
|
| 447 |
-
def urlopen(req, timeout=None):
|
| 448 |
-
headers = _headers(req)
|
| 449 |
-
if req.full_url.endswith("/run"):
|
| 450 |
-
return _json_response({"id": "job-url", "status": "IN_QUEUE"})
|
| 451 |
-
if "/status/" in req.full_url:
|
| 452 |
-
return _json_response(
|
| 453 |
-
{
|
| 454 |
-
"id": "job-url",
|
| 455 |
-
"status": "COMPLETED",
|
| 456 |
-
"output": {"video_url": "https://cdn.example.test/clip.mp4"},
|
| 457 |
-
}
|
| 458 |
-
)
|
| 459 |
-
self.assertEqual(req.full_url, "https://cdn.example.test/clip.mp4")
|
| 460 |
-
self.assertNotIn("authorization", headers)
|
| 461 |
-
return _Body(self.video_bytes)
|
| 462 |
-
|
| 463 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 464 |
-
dest = Path(tmp) / "out.mp4"
|
| 465 |
-
runpod_i2v.generate_i2v(
|
| 466 |
-
self._still(Path(tmp)),
|
| 467 |
-
dest,
|
| 468 |
-
prompt="pan",
|
| 469 |
-
negative_prompt="blurry",
|
| 470 |
-
duration_seconds=2,
|
| 471 |
-
steps=4,
|
| 472 |
-
seed=1,
|
| 473 |
-
urlopen=urlopen,
|
| 474 |
-
sleep=lambda _s: None,
|
| 475 |
-
now=lambda: 0.0,
|
| 476 |
-
)
|
| 477 |
-
self.assertEqual(dest.read_bytes(), self.video_bytes)
|
| 478 |
-
|
| 479 |
-
def test_failed_job_is_a_clear_error(self):
|
| 480 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 481 |
-
|
| 482 |
-
def urlopen(req, timeout=None):
|
| 483 |
-
if req.full_url.endswith("/run"):
|
| 484 |
-
return _json_response({"id": "job-9", "status": "IN_QUEUE"})
|
| 485 |
-
return _json_response(
|
| 486 |
-
{"id": "job-9", "status": "FAILED", "error": "CUDA out of memory"}
|
| 487 |
-
)
|
| 488 |
-
|
| 489 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 490 |
-
dest = Path(tmp) / "out.mp4"
|
| 491 |
-
with self.assertRaises(runpod_i2v.RunpodError) as caught:
|
| 492 |
-
runpod_i2v.generate_i2v(
|
| 493 |
-
self._still(Path(tmp)),
|
| 494 |
-
dest,
|
| 495 |
-
prompt="pan",
|
| 496 |
-
negative_prompt="blurry",
|
| 497 |
-
duration_seconds=2,
|
| 498 |
-
steps=4,
|
| 499 |
-
seed=1,
|
| 500 |
-
urlopen=urlopen,
|
| 501 |
-
sleep=lambda _s: None,
|
| 502 |
-
now=lambda: 0.0,
|
| 503 |
-
)
|
| 504 |
-
self.assertFalse(dest.exists())
|
| 505 |
-
message = str(caught.exception)
|
| 506 |
-
self.assertIn("job-9", message)
|
| 507 |
-
self.assertIn("CUDA out of memory", message)
|
| 508 |
-
self.assertNotIn(API_KEY, message)
|
| 509 |
-
|
| 510 |
-
def test_completed_without_video_errors(self):
|
| 511 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 512 |
-
|
| 513 |
-
def urlopen(req, timeout=None):
|
| 514 |
-
if req.full_url.endswith("/run"):
|
| 515 |
-
return _json_response({"id": "job-empty", "status": "IN_QUEUE"})
|
| 516 |
-
return _json_response(
|
| 517 |
-
{
|
| 518 |
-
"id": "job-empty",
|
| 519 |
-
"status": "COMPLETED",
|
| 520 |
-
"output": {"error": "video not found"},
|
| 521 |
-
}
|
| 522 |
-
)
|
| 523 |
-
|
| 524 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 525 |
-
with self.assertRaises(runpod_i2v.RunpodError) as caught:
|
| 526 |
-
runpod_i2v.generate_i2v(
|
| 527 |
-
self._still(Path(tmp)),
|
| 528 |
-
Path(tmp) / "out.mp4",
|
| 529 |
-
prompt="pan",
|
| 530 |
-
negative_prompt="blurry",
|
| 531 |
-
duration_seconds=2,
|
| 532 |
-
steps=4,
|
| 533 |
-
seed=1,
|
| 534 |
-
urlopen=urlopen,
|
| 535 |
-
sleep=lambda _s: None,
|
| 536 |
-
now=lambda: 0.0,
|
| 537 |
-
)
|
| 538 |
-
self.assertIn("video not found", str(caught.exception))
|
| 539 |
-
|
| 540 |
-
def test_http_401_redacts_key(self):
|
| 541 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 542 |
-
|
| 543 |
-
def urlopen(req, timeout=None):
|
| 544 |
-
payload = json.dumps({"error": f"nope {API_KEY}"}).encode()
|
| 545 |
-
raise urllib.error.HTTPError(
|
| 546 |
-
req.full_url, 401, "Unauthorized", hdrs=None, fp=io.BytesIO(payload)
|
| 547 |
-
)
|
| 548 |
-
|
| 549 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 550 |
-
with self.assertRaises(runpod_i2v.RunpodError) as caught:
|
| 551 |
-
runpod_i2v.generate_i2v(
|
| 552 |
-
self._still(Path(tmp)),
|
| 553 |
-
Path(tmp) / "out.mp4",
|
| 554 |
-
prompt="pan",
|
| 555 |
-
negative_prompt="blurry",
|
| 556 |
-
duration_seconds=2,
|
| 557 |
-
steps=4,
|
| 558 |
-
seed=1,
|
| 559 |
-
urlopen=urlopen,
|
| 560 |
-
sleep=lambda _s: None,
|
| 561 |
-
now=lambda: 0.0,
|
| 562 |
-
)
|
| 563 |
-
message = str(caught.exception)
|
| 564 |
-
self.assertIn("401", message)
|
| 565 |
-
self.assertIn("RUNPOD_API_KEY", message)
|
| 566 |
-
self.assertNotIn(API_KEY, message)
|
| 567 |
-
|
| 568 |
-
def test_client_timeout_cancels_the_job(self):
|
| 569 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 570 |
-
clock = _Clock()
|
| 571 |
-
cancelled: list[str] = []
|
| 572 |
-
|
| 573 |
-
def urlopen(req, timeout=None):
|
| 574 |
-
if req.full_url.endswith("/run"):
|
| 575 |
-
return _json_response({"id": "job-slow", "status": "IN_QUEUE"})
|
| 576 |
-
if "/cancel/" in req.full_url:
|
| 577 |
-
cancelled.append(req.full_url)
|
| 578 |
-
return _json_response({"id": "job-slow", "status": "CANCELLED"})
|
| 579 |
-
return _json_response({"id": "job-slow", "status": "IN_QUEUE"})
|
| 580 |
-
|
| 581 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 582 |
-
with self.assertRaises(runpod_i2v.RunpodError) as caught:
|
| 583 |
-
runpod_i2v.generate_i2v(
|
| 584 |
-
self._still(Path(tmp)),
|
| 585 |
-
Path(tmp) / "out.mp4",
|
| 586 |
-
prompt="pan",
|
| 587 |
-
negative_prompt="blurry",
|
| 588 |
-
duration_seconds=2,
|
| 589 |
-
steps=4,
|
| 590 |
-
seed=1,
|
| 591 |
-
urlopen=urlopen,
|
| 592 |
-
sleep=clock.sleep,
|
| 593 |
-
now=clock.now,
|
| 594 |
-
timeout_s=10,
|
| 595 |
-
poll_interval_s=5,
|
| 596 |
-
)
|
| 597 |
-
message = str(caught.exception)
|
| 598 |
-
self.assertIn("job-slow", message)
|
| 599 |
-
self.assertIn("cold-starting", message)
|
| 600 |
-
self.assertNotIn(API_KEY, message)
|
| 601 |
-
self.assertEqual(cancelled, [f"https://api.runpod.ai/v2/{ENDPOINT}/cancel/job-slow"])
|
| 602 |
-
|
| 603 |
-
def test_transient_status_error_is_retried(self):
|
| 604 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 605 |
-
state = {"status_calls": 0}
|
| 606 |
-
|
| 607 |
-
def urlopen(req, timeout=None):
|
| 608 |
-
if req.full_url.endswith("/run"):
|
| 609 |
-
return _json_response({"id": "job-retry", "status": "IN_QUEUE"})
|
| 610 |
-
state["status_calls"] += 1
|
| 611 |
-
if state["status_calls"] == 1:
|
| 612 |
-
raise urllib.error.URLError("timed out")
|
| 613 |
-
return _json_response(
|
| 614 |
-
{"id": "job-retry", "status": "COMPLETED", "output": {"video": self.video_b64}}
|
| 615 |
-
)
|
| 616 |
-
|
| 617 |
-
with tempfile.TemporaryDirectory() as tmp:
|
| 618 |
-
dest = Path(tmp) / "out.mp4"
|
| 619 |
-
runpod_i2v.generate_i2v(
|
| 620 |
-
self._still(Path(tmp)),
|
| 621 |
-
dest,
|
| 622 |
-
prompt="pan",
|
| 623 |
-
negative_prompt="blurry",
|
| 624 |
-
duration_seconds=2,
|
| 625 |
-
steps=4,
|
| 626 |
-
seed=1,
|
| 627 |
-
urlopen=urlopen,
|
| 628 |
-
sleep=lambda _s: None,
|
| 629 |
-
now=lambda: 0.0,
|
| 630 |
-
)
|
| 631 |
-
self.assertEqual(dest.read_bytes(), self.video_bytes)
|
| 632 |
-
self.assertEqual(state["status_calls"], 2)
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
class AppFlowTests(EnvCase):
|
| 636 |
-
@classmethod
|
| 637 |
-
def setUpClass(cls):
|
| 638 |
-
cls._tmp = tempfile.TemporaryDirectory()
|
| 639 |
-
cls.video_path = Path(cls._tmp.name) / "clip.mp4"
|
| 640 |
-
_make_clip(cls.video_path, size="480x832", duration=1.0)
|
| 641 |
-
cls.video_bytes = cls.video_path.read_bytes()
|
| 642 |
-
cls.video_b64 = base64.b64encode(cls.video_bytes).decode("ascii")
|
| 643 |
-
|
| 644 |
-
@classmethod
|
| 645 |
-
def tearDownClass(cls):
|
| 646 |
-
cls._tmp.cleanup()
|
| 647 |
-
|
| 648 |
-
def test_generate_extend_and_auto_extend_each_call_runpod(self):
|
| 649 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 650 |
-
os.environ["RUNPOD_ENDPOINT_ID"] = ENDPOINT
|
| 651 |
-
runs: list[dict] = []
|
| 652 |
-
|
| 653 |
-
def urlopen(req, timeout=None):
|
| 654 |
-
headers = _headers(req)
|
| 655 |
-
self.assertEqual(headers.get("authorization"), f"Bearer {API_KEY}")
|
| 656 |
-
self.assertIn(f"/v2/{ENDPOINT}/", req.full_url)
|
| 657 |
-
if req.get_method() == "POST" and req.full_url.endswith("/run"):
|
| 658 |
-
payload = json.loads(req.data.decode())["input"]
|
| 659 |
-
runs.append(payload)
|
| 660 |
-
job_id = f"job-{len(runs)}"
|
| 661 |
-
return _json_response({"id": job_id, "status": "IN_QUEUE"})
|
| 662 |
-
if "/status/" in req.full_url:
|
| 663 |
-
job_id = req.full_url.rstrip("/").rsplit("/", 1)[-1]
|
| 664 |
-
return _json_response(
|
| 665 |
-
{
|
| 666 |
-
"id": job_id,
|
| 667 |
-
"status": "COMPLETED",
|
| 668 |
-
"output": {"video": f"data:video/mp4;base64,{self.video_b64}"},
|
| 669 |
-
}
|
| 670 |
-
)
|
| 671 |
-
raise AssertionError(f"unexpected request {req.get_method()} {req.full_url}")
|
| 672 |
-
|
| 673 |
-
from PIL import Image
|
| 674 |
-
|
| 675 |
-
still = Image.new("RGB", (480, 800), (10, 20, 30))
|
| 676 |
-
with patch("urllib.request.urlopen", urlopen):
|
| 677 |
-
video, _download, status, last, state = app.do_generate(
|
| 678 |
-
still,
|
| 679 |
-
"make it move",
|
| 680 |
-
3.5,
|
| 681 |
-
10,
|
| 682 |
-
"blurry",
|
| 683 |
-
42,
|
| 684 |
-
False,
|
| 685 |
-
6,
|
| 686 |
-
16,
|
| 687 |
-
True,
|
| 688 |
-
{},
|
| 689 |
-
)
|
| 690 |
-
self.assertEqual(len(runs), 1)
|
| 691 |
-
self.assertEqual(runs[0]["prompt"], "make it move")
|
| 692 |
-
self.assertEqual(runs[0]["seed"], 42)
|
| 693 |
-
self.assertTrue(Path(video).exists())
|
| 694 |
-
self.assertGreater(app.video_duration_seconds(video), 0.5)
|
| 695 |
-
self.assertIn(ENDPOINT, status)
|
| 696 |
-
self.assertTrue(Path(last).exists())
|
| 697 |
-
|
| 698 |
-
video, _download, status, last, state = app.do_extend(
|
| 699 |
-
"make it move",
|
| 700 |
-
"keep walking",
|
| 701 |
-
app.EXTEND_START_LAST_FRAME,
|
| 702 |
-
None,
|
| 703 |
-
3.5,
|
| 704 |
-
10,
|
| 705 |
-
"blurry",
|
| 706 |
-
42,
|
| 707 |
-
False,
|
| 708 |
-
6,
|
| 709 |
-
16,
|
| 710 |
-
True,
|
| 711 |
-
state,
|
| 712 |
-
)
|
| 713 |
-
self.assertEqual(len(runs), 2)
|
| 714 |
-
self.assertEqual(runs[1]["prompt"], "keep walking")
|
| 715 |
-
self.assertEqual(len(state["segments"]), 2)
|
| 716 |
-
self.assertGreater(app.video_duration_seconds(video), 1.5)
|
| 717 |
-
|
| 718 |
-
video, _download, status, _last, state = app.do_auto_extend(
|
| 719 |
-
2.5,
|
| 720 |
-
"make it move",
|
| 721 |
-
"",
|
| 722 |
-
app.EXTEND_START_LAST_FRAME,
|
| 723 |
-
None,
|
| 724 |
-
3.5,
|
| 725 |
-
10,
|
| 726 |
-
"blurry",
|
| 727 |
-
42,
|
| 728 |
-
False,
|
| 729 |
-
6,
|
| 730 |
-
16,
|
| 731 |
-
True,
|
| 732 |
-
state,
|
| 733 |
-
)
|
| 734 |
-
self.assertEqual(len(runs), 3)
|
| 735 |
-
self.assertEqual(len(state["segments"]), 3)
|
| 736 |
-
self.assertGreater(app.video_duration_seconds(video), 2.5)
|
| 737 |
-
self.assertIn("Runpod", status)
|
| 738 |
-
for payload in runs:
|
| 739 |
-
self.assertEqual((payload["width"], payload["height"]), (480, 832))
|
| 740 |
-
self.assertNotIn("image_url", payload)
|
| 741 |
-
self.assertTrue(payload["image_base64"])
|
| 742 |
-
self.assertFalse(payload["image_base64"].startswith("data:"))
|
| 743 |
-
|
| 744 |
-
def test_generate_surfaces_runpod_auth_error(self):
|
| 745 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 746 |
-
|
| 747 |
-
def urlopen(req, timeout=None):
|
| 748 |
-
payload = json.dumps({"error": f"unauthorized {API_KEY}"}).encode()
|
| 749 |
-
raise urllib.error.HTTPError(
|
| 750 |
-
req.full_url, 401, "Unauthorized", hdrs=None, fp=io.BytesIO(payload)
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
from PIL import Image
|
| 754 |
-
|
| 755 |
-
with patch("urllib.request.urlopen", urlopen):
|
| 756 |
-
with self.assertRaises(app.gr.Error) as caught:
|
| 757 |
-
app.do_generate(
|
| 758 |
-
Image.new("RGB", (64, 64), (1, 2, 3)),
|
| 759 |
-
"prompt",
|
| 760 |
-
3.5,
|
| 761 |
-
4,
|
| 762 |
-
"blurry",
|
| 763 |
-
1,
|
| 764 |
-
False,
|
| 765 |
-
6,
|
| 766 |
-
16,
|
| 767 |
-
True,
|
| 768 |
-
{},
|
| 769 |
-
)
|
| 770 |
-
message = str(caught.exception)
|
| 771 |
-
self.assertIn("Generation failed", message)
|
| 772 |
-
self.assertIn("401", message)
|
| 773 |
-
self.assertNotIn(API_KEY, message)
|
| 774 |
-
|
| 775 |
-
def test_zerogpu_flag_does_not_call_runpod(self):
|
| 776 |
-
os.environ["RUNPOD_API_KEY"] = API_KEY
|
| 777 |
-
os.environ["WAN_BACKEND"] = "zerogpu"
|
| 778 |
-
calls = {"runpod": 0, "zero": 0}
|
| 779 |
-
|
| 780 |
-
def urlopen(req, timeout=None):
|
| 781 |
-
calls["runpod"] += 1
|
| 782 |
-
raise AssertionError("Runpod was called despite WAN_BACKEND=zerogpu")
|
| 783 |
-
|
| 784 |
-
def zerogpu(*_args, **_kwargs):
|
| 785 |
-
calls["zero"] += 1
|
| 786 |
-
return self.video_path
|
| 787 |
-
|
| 788 |
-
with patch("urllib.request.urlopen", urlopen), patch.object(
|
| 789 |
-
app, "call_zerogpu_i2v", zerogpu
|
| 790 |
-
):
|
| 791 |
-
result = app.call_wan_i2v(
|
| 792 |
-
self.video_path,
|
| 793 |
-
"prompt",
|
| 794 |
-
3.5,
|
| 795 |
-
4,
|
| 796 |
-
"neg",
|
| 797 |
-
1,
|
| 798 |
-
False,
|
| 799 |
-
6,
|
| 800 |
-
16,
|
| 801 |
-
True,
|
| 802 |
-
None,
|
| 803 |
-
)
|
| 804 |
-
self.assertEqual(result, self.video_path)
|
| 805 |
-
self.assertEqual(calls, {"runpod": 0, "zero": 1})
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
if __name__ == "__main__":
|
| 809 |
-
unittest.main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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