wan22-extend / runpod_i2v.py
Superagent
Deploy password-gated build: drop HF OAuth login (fixes iOS redirect loop)
fa2be82
Raw History Blame Contribute Delete
25.2 kB
"""Runpod serverless client for Wan 2.2 TI2V segments.
Calls the already-deployed endpoint (default ``kyujeqw2gt779h``) with the
worker input contract: prompt, negative_prompt, image_base64, width, height,
length, steps, cfg, seed. Jobs are submitted to ``/run`` and polled on
``/status/{id}`` because a cold worker (workersMin=0) plus model download
can take several minutes.
The API key is read from the environment only and is never written into
errors, logs, or the job body.
"""
from __future__ import annotations
import base64
import io
import json
import math
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any, Callable
from PIL import Image, ImageOps
# Historical default for the wan22-extend-i2v endpoint. Prefer an explicit
# RUNPOD_EXTEND_ENDPOINT_ID (or legacy RUNPOD_ENDPOINT_ID) in production.
DEFAULT_ENDPOINT_ID = "kyujeqw2gt779h"
DEFAULT_CFG = 2.0
DEFAULT_TIMEOUT_S = 45 * 60
DEFAULT_POLL_S = 5.0
WAN_FPS = 16
MIN_LENGTH = 17
MAX_LENGTH = 81
MAX_VIDEO_BYTES = 80 * 1024 * 1024
# 480p buckets, multiples of 16, area near the worker example 480×832.
# Phone stills land on 480×832; landscape stills land on 832×480.
RESOLUTION_BUCKETS: tuple[tuple[int, int], ...] = (
(832, 480),
(768, 512),
(704, 544),
(640, 640),
(544, 704),
(512, 768),
(480, 832),
)
_ZERO_BACKENDS = frozenset({"zerogpu", "zero", "hf", "gradio"})
_RUNPOD_BACKENDS = frozenset({"runpod", "runpod-i2v"})
_TRUE = frozenset({"1", "true", "yes", "on"})
ProgressFn = Callable[[str, float], None]
UrlOpenFn = Callable[..., Any]
SleepFn = Callable[[float], None]
NowFn = Callable[[], float]
class RunpodError(Exception):
"""User-facing Runpod failure. The message must not contain the API key."""
def _env(env: dict[str, str] | None) -> dict[str, str]:
if env is None:
return dict(os.environ)
return env
def active_backend(env: dict[str, str] | None = None) -> str:
"""Prefer RunPod. ZeroGPU only when explicitly opted in.
``WAN_BACKEND=zerogpu`` / ``USE_ZERGPU=1`` force the HF Space fallback.
Otherwise the app stays on RunPod so missing secrets surface as clear
errors instead of an expired ZeroGPU proxy token.
"""
env = _env(env)
backend = (env.get("WAN_BACKEND") or "").strip().lower()
force_zero = (env.get("USE_ZERGPU") or "").strip().lower() in _TRUE
if backend in _ZERO_BACKENDS or force_zero:
return "zerogpu"
if backend in _RUNPOD_BACKENDS:
return "runpod"
# Default path is RunPod even when the API key is missing — callers then
# hit require_api_key / require_endpoint_id with an actionable message.
return "runpod"
def endpoint_id(env: dict[str, str] | None = None) -> str:
"""Resolve the extend I2V endpoint id.
Order: ``RUNPOD_EXTEND_ENDPOINT_ID``, legacy ``RUNPOD_ENDPOINT_ID``,
then the historical default. Prefer setting ``RUNPOD_EXTEND_ENDPOINT_ID``
explicitly once a new endpoint is deployed.
"""
env = _env(env)
for name in ("RUNPOD_EXTEND_ENDPOINT_ID", "RUNPOD_ENDPOINT_ID"):
value = (env.get(name) or "").strip()
if value:
return value
return DEFAULT_ENDPOINT_ID
def require_endpoint_id(env: dict[str, str] | None = None) -> str:
"""Fail clearly when neither extend endpoint env var is set.
The historical default remains available via ``endpoint_id()`` for local
experiments, but the combined app requires an explicit id so a missing
deploy cannot silently hit a deleted endpoint.
"""
env = _env(env)
for name in ("RUNPOD_EXTEND_ENDPOINT_ID", "RUNPOD_ENDPOINT_ID"):
value = (env.get(name) or "").strip()
if value:
return value
raise RunpodError(
"RunPod extend is selected but no endpoint id is set. "
"Add RUNPOD_EXTEND_ENDPOINT_ID (or legacy RUNPOD_ENDPOINT_ID) "
"as a Space secret / env var, then rebuild. "
"Deploy the wan22 I2V serverless endpoint first — this app does not create it. "
"Set WAN_BACKEND=zerogpu or USE_ZERGPU=1 only if you intentionally want the "
"ZeroGPU fallback."
)
def normalize_base_url(url: str) -> str:
"""Accept a base URL or the documented ``/run`` / ``/runsync`` URLs.
Query strings and fragments are dropped so a token pasted into
``RUNPOD_ENDPOINT_URL`` is not stored on the client or written to logs.
"""
parts = urllib.parse.urlsplit(url.strip())
path = parts.path.rstrip("/")
for suffix in ("/runsync", "/run"):
if path.endswith(suffix):
path = path[: -len(suffix)]
break
return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path.rstrip("/"), "", ""))
def endpoint_base_url(env: dict[str, str] | None = None) -> str:
env = _env(env)
override = (env.get("RUNPOD_ENDPOINT_URL") or "").strip()
if override:
return normalize_base_url(override)
return f"https://api.runpod.ai/v2/{endpoint_id(env)}"
def _env_float(env: dict[str, str], name: str, default: float, minimum: float) -> float:
raw = (env.get(name) or "").strip()
if not raw:
return default
try:
value = float(raw)
except ValueError:
return default
if value < minimum:
return default
return value
def configured_cfg(env: dict[str, str] | None = None) -> float:
env = _env(env)
raw = (env.get("RUNPOD_CFG") or "").strip()
if not raw:
return DEFAULT_CFG
try:
value = float(raw)
except ValueError:
return DEFAULT_CFG
if value <= 0:
return DEFAULT_CFG
return value
def require_api_key(env: dict[str, str] | None = None) -> str:
env = _env(env)
key = (env.get("RUNPOD_API_KEY") or "").strip()
if not key:
raise RunpodError(
"RunPod is selected but RUNPOD_API_KEY is not set. "
"Add RUNPOD_API_KEY plus RUNPOD_EXTEND_ENDPOINT_ID "
"(and RUNPOD_FACESWAP_ENDPOINT_ID for swap) as env / Space secrets, "
"then rebuild. Set WAN_BACKEND=zerogpu or USE_ZERGPU=1 only if you "
"intentionally want the ZeroGPU fallback."
)
return key
def duration_to_length(duration_seconds: float, fps: int = WAN_FPS) -> int:
"""Map a segment length in seconds to Wan frame count (4n+1) at 16 fps."""
duration_seconds = max(0.0, float(duration_seconds))
raw = int(round(duration_seconds * int(fps)))
# Nearest 4n+1. Half steps round away from zero via the +2 bias.
n = (raw - 1 + 2) // 4
length = 4 * n + 1
if length < MIN_LENGTH:
length = MIN_LENGTH
if length > MAX_LENGTH:
length = MAX_LENGTH
if (length - 1) % 4 != 0:
length = max(MIN_LENGTH, ((length - 1) // 4) * 4 + 1)
return length
def resolution_for_size(src_w: int, src_h: int) -> tuple[int, int]:
"""Pick a 480p bucket whose aspect is closest to the still."""
if src_w < 1 or src_h < 1:
return 480, 832
aspect = src_w / src_h
def distance(bucket: tuple[int, int]) -> float:
bw, bh = bucket
return abs(math.log(aspect / (bw / bh)))
return min(RESOLUTION_BUCKETS, key=distance)
def cover_resize(image: Image.Image, width: int, height: int) -> Image.Image:
"""Scale-and-center-crop so ``image`` fills width×height."""
image = image.convert("RGB")
src_w, src_h = image.size
if src_w < 1 or src_h < 1:
raise RunpodError("Input image has no pixels.")
if src_w == width and src_h == height:
return image
scale = max(width / src_w, height / src_h)
new_w = max(1, int(round(src_w * scale)))
new_h = max(1, int(round(src_h * scale)))
resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
left = max(0, (new_w - width) // 2)
top = max(0, (new_h - height) // 2)
cropped = resized.crop((left, top, left + width, top + height))
if cropped.size != (width, height):
cropped = cropped.resize((width, height), Image.Resampling.LANCZOS)
return cropped
def resolve_seed(seed: int, randomize: bool) -> int:
if randomize:
return int.from_bytes(os.urandom(4), "big") % (2**31 - 1)
return int(seed)
def _redact(text: str, secret: str) -> str:
if secret and secret in text:
return text.replace(secret, "[redacted]")
return text
def _short(text: str, secret: str = "", limit: int = 500) -> str:
text = _redact(text or "", secret)
# Drop embedded base64 blobs so a failed payload cannot flood the UI.
cleaned: list[str] = []
for token in text.split():
if len(token) > 80 and all(c.isalnum() or c in "+/=" for c in token):
cleaned.append("[omitted]")
else:
cleaned.append(token)
text = " ".join(cleaned).strip()
if len(text) > limit:
return text[:limit] + "…"
return text
def _looks_like_mp4(data: bytes) -> bool:
return len(data) >= 12 and b"ftyp" in data[:64]
def _is_video_key(key: str) -> bool:
lowered = key.lower().replace("-", "_")
return lowered in {
"video",
"video_base64",
"video_url",
"mp4",
"output_video",
"result",
}
def _decode_video_text(text: str) -> bytes | None:
raw = text.strip()
if raw.startswith("data:"):
if "," not in raw:
return None
raw = raw.split(",", 1)[1]
if raw.startswith("http://") or raw.startswith("https://"):
return None
try:
return base64.b64decode(raw, validate=False)
except Exception:
return None
def _iter_video_candidates(obj: Any, keyed: bool = False, depth: int = 0):
if depth > 8 or obj is None:
return
if isinstance(obj, str):
if keyed or obj.startswith("data:video") or obj.startswith(("http://", "https://")):
yield obj
return
if isinstance(obj, dict):
for key, value in obj.items():
if _is_video_key(str(key)):
yield from _iter_video_candidates(value, True, depth + 1)
for key, value in obj.items():
if not _is_video_key(str(key)):
yield from _iter_video_candidates(value, keyed, depth + 1)
return
if isinstance(obj, (list, tuple)):
for item in obj[:12]:
yield from _iter_video_candidates(item, keyed, depth + 1)
def _output_has_video(payload: Any) -> bool:
output = payload.get("output") if isinstance(payload, dict) else payload
for candidate in _iter_video_candidates(output, isinstance(output, str)):
if isinstance(candidate, str) and (
candidate.startswith(("http://", "https://", "data:video"))
or (_decode_video_text(candidate) and _looks_like_mp4(_decode_video_text(candidate) or b""))
):
return True
return False
def _failure_message(job_id: str, body: dict[str, Any], secret: str) -> str:
status = str(body.get("status") or "FAILED")
err: Any = body.get("error")
output = body.get("output")
if not err and isinstance(output, dict):
err = output.get("error") or output.get("errors")
if not err and isinstance(output, str) and not output.startswith("data:"):
err = output
detail = _short(str(err), secret) if err else "no error details returned"
return f"Runpod job {job_id} failed ({status}): {detail}"
def _load_rgb(image_path: Path) -> Image.Image:
try:
with Image.open(image_path) as opened:
image = ImageOps.exif_transpose(opened)
if image is None:
raise RunpodError(f"Could not read the still image ({image_path.name}).")
image.load()
return image.copy().convert("RGB")
except RunpodError:
raise
except Exception as exc:
raise RunpodError(
f"Could not read the still image ({image_path.name}): {exc}"
) from exc
def _jpeg_base64(image_path: Path, width: int, height: int) -> str:
fitted = cover_resize(_load_rgb(image_path), width, height)
buf = io.BytesIO()
fitted.save(buf, format="JPEG", quality=90, optimize=True)
# Raw base64, not a data: URI. The worker decodes with b64decode, and a
# data-URI prefix is not valid base64 alphabet-only input.
return base64.b64encode(buf.getvalue()).decode("ascii")
def _image_size(image_path: Path) -> tuple[int, int]:
return _load_rgb(image_path).size
class RunpodClient:
def __init__(
self,
api_key: str,
base_url: str,
*,
timeout_s: float = DEFAULT_TIMEOUT_S,
poll_interval_s: float = DEFAULT_POLL_S,
urlopen: UrlOpenFn | None = None,
sleep: SleepFn | None = None,
now: NowFn | None = None,
) -> None:
self.api_key = api_key
self.base_url = base_url.rstrip("/")
self.timeout_s = timeout_s
self.poll_interval_s = poll_interval_s
self._urlopen = urlopen or urllib.request.urlopen
self._sleep = sleep or time.sleep
self._now = now or time.monotonic
def generate(
self,
image_path: Path,
dest: Path,
*,
prompt: str,
negative_prompt: str,
duration_seconds: float,
steps: int,
seed: int,
cfg: float,
width: int | None = None,
height: int | None = None,
on_progress: ProgressFn | None = None,
) -> Path:
if width is None or height is None:
src_w, src_h = _image_size(image_path)
width, height = resolution_for_size(src_w, src_h)
length = duration_to_length(duration_seconds)
steps = max(1, int(steps))
image_b64 = _jpeg_base64(image_path, width, height)
payload = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"image_base64": image_b64,
"width": int(width),
"height": int(height),
"length": int(length),
"steps": steps,
"cfg": float(cfg),
"seed": int(seed),
}
if on_progress:
on_progress("submit", 0.0)
print(
f"[runpod] submit {self.base_url}/run {width}x{height} "
f"frames={length} steps={steps} cfg={cfg} seed={seed}",
flush=True,
)
submitted = self._request_json(
"POST",
f"{self.base_url}/run",
{"input": payload},
timeout=120,
retry_transient=False,
)
if not isinstance(submitted, dict):
raise RunpodError("Runpod /run did not return a job object.")
if submitted.get("error") and not submitted.get("id"):
raise RunpodError(
f"Runpod rejected the job: {_short(str(submitted.get('error')), self.api_key)}"
)
job_id = str(submitted.get("id") or "").strip()
if not job_id:
raise RunpodError(
f"Runpod did not return a job id: {_short(json.dumps(submitted), self.api_key)}"
)
status = str(submitted.get("status") or "").upper()
if status == "COMPLETED":
body = submitted
elif status in {"FAILED", "CANCELLED", "TIMED_OUT"}:
raise RunpodError(_failure_message(job_id, submitted, self.api_key))
else:
body = self._poll(job_id, on_progress)
video = self._extract_video(body)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(video)
if on_progress:
on_progress("save", 0.0)
print(f"[runpod] job {job_id} saved {dest.name} ({len(video)} bytes)", flush=True)
return dest
def _poll(self, job_id: str, on_progress: ProgressFn | None) -> dict[str, Any]:
start = self._now()
last = "IN_QUEUE"
while True:
body = self._request_json(
"GET",
f"{self.base_url}/status/{job_id}",
None,
timeout=60,
retry_transient=True,
)
if not isinstance(body, dict):
raise RunpodError(f"Runpod status for job {job_id} was not a JSON object.")
status = str(body.get("status") or "").upper() or last
last = status
elapsed = self._now() - start
print(f"[runpod] job {job_id} {status} ({int(elapsed)}s)", flush=True)
if on_progress:
on_progress(status, elapsed)
if status == "COMPLETED":
output = body.get("output")
if isinstance(output, dict) and output.get("error") and not _output_has_video(body):
raise RunpodError(
f"Runpod job {job_id} completed with an error: "
f"{_short(str(output.get('error')), self.api_key)}"
)
return body
if status in {"FAILED", "CANCELLED", "TIMED_OUT", "ERROR"}:
raise RunpodError(_failure_message(job_id, body, self.api_key))
if self._now() - start >= self.timeout_s:
self._cancel(job_id)
raise RunpodError(
f"Runpod job {job_id} did not finish within {int(self.timeout_s)}s "
f"(last status: {last}). The worker may still be cold-starting "
f"or downloading the model. Try Generate again in a few minutes."
)
self._sleep(self.poll_interval_s)
def _cancel(self, job_id: str) -> None:
try:
self._request_json(
"POST",
f"{self.base_url}/cancel/{job_id}",
{},
timeout=30,
retry_transient=False,
)
print(f"[runpod] cancelled job {job_id} after client timeout", flush=True)
except RunpodError as exc:
print(f"[runpod] cancel {job_id} failed: {_short(str(exc), self.api_key)}", flush=True)
def _extract_video(self, body: dict[str, Any]) -> bytes:
output = body.get("output")
secret = self.api_key
for candidate in _iter_video_candidates(output, isinstance(output, str)):
if not isinstance(candidate, str):
continue
text = candidate.strip()
if text.startswith(("http://", "https://")):
downloaded = self._download(text)
if _looks_like_mp4(downloaded):
return downloaded
continue
decoded = _decode_video_text(text)
if decoded and _looks_like_mp4(decoded):
if len(decoded) > MAX_VIDEO_BYTES:
raise RunpodError("Runpod returned a video larger than 80MB.")
return decoded
raise RunpodError(
"Runpod finished the job but did not return a playable MP4 "
f"(status payload: {_short(json.dumps(body)[:400], secret)})."
)
def _download(self, url: str) -> bytes:
headers = {"Accept": "video/mp4,application/octet-stream,*/*"}
# Only attach the key to Runpod's own API. Signed output URLs do not need it,
# and sending it to an arbitrary host would leak the secret.
host = (urllib.parse.urlparse(url).hostname or "").lower()
if host == "api.runpod.ai" or host.endswith(".api.runpod.ai"):
headers["Authorization"] = f"Bearer {self.api_key}"
request = urllib.request.Request(url, headers=headers, method="GET")
try:
with self._urlopen(request, timeout=120) as response:
data = response.read(MAX_VIDEO_BYTES + 1)
except urllib.error.HTTPError as exc:
detail = _read_http_error(exc, self.api_key)
raise RunpodError(f"Runpod video download failed (HTTP {exc.code}): {detail}") from exc
except urllib.error.URLError as exc:
raise RunpodError(
f"Could not download the Runpod video ({_short(str(exc.reason), self.api_key)})."
) from exc
if len(data) > MAX_VIDEO_BYTES:
raise RunpodError("Runpod returned a video larger than 80MB.")
return data
def _request_json(
self,
method: str,
url: str,
body: dict[str, Any] | None,
*,
timeout: float,
retry_transient: bool,
) -> Any:
attempts = 4 if retry_transient else 1
last_error: RunpodError | None = None
for attempt in range(attempts):
try:
return self._request_once(method, url, body, timeout)
except RunpodError as exc:
last_error = exc
if not retry_transient or attempt == attempts - 1 or not _is_transient(str(exc)):
raise
self._sleep(min(2**attempt, 8))
assert last_error is not None
raise last_error
def _request_once(self, method: str, url: str, body: dict[str, Any] | None, timeout: float) -> Any:
data = None
headers = {
"Authorization": f"Bearer {self.api_key}",
"Accept": "application/json",
}
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with self._urlopen(request, timeout=timeout) as response:
raw = response.read()
except urllib.error.HTTPError as exc:
detail = _read_http_error(exc, self.api_key)
if exc.code == 401:
raise RunpodError(
"Runpod rejected the API key (HTTP 401). "
"Check the RUNPOD_API_KEY Space secret and rebuild."
) from exc
if exc.code == 404:
raise RunpodError(
"Runpod endpoint was not found (HTTP 404). "
f"Check RUNPOD_ENDPOINT_ID (expected {DEFAULT_ENDPOINT_ID}). {detail}"
) from exc
raise RunpodError(f"Runpod request failed (HTTP {exc.code}): {detail}") from exc
except urllib.error.URLError as exc:
raise RunpodError(
"Could not reach Runpod "
f"({_short(str(getattr(exc, 'reason', exc)), self.api_key)}). "
"Check the Space network and RUNPOD_ENDPOINT_URL."
) from exc
if not raw:
raise RunpodError("Runpod returned an empty response.")
try:
return json.loads(raw.decode("utf-8"))
except Exception as exc:
raise RunpodError(
f"Runpod returned non-JSON: {_short(raw.decode('utf-8', errors='replace'), self.api_key)}"
) from exc
def _is_transient(message: str) -> bool:
lowered = message.lower()
return any(
token in lowered
for token in (
"http 502",
"http 503",
"http 504",
"could not reach runpod",
"timed out",
)
)
def _read_http_error(exc: urllib.error.HTTPError, secret: str) -> str:
try:
raw = exc.read().decode("utf-8", errors="replace")
except Exception:
raw = str(exc)
try:
parsed = json.loads(raw)
except Exception:
parsed = None
if isinstance(parsed, dict) and parsed.get("error"):
return _short(str(parsed["error"]), secret)
return _short(raw, secret)
def generate_i2v(
image_path: Path,
dest: Path,
*,
prompt: str,
negative_prompt: str,
duration_seconds: float,
steps: int,
seed: int,
cfg: float | None = None,
width: int | None = None,
height: int | None = None,
env: dict[str, str] | None = None,
on_progress: ProgressFn | None = None,
urlopen: UrlOpenFn | None = None,
sleep: SleepFn | None = None,
now: NowFn | None = None,
timeout_s: float | None = None,
poll_interval_s: float | None = None,
) -> Path:
"""Submit one I2V segment and write an MP4 to ``dest``."""
env_map = _env(env)
api_key = require_api_key(env_map)
# URL uses endpoint_id() (env or historical default). Combined-app UI
# calls require_endpoint_id() so a missing deploy fails before submit.
if timeout_s is None:
timeout_s = _env_float(env_map, "RUNPOD_TIMEOUT_SECONDS", DEFAULT_TIMEOUT_S, 1.0)
if poll_interval_s is None:
poll_interval_s = _env_float(env_map, "RUNPOD_POLL_INTERVAL_SECONDS", DEFAULT_POLL_S, 1.0)
if cfg is None:
cfg = configured_cfg(env_map)
client = RunpodClient(
api_key,
endpoint_base_url(env_map),
timeout_s=timeout_s,
poll_interval_s=poll_interval_s,
urlopen=urlopen,
sleep=sleep,
now=now,
)
return client.generate(
Path(image_path),
Path(dest),
prompt=prompt,
negative_prompt=negative_prompt,
duration_seconds=duration_seconds,
steps=steps,
seed=seed,
cfg=cfg,
width=width,
height=height,
on_progress=on_progress,
)