Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Unsloth Studio: restyle a video with Cosmos3-Nano-Sim-Transfer on sd-server (#16975)

Leo Borcherding945d2b62f674
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index a6e74f3f973..7eed63c54bb 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -277,6 +277,30 @@ def _release_idle_video_servers(reason: str) -> None:
logger.warning("gpu_arbiter: could not release the idle video sd-server: %s", exc)
+# Set by the restyle route around its own acquire, which a reserved runner must not refuse.
+restyle_handoff: ContextVar[bool] = ContextVar("restyle_handoff", default = False)
+
+
+def _refuse_beside_a_running_restyle() -> None:
+ module = sys.modules.get("core.inference.video_restyle")
+ if module is not None and not restyle_handoff.get() and module.runner.holds_gpu():
+ raise RestyleRunningError()
+
+
+def _release_idle_restyle_server() -> None:
+ module = sys.modules.get("core.inference.video_restyle")
+ if module is None:
+ return
+ try:
+ released = module.runner.unload_if_idle()
+ except Exception as exc: # noqa: BLE001 - never block an acquire on this
+ logger.warning("gpu_arbiter: could not release the idle restyle sd-server: %s", exc)
+ return
+ if not released and not restyle_handoff.get():
+ # A restyle reserved the server after the refusal check: its VRAM is not coming back.
+ raise RestyleRunningError()
+
+
def _release_idle_decision_worker() -> None:
module = sys.modules.get("core.systemone.laya_runtime")
if module is None:
@@ -609,6 +633,21 @@ class GpuBusyForAnotherAccountError(GpuOwnerBusyError):
)
+class RestyleRunningError(GpuOwnerBusyError):
+ """A video restyle holds the GPU outside every owner; a load waits for it (409, retryable)."""
+
+ def __init__(self):
+ super().__init__("video restyle")
+
+ def as_http_exception(self, path: Optional[str] = None):
+ from fastapi import HTTPException
+ return HTTPException(
+ status_code = 409,
+ detail = "A video restyle is running. Try again when it finishes, or cancel it.",
+ headers = {"Retry-After": "30"},
+ )
+
+
def other_accounts_active(account_id: str) -> int:
from state import active_generations
@@ -643,7 +682,7 @@ def acquire_for_request(
from core.inference.gpu_residency import ChatLoadInFlightRefusal
try:
return acquire_for(owner, register, **kwargs)
- except (GpuBusyForAnotherAccountError, ChatLoadInFlightRefusal) as exc:
+ except (GpuBusyForAnotherAccountError, ChatLoadInFlightRefusal, RestyleRunningError) as exc:
raise exc.as_http_exception() from exc
@@ -692,6 +731,7 @@ def acquire_for(
admit()
if expected_current is not None and (_owner, _owner_epoch) != expected_current:
raise OwnerChangedError("The resident GPU model changed; retry the load.")
+ _refuse_beside_a_running_restyle()
coreside = policy != "off" and owner in _KEPT_UNDER_ALWAYS
if (register is not None or replacing) and not coreside:
raise_if_other_accounts_active(acting)
@@ -741,6 +781,7 @@ def acquire_for(
_EVICTORS[name]()
note_evictions(unloading, sink)
_drop_resident(name)
+ _release_idle_restyle_server()
if owner != VIDEO and not (coreside and VIDEO in _residents):
# A resident H3 sd-server sits outside every owner's teardown.
_release_idle_video_servers(f"GPU acquired for {owner}")
diff --git a/studio/backend/core/inference/video_restyle.py b/studio/backend/core/inference/video_restyle.py
new file mode 100644
index 00000000000..9be6e0f88d8
--- /dev/null
+++ b/studio/backend/core/inference/video_restyle.py
@@ -0,0 +1,768 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cosmos3-Nano-Sim-Transfer video restyle on a resident sd-server. Import-light: numpy, PIL and av load lazily."""
+
+from __future__ import annotations
+
+import base64
+import contextlib
+import io
+import os
+import re
+import shutil
+import tempfile
+import threading
+import time
+import uuid
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from core.inference.sd_cpp_args import SdCppModelFiles
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+MODEL_ID = "nvidia/Cosmos3-Nano-Sim-Transfer"
+WIDTH = 832
+HEIGHT = 480
+FPS = 30
+MAX_FRAMES = 121
+MIN_FRAMES = 5
+# NVIDIA's reference control is cv2.Canny(rgb, 100, 200) on the resized RGB frames.
+CANNY_LOW = 100
+CANNY_HIGH = 200
+
+MODEL_ENV = "UNSLOTH_COSMOS3_TRANSFER_MODEL"
+VAE_ENV = "UNSLOTH_COSMOS3_TRANSFER_VAE"
+
+IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
+
+_LATENT_RE = re.compile(r"cosmos3: latent frame (\d+)/(\d+)")
+_DECODE_RE = re.compile(r"cosmos3: \d+ latent frames in")
+
+_TERMINAL = ("done", "error", "cancelled")
+MEDIA_KINDS = ("input", "control", "output")
+# No protocols: a concat or HLS playlist upload would otherwise open the files it names.
+_NO_PROTOCOLS = {"protocol_whitelist": "none"}
+
+
+class RestyleError(ValueError):
+ """Shown to the user."""
+
+
+class RestyleBusy(RuntimeError):
+ pass
+
+
+def snap_frame_count(count: int) -> int:
+ """Largest ``4n + 1`` (Wan2.2 temporal compression) not above ``count`` or ``MAX_FRAMES``."""
+ count = min(int(count), MAX_FRAMES)
+ if count < MIN_FRAMES:
+ raise RestyleError(f"Need at least {MIN_FRAMES} frames, got {count}.")
+ return ((count - 1) // 4) * 4 + 1
+
+
+def model_files(env: Optional[dict[str, str]] = None) -> SdCppModelFiles:
+ env = os.environ if env is None else env
+ model = (env.get(MODEL_ENV) or "").strip()
+ vae = (env.get(VAE_ENV) or "").strip()
+ missing = [
+ name
+ for name, path in ((MODEL_ENV, model), (VAE_ENV, vae))
+ if not path or not Path(path).is_file()
+ ]
+ if missing:
+ raise RestyleError(
+ "Cosmos3 transfer weights not found. Set "
+ + " and ".join(missing)
+ + " to the merged transformer and the Wan2.2 VAE (.safetensors or .gguf)."
+ )
+ return SdCppModelFiles(diffusion_model = model, vae = vae)
+
+
+def fit_frame(
+ image: Any,
+ width: int = WIDTH,
+ height: int = HEIGHT,
+) -> Any:
+ """Scale to cover ``width`` x ``height`` and centre-crop, so the clip is never stretched."""
+ from PIL import Image
+
+ image = image.convert("RGB")
+ if image.size == (width, height):
+ return image
+ # Resample only the centred source box: scaling the whole frame first can allocate far past the output.
+ scale = max(width / image.width, height / image.height)
+ box_w, box_h = width / scale, height / scale
+ left, top = (image.width - box_w) / 2, (image.height - box_h) / 2
+ return image.resize(
+ (width, height), Image.Resampling.BICUBIC, box = (left, top, left + box_w, top + box_h)
+ )
+
+
+def frames_from_video(
+ data: bytes,
+ limit: int = MAX_FRAMES,
+ fps: int = FPS,
+) -> list[Any]:
+ """Frames at ``fps`` by presentation time (held when the source is slower), up to ``limit``."""
+ import av
+ from PIL import Image
+
+ from core.training.diffusion_h3_clips import apply_display_rotation, display_rotation_degrees
+
+ out: list[Any] = []
+ try:
+ with av.open(io.BytesIO(data), options = _NO_PROTOCOLS) as container:
+ if not container.streams.video:
+ raise RestyleError("The file has no video track.")
+ stream = container.streams.video[0]
+ rate = float(stream.average_rate or stream.guessed_rate or fps)
+ first: Optional[float] = None
+ last = 0.0
+ prev = None
+ fitted = None
+
+ def keep() -> Any:
+ # Fit only frames that are kept (a 120 fps source drops 3 in 4), and as they are kept:
+ # 121 full-size 4K frames would hold about 3 GB.
+ nonlocal fitted
+ if fitted is None:
+ theta = display_rotation_degrees(prev, stream)
+ fitted = fit_frame(apply_display_rotation(prev.to_image(), theta, Image))
+ return fitted
+
+ for index, frame in enumerate(container.decode(stream)):
+ t = frame.time if frame.time is not None else index / rate
+ if first is None:
+ first = t
+ t -= first
+ while prev is not None and len(out) < limit and t > len(out) / fps + 1e-6:
+ out.append(keep())
+ if len(out) >= limit:
+ break
+ prev, fitted, last = frame, None, t
+ # The final frame is held for its own interval too, so a slow source keeps its last scene.
+ while (
+ prev is not None
+ and len(out) < limit
+ and (not out or last + 1 / rate > len(out) / fps + 1e-6)
+ ):
+ out.append(keep())
+ except RestyleError:
+ raise
+ except Exception as exc: # noqa: BLE001 -- any decode failure is a bad upload
+ logger.info("restyle: could not decode upload: %s", exc)
+ raise RestyleError(
+ "Could not read this video. Try an MP4 (H.264), WebM or MOV file, or a folder of frames."
+ ) from exc
+ if not out:
+ raise RestyleError("The video has no frames.")
+ return out
+
+
+def video_seconds(data: bytes) -> Optional[float]:
+ import av
+ try:
+ with av.open(io.BytesIO(data), options = _NO_PROTOCOLS) as container:
+ if container.duration:
+ return container.duration / 1_000_000
+ stream = container.streams.video[0]
+ if stream.duration and stream.time_base:
+ return float(stream.duration * stream.time_base)
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def frames_from_images(items: list[tuple[str, bytes]], limit: int = MAX_FRAMES) -> list[Any]:
+ """A folder of frames, in file-name order like sd-cli's ``--control-video``."""
+ from PIL import Image
+
+ named = sorted(
+ ((name, data) for name, data in items if name.lower().endswith(IMAGE_SUFFIXES)),
+ key = lambda item: item[0],
+ )
+ out = []
+ for name, data in named[:limit]:
+ try:
+ with Image.open(io.BytesIO(data)) as image:
+ out.append(fit_frame(image))
+ except Exception as exc: # noqa: BLE001
+ raise RestyleError(f"Could not read frame {Path(name).name}: {exc}") from exc
+ return out
+
+
+def canny_edges(
+ rgb: Any,
+ low: int = CANNY_LOW,
+ high: int = CANNY_HIGH,
+) -> Any:
+ """``cv2.Canny(rgb, low, high)`` in numpy (3x3 Sobel, L1, strongest channel): OpenCV is not a Studio dependency."""
+ import numpy as np
+
+ img = np.asarray(rgb, dtype = np.int32)
+ if img.ndim == 2:
+ img = img[..., None]
+ h, w = img.shape[:2]
+ p = np.pad(img, ((1, 1), (1, 1), (0, 0)), mode = "edge")
+ dx = (p[:-2, 2:] + 2 * p[1:-1, 2:] + p[2:, 2:]) - (p[:-2, :-2] + 2 * p[1:-1, :-2] + p[2:, :-2])
+ dy = (p[2:, :-2] + 2 * p[2:, 1:-1] + p[2:, 2:]) - (p[:-2, :-2] + 2 * p[:-2, 1:-1] + p[:-2, 2:])
+ mag = np.abs(dx) + np.abs(dy)
+ pick = mag.argmax(axis = -1)[..., None]
+ dx = np.take_along_axis(dx, pick, -1)[..., 0].astype(np.int64)
+ dy = np.take_along_axis(dy, pick, -1)[..., 0].astype(np.int64)
+ mag = np.take_along_axis(mag, pick, -1)[..., 0]
+
+ m = np.pad(mag, 1)
+ c = m[1:-1, 1:-1]
+ ax = np.abs(dx)
+ ay = np.abs(dy) << 15
+ tg22 = ax * 13573 # round(tan(22.5 deg) * 2**15), as in OpenCV
+ tg67 = tg22 + (ax << 16)
+ horizontal = ay < tg22
+ vertical = ay > tg67
+ same_sign = (dx ^ dy) >= 0
+ keep = np.where(
+ horizontal,
+ (c > m[1:-1, :-2]) & (c >= m[1:-1, 2:]),
+ np.where(
+ vertical,
+ (c > m[:-2, 1:-1]) & (c >= m[2:, 1:-1]),
+ np.where(
+ same_sign,
+ (c > m[:-2, :-2]) & (c > m[2:, 2:]),
+ (c > m[:-2, 2:]) & (c > m[2:, :-2]),
+ ),
+ ),
+ )
+ weak = keep & (c > low)
+
+ pw = w + 2
+ weak_flat = np.zeros((h + 2) * pw, dtype = bool)
+ weak_flat.reshape(h + 2, pw)[1:-1, 1:-1] = weak
+ edge = np.zeros_like(weak_flat)
+ frontier = np.flatnonzero(np.pad(weak & (c > high), 1))
+ edge[frontier] = True
+ offsets = np.array([-pw - 1, -pw, -pw + 1, -1, 1, pw - 1, pw, pw + 1])
+ while frontier.size:
+ nb = (frontier[:, None] + offsets).ravel()
+ nb = np.unique(nb[weak_flat[nb] & ~edge[nb]])
+ edge[nb] = True
+ frontier = nb
+ return edge.reshape(h + 2, pw)[1:-1, 1:-1].astype(np.uint8) * 255
+
+
+def _png_b64(array: Any) -> str:
+ from PIL import Image
+
+ buf = io.BytesIO()
+ Image.fromarray(array).save(buf, format = "PNG", compress_level = 1)
+ return base64.b64encode(buf.getvalue()).decode("ascii")
+
+
+def control_frames(frames: list[Any]) -> list[Any]:
+ import numpy as np
+ return [np.repeat(canny_edges(np.asarray(f))[..., None], 3, axis = -1) for f in frames]
+
+
+def control_frames_b64(frames: list[Any]) -> list[str]:
+ return [_png_b64(edges) for edges in control_frames(frames)]
+
+
+def _jpeg_b64(array: Any) -> str:
+ from PIL import Image
+
+ buf = io.BytesIO()
+ Image.fromarray(array).save(buf, format = "JPEG", quality = 85)
+ return base64.b64encode(buf.getvalue()).decode("ascii")
+
+
+def preview(frames: list[Any], source_seconds: Optional[float] = None) -> dict[str, Any]:
+ import numpy as np
+
+ if not frames:
+ raise RestyleError("No frames found in the upload.")
+ count = snap_frame_count(len(frames))
+ frame = np.asarray(fit_frame(frames[count // 2]))
+ return {
+ "frames": count,
+ "seconds": count / float(FPS),
+ "source_seconds": source_seconds,
+ "width": WIDTH,
+ "height": HEIGHT,
+ "frame_jpeg": _jpeg_b64(frame),
+ "edges_jpeg": _jpeg_b64(control_frames([frame])[0]),
+ }
+
+
+# The progress line ``parse_progress`` reads; only an sd.cpp build with the Cosmos3 port prints it.
+_COSMOS3_MARKER = b"cosmos3: latent frame"
+_MARKER_CACHE: dict[tuple[str, int, int], bool] = {}
+
+
+def _file_has_marker(path: Path) -> bool:
+ import mmap
+ try:
+ stat = path.stat()
+ key = (str(path), stat.st_mtime_ns, stat.st_size)
+ if key not in _MARKER_CACHE:
+ with path.open("rb") as f, mmap.mmap(f.fileno(), 0, access = mmap.ACCESS_READ) as m:
+ _MARKER_CACHE[key] = m.find(_COSMOS3_MARKER) >= 0
+ return _MARKER_CACHE[key]
+ except (OSError, ValueError):
+ return False
+
+
+def binary_supports_cosmos3(binary: str) -> bool:
+ """The sd-server binary, or a stable-diffusion library next to it, carries the Cosmos3 port."""
+ path = Path(binary)
+ candidates = [
+ path,
+ *sorted(path.parent.glob("*stable-diffusion*")),
+ *sorted(path.parent.glob("libsd*")),
+ ]
+ return any(c.is_file() and _file_has_marker(c) for c in candidates)
+
+
+def availability(env: Optional[dict[str, str]] = None) -> dict[str, Any]:
+ try:
+ model_files(env)
+ except RestyleError:
+ return {
+ "available": False,
+ "reason": "The Cosmos3-Nano-Sim-Transfer weights are not set up on this machine.",
+ }
+ from core.inference.sd_cpp_engine import find_sd_server_binary
+
+ binary = find_sd_server_binary()
+ if not binary or not binary_supports_cosmos3(binary):
+ return {
+ "available": False,
+ "reason": "No stable-diffusion.cpp server with Cosmos3 support is installed.",
+ }
+ return {"available": True, "reason": None}
+
+
+def build_restyle_request(
+ *,
+ prompt: str,
+ control_frames: list[str],
+ seed: int,
+ width: int = WIDTH,
+ height: int = HEIGHT,
+ fps: int = FPS,
+) -> dict:
+ """POST body for sd-server ``/sdcpp/v1/vid_gen``; the sampler is fixed by the model, so no steps or CFG."""
+ if not (prompt or "").strip():
+ raise RestyleError("A prompt is required.")
+ frames = snap_frame_count(len(control_frames))
+ return {
+ "prompt": prompt.strip(),
+ "width": int(width),
+ "height": int(height),
+ "video_frames": frames,
+ "fps": int(fps),
+ "seed": int(seed),
+ "control_frames": list(control_frames[:frames]),
+ "output_format": "avi",
+ "output_compression": 90,
+ }
+
+
+def parse_progress(line: str) -> Optional[tuple[int, int]]:
+ match = _LATENT_RE.search(line)
+ return (int(match.group(1)), int(match.group(2))) if match else None
+
+
+def encode_mp4(frames: list[Any], fps: int = FPS) -> bytes:
+ import av
+ import numpy as np
+
+ buf = io.BytesIO()
+ with av.open(buf, mode = "w", format = "mp4") as dst:
+ stream = dst.add_stream("libx264", rate = fps)
+ stream.width = frames[0].width
+ stream.height = frames[0].height
+ stream.pix_fmt = "yuv420p"
+ for frame in frames:
+ for packet in stream.encode(
+ av.VideoFrame.from_ndarray(np.asarray(frame), format = "rgb24")
+ ):
+ dst.mux(packet)
+ for packet in stream.encode():
+ dst.mux(packet)
+ return buf.getvalue()
+
+
+def validate_request(prompt: str, frames: list[Any]) -> tuple[int, SdCppModelFiles]:
+ """Everything a start can refuse with 400, checked before the route takes the GPU."""
+ if not (prompt or "").strip():
+ raise RestyleError("A prompt is required.")
+ if not frames:
+ raise RestyleError("No frames found in the upload.")
+ return snap_frame_count(len(frames)), model_files()
+
+
+class RestyleRunner:
+ def __init__(self, server_factory: Optional[Callable[[str], Any]] = None) -> None:
+ self._lock = threading.Lock()
+ self._server: Any = None
+ self._server_files: Optional[SdCppModelFiles] = None
+ self._server_factory = server_factory
+ self._cancel = threading.Event()
+ self._state: dict[str, Any] = {"active": False, "phase": None}
+ self._owner: Optional[str] = None
+ self._workdir: Optional[Path] = None
+ self._loading: Any = None
+ self._stopping = 0
+ self._stopped = threading.Condition(self._lock)
+ # Set once the clip is being published; a cancel after that point is refused, not half-honoured.
+ self._publishing = False
+ # Held from before an upload is read until ``start``, so a second request is refused up front.
+ self._reservation: Optional[str] = None
+ self._reservation_owner: Optional[str] = None
+
+ def owned_by(self, owner: Optional[str]) -> bool:
+ return self._owner is not None and self._owner == owner
+
+ def progress(self, owner: Optional[str] = None) -> dict[str, Any]:
+ """Another account sees only whether the runner is busy, never the prompt's outputs."""
+ with self._lock:
+ state = self._state
+ pending = self._reservation is not None and (
+ owner is None or self._reservation_owner == owner
+ )
+ if owner is not None and not self.owned_by(owner):
+ return {"active": bool(state.get("active")), "phase": None, "pending": pending}
+ return {**state, "pending": pending}
+
+ def reserve(self, owner: Optional[str] = None) -> str:
+ with self._lock:
+ if self._state.get("active") or self._reservation is not None:
+ raise RestyleBusy("A restyle is already running.")
+ self._reservation = uuid.uuid4().hex
+ self._reservation_owner = owner
+ return self._reservation
+
+ def release(self, reservation: str) -> None:
+ with self._lock:
+ if self._reservation == reservation:
+ self._reservation = None
+
+ def _update(self, **fields: Any) -> None:
+ self._state = {**self._state, **fields}
+
+ def start(
+ self,
+ *,
+ prompt: str,
+ frames: list[Any],
+ seed: Optional[int] = None,
+ owner: Optional[str] = None,
+ reservation: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Validate and claim the runner; the caller runs ``run`` on a worker thread."""
+ count, files = validate_request(prompt, frames)
+ seed = (
+ int(seed) if seed is not None else int.from_bytes(os.urandom(4), "little") & 0x7FFFFFFF
+ )
+ from state import active_generations
+
+ with self._lock:
+ if owner is not None and active_generations.fenced(owner):
+ raise RestyleError("This account is being removed.")
+ if self._state.get("active") or self._reservation not in (None, reservation):
+ raise RestyleBusy("A restyle is already running.")
+ # Allocated before anything changes hands: a failure here leaves the old job and owner intact.
+ workdir = Path(tempfile.mkdtemp(prefix = "unsloth-restyle-"))
+ job_id = uuid.uuid4().hex
+ self._reservation = None
+ self._cancel.clear()
+ self._publishing = False
+ self._owner = owner
+ if self._workdir is not None:
+ shutil.rmtree(self._workdir, ignore_errors = True)
+ self._workdir = workdir
+ self._state = {
+ "active": True,
+ "id": job_id,
+ "phase": "edges",
+ "step": 0,
+ "total": (count - 1) // 4 + 1,
+ "num_frames": count,
+ "error": None,
+ "video": None,
+ "seed": seed,
+ "started_at": time.time(),
+ }
+ return {
+ "id": job_id,
+ "prompt": prompt.strip(),
+ "frames": [fit_frame(f) for f in frames[:count]],
+ "seed": seed,
+ "files": files,
+ }
+
+ def media_path(
+ self,
+ job_id: str,
+ kind: str,
+ owner: Optional[str] = None,
+ ) -> Optional[Path]:
+ with self._lock:
+ if kind not in MEDIA_KINDS or self._state.get("id") != job_id:
+ return None
+ if owner is not None and not self.owned_by(owner):
+ return None
+ path = self._workdir / f"{kind}.mp4" if self._workdir is not None else None
+ return path if path is not None and path.is_file() else None
+
+ def cancel(self, owner: Optional[str] = None) -> bool:
+ with self._lock:
+ if (
+ not self._state.get("active")
+ or self._publishing
+ or (owner is not None and not self.owned_by(owner))
+ ):
+ return False
+ self._cancel.set()
+ loading = self._loading
+ if loading is not None:
+ loading.stop()
+ return True
+
+ def retire(self, owner: str) -> bool:
+ """Cancel ``owner``'s job for account retirement; True while it still holds the runner.
+ A reservation of ``owner``'s is dropped; its request then meets the fence in ``start``."""
+ with self._lock:
+ if self._reservation is not None and self._reservation_owner == owner:
+ self._reservation = None
+ held = bool(self._state.get("active")) and self.owned_by(owner)
+ if held:
+ self.cancel(owner)
+ return held
+
+ def _finish(self, **fields: Any) -> None:
+ # The server is detached in the same step that ends the job: a restyle that claims the runner
+ # next can never reuse a server this worker is about to stop. Not kept resident either: an idle
+ # ~30 GB server would sit outside every other loader's VRAM accounting (stop() counts in holds_gpu).
+ with self._lock:
+ server = self._detach_locked()
+ self._update(active = False, **fields)
+ self._stop(server)
+ self._release_video_claim()
+
+ def _release_video_claim(self) -> None:
+ if self._server_factory is not None:
+ return
+ try:
+ from core.inference import gpu_arbiter
+ from core.inference.video import get_video_backend
+
+ video = get_video_backend()
+
+ def idle() -> bool:
+ return not (
+ self.holds_gpu() or video.loading_repo_ids() or video.status().get("loaded")
+ )
+
+ gpu_arbiter.release_if(gpu_arbiter.VIDEO, idle)
+ except Exception as exc: # noqa: BLE001 -- the job's outcome is already recorded
+ logger.warning("restyle: could not release the VIDEO claim: %s", exc)
+
+ def unload(self) -> None:
+ with self._lock:
+ server = self._detach_locked()
+ self._stop(server)
+
+ def _detach_locked(self) -> Any:
+ server, self._server, self._server_files = self._server, None, None
+ if server is not None:
+ self._stopping += 1
+ return server
+
+ def _stop(self, server: Any) -> None:
+ # Counted until stop() returns, so the managed tree stays pinned (is_alive) while the process exits.
+ if server is None:
+ return
+ try:
+ server.stop()
+ finally:
+ with self._lock:
+ self._stopping -= 1
+ self._stopped.notify_all()
+
+ def holds_gpu(self) -> bool:
+ """A job runs, a request is reserved to start one, or a detached server is still exiting."""
+ with self._lock:
+ return (
+ bool(self._state.get("active"))
+ or self._reservation is not None
+ or self._stopping > 0
+ )
+
+ def unload_if_idle(self, owner: Optional[str] = None) -> bool:
+ """Detach the server under the same lock ``start`` claims, so a restyle can't begin in between.
+ A reservation counts as busy: that request is about to reuse the server. With ``owner``, only
+ a server whose last job was ``owner``'s is detached (RestyleBusy otherwise)."""
+ with self._lock:
+ if self._state.get("active") or self._reservation is not None:
+ return False
+ if owner is not None and self._server is not None and not self.owned_by(owner):
+ raise RestyleBusy("Another account's restyle model is loaded.")
+ server = self._detach_locked()
+ self._stop(server)
+ with self._lock:
+ self._stopped.wait_for(lambda: self._stopping == 0, timeout = 120)
+ return True
+
+ def is_alive(self) -> bool:
+ server = self._server
+ return (
+ (server is not None and server.is_alive())
+ or self._loading is not None
+ or self._stopping > 0
+ )
+
+ def _tree_lease(self) -> Any:
+ if self._server_factory is not None:
+ return contextlib.nullcontext()
+ from core.inference.sd_cpp_backend import _tree_reader
+ from core.inference.sd_cpp_engine import find_sd_server_binary
+
+ return _tree_reader(find_sd_server_binary(), self._cancel, "cancelled")
+
+ def _ensure_server(self, files: SdCppModelFiles) -> Any:
+ if self._server is not None and self._server_files == files and self._server.is_alive():
+ return self._server
+ self.unload()
+ # A server another caller detached may still hold its VRAM: never launch beside it.
+ with self._lock:
+ self._stopped.wait_for(lambda: self._stopping == 0, timeout = 120)
+ if self._server_factory is not None:
+ server = self._server_factory(files.diffusion_model)
+ else:
+ from core.inference.sd_cpp_engine import find_sd_server_binary
+ from core.inference.sd_cpp_server import SdCppServer
+
+ binary = find_sd_server_binary()
+ if not binary:
+ raise RestyleError(
+ "No sd-server binary found. Point SD_SERVER_PATH at a stable-diffusion.cpp "
+ "build with Cosmos3 support."
+ )
+ server = SdCppServer(binary)
+ from core.inference.sd_cpp_backend import register_tree_holder
+ from core.inference.sd_cpp_engine import is_managed_binary
+
+ if is_managed_binary(binary):
+ # A resident server pins Studio's managed sd.cpp tree: an upgrade waits (is_alive).
+ register_tree_holder(self)
+ self._update(phase = "loading")
+ self._loading = server
+ try:
+ if self._cancel.is_set():
+ server.stop()
+ server.start(files)
+ finally:
+ self._loading = None
+ self._server, self._server_files = server, files
+ return server
+
+ def run(
+ self,
+ job: dict[str, Any],
+ save: Optional[Callable[[bytes, dict], Any]] = None,
+ ) -> None:
+ """Worker body; every outcome lands in the progress state, nothing is raised."""
+ from PIL import Image
+
+ from core.inference.sd_cpp_engine import SdCppCancelled
+ from core.inference.video_minimax_h3 import transcode_video_to_mp4
+
+ workdir = self._workdir
+ frames = job["frames"]
+ lease = contextlib.ExitStack()
+ try:
+ assert workdir is not None
+ (workdir / "input.mp4").write_bytes(encode_mp4(frames))
+ edges = control_frames(frames)
+ (workdir / "control.mp4").write_bytes(encode_mp4([Image.fromarray(e) for e in edges]))
+ control = [_png_b64(e) for e in edges]
+ if self._cancel.is_set():
+ raise SdCppCancelled("cancelled")
+ payload = build_restyle_request(
+ prompt = job["prompt"], control_frames = control, seed = job["seed"]
+ )
+ lease.enter_context(self._tree_lease())
+ server = self._ensure_server(job["files"])
+ self._update(phase = "generate")
+ first: list[float] = []
+
+ def on_line(line: str) -> None:
+ hit = parse_progress(line)
+ if hit is not None:
+ done, total = hit
+ now = time.monotonic()
+ if not first:
+ first.append(now)
+ eta = (now - first[0]) / (done - 1) * (total - done) if done > 1 else None
+ self._update(step = done, total = total, eta_seconds = eta)
+ elif _DECODE_RE.search(line):
+ self._update(phase = "decode", eta_seconds = None)
+
+ avi = server.vid_gen(payload, on_step = on_line, cancel_event = self._cancel)
+ lease.close()
+ self._update(phase = "export", eta_seconds = None)
+ raw = workdir / "output.avi"
+ raw.write_bytes(avi)
+ mp4 = transcode_video_to_mp4(raw, fps = FPS)
+ raw.unlink(missing_ok = True)
+ with self._lock:
+ if self._cancel.is_set():
+ raise SdCppCancelled("cancelled")
+ self._publishing = True
+ (workdir / "output.mp4").write_bytes(mp4)
+ record = None
+ if save is not None:
+ count = payload["video_frames"]
+ record = save(
+ mp4,
+ {
+ "prompt": job["prompt"],
+ "negative_prompt": None,
+ "width": WIDTH,
+ "height": HEIGHT,
+ "num_frames": count,
+ "fps": FPS,
+ "duration_s": count / float(FPS),
+ "steps": 4,
+ "guidance": 1.0,
+ "seed": job["seed"],
+ "has_audio": False,
+ "conditioning": "restyle",
+ "model": MODEL_ID,
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ },
+ )
+ self._finish(phase = "done", video = record)
+ except SdCppCancelled:
+ self._finish(phase = "cancelled")
+ except Exception as exc: # noqa: BLE001 -- surfaced through progress
+ if self._cancel.is_set():
+ self._finish(phase = "cancelled")
+ else:
+ logger.warning("restyle failed: %s", exc)
+ self._finish(phase = "error", error = str(exc))
+ finally:
+ lease.close()
+
+
+runner = RestyleRunner()
+
+
+def generation_in_flight() -> bool:
+ """For the desktop watchdog's busy budget; a lock-free read, like the other media modules'."""
+ return bool(runner._state.get("active"))
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 917f40a106a..4c0fd860aa3 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -467,6 +467,7 @@ from routes.llama import router as llama_router
from routes.engines import router as engines_router
from routes.llama_compat import is_engine_probe_path, router as llama_compat_router
from routes.whisper import router as whisper_router
+from routes.video_restyle import router as video_restyle_router
from routes.npu import router as npu_router
from routes.preview import router as preview_router
from hub.routes import (
@@ -1601,6 +1602,7 @@ from utils.upload_limits import ( # noqa: E402
UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,
VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,
VIDEO_INPUT_REFERENCE_MAX_BYTES,
+ VIDEO_RESTYLE_UPLOAD_MAX_BYTES,
audio_input_max_bytes,
default_request_body_limit_bytes,
upload_request_limit_bytes,
@@ -1653,6 +1655,10 @@ _VIDEO_MULTIPART_UPLOAD_PATHS = (
"/api/inference/videos",
)
_LIBRARY_UPLOAD_PATH = "/api/library/uploads"
+_VIDEO_RESTYLE_UPLOAD_PATHS = (
+ "/api/inference/video/restyle",
+ "/api/inference/video/restyle/preview",
+)
# RAG document uploads (knowledge base, thread, project, extract-text): multipart, capped by RAG_MAX_UPLOAD_BYTES in the route and
# spooled by FastAPI, so they pass through on Content-Length instead of being held in memory here.
_RAG_DOCUMENT_UPLOAD_RE = _re.compile(
@@ -1676,6 +1682,7 @@ _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (
*_STT_MULTIPART_UPLOAD_PATHS,
*_VIDEO_MULTIPART_UPLOAD_PATHS,
_LIBRARY_UPLOAD_PATH,
+ *_VIDEO_RESTYLE_UPLOAD_PATHS,
_OPENAI_FILES_UPLOAD_PATH,
)
# Runs before auth, so only small bounded uploads may omit Content-Length; others keep 411.
@@ -1694,6 +1701,8 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:
)
if path.rstrip("/") == _LIBRARY_UPLOAD_PATH:
return upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)
+ if path.rstrip("/") in _VIDEO_RESTYLE_UPLOAD_PATHS:
+ return upload_request_limit_bytes(VIDEO_RESTYLE_UPLOAD_MAX_BYTES)
if path.rstrip("/") in _AUDIO_INPUT_UPLOAD_PATHS:
# None means no cap, as the route treats it.
cap = audio_input_max_bytes()
@@ -2103,6 +2112,7 @@ app.include_router(inference_studio_router, prefix = "/api/inference", tags = ["
# Unsloth-only text-to-video endpoints; not exposed on the /v1 OpenAI-compat prefix.
app.include_router(video_router, prefix = "/api/inference", tags = ["inference"])
app.include_router(video_openai_router, prefix = "/api/inference", tags = ["inference"])
+app.include_router(video_restyle_router, prefix = "/api/inference", tags = ["inference"])
app.include_router(video_openai_router, prefix = "/v1", tags = ["openai-compat"])
app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])
@@ -2264,6 +2274,7 @@ def _torch_warm_in_progress() -> bool:
# generation_in_flight() modules: engines cover renders; routes.inference covers image persistence.
_MEDIA_BACKEND_MODULES = (
"core.inference.video",
+ "core.inference.video_restyle",
"core.inference.diffusion",
"core.inference.sd_cpp_backend",
"core.inference.mlx_diffusion_backend",
diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.py
index c014e7bb04e..bccc4335f40 100644
--- a/studio/backend/routes/accounts.py
+++ b/studio/backend/routes/accounts.py
@@ -86,7 +86,10 @@ def retire_account_roots(account: AccountContext):
retire_account_image_jobs(account.account_id)
image_active = cancel_generation_for_account(account.account_id)
- if video_active or image_active:
+ from core.inference import video_restyle
+
+ restyle_active = video_restyle.runner.retire(account.account_id)
+ if video_active or image_active or restyle_active:
raise AccountRetirementError("Media generation is still active; retry deletion")
# A load the account started before its tombstone is torn down here; one after it is refused.
from core.inference import video as video_module
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index a0113020602..5e99e375b9f 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2471,6 +2471,7 @@ async def start_training(
except Exception as e:
logger.warning("Could not unload diffusion model for training: %s", e)
+ _free_restyle_for_training()
try:
# Video pipelines load under the VIDEO arbiter owner; tear down too. Must precede the chat block.
from core.inference import gpu_arbiter
@@ -3530,6 +3531,22 @@ def diffusion_dataset_interlock():
raise HTTPException(status_code = 409, detail = str(exc)) from exc
+def _free_restyle_for_training() -> None:
+ """The restyle sd-server sits outside the arbiter's owners; a running restyle refuses the start."""
+ from core.inference import video_restyle
+ from routes.training_vram import ManagedEngineStillRunning
+
+ try:
+ idle = video_restyle.runner.unload_if_idle()
+ except Exception as e: # noqa: BLE001
+ logger.warning("Could not unload the video restyle server for training: %s", e)
+ return
+ if not idle:
+ raise ManagedEngineStillRunning(
+ "A video restyle is running. Cancel it or wait for it to finish."
+ )
+
+
def _free_gpu_for_diffusion_training() -> None:
"""Frees resident GPU models first; the trainer's SDXL pipeline would OOM beside them."""
try:
@@ -3565,6 +3582,7 @@ def _free_gpu_for_diffusion_training() -> None:
except Exception as e: # noqa: BLE001
logger.warning("Could not unload Images pipeline for diffusion training: %s", e)
+ _free_restyle_for_training()
try:
from core.inference import gpu_arbiter
from core.inference.video import get_video_backend
diff --git a/studio/backend/routes/video_restyle.py b/studio/backend/routes/video_restyle.py
new file mode 100644
index 00000000000..7aa097c1813
--- /dev/null
+++ b/studio/backend/routes/video_restyle.py
@@ -0,0 +1,246 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Video restyle routes (Cosmos3-Nano-Sim-Transfer on sd-server)."""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+from typing import Any, Optional
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from fastapi.responses import FileResponse
+from starlette.datastructures import UploadFile
+
+from auth.authentication import get_current_subject
+from core.inference import gpu_arbiter
+from core.inference.chat_swap_kv import acquire_then_close, save_chat_kv_before_swap
+from core.inference import video_restyle
+from core.inference.video_restyle import RestyleBusy, RestyleError
+from hub.services.models import account_access
+from state import active_generations
+from utils.account_context import account_thread, current_account_id
+from utils.multi_model_settings import get_multi_model_mode
+from utils.upload_limits import VIDEO_RESTYLE_UPLOAD_MAX_BYTES
+
+router = APIRouter()
+
+
+def _save_to_gallery(mp4: bytes, meta: dict) -> Optional[dict]:
+ from core.inference import video_gallery
+ try:
+ return video_gallery.save(mp4, meta)
+ except Exception: # noqa: BLE001 -- the clip is still served from the job dir
+ return None
+
+
+async def _read_upload(request: Request) -> tuple[dict[str, Any], list[tuple[str, bytes]]]:
+ try:
+ form = await request.form(max_files = video_restyle.MAX_FRAMES + 8)
+ except Exception: # noqa: BLE001
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Send one clip or at most {video_restyle.MAX_FRAMES} frames as multipart/form-data.",
+ )
+ fields = {key: form.get(key) for key in ("prompt", "seed") if isinstance(form.get(key), str)}
+ uploads = [
+ (name, value)
+ for name, value in form.multi_items()
+ if name in ("video", "frames") and isinstance(value, UploadFile)
+ ]
+ if sum(value.size or 0 for _, value in uploads) > VIDEO_RESTYLE_UPLOAD_MAX_BYTES:
+ raise HTTPException(status_code = 413, detail = "The upload is too large.")
+ files = [(name + ":" + (value.filename or ""), await value.read()) for name, value in uploads]
+ return fields, files
+
+
+async def _frames_from_upload(files: list[tuple[str, bytes]]) -> tuple[list[Any], Optional[float]]:
+ videos = [data for name, data in files if name.startswith("video:")]
+ frames_in = [
+ (name.split(":", 1)[1], data) for name, data in files if name.startswith("frames:")
+ ]
+ if len(videos) == 1 and not frames_in:
+ frames = await asyncio.to_thread(video_restyle.frames_from_video, videos[0])
+ return frames, await asyncio.to_thread(video_restyle.video_seconds, videos[0])
+ if frames_in and not videos:
+ return await asyncio.to_thread(video_restyle.frames_from_images, frames_in), None
+ raise RestyleError("Send one video file or a folder of frames.")
+
+
[email protected]("/video/restyle/status")
+async def restyle_status(current_subject: str = Depends(get_current_subject)):
+ return await asyncio.to_thread(video_restyle.availability)
+
+
[email protected]("/video/restyle/preview")
+async def preview_restyle(request: Request, current_subject: str = Depends(get_current_subject)):
+ _, files = await _read_upload(request)
+ try:
+ frames, seconds = await _frames_from_upload(files)
+ return await asyncio.to_thread(video_restyle.preview, frames, seconds)
+ except RestyleError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc))
+
+
[email protected]("/video/restyle")
+async def start_restyle(request: Request, current_subject: str = Depends(get_current_subject)):
+ if account_access.managed_account():
+ await asyncio.to_thread(account_access.require_model_allowed, video_restyle.MODEL_ID)
+ try:
+ reservation = video_restyle.runner.reserve(current_account_id())
+ except RestyleBusy as exc:
+ raise HTTPException(status_code = 409, detail = str(exc))
+ # Released here until the shielded start takes it over, which then releases it itself:
+ # a cancelled request must not free a reservation that start() is still about to use.
+ lease = {"route": True}
+ try:
+ return await _start_reserved(request, reservation, lease)
+ finally:
+ if lease["route"]:
+ video_restyle.runner.release(reservation)
+
+
+def _admit_and_start(**kwargs: Any) -> dict[str, Any]:
+ # Same interlock as a video load: refuse beside training, and hold the training admission while
+ # the runner turns active so a training start in between sees it and refuses.
+ from core.training.diffusion_training_service import TrainingActiveError
+ from routes.inference import _diffusion_training_admission
+ from routes.video import _guard_video_load_against_training
+
+ mode = kwargs.pop("mode", None)
+ try:
+ with _diffusion_training_admission():
+ _guard_video_load_against_training()
+ _take_the_gpu(mode)
+ job = video_restyle.runner.start(**kwargs)
+ except TrainingActiveError as exc:
+ raise HTTPException(status_code = 409, detail = f"{exc} Try again when it finishes.")
+ finally:
+ video_restyle.runner.release(kwargs.get("reservation"))
+ # Launched here, inside the shielded call: a request cancelled after start() must not leave
+ # an active runner with no worker.
+ account_thread(
+ target = video_restyle.runner.run,
+ args = (job, _save_to_gallery),
+ daemon = True,
+ name = "video-restyle",
+ ).start()
+ return job
+
+
+def _take_the_gpu(mode: Optional[str] = None) -> None:
+ # The restyle sd-server (~30 GB) is a video workload: chat and image models go through the
+ # arbiter's eviction; the Create video model, which shares the VIDEO owner, is checked in ``admit``
+ # (under the arbiter lock, so a Create load cannot register in between) and unloaded in
+ # ``register``, which runs only once every other refusal has passed.
+ from core.inference import gpu_arbiter
+ from core.inference.video import generation_account_in_flight, get_video_backend
+ from utils.multi_model_settings import get_multi_model_mode
+
+ if mode is None:
+ mode = get_multi_model_mode()
+ video = get_video_backend()
+
+ def admit() -> None:
+ if video.loading_repo_ids():
+ raise HTTPException(
+ status_code = 409, detail = "A video model is loading. Try again when it finishes."
+ )
+ if not video.status().get("loaded"):
+ return
+ if generation_account_in_flight() is not None:
+ raise HTTPException(
+ status_code = 409, detail = "A video is generating. Try again when it finishes."
+ )
+ if mode == "always":
+ raise HTTPException(
+ status_code = 409,
+ detail = "Unload the Create video model first: Keep multiple models loaded is set to Always.",
+ )
+
+ def register() -> None:
+ if video.status().get("loaded"):
+ video.unload()
+
+ handoff = gpu_arbiter.restyle_handoff.set(True)
+ try:
+ gpu_arbiter.acquire_for_request(gpu_arbiter.VIDEO, register, policy = mode, admit = admit)
+ except gpu_arbiter.MultiModelAlwaysRefusal as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ finally:
+ gpu_arbiter.restyle_handoff.reset(handoff)
+
+
+async def _start_reserved(request: Request, reservation: str, lease: dict):
+ fields, files = await _read_upload(request)
+ seed: Optional[int] = None
+ if fields.get("seed"):
+ try:
+ seed = int(fields["seed"])
+ except ValueError:
+ raise HTTPException(status_code = 400, detail = "seed must be an integer.")
+ try:
+ frames, _ = await _frames_from_upload(files)
+ prompt, owner = fields.get("prompt") or "", current_account_id()
+ if owner is not None and active_generations.fenced(owner):
+ raise HTTPException(status_code = 403, detail = "This account is being removed.")
+ await asyncio.to_thread(video_restyle.validate_request, prompt, frames)
+ mode = await asyncio.to_thread(get_multi_model_mode)
+ swap = await save_chat_kv_before_swap(gpu_arbiter.VIDEO, "video", policy = mode)
+ lease["route"] = False
+ job = await acquire_then_close(
+ swap,
+ functools.partial(
+ _admit_and_start,
+ mode = mode,
+ prompt = prompt,
+ frames = frames,
+ seed = seed,
+ owner = owner,
+ reservation = reservation,
+ ),
+ )
+ except RestyleBusy as exc:
+ raise HTTPException(status_code = 409, detail = str(exc))
+ except RestyleError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc))
+ return video_restyle.runner.progress(current_account_id())
+
+
[email protected]("/video/restyle/progress")
+async def restyle_progress(current_subject: str = Depends(get_current_subject)):
+ return video_restyle.runner.progress(current_account_id())
+
+
[email protected]("/video/restyle/cancel")
+async def cancel_restyle(current_subject: str = Depends(get_current_subject)):
+ return {"cancelled": await asyncio.to_thread(video_restyle.runner.cancel, current_account_id())}
+
+
[email protected]("/video/restyle/unload")
+async def unload_restyle(current_subject: str = Depends(get_current_subject)):
+ # A managed account may only unload a server its own last job loaded (as video unload checks).
+ owner = None
+ if account_access.managed_account():
+ await asyncio.to_thread(account_access.require_model_allowed, video_restyle.MODEL_ID)
+ owner = current_account_id()
+ try:
+ unloaded = await asyncio.to_thread(video_restyle.runner.unload_if_idle, owner)
+ except RestyleBusy as exc:
+ raise HTTPException(status_code = 403, detail = str(exc))
+ if not unloaded:
+ raise HTTPException(status_code = 409, detail = "A restyle is running.")
+ return {"unloaded": True}
+
+
[email protected]("/video/restyle/{job_id}/{kind}.mp4")
+async def restyle_media(
+ job_id: str,
+ kind: str,
+ current_subject: str = Depends(get_current_subject),
+):
+ path = video_restyle.runner.media_path(job_id, kind, current_account_id())
+ if path is None:
+ raise HTTPException(status_code = 404, detail = "Not found.")
+ return FileResponse(path, media_type = "video/mp4")
diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.py
index f4ba89180ab..d4c4503d6a4 100644
--- a/studio/backend/tests/multi_account/factories_media.py
+++ b/studio/backend/tests/multi_account/factories_media.py
@@ -521,4 +521,9 @@ SKIPPED = {
"routes.npu:DELETE:/models/{model_id}": _NPU_INSTALLATION_MODEL,
"routes.npu:POST:/models/{model_id}/download": _NPU_INSTALLATION_MODEL,
"routes.npu:GET:/models/{model_id}/download": _NPU_INSTALLATION_MODEL,
+ "routes.video_restyle:GET:/video/restyle/{job_id}/{kind}.mp4": (
+ "serves the in-memory restyle runner's current job, not a stored object, so there is "
+ "nothing to seed; media_path answers only the job's own account "
+ "(test_runner_hides_another_accounts_job)"
+ ),
}
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index 35067d45675..0714ae3e672 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -807,6 +807,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):
whisper_module.router = APIRouter()
npu_module = ModuleType("routes.npu")
npu_module.router = APIRouter()
+ video_restyle_module = ModuleType("routes.video_restyle")
+ video_restyle_module.router = APIRouter()
profile_stats_module = ModuleType("routes.profile_stats")
profile_stats_module.router = APIRouter()
accounts_module = ModuleType("routes.accounts")
@@ -848,6 +850,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):
monkeypatch.setitem(sys.modules, "routes.preview", preview_module)
monkeypatch.setitem(sys.modules, "routes.whisper", whisper_module)
monkeypatch.setitem(sys.modules, "routes.npu", npu_module)
+ monkeypatch.setitem(sys.modules, "routes.video_restyle", video_restyle_module)
monkeypatch.setitem(sys.modules, "routes.profile_stats", profile_stats_module)
monkeypatch.setitem(sys.modules, "routes.accounts", accounts_module)
monkeypatch.setitem(sys.modules, "routes.library", library_module)
diff --git a/studio/backend/tests/test_liveness_reports_inference_active.py b/studio/backend/tests/test_liveness_reports_inference_active.py
index b8232a25b81..4bcc628112b 100644
--- a/studio/backend/tests/test_liveness_reports_inference_active.py
+++ b/studio/backend/tests/test_liveness_reports_inference_active.py
@@ -90,15 +90,18 @@ idle_after = probe()
# Keep this independent of main._MEDIA_BACKEND_MODULES so omissions are detected.
media_modules = (
"core.inference.video",
+ "core.inference.video_restyle",
"core.inference.diffusion",
"core.inference.sd_cpp_backend",
"core.inference.mlx_diffusion_backend",
"routes.inference",
)
-# routes.inference is imported at startup regardless, so the ML-stack question is only
-# about the three engines.
+# routes.inference and the import-light restyle module load at startup regardless, so the
+# ML-stack question is only about the three engines.
media_import_free = [
- name for name in media_modules if name.startswith("core.") and name in sys.modules
+ name
+ for name in media_modules
+ if name.startswith("core.") and name != "core.inference.video_restyle" and name in sys.modules
]
scanned = list(getattr(main, "_MEDIA_BACKEND_MODULES", ()) or ())
diff --git a/studio/backend/tests/test_video_restyle.py b/studio/backend/tests/test_video_restyle.py
new file mode 100644
index 00000000000..38084edba67
--- /dev/null
+++ b/studio/backend/tests/test_video_restyle.py
@@ -0,0 +1,1254 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic: the restyle workflow's frame prep, Canny control, request body and runner; sd-server is faked."""
+
+from __future__ import annotations
+
+import base64
+import io
+import threading
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from core.inference import video_restyle as vr
+
+
+def weights(tmp_path, monkeypatch):
+ model = tmp_path / "cosmos3.safetensors"
+ vae = tmp_path / "wan2.2_vae.safetensors"
+ model.write_bytes(b"x")
+ vae.write_bytes(b"x")
+ monkeypatch.setenv(vr.MODEL_ENV, str(model))
+ monkeypatch.setenv(vr.VAE_ENV, str(vae))
+ return model, vae
+
+
+ "count, expected", [(5, 5), (8, 5), (9, 9), (120, 117), (121, 121), (400, 121)]
+)
+def test_snap_frame_count(count, expected):
+ assert vr.snap_frame_count(count) == expected
+
+
+def test_snap_frame_count_refuses_short_clip():
+ with pytest.raises(vr.RestyleError):
+ vr.snap_frame_count(4)
+
+
+def test_model_files_names_missing_env(monkeypatch):
+ monkeypatch.delenv(vr.MODEL_ENV, raising = False)
+ monkeypatch.delenv(vr.VAE_ENV, raising = False)
+ with pytest.raises(vr.RestyleError, match = vr.MODEL_ENV):
+ vr.model_files()
+
+
+def test_model_files_from_env(weights):
+ files = vr.model_files()
+ assert files.diffusion_model == str(weights[0])
+ assert files.vae == str(weights[1])
+
+
+def test_build_restyle_request_trims_to_4n_plus_1():
+ req = vr.build_restyle_request(prompt = " red rally car ", control_frames = ["f"] * 12, seed = 7)
+ assert req["video_frames"] == 9
+ assert len(req["control_frames"]) == 9
+ assert req["prompt"] == "red rally car"
+ assert (req["width"], req["height"], req["fps"], req["seed"]) == (832, 480, 30, 7)
+ assert req["output_format"] == "avi"
+ # The distilled sampler is fixed inside sd.cpp.
+ assert "sample_params" not in req
+
+
+def test_build_restyle_request_needs_prompt():
+ with pytest.raises(vr.RestyleError):
+ vr.build_restyle_request(prompt = " ", control_frames = ["f"] * 5, seed = 0)
+
+
+def test_parse_progress():
+ assert vr.parse_progress(
+ "[INFO ] cosmos3_transfer.cpp:354 - cosmos3: latent frame 3/31 in 512 ms"
+ ) == (3, 31)
+ assert vr.parse_progress("cosmos3: control video encoded to 31x60x104 latents") is None
+
+
+def test_canny_flat_image_has_no_edges():
+ assert vr.canny_edges(np.full((40, 60, 3), 128, np.uint8)).max() == 0
+
+
+def test_canny_step_edge_is_one_thin_line():
+ img = np.zeros((40, 60, 3), np.uint8)
+ img[:, 30:] = 255
+ edges = vr.canny_edges(img)
+ cols = np.flatnonzero(edges.any(axis = 0))
+ assert edges.dtype == np.uint8 and set(np.unique(edges)) == {0, 255}
+ assert len(cols) == 1 and cols[0] in (29, 30)
+ assert edges[:, cols[0]].all()
+
+
+def test_canny_hysteresis_keeps_weak_only_when_connected():
+ # Left half: strong step joined to a weak step (kept). Right: an isolated weak step (dropped).
+ img = np.zeros((40, 80), np.uint8)
+ img[:, 20:] = 40 # |dx| + |dy| = 160 on the line: weak (100..200)
+ img[:20, 20:40] = 200 # strong part of the same line
+ img[:, 60:] = 80 # isolated weak step at x=60
+ edges = vr.canny_edges(np.repeat(img[..., None], 3, -1))
+ assert edges[30, 19:21].any() # weak part, connected
+ assert not edges[:, 58:62].any()
+
+
+def test_fit_frame_covers_target():
+ out = vr.fit_frame(Image.new("RGB", (1920, 1080)))
+ assert out.size == (vr.WIDTH, vr.HEIGHT)
+ out = vr.fit_frame(Image.new("RGB", (300, 600)))
+ assert out.size == (vr.WIDTH, vr.HEIGHT)
+
+
+def _png(color):
+ buf = io.BytesIO()
+ Image.new("RGB", (8, 8), color).save(buf, format = "PNG")
+ return buf.getvalue()
+
+
+def test_frames_from_images_sorted_and_filtered():
+ items = [("b/002.png", _png("blue")), ("b/notes.txt", b"hi"), ("b/001.png", _png("red"))]
+ frames = vr.frames_from_images(items)
+ assert [f.getpixel((0, 0)) for f in frames] == [(255, 0, 0), (0, 0, 255)]
+
+
+def _clip(fps, count):
+ import av
+
+ buf = io.BytesIO()
+ with av.open(buf, mode = "w", format = "mp4") as dst:
+ stream = dst.add_stream("libx264", rate = fps)
+ stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"
+ for i in range(count):
+ frame = np.full((48, 64, 3), (i * 10) % 256, np.uint8)
+ for packet in stream.encode(av.VideoFrame.from_ndarray(frame, format = "rgb24")):
+ dst.mux(packet)
+ for packet in stream.encode():
+ dst.mux(packet)
+ return buf.getvalue()
+
+
[email protected]("fps, count, expected", [(30, 20, 20), (60, 40, 20), (15, 10, 19)])
+def test_frames_from_video_resamples_to_30fps(fps, count, expected):
+ frames = vr.frames_from_video(_clip(fps, count))
+ assert abs(len(frames) - expected) <= 1
+
+
+def test_frames_from_video_caps_length():
+ assert len(vr.frames_from_video(_clip(30, 140))) == vr.MAX_FRAMES
+
+
+def test_frames_from_video_rejects_garbage():
+ with pytest.raises(vr.RestyleError):
+ vr.frames_from_video(b"not a video")
+
+
+class _FakeServer:
+ def __init__(
+ self,
+ avi,
+ *,
+ fail = None,
+ ):
+ self.avi = avi
+ self.fail = fail
+ self.started = 0
+ self.payloads = []
+
+ def is_alive(self):
+ return True
+
+ def start(self, files):
+ self.started += 1
+
+ def stop(self):
+ pass
+
+ def vid_gen(
+ self,
+ payload,
+ *,
+ on_step = None,
+ cancel_event = None,
+ ):
+ self.payloads.append(payload)
+ if self.fail is not None:
+ raise self.fail
+ for t in range(1, 3):
+ on_step(f"cosmos3: latent frame {t}/2 in 500 ms")
+ on_step("cosmos3: 2 latent frames in 1.00s (500.0 ms per latent frame)")
+ return self.avi
+
+
+def _frames(n):
+ return [Image.new("RGB", (64, 48), (i * 20 % 256, 0, 0)) for i in range(n)]
+
+
+def test_runner_end_to_end_with_fake_server(weights, monkeypatch):
+ server = _FakeServer(b"AVI")
+ runner = vr.RestyleRunner(server_factory = lambda _model: server)
+ monkeypatch.setattr(
+ "core.inference.video_minimax_h3.transcode_video_to_mp4",
+ lambda path, fps: b"MP4:" + path.read_bytes(),
+ )
+ saved = []
+ job = runner.start(prompt = "red car", frames = _frames(7), seed = 3)
+ assert runner.progress()["active"] and runner.progress()["total"] == 2
+ with pytest.raises(vr.RestyleBusy):
+ runner.start(prompt = "again", frames = _frames(5))
+ runner.run(job, save = lambda mp4, meta: saved.append((mp4, meta)) or {"id": "v1"})
+
+ state = runner.progress()
+ assert state["phase"] == "done" and not state["active"]
+ assert (state["step"], state["total"]) == (2, 2)
+ assert state["eta_seconds"] is None # cleared once decoding starts
+ assert state["video"] == {"id": "v1"}
+ payload = server.payloads[0]
+ assert payload["video_frames"] == 5 and len(payload["control_frames"]) == 5
+ control = Image.open(io.BytesIO(base64.b64decode(payload["control_frames"][0])))
+ assert control.size == (vr.WIDTH, vr.HEIGHT) and control.mode == "RGB"
+ assert saved[0][0] == b"MP4:AVI" and saved[0][1]["model"] == vr.MODEL_ID
+ # The gallery lists only sidecars its own model accepts.
+ from core.inference import video_gallery
+ from models.inference import GalleryVideo
+
+ assert all(k in saved[0][1] for k in video_gallery._REQUIRED_META)
+ GalleryVideo(id = "v1", url = "/x", **saved[0][1])
+ assert state["seed"] == 3
+ for kind in ("input", "control", "output"):
+ assert runner.media_path(state["id"], kind) is not None
+ assert runner.media_path("other", "output") is None
+ # The server is stopped when the job ends, so nothing idle holds VRAM between restyles.
+ assert runner._server is None and not runner.holds_gpu()
+ runner.run(runner.start(prompt = "blue car", frames = _frames(5)))
+ assert server.started == 2 and runner._server is None
+
+
+def test_runner_reports_failure(weights):
+ runner = vr.RestyleRunner(
+ server_factory = lambda _model: _FakeServer(b"", fail = RuntimeError("boom"))
+ )
+ runner.run(runner.start(prompt = "x", frames = _frames(5)))
+ state = runner.progress()
+ assert state["phase"] == "error" and "boom" in state["error"] and not state["active"]
+
+
+def test_runner_cancel_before_generate(weights):
+ server = _FakeServer(b"AVI")
+ runner = vr.RestyleRunner(server_factory = lambda _model: server)
+ job = runner.start(prompt = "x", frames = _frames(5))
+ assert runner.cancel()
+ runner.run(job)
+ assert runner.progress()["phase"] == "cancelled"
+ assert server.payloads == []
+
+
+def test_runner_start_needs_weights(monkeypatch):
+ monkeypatch.delenv(vr.MODEL_ENV, raising = False)
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b""))
+ with pytest.raises(vr.RestyleError):
+ runner.start(prompt = "x", frames = _frames(5))
+ assert not runner.progress()["active"]
+
+
+def test_route_rejects_mixed_upload(weights, monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from routes import video_restyle as route
+
+ app = FastAPI()
+ app.include_router(route.router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "owner"
+ client = TestClient(app)
+ files = [
+ ("video", ("a.mp4", b"x", "video/mp4")),
+ ("frames", ("001.png", _png("red"), "image/png")),
+ ]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": "x"}, files = files)
+ assert res.status_code == 400
+ res = client.post(
+ "/api/inference/video/restyle", data = {"prompt": "x", "seed": "abc"}, files = files[1:]
+ )
+ assert res.status_code == 400
+ assert client.get("/api/inference/video/restyle/nope/output.mp4").status_code == 404
+
+
+def test_runner_hides_another_accounts_job(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ job = runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+ assert runner.progress("bob") == {"active": True, "phase": None, "pending": False}
+ assert not runner.cancel("bob")
+ assert runner.progress("alice")["id"] == job["id"]
+ assert runner.cancel("alice")
+
+
+def test_cancel_aborts_a_loading_server(weights):
+ started = threading.Event()
+ released = threading.Event()
+
+ class _SlowServer(_FakeServer):
+ def start(self, files):
+ started.set()
+ assert released.wait(5)
+ raise vr_cancelled("startup cancelled")
+
+ def stop(self):
+ released.set()
+
+ from core.inference.sd_cpp_engine import SdCppCancelled as vr_cancelled
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _SlowServer(b""))
+ job = runner.start(prompt = "x", frames = _frames(5))
+ worker = threading.Thread(target = runner.run, args = (job,))
+ worker.start()
+ assert started.wait(5)
+ assert runner.progress()["phase"] == "loading"
+ assert runner.cancel()
+ assert released.is_set() # the cancel stopped the load itself
+ worker.join(5)
+ assert runner.progress()["phase"] == "cancelled"
+
+
+def test_cancel_during_export_publishes_nothing(weights, monkeypatch):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+
+ def transcode(path, fps):
+ assert runner.cancel()
+ return b"MP4"
+
+ monkeypatch.setattr("core.inference.video_minimax_h3.transcode_video_to_mp4", transcode)
+ saved = []
+ job = runner.start(prompt = "x", frames = _frames(5))
+ runner.run(job, save = lambda mp4, meta: saved.append(mp4))
+ assert runner.progress()["phase"] == "cancelled"
+ assert saved == [] and runner.media_path(job["id"], "output") is None
+
+
+def test_body_middleware_streams_the_restyle_upload():
+ import main
+ from utils.upload_limits import VIDEO_RESTYLE_UPLOAD_MAX_BYTES, upload_request_limit_bytes
+
+ path = "/api/inference/video/restyle"
+ assert path in main._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS
+ assert path + "/preview" in main._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS
+ for p in (path, path + "/", path + "/preview"):
+ assert main._get_upload_passthrough_request_max_bytes(p) == upload_request_limit_bytes(
+ VIDEO_RESTYLE_UPLOAD_MAX_BYTES
+ )
+ # Its JSON siblings keep the normal cap.
+ assert path + "/cancel" not in main._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS
+
+
+def test_route_refuses_an_oversized_upload_before_reading(weights, monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from routes import video_restyle as route
+
+ monkeypatch.setattr(route, "VIDEO_RESTYLE_UPLOAD_MAX_BYTES", 100)
+ app = FastAPI()
+ app.include_router(route.router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "owner"
+ res = TestClient(app).post(
+ "/api/inference/video/restyle",
+ data = {"prompt": "x"},
+ files = [("video", ("a.mp4", b"x" * 200, "video/mp4"))],
+ )
+ assert res.status_code == 413
+
+
+def test_cancel_is_refused_once_publishing_starts(weights, monkeypatch):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(
+ "core.inference.video_minimax_h3.transcode_video_to_mp4", lambda path, fps: b"MP4"
+ )
+ answers = []
+
+ def save(mp4, meta):
+ answers.append(runner.cancel())
+ return {"id": "v"}
+
+ runner.run(runner.start(prompt = "x", frames = _frames(5)), save = save)
+ assert answers == [False]
+ assert runner.progress()["phase"] == "done"
+
+
+def test_frames_are_fitted_as_they_are_read():
+ big = io.BytesIO()
+ Image.new("RGB", (1920, 1080), "red").save(big, format = "PNG")
+ (frame,) = vr.frames_from_images([("001.png", big.getvalue())])
+ assert frame.size == (vr.WIDTH, vr.HEIGHT)
+ assert {f.size for f in vr.frames_from_video(_clip(30, 6))} == {(vr.WIDTH, vr.HEIGHT)}
+
+
+def test_unload_if_idle_refuses_while_a_restyle_holds_the_runner(weights):
+ stopped = []
+
+ class _Server(_FakeServer):
+ def stop(self):
+ stopped.append(True)
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Server(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ runner.start(prompt = "x", frames = _frames(5))
+ assert not runner.unload_if_idle()
+ assert stopped == [] and runner._server is not None
+ runner._update(active = False)
+ assert runner.unload_if_idle()
+ assert stopped == [True] and runner._server is None
+
+
+def test_progress_waits_for_start_to_swap_owner_and_state(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ out = []
+ runner._lock.acquire()
+ reader = threading.Thread(target = lambda: out.append(runner.progress("bob")))
+ reader.start()
+ reader.join(0.2)
+ assert reader.is_alive() and out == []
+ runner._lock.release()
+ reader.join(5)
+ assert out == [{"active": False, "phase": None, "pending": False}]
+
+
+def test_reservation_refuses_a_second_upload_until_released(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ token = runner.reserve()
+ with pytest.raises(vr.RestyleBusy):
+ runner.reserve()
+ with pytest.raises(vr.RestyleBusy):
+ runner.start(prompt = "x", frames = _frames(5))
+ runner.release("someone-else")
+ with pytest.raises(vr.RestyleBusy):
+ runner.reserve()
+ runner.release(token)
+ other = runner.reserve()
+ assert runner.start(prompt = "x", frames = _frames(5), reservation = other)["id"]
+ runner.release(other)
+ with pytest.raises(vr.RestyleBusy):
+ runner.reserve()
+
+
+def test_route_refuses_before_reading_the_upload(weights, monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from routes import video_restyle as route
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(vr, "runner", runner)
+ decoded = []
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: decoded.append(data) or _frames(5))
+ app = FastAPI()
+ app.include_router(route.router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "owner"
+ client = TestClient(app)
+ token = runner.reserve()
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": "x"}, files = files)
+ assert res.status_code == 409 and decoded == []
+ runner.release(token)
+ res = client.post("/api/inference/video/restyle", data = {"prompt": ""}, files = files)
+ assert res.status_code == 400 and len(decoded) == 1
+ # The failed request gave its reservation back.
+ runner.release(runner.reserve())
+
+
+def test_media_path_waits_for_start_to_swap_owner_and_state(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ out = []
+ runner._lock.acquire()
+ reader = threading.Thread(target = lambda: out.append(runner.media_path("old", "output", "bob")))
+ reader.start()
+ reader.join(0.2)
+ assert reader.is_alive() and out == []
+ runner._lock.release()
+ reader.join(5)
+ assert out == [None]
+
+
+def test_frames_from_video_error_is_plain():
+ with pytest.raises(vr.RestyleError) as err:
+ vr.frames_from_video(b"not a video")
+ assert "MP4" in str(err.value) and "Errno" not in str(err.value)
+
+
+def test_preview_reports_frames_used_and_edges():
+ out = vr.preview(_frames(140), source_seconds = 18.0)
+ assert out["frames"] == vr.MAX_FRAMES and out["seconds"] == pytest.approx(121 / 30)
+ assert out["source_seconds"] == 18.0
+ for key in ("frame_jpeg", "edges_jpeg"):
+ image = Image.open(io.BytesIO(base64.b64decode(out[key])))
+ assert image.size == (vr.WIDTH, vr.HEIGHT)
+ with pytest.raises(vr.RestyleError):
+ vr.preview(_frames(3))
+
+
+def test_availability_names_what_is_missing(weights, monkeypatch, tmp_path):
+ monkeypatch.setattr("core.inference.sd_cpp_engine.find_sd_server_binary", lambda: None)
+ out = vr.availability()
+ assert not out["available"] and "stable-diffusion.cpp" in out["reason"]
+ plain = tmp_path / "bin" / "sd-server"
+ plain.parent.mkdir()
+ plain.write_bytes(b"\x7fELF generic sd-server")
+ monkeypatch.setattr("core.inference.sd_cpp_engine.find_sd_server_binary", lambda: str(plain))
+ assert not vr.availability()["available"]
+ (plain.parent / "libstable-diffusion.so").write_bytes(b"..." + vr._COSMOS3_MARKER + b" %d/%d")
+ assert vr.availability() == {"available": True, "reason": None}
+ assert not vr.availability({})["available"]
+
+
+def test_random_seed_is_reported(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ job = runner.start(prompt = "x", frames = _frames(5))
+ assert runner.progress()["seed"] == job["seed"]
+
+
+def test_route_preview_and_status(weights, monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from routes import video_restyle as route
+
+ app = FastAPI()
+ app.include_router(route.router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "owner"
+ client = TestClient(app)
+ res = client.post(
+ "/api/inference/video/restyle/preview",
+ files = [("video", ("a.mp4", _clip(30, 20), "video/mp4"))],
+ )
+ assert res.status_code == 200 and res.json()["frames"] == 17
+ res = client.post(
+ "/api/inference/video/restyle/preview",
+ files = [("video", ("a.mp4", b"junk", "video/mp4"))],
+ )
+ assert res.status_code == 400 and "MP4" in res.json()["detail"]
+ monkeypatch.setattr("core.inference.sd_cpp_engine.find_sd_server_binary", lambda: None)
+ assert client.get("/api/inference/video/restyle/status").json()["available"] is False
+
+
+def test_frames_from_video_fits_only_kept_frames(monkeypatch):
+ calls = []
+ real = vr.fit_frame
+ monkeypatch.setattr(vr, "fit_frame", lambda image: calls.append(1) or real(image))
+ frames = vr.frames_from_video(_clip(120, 40))
+ # 40 frames at 120 fps is a third of a second: 10 frames at 30 fps, each fitted once.
+ assert abs(len(frames) - 10) <= 1 and len(calls) == len(frames)
+
+
[email protected]("owner", ["chat", "diffusion", "video"])
+def test_gpu_acquire_releases_an_idle_restyle_server(weights, monkeypatch, owner):
+ import core.inference.gpu_arbiter as arb
+
+ stopped = []
+
+ class _Server(_FakeServer):
+ def stop(self):
+ stopped.append(True)
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Server(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(arb, "_owner", None)
+ monkeypatch.setattr(arb, "_release_idle_video_servers", lambda reason: None)
+ arb.acquire_for(owner)
+ assert stopped == [True] and runner._server is None
+
+
+def test_gpu_acquire_keeps_a_running_restyle_server(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ server = runner._ensure_server(vr.model_files())
+ runner.start(prompt = "x", frames = _frames(5))
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(arb, "_owner", None)
+ with pytest.raises(arb.RestyleRunningError):
+ arb.acquire_for(arb.CHAT)
+ assert runner._server is server
+
+
+def _route_client(monkeypatch, runner):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from auth.authentication import get_current_subject
+ from routes import video_restyle as route
+
+ monkeypatch.setattr(vr, "runner", runner)
+ app = FastAPI()
+ app.include_router(route.router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "owner"
+ return TestClient(app)
+
+
[email protected]("allowed", [False, True])
+def test_route_enforces_the_model_allowlist(weights, monkeypatch, allowed):
+ from hub.services.models import account_access
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ decoded = []
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: decoded.append(data) or _frames(5))
+ monkeypatch.setattr(account_access, "managed_account", lambda: True)
+ monkeypatch.setattr(account_access, "model_allowlist", lambda: {"some/other-model"})
+ monkeypatch.setattr(account_access, "model_allowed", lambda repo_id: allowed)
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": ""}, files = files)
+ if allowed:
+ assert res.status_code == 400 and len(decoded) == 1
+ else:
+ assert res.status_code == 403 and decoded == []
+
+
+def test_route_cancel_runs_off_the_event_loop(weights, monkeypatch):
+ import asyncio
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ loops = []
+
+ def cancel(owner = None):
+ try:
+ loops.append(asyncio.get_running_loop())
+ except RuntimeError:
+ loops.append(None)
+ return True
+
+ monkeypatch.setattr(runner, "cancel", cancel)
+ assert client.post("/api/inference/video/restyle/cancel").json() == {"cancelled": True}
+ assert loops == [None]
+
+
+def test_training_teardown_releases_an_idle_restyle_server(weights, monkeypatch):
+ from routes import training
+
+ stopped = []
+
+ class _Server(_FakeServer):
+ def stop(self):
+ stopped.append(True)
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Server(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ monkeypatch.setattr(vr, "runner", runner)
+ training._free_restyle_for_training()
+ assert stopped == [True] and runner._server is None
+
+
+def test_training_teardown_refuses_while_a_restyle_runs(weights, monkeypatch):
+ from routes import training
+ from routes.training_vram import ManagedEngineStillRunning
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ server = runner._ensure_server(vr.model_files())
+ runner.start(prompt = "x", frames = _frames(5))
+ monkeypatch.setattr(vr, "runner", runner)
+ with pytest.raises(ManagedEngineStillRunning):
+ training._free_restyle_for_training()
+ assert runner._server is server
+
+
+def test_diffusion_training_teardown_includes_the_restyle_server(monkeypatch):
+ from routes import training
+
+ class _Called(Exception):
+ pass
+
+ def called():
+ raise _Called
+
+ monkeypatch.setattr(training, "_free_restyle_for_training", called)
+ with pytest.raises(_Called):
+ training._free_gpu_for_diffusion_training()
+
+
+def test_fit_frame_never_resamples_past_the_output(monkeypatch):
+ real = Image.Image.resize
+ sizes = []
+
+ def resize(self, size, *args, **kwargs):
+ sizes.append(tuple(size))
+ assert size[0] * size[1] <= vr.WIDTH * vr.HEIGHT, size
+ return real(self, size, *args, **kwargs)
+
+ monkeypatch.setattr(Image.Image, "resize", resize)
+ out = vr.fit_frame(Image.new("RGB", (1, 20000), (9, 9, 9)))
+ assert out.size == (vr.WIDTH, vr.HEIGHT) and sizes
+
+
+def test_retire_cancels_only_the_owners_job(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+ assert not runner.retire("bob")
+ assert runner.retire("alice") and runner._cancel.is_set()
+
+
+def test_start_refuses_a_fenced_account(weights):
+ from state import active_generations
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ active_generations.fence("alice")
+ try:
+ with pytest.raises(vr.RestyleError):
+ runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+ finally:
+ active_generations.lift_fence("alice")
+ runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+
+
+def test_route_refuses_a_restyle_beside_training(weights, monkeypatch):
+ import core.training as training_pkg
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: _frames(5))
+
+ class _Training:
+ def is_training_active(self):
+ return True
+
+ monkeypatch.setattr(training_pkg, "get_training_backend", lambda: _Training())
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": "x"}, files = files)
+ assert res.status_code == 409 and "training" in res.json()["detail"]
+ assert not runner.progress().get("active")
+
+
+def test_a_concat_playlist_upload_cannot_read_local_files(tmp_path, monkeypatch):
+ (tmp_path / "secret.mp4").write_bytes(_clip(30, 10))
+ monkeypatch.chdir(tmp_path)
+ playlist = b"ffconcat version 1.0\nfile 'secret.mp4'\n"
+ with pytest.raises(vr.RestyleError):
+ vr.frames_from_video(playlist)
+ assert vr.video_seconds(playlist) is None
+
+
+def test_route_maps_a_diffusion_training_admission_refusal_to_409(weights, monkeypatch):
+ import contextlib
+
+ from core.training.diffusion_training_service import TrainingActiveError
+ from routes import inference
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: _frames(5))
+
+ @contextlib.contextmanager
+ def refused():
+ raise TrainingActiveError("A diffusion training run holds the GPU.")
+ yield
+
+ monkeypatch.setattr(inference, "_diffusion_training_admission", refused)
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": "x"}, files = files)
+ assert res.status_code == 409 and not runner.progress().get("active")
+
+
+def test_frames_from_video_holds_the_last_frame_of_a_slow_source():
+ frames = vr.frames_from_video(_clip(1, 4))
+ assert len(frames) == 120
+ # The 4th second shows the 4th source frame, not the 3rd.
+ assert frames[-1].getpixel((0, 0)) != frames[60].getpixel((0, 0))
+
+
+def test_a_reserved_runner_keeps_its_server(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ server = runner._ensure_server(vr.model_files())
+ token = runner.reserve()
+ assert not runner.unload_if_idle() and runner._server is server
+ runner.release(token)
+ assert runner.unload_if_idle() and runner._server is None
+
+
+class _Video:
+ def __init__(
+ self,
+ loaded,
+ loading = (),
+ ):
+ self.loaded, self.loading, self.unloaded = loaded, loading, 0
+
+ def loading_repo_ids(self):
+ return self.loading
+
+ def status(self):
+ return {"loaded": self.loaded}
+
+ def unload(self):
+ self.unloaded += 1
+
+
+def _gpu_handoff(
+ monkeypatch,
+ mode,
+ video,
+ generating = None,
+):
+ import core.inference.gpu_arbiter as arb
+ import core.inference.video as video_module
+ import utils.multi_model_settings as mms
+
+ acquired = []
+ monkeypatch.setattr(mms, "get_multi_model_mode", lambda: mode)
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: video)
+ monkeypatch.setattr(video_module, "generation_account_in_flight", lambda: generating)
+
+ def acquire(
+ owner,
+ register = None,
+ admit = None,
+ **kw,
+ ):
+ admit()
+ register()
+ acquired.append((owner, kw))
+
+ monkeypatch.setattr(arb, "acquire_for_request", acquire)
+ return acquired
+
+
+def test_start_takes_the_gpu_as_video_and_unloads_the_create_model(weights, monkeypatch):
+ from routes import video_restyle as route
+
+ video = _Video(loaded = True)
+ acquired = _gpu_handoff(monkeypatch, "off", video)
+ route._take_the_gpu()
+ assert video.unloaded == 1 and acquired == [("video", {"policy": "off"})]
+
+
[email protected]("mode, generating", [("always", None), ("off", "alice")])
+def test_start_refuses_to_drop_a_create_model_it_must_keep(weights, monkeypatch, mode, generating):
+ from fastapi import HTTPException
+
+ from routes import video_restyle as route
+
+ video = _Video(loaded = True)
+ acquired = _gpu_handoff(monkeypatch, mode, video, generating)
+ with pytest.raises(HTTPException) as exc:
+ route._take_the_gpu()
+ assert exc.value.status_code == 409 and video.unloaded == 0 and acquired == []
+
+
+def test_start_refuses_while_a_create_model_loads(weights, monkeypatch):
+ from fastapi import HTTPException
+
+ from routes import video_restyle as route
+
+ video = _Video(loaded = False, loading = ("org/some-video-model",))
+ acquired = _gpu_handoff(monkeypatch, "off", video)
+ with pytest.raises(HTTPException) as exc:
+ route._take_the_gpu()
+ assert exc.value.status_code == 409 and acquired == []
+
+
+def test_gpu_acquire_is_refused_while_a_restyle_runs(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+
+ evicted = []
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ runner.start(prompt = "x", frames = _frames(5))
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(arb, "_owner", None)
+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: evicted.append("chat"))
+ with pytest.raises(arb.RestyleRunningError):
+ arb.acquire_for(arb.DIFFUSION)
+ assert evicted == []
+ assert arb.RestyleRunningError().as_http_exception().status_code == 409
+
+
+def test_a_reserved_runner_refuses_other_loads_but_not_its_own_handoff(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ server = runner._ensure_server(vr.model_files())
+ runner.reserve()
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(arb, "_owner", None)
+ monkeypatch.setattr(arb, "_release_idle_video_servers", lambda reason: None)
+ with pytest.raises(arb.RestyleRunningError):
+ arb.acquire_for(arb.CHAT)
+ token = arb.restyle_handoff.set(True)
+ try:
+ arb.acquire_for(arb.VIDEO)
+ finally:
+ arb.restyle_handoff.reset(token)
+ assert runner._server is server
+
+
+def test_an_invalid_request_is_refused_before_the_gpu_handoff(weights, monkeypatch):
+ from routes import video_restyle as route
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: _frames(5))
+ took = []
+ monkeypatch.setattr(route, "_take_the_gpu", lambda: took.append(True))
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": " "}, files = files)
+ assert res.status_code == 400 and took == []
+
+
+def test_the_create_check_runs_under_the_arbiter_lock(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+ import core.inference.video as video_module
+ import utils.multi_model_settings as mms
+ from fastapi import HTTPException
+
+ from routes import video_restyle as route
+
+ held = []
+
+ class _Loading(_Video):
+ def loading_repo_ids(self):
+ held.append(arb._lock.locked())
+ return ("org/some-video-model",)
+
+ evicted = []
+ monkeypatch.setattr(mms, "get_multi_model_mode", lambda: "off")
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: _Loading(False))
+ monkeypatch.setattr(arb, "_owner", None)
+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: evicted.append("chat"))
+ with pytest.raises(HTTPException) as exc:
+ route._take_the_gpu()
+ assert exc.value.status_code == 409 and held == [True] and evicted == []
+
+
+def test_retire_drops_the_accounts_reservation(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ runner.reserve("bob")
+ assert not runner.retire("alice") and runner.holds_gpu()
+ assert not runner.retire("bob") and not runner.holds_gpu()
+
+
+def test_unload_refuses_another_accounts_server(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+ runner._ensure_server(vr.model_files())
+ runner._update(active = False)
+ with pytest.raises(vr.RestyleBusy):
+ runner.unload_if_idle("bob")
+ assert runner._server is not None
+ assert runner.unload_if_idle("alice") and runner._server is None
+
+
+def test_a_refused_handoff_keeps_the_create_model(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+ import core.inference.video as video_module
+ import utils.multi_model_settings as mms
+ from fastapi import HTTPException
+
+ from routes import video_restyle as route
+
+ video = _Video(loaded = True)
+ monkeypatch.setattr(mms, "get_multi_model_mode", lambda: "fit")
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: video)
+ monkeypatch.setattr(video_module, "generation_account_in_flight", lambda: None)
+
+ def acquire(
+ owner,
+ register = None,
+ admit = None,
+ **kw,
+ ):
+ admit()
+ raise HTTPException(status_code = 409, detail = "another account is generating")
+
+ monkeypatch.setattr(arb, "acquire_for_request", acquire)
+ with pytest.raises(HTTPException):
+ route._take_the_gpu()
+ assert video.unloaded == 0
+
+
+def test_a_resident_server_holds_the_managed_sd_cpp_tree(weights, monkeypatch):
+ import core.inference.sd_cpp_backend as backend
+ import core.inference.sd_cpp_engine as engine
+ import core.inference.sd_cpp_server as server_module
+
+ monkeypatch.setattr(engine, "find_sd_server_binary", lambda: "/managed/sd-server")
+ monkeypatch.setattr(engine, "is_managed_binary", lambda binary: True)
+ monkeypatch.setattr(server_module, "SdCppServer", lambda binary: _FakeServer(b"AVI"))
+ runner = vr.RestyleRunner()
+ try:
+ runner._ensure_server(vr.model_files())
+ assert backend._external_tree_holder_alive()
+ runner.unload()
+ assert not backend._external_tree_holder_alive()
+ finally:
+ backend.unregister_tree_holder(runner)
+
+
+def test_a_stopping_server_still_pins_the_tree(weights):
+ import threading
+
+ release = threading.Event()
+ stopping = threading.Event()
+
+ class _Slow(_FakeServer):
+ def stop(self):
+ stopping.set()
+ assert release.wait(5)
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Slow(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ worker = threading.Thread(target = runner.unload)
+ worker.start()
+ assert stopping.wait(5)
+ assert runner._server is None and runner.is_alive()
+ release.set()
+ worker.join(5)
+ assert not runner.is_alive()
+
+
+def test_a_stopping_server_holds_the_gpu_and_unload_waits_for_it(weights):
+ import threading
+
+ release = threading.Event()
+ stopping = threading.Event()
+
+ class _Slow(_FakeServer):
+ def stop(self):
+ stopping.set()
+ assert release.wait(5)
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Slow(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ first = threading.Thread(target = runner.unload)
+ first.start()
+ assert stopping.wait(5) and runner.holds_gpu()
+ done = []
+ second = threading.Thread(target = lambda: done.append(runner.unload_if_idle()))
+ second.start()
+ second.join(0.3)
+ assert done == []
+ release.set()
+ first.join(5)
+ second.join(5)
+ assert done == [True] and not runner.holds_gpu()
+
+
+def test_start_saves_the_chat_kv_around_the_handoff(weights, monkeypatch):
+ from routes import video_restyle as route
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ client = _route_client(monkeypatch, runner)
+ monkeypatch.setattr(vr, "frames_from_video", lambda data: _frames(5))
+ monkeypatch.setattr(runner, "run", lambda job, save = None: None)
+ calls = []
+
+ class _Swap:
+ def close(self):
+ calls.append("close")
+
+ async def save(owner, media, **kw):
+ calls.append(("save", owner, media, kw.get("policy")))
+ return _Swap()
+
+ monkeypatch.setattr(route, "save_chat_kv_before_swap", save)
+ monkeypatch.setattr(route, "get_multi_model_mode", lambda: "off")
+ monkeypatch.setattr(route, "_take_the_gpu", lambda mode = None: calls.append(("take", mode)))
+ files = [("video", ("a.mp4", b"x", "video/mp4"))]
+ res = client.post("/api/inference/video/restyle", data = {"prompt": "x"}, files = files)
+ assert res.status_code == 200
+ assert calls == [("save", "video", "video", "off"), ("take", "off"), "close"]
+
+
+def test_a_new_server_waits_for_the_previous_one_to_stop(weights):
+ import threading
+
+ release = threading.Event()
+ stopping = threading.Event()
+ started = []
+
+ class _Slow(_FakeServer):
+ def stop(self):
+ stopping.set()
+ assert release.wait(5)
+
+ def start(self, files):
+ started.append(release.is_set())
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Slow(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ started.clear()
+ unloading = threading.Thread(target = runner.unload)
+ unloading.start()
+ assert stopping.wait(5)
+ launching = threading.Thread(target = runner._ensure_server, args = (vr.model_files(),))
+ launching.start()
+ launching.join(0.3)
+ assert started == []
+ release.set()
+ unloading.join(5)
+ launching.join(5)
+ assert started == [True]
+
+
+def test_a_dead_resident_server_does_not_pin_the_tree(weights):
+ class _Dead(_FakeServer):
+ def is_alive(self):
+ return False
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _Dead(b"AVI"))
+ runner._ensure_server(vr.model_files())
+ assert runner._server is not None and not runner.is_alive()
+
+
+def test_an_unload_refused_mid_acquire_refuses_the_acquire(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(runner, "holds_gpu", lambda: False)
+ monkeypatch.setattr(runner, "unload_if_idle", lambda owner = None: False)
+ monkeypatch.setattr(arb, "_owner", None)
+ monkeypatch.setattr(arb, "_release_idle_video_servers", lambda reason: None)
+ with pytest.raises(arb.RestyleRunningError):
+ arb.acquire_for(arb.CHAT)
+
+
+def test_the_worker_starts_inside_the_shielded_start(weights, monkeypatch):
+ import threading
+
+ from routes import video_restyle as route
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(vr, "runner", runner)
+ monkeypatch.setattr(route, "_take_the_gpu", lambda mode = None: None)
+ ran = threading.Event()
+ monkeypatch.setattr(runner, "run", lambda job, save = None: ran.set())
+ job = route._admit_and_start(
+ prompt = "x", frames = _frames(5), seed = 1, owner = None, reservation = None
+ )
+ assert job["id"] and ran.wait(5)
+
+
+def test_the_shielded_start_releases_the_reservation_itself(weights, monkeypatch):
+ from fastapi import HTTPException
+
+ from routes import video_restyle as route
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(vr, "runner", runner)
+
+ def refuse(mode = None):
+ assert runner.holds_gpu() # still reserved while the handoff runs
+ raise HTTPException(status_code = 409, detail = "busy")
+
+ monkeypatch.setattr(route, "_take_the_gpu", refuse)
+ token = runner.reserve("alice")
+ with pytest.raises(HTTPException):
+ route._admit_and_start(
+ prompt = "x", frames = _frames(5), seed = 1, owner = "alice", reservation = token
+ )
+ assert not runner.holds_gpu()
+
+
+def test_progress_reports_a_pending_start_to_its_account(weights):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ runner.reserve("alice")
+ assert runner.progress("alice")["pending"] is True
+ assert runner.progress("bob")["pending"] is False
+
+
+def test_frames_from_video_applies_the_display_rotation(monkeypatch):
+ import core.training.diffusion_h3_clips as clips
+
+ sizes = []
+ real = vr.fit_frame
+ monkeypatch.setattr(clips, "display_rotation_degrees", lambda frame, stream: 90)
+ monkeypatch.setattr(vr, "fit_frame", lambda image: sizes.append(image.size) or real(image))
+ vr.frames_from_video(_clip(30, 3))
+ assert sizes and all(size == (48, 64) for size in sizes) # coded 64x48, displayed portrait
+
+
+def test_a_failed_start_leaves_the_previous_owner_and_job(weights, monkeypatch):
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ job = runner.start(prompt = "x", frames = _frames(5), owner = "alice")
+ runner._update(active = False, phase = "done")
+
+ def full(*args, **kwargs):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(vr.tempfile, "mkdtemp", full)
+ with pytest.raises(OSError):
+ runner.start(prompt = "y", frames = _frames(5), owner = "bob")
+ assert runner.owned_by("alice") and runner.progress("alice")["id"] == job["id"]
+ assert runner.progress("bob").get("id") is None
+
+
+def test_a_finished_job_has_already_released_its_server(weights, monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.video_minimax_h3.transcode_video_to_mp4", lambda path, fps: b"MP4"
+ )
+ seen = []
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ real = runner._update
+
+ def update(**fields):
+ real(**fields)
+ if fields.get("active") is False:
+ seen.append(runner._server)
+
+ monkeypatch.setattr(runner, "_update", update)
+ runner.run(runner.start(prompt = "x", frames = _frames(5)))
+ assert runner.progress()["phase"] == "done" and seen == [None]
+
+
+def test_a_running_restyle_counts_as_inference_activity(weights, monkeypatch):
+ import main
+
+ runner = vr.RestyleRunner(server_factory = lambda _model: _FakeServer(b"AVI"))
+ monkeypatch.setattr(vr, "runner", runner)
+ assert "core.inference.video_restyle" in main._MEDIA_BACKEND_MODULES
+ assert not vr.generation_in_flight()
+ runner.start(prompt = "x", frames = _frames(5))
+ assert vr.generation_in_flight() and main._media_generation_active()
+
+
[email protected]("create_loaded", [False, True])
+def test_finishing_releases_the_video_claim_unless_create_holds_it(
+ weights, monkeypatch, create_loaded
+):
+ import core.inference.gpu_arbiter as arb
+ import core.inference.video as video_module
+
+ released = []
+ monkeypatch.setattr(
+ arb, "release_if", lambda owner, idle: idle() and released.append(owner) is None
+ )
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: _Video(loaded = create_loaded))
+ runner = vr.RestyleRunner()
+ runner._finish(phase = "done")
+ assert released == ([] if create_loaded else [arb.VIDEO])
+
+
+def test_the_video_claim_idle_check_runs_under_the_arbiter_lock(weights, monkeypatch):
+ import core.inference.gpu_arbiter as arb
+ import core.inference.video as video_module
+
+ held = []
+
+ class _Probe(_Video):
+ def status(self):
+ held.append(arb._lock.locked())
+ return {"loaded": False}
+
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: _Probe(False))
+ monkeypatch.setattr(arb, "_view", lambda: {arb.VIDEO})
+ monkeypatch.setattr(arb, "_drop_resident", lambda owner: None)
+ vr.RestyleRunner()._release_video_claim()
+ assert held == [True]
diff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.py
index 1e5229e550c..0ed7f79f0f4 100644
--- a/studio/backend/utils/upload_limits.py
+++ b/studio/backend/utils/upload_limits.py
@@ -23,6 +23,8 @@ VIDEO_INPUT_REFERENCE_B64_MAX_CHARS = ((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) //
VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES = VIDEO_INPUT_REFERENCE_B64_MAX_CHARS + 64 * 1024
LIBRARY_UPLOAD_MAX_BYTES = 512 * _BYTES_PER_MB
+# One clip or up to 121 frames for the video restyle workflow.
+VIDEO_RESTYLE_UPLOAD_MAX_BYTES = 512 * _BYTES_PER_MB
# One file into a chat's sandbox folder, the Library's per-file cap.
SANDBOX_UPLOAD_MAX_BYTES = LIBRARY_UPLOAD_MAX_BYTES
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index d3646ed2bd9..144b03e316c 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -434,3 +434,92 @@ export async function fetchGalleryVideoExport(
if (!res.ok) throw new Error(await readFastApiError(res));
return res.blob();
}
+
+export interface VideoRestyleProgress {
+ active: boolean;
+ pending?: boolean;
+ id?: string;
+ phase: string | null;
+ // Latent frames done out of total; Cosmos3 makes one per 4 output frames.
+ step?: number;
+ total?: number;
+ num_frames?: number;
+ eta_seconds?: number | null;
+ error?: string | null;
+ video?: GalleryVideo | null;
+ seed?: number | null;
+}
+
+export interface VideoRestyleStatus {
+ available: boolean;
+ reason: string | null;
+}
+
+export interface VideoRestylePreview {
+ frames: number;
+ seconds: number;
+ source_seconds: number | null;
+ width: number;
+ height: number;
+ frame_jpeg: string;
+ edges_jpeg: string;
+}
+
+export async function fetchVideoRestyleStatus(): Promise<VideoRestyleStatus> {
+ return parseJson(await authFetch("/api/inference/video/restyle/status"));
+}
+
+function restyleForm(video?: File | null, frames?: File[]): FormData {
+ const form = new FormData();
+ if (video) form.append("video", video);
+ for (const frame of frames ?? []) form.append("frames", frame, frame.name);
+ return form;
+}
+
+/** The frames a restyle would use and one of them with its edge control. Runs no model. */
+export async function previewVideoRestyle(input: {
+ video?: File | null;
+ frames?: File[];
+}): Promise<VideoRestylePreview> {
+ return parseJson(
+ await authFetch("/api/inference/video/restyle/preview", {
+ method: "POST",
+ body: restyleForm(input.video, input.frames),
+ }),
+ );
+}
+
+export async function startVideoRestyle(input: {
+ prompt: string;
+ seed?: number | null;
+ video?: File | null;
+ frames?: File[];
+}): Promise<VideoRestyleProgress> {
+ const form = restyleForm(input.video, input.frames);
+ form.append("prompt", input.prompt);
+ if (input.seed != null) form.append("seed", String(input.seed));
+ return parseJson(
+ await authFetch("/api/inference/video/restyle", { method: "POST", body: form }),
+ );
+}
+
+export async function fetchVideoRestyleProgress(): Promise<VideoRestyleProgress> {
+ return parseJson(await authFetch("/api/inference/video/restyle/progress"));
+}
+
+export async function cancelVideoRestyle(): Promise<{ cancelled: boolean }> {
+ return parseJson(
+ await authFetch("/api/inference/video/restyle/cancel", { method: "POST" }),
+ );
+}
+
+export async function fetchVideoRestyleClip(
+ id: string,
+ kind: "input" | "control" | "output",
+): Promise<Blob> {
+ const response = await authFetch(
+ `/api/inference/video/restyle/${encodeURIComponent(id)}/${kind}.mp4`,
+ );
+ if (!response.ok) throw new Error(await readFastApiError(response));
+ return response.blob();
+}
diff --git a/studio/frontend/src/features/video/restyle-panel.tsx b/studio/frontend/src/features/video/restyle-panel.tsx
new file mode 100644
index 00000000000..0a76b0fd726
--- /dev/null
+++ b/studio/frontend/src/features/video/restyle-panel.tsx
@@ -0,0 +1,455 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Progress } from "@/components/ui/progress";
+import { Spinner } from "@/components/ui/spinner";
+import { Textarea } from "@/components/ui/textarea";
+import { notifyGalleryChanged } from "@/lib/gallery-flags";
+import {
+ cancelVideoRestyle,
+ fetchVideoRestyleClip,
+ fetchVideoRestyleProgress,
+ fetchVideoRestyleStatus,
+ previewVideoRestyle,
+ startVideoRestyle,
+ type VideoRestylePreview,
+ type VideoRestyleProgress,
+ type VideoRestyleStatus,
+} from "./api";
+
+const POLL_MS = 1000;
+const MAX_FRAMES = 121;
+const IMAGE_RE = /\.(png|jpe?g|webp|bmp)$/i;
+
+const PHASE_LABEL: Record<string, string> = {
+ edges: "Tracing edges",
+ loading: "Loading Cosmos3 (about a minute)",
+ generate: "Restyling",
+ decode: "Decoding video",
+ export: "Saving",
+};
+
+const CLIPS = [
+ { kind: "input", label: "Input" },
+ { kind: "control", label: "Edges (what the model follows)" },
+ { kind: "output", label: "Restyled" },
+] as const;
+
+// Cosmos3 makes one latent frame per 4 output frames (the first stands alone).
+function outputFrames(step: number, total?: number): number {
+ const done = step <= 0 ? 0 : 1 + 4 * (step - 1);
+ return total ? Math.min(done, total) : done;
+}
+
+function seconds(value: number): string {
+ return `${value.toFixed(1)} s`;
+}
+
+function useObjectUrl(blob: Blob | null): string | null {
+ const url = useMemo(() => (blob ? URL.createObjectURL(blob) : null), [blob]);
+ useEffect(
+ () => () => {
+ if (url) {
+ URL.revokeObjectURL(url);
+ }
+ },
+ [url],
+ );
+ return url;
+}
+
+export function VideoRestylePanel({ active }: { active: boolean }) {
+ const [video, setVideo] = useState<File | null>(null);
+ const [frames, setFrames] = useState<File[]>([]);
+ const [prompt, setPrompt] = useState("");
+ const [seed, setSeed] = useState("");
+ const [progress, setProgress] = useState<VideoRestyleProgress | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [status, setStatus] = useState<VideoRestyleStatus | null>(null);
+ const [preview, setPreview] = useState<VideoRestylePreview | null>(null);
+ const [previewing, setPreviewing] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [cancelling, setCancelling] = useState(false);
+ const [outcomeStale, setOutcomeStale] = useState(false);
+ const [inputClip, setInputClip] = useState<Blob | null>(null);
+ const [controlClip, setControlClip] = useState<Blob | null>(null);
+ const [outputClip, setOutputClip] = useState<Blob | null>(null);
+ const [retrying, setRetrying] = useState(false);
+ const urls = {
+ input: useObjectUrl(inputClip),
+ control: useObjectUrl(controlClip),
+ output: useObjectUrl(outputClip),
+ };
+ const players = useRef<Record<string, HTMLVideoElement | null>>({});
+ const loadedFor = useRef<string | null>(null);
+ // The newest job progress named; a clip chosen after it marks that job's result as discarded.
+ const lastJob = useRef<string | null>(null);
+ const previewFor = useRef(0);
+ // Bumped whenever the shown clips are cleared, so an older download cannot repopulate them.
+ const clipsFor = useRef(0);
+
+ const running = progress?.active === true || progress?.pending === true;
+ if (!running && cancelling) setCancelling(false);
+ const unavailable = status !== null && !status.available;
+
+ const refresh = useCallback(async () => {
+ // Taken before the progress request: a clip chosen while it is in flight voids its result.
+ const ticket = clipsFor.current;
+ try {
+ const next = await fetchVideoRestyleProgress();
+ if (next.id) lastJob.current = next.id;
+ setProgress(next);
+ if (next.phase === "error") {
+ setError(next.error ?? "Restyle failed.");
+ }
+ if (ticket !== clipsFor.current) {
+ // A clip was chosen meanwhile: a finished job this stale answer names was discarded with it.
+ if (next.phase === "done" && next.id) loadedFor.current = next.id;
+ return;
+ }
+ if (next.phase === "done" && next.id && loadedFor.current !== next.id) {
+ loadedFor.current = next.id;
+ if (next.video) notifyGalleryChanged("videos");
+ let clips: Blob[];
+ try {
+ clips = await Promise.all(
+ CLIPS.map((clip) => fetchVideoRestyleClip(next.id as string, clip.kind)),
+ );
+ } catch (err) {
+ // Retry only for the selection that asked: a result a new clip discarded stays discarded.
+ if (loadedFor.current === next.id && ticket === clipsFor.current) loadedFor.current = null;
+ throw err;
+ }
+ const [input, control, output] = clips;
+ if (ticket !== clipsFor.current) return;
+ setInputClip(input);
+ setControlClip(control);
+ setOutputClip(output);
+ }
+ setRetrying(false);
+ } catch (err) {
+ setRetrying(true);
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!active) {
+ return;
+ }
+ fetchVideoRestyleStatus()
+ .then(setStatus)
+ .catch(() => setStatus(null));
+ }, [active]);
+
+ const choose = async (next: { video: File | null; frames: File[] }) => {
+ if (running || submitting) return;
+ setVideo(next.video);
+ setFrames(next.frames);
+ setPreview(null);
+ setError(null);
+ setOutcomeStale(true);
+ clipsFor.current += 1;
+ loadedFor.current = lastJob.current;
+ setInputClip(null);
+ setControlClip(null);
+ setOutputClip(null);
+ if (!next.video && next.frames.length === 0) {
+ return;
+ }
+ const ticket = ++previewFor.current;
+ setPreviewing(true);
+ try {
+ const result = await previewVideoRestyle(next);
+ if (ticket === previewFor.current) setPreview(result);
+ } catch (err) {
+ if (ticket === previewFor.current) setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ if (ticket === previewFor.current) setPreviewing(false);
+ }
+ };
+
+ useEffect(() => {
+ if (!active) {
+ return;
+ }
+ const kick = window.setTimeout(() => void refresh(), 0);
+ const timer =
+ running || retrying ? window.setInterval(() => void refresh(), POLL_MS) : undefined;
+ return () => {
+ window.clearTimeout(kick);
+ window.clearInterval(timer);
+ };
+ }, [active, running, retrying, refresh]);
+
+ const submit = async () => {
+ if (submitting) return;
+ setSubmitting(true);
+ setOutcomeStale(false);
+ setError(null);
+ clipsFor.current += 1;
+ setInputClip(null);
+ setControlClip(null);
+ setOutputClip(null);
+ try {
+ const parsedSeed = seed.trim() === "" ? null : Number.parseInt(seed, 10);
+ setProgress(
+ await startVideoRestyle({
+ prompt,
+ seed: Number.isFinite(parsedSeed) ? parsedSeed : null,
+ video,
+ frames,
+ }),
+ );
+ } catch (err) {
+ // The start may have been accepted with its response lost: poll until progress answers.
+ setRetrying(true);
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const syncPlay = (play: boolean) => {
+ for (const el of Object.values(players.current)) {
+ if (!el) continue;
+ if (play) {
+ el.currentTime = 0;
+ void el.play();
+ } else {
+ el.pause();
+ }
+ }
+ };
+
+ const source = video ? video.name : frames.length ? `${frames.length} frames` : null;
+ const step = progress?.step ?? 0;
+ const total = progress?.total ?? 0;
+ const phase = progress?.phase ?? null;
+ const busy = running || submitting;
+ const trimmed =
+ preview?.source_seconds != null && preview.source_seconds > preview.seconds + 0.05;
+
+ return (
+ <div className="flex min-h-0 w-full min-w-0 flex-1 flex-col overflow-y-auto @[50rem]:flex-row @[50rem]:overflow-hidden">
+ <div className="flex w-full shrink-0 flex-col gap-4 border-b border-border/60 px-10 pt-9 pb-6 max-sm:px-5 @[50rem]:w-[min(var(--media-rail-width,calc(408px*var(--ui-space-scale,1))),calc(100%-var(--media-header-min-width)))] @[50rem]:overflow-y-auto @[50rem]:border-r @[50rem]:border-b-0">
+ <div className="grid gap-1.5">
+ <h2 className="font-heading text-xl font-medium leading-none text-foreground">
+ Restyle a video
+ </h2>
+ <p className="text-xs text-muted-foreground">
+ Cosmos3-Nano-Sim-Transfer keeps the clip's shapes and motion (from its edges) and
+ repaints it from your prompt. Uses up to the first 4 seconds, at 832 x 480 and 30 fps.
+ </p>
+ </div>
+
+ {unavailable && (
+ <Alert data-testid="restyle-unavailable">
+ <AlertTitle>Restyle is not set up here</AlertTitle>
+ <AlertDescription>
+ {status?.reason} It needs an NVIDIA GPU with about 40 GB of memory and has only been
+ tested on Linux.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <div className="grid gap-2">
+ <Label>Input</Label>
+ <div className="flex flex-wrap gap-2">
+ <Button asChild={true} variant="outline" size="sm" disabled={busy}>
+ <label>
+ Choose video
+ <input
+ type="file"
+ accept="video/*"
+ className="hidden"
+ disabled={busy}
+ onChange={(e) => {
+ void choose({ video: e.target.files?.[0] ?? null, frames: [] });
+ e.target.value = "";
+ }}
+ />
+ </label>
+ </Button>
+ <Button asChild={true} variant="outline" size="sm" disabled={busy}>
+ <label>
+ Choose frame folder
+ <input
+ type="file"
+ multiple={true}
+ className="hidden"
+ disabled={busy}
+ {...({ webkitdirectory: "", directory: "" } as object)}
+ onChange={(e) => {
+ const picked = Array.from(e.target.files ?? [])
+ .filter((f) => IMAGE_RE.test(f.name))
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+ .slice(0, MAX_FRAMES);
+ void choose({ video: null, frames: picked });
+ e.target.value = "";
+ }}
+ />
+ </label>
+ </Button>
+ </div>
+ <span className="truncate text-xs text-muted-foreground">
+ {source ?? "No input chosen"}
+ </span>
+ {previewing && (
+ <span className="text-xs text-muted-foreground">Reading the clip...</span>
+ )}
+ {preview && (
+ <div className="grid gap-1.5" data-testid="restyle-preview">
+ <div className="grid grid-cols-2 gap-2">
+ <img
+ src={`data:image/jpeg;base64,${preview.frame_jpeg}`}
+ alt="A frame of the input"
+ className="w-full rounded-md bg-black"
+ />
+ <img
+ src={`data:image/jpeg;base64,${preview.edges_jpeg}`}
+ alt="The edges the model follows for that frame"
+ className="w-full rounded-md bg-black"
+ />
+ </div>
+ <span className="text-xs text-muted-foreground">
+ Control: edges (Canny). Uses {preview.frames} frames, {seconds(preview.seconds)}
+ {trimmed && ` of a ${seconds(preview.source_seconds as number)} clip`}.
+ </span>
+ </div>
+ )}
+ </div>
+
+ <div className="grid gap-2">
+ <Label htmlFor="restyle-prompt">Prompt</Label>
+ <Textarea
+ id="restyle-prompt"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="Make it a red rally car at golden hour"
+ rows={4}
+ disabled={busy}
+ />
+ </div>
+
+ <div className="grid gap-2">
+ <Label htmlFor="restyle-seed">Seed</Label>
+ <Input
+ id="restyle-seed"
+ inputMode="numeric"
+ value={seed}
+ onChange={(e) => setSeed(e.target.value.replace(/[^0-9]/g, ""))}
+ placeholder="Random"
+ disabled={busy}
+ />
+ </div>
+
+ {running ? (
+ <Button
+ variant="outline"
+ className="h-11 text-ui-14"
+ disabled={cancelling}
+ onClick={() => {
+ setCancelling(true);
+ // A pending start cannot be cancelled yet (cancelled: false): keep Cancel usable.
+ void cancelVideoRestyle()
+ .then((r) => {
+ if (!r.cancelled) setCancelling(false);
+ })
+ .catch(() => setCancelling(false));
+ }}
+ >
+ <Spinner className="mr-2 size-4" />
+ {cancelling ? "Stopping..." : "Cancel"}
+ </Button>
+ ) : (
+ <Button
+ variant="primary"
+ className="h-11 text-ui-14 bg-control-accent text-control-accent-foreground hover:bg-control-accent/85 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100"
+ disabled={!source || !prompt.trim() || submitting || previewing || unavailable}
+ onClick={() => void submit()}
+ >
+ {submitting ? "Uploading..." : "Restyle"}
+ </Button>
+ )}
+
+ {running && phase && (
+ <div className="grid gap-1.5" data-testid="restyle-progress">
+ <div className="flex justify-between text-xs text-muted-foreground">
+ <span>
+ {cancelling
+ ? "Stopping"
+ : phase === "generate" && step === 0
+ ? "Preparing the edges for the model"
+ : (PHASE_LABEL[phase] ?? phase)}
+ </span>
+ {phase === "generate" && step > 0 && (
+ <span>
+ Frame {outputFrames(step, progress?.num_frames)} of {progress?.num_frames ?? "?"}
+ {!cancelling &&
+ progress?.eta_seconds != null &&
+ ` · about ${Math.ceil(progress.eta_seconds)} s left`}
+ </span>
+ )}
+ </div>
+ <Progress
+ value={phase === "generate" && total > 0 ? (100 * step) / total : undefined}
+ indeterminate={phase !== "generate" || step === 0}
+ />
+ </div>
+ )}
+ {phase === "cancelled" && !running && !outcomeStale && (
+ <p className="text-xs text-muted-foreground">Cancelled.</p>
+ )}
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ </div>
+
+ {/* justify-center-safe: three stacked players can be taller than the pane; plain centering would
+ push them up over the form. */}
+ <div className="flex min-h-[60dvh] min-w-0 flex-1 flex-col items-center justify-center-safe gap-4 p-6 @[50rem]:min-h-0 @[50rem]:overflow-y-auto">
+ {urls.input && urls.control && urls.output ? (
+ <>
+ <div className="grid w-full max-w-7xl grid-cols-1 gap-3 @[60rem]:grid-cols-3">
+ {CLIPS.map((clip) => (
+ <figure key={clip.kind} className="grid gap-1.5">
+ <video
+ ref={(el) => {
+ players.current[clip.kind] = el;
+ }}
+ src={urls[clip.kind] ?? undefined}
+ muted={true}
+ loop={true}
+ playsInline={true}
+ controls={true}
+ className="w-full rounded-lg bg-black"
+ />
+ <figcaption className="text-xs text-muted-foreground">{clip.label}</figcaption>
+ </figure>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" onClick={() => syncPlay(true)}>
+ Play all
+ </Button>
+ <Button size="sm" variant="outline" onClick={() => syncPlay(false)}>
+ Pause
+ </Button>
+ {progress?.seed != null && (
+ <span className="text-xs text-muted-foreground">Seed {progress.seed}</span>
+ )}
+ </div>
+ </>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ The input, its edges and the restyled clip play here side by side.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 6f5757886f0..e90e5e17a35 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -23,6 +23,7 @@ import {
FlimSlateIcon,
ImageCropIcon,
InformationCircleIcon,
+ PaintBrush02Icon,
Refresh01Icon,
SparklesIcon,
} from "@hugeicons/core-free-icons";
@@ -57,6 +58,7 @@ import {
} from "@/features/library";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { buildVideoTourSteps } from "./tour";
+import { VideoRestylePanel } from "./restyle-panel";
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
import {
applyPin,
@@ -1314,15 +1316,18 @@ function VideoGenerator({
const { familyOverride, setFamilyOverride, familySelect, opaqueKind, selectorModelId } = useFamilyOverride(status, status?.supported_families);
// Controlled so the body-portaled selector force-closes when off-tab.
const [selectorOpen, setSelectorOpen] = useState(false);
- const [pageMode, setPageMode] = useState<"create" | "train">("create");
+ const [pageMode, setPageMode] = useState<"create" | "restyle" | "train">("create");
// Mounted on first visit, then hidden rather than unmounted, so switching to Create keeps the training form.
const [trainMounted, setTrainMounted] = useState(false);
if (pageMode === "train" && !trainMounted) setTrainMounted(true);
+ // Kept mounted once opened: its poll is what saves a finished restyle into the gallery.
+ const [restyleMounted, setRestyleMounted] = useState(false);
+ if (pageMode === "restyle" && !restyleMounted) setRestyleMounted(true);
const [trainFamilies, setTrainFamilies] = useState<TrainFamilyOption[]>([]);
const [trainFamilyName, setTrainFamilyName] = useState("flux.1");
const [trainBaseChoice, setTrainBaseChoice] = useState("");
const navigateToImages = useNavigate();
- const tourSteps = useMemo(() => buildVideoTourSteps({ pageMode }), [pageMode]);
+ const tourSteps = useMemo(() => buildVideoTourSteps({ pageMode: pageMode === "train" ? "train" : "create" }), [pageMode]);
const [pendingH3Load, setPendingH3Load] = useState<PendingH3Load | null>(null);
const tour = useGuidedTourController({
id: "video",
@@ -2435,16 +2440,16 @@ function VideoGenerator({
setQuant(null);
}, [refreshStatus, dropResidentState]);
- // Starting a training run unloads the video model, so re-read it on the way back to Create. Status only:
- // dropResidentState would cancel the poll of a load still running from before the switch.
- const leftForTrain = useRef(false);
+ // Starting a training run or a restyle unloads the video model, so re-read it on the way back to Create.
+ // Status only: dropResidentState would cancel the poll of a load still running from before the switch.
+ const leftCreate = useRef(false);
useEffect(() => {
- if (pageMode === "train") {
- leftForTrain.current = true;
+ if (pageMode !== "create") {
+ leftCreate.current = true;
return;
}
- if (!active || !leftForTrain.current) return;
- leftForTrain.current = false;
+ if (!active || !leftCreate.current) return;
+ leftCreate.current = false;
void refreshStatus();
}, [active, pageMode, refreshStatus]);
@@ -3965,6 +3970,10 @@ function VideoGenerator({
setTrainBaseChoice(repo);
}}
/>
+ ) : pageMode === "restyle" ? (
+ <span className="ml-1.5 flex h-[var(--studio-chat-control-height,34px)] items-center truncate px-2.5 text-sm font-medium text-foreground">
+ Cosmos3-Nano-Sim-Transfer
+ </span>
) : (
<ModelSelector
triggerDataTour="video-model"
@@ -4025,11 +4034,12 @@ function VideoGenerator({
dataTour="video-mode"
ariaLabel="Page mode"
value={pageMode}
- onValueChange={(v) => setPageMode(v as "create" | "train")}
+ onValueChange={(v) => setPageMode(v as "create" | "restyle" | "train")}
fit={true}
className="h-[calc(34px*var(--ui-space-scale,1))] [&>button]:h-[calc(34px*var(--ui-space-scale,1))] [&>button]:px-7 @[68rem]:[&>button]:px-14 [[data-media-header-tight]_&]:[&>button]:px-4 @max-[30rem]:[&>button]:px-2.5 @max-[30rem]:[&>button>[data-pill-tab-label]]:sr-only"
tabs={[
{ value: "create", label: "Create", icon: <HugeiconsIcon icon={SparklesIcon} className="size-3.5" /> },
+ { value: "restyle", label: "Restyle", icon: <HugeiconsIcon icon={PaintBrush02Icon} className="size-3.5" /> },
{ value: "train", label: "Train", icon: <HugeiconsIcon icon={TestTubeOutlineIcon} className="size-3.5" /> },
]}
/>
@@ -4065,7 +4075,12 @@ function VideoGenerator({
/>
</div>
)}
- {pageMode !== "train" && (
+ {restyleMounted && (
+ <div className={pageMode === "restyle" ? "contents" : "hidden"} inert={pageMode !== "restyle" || undefined}>
+ <VideoRestylePanel active={active} />
+ </div>
+ )}
+ {pageMode === "create" && (
/* overflow-x-hidden: an unset overflow-x computes to auto beside overflow-y-auto, letting a
wide row pan the page sideways on a phone. */
<div className="flex min-h-0 w-full min-w-0 flex-1 flex-col overflow-y-auto overflow-x-hidden @[50rem]:flex-row @[50rem]:overflow-hidden">
diff --git a/studio/frontend/tests/video-train-deploy-tour.test.ts b/studio/frontend/tests/video-train-deploy-tour.test.ts
index cf7e03e261f..67c8f599502 100644
--- a/studio/frontend/tests/video-train-deploy-tour.test.ts
+++ b/studio/frontend/tests/video-train-deploy-tour.test.ts
@@ -26,11 +26,11 @@ test("the tour attaches to the first visible target, not a hidden page's", () =>
assert.doesNotMatch(src, /document\.querySelector\(sel\)/);
});
-test("Video re-reads its model status when returning from Train to Create", () => {
+test("Video re-reads its model status when returning from Train or Restyle to Create", () => {
const src = readSrc("features/video/video-page.tsx");
assert.match(
src,
- /if \(pageMode === "train"\) \{\s*leftForTrain\.current = true;\s*return;\s*\}\s*if \(!active \|\| !leftForTrain\.current\) return;\s*leftForTrain\.current = false;\s*void refreshStatus\(\);\s*\}, \[active, pageMode, refreshStatus\]\);/,
+ /if \(pageMode !== "create"\) \{\s*leftCreate\.current = true;\s*return;\s*\}\s*if \(!active \|\| !leftCreate\.current\) return;\s*leftCreate\.current = false;\s*void refreshStatus\(\);\s*\}, \[active, pageMode, refreshStatus\]\);/,
);
});
@@ -50,7 +50,13 @@ for (const page of ["features/images/images-page.tsx", "features/video/video-pag
src,
/\{trainMounted && \(\s*<div className=\{pageMode === "train" \? "contents" : "hidden"\} inert=\{pageMode !== "train" \|\| undefined\}>\s*<DiffusionTrainPanel/,
);
- assert.match(src, /\/>\s*<\/div>\s*\)\}\s*\{pageMode !== "train" && \(/);
+ // Video has a third mode, Restyle, so its Create view is gated on "create" rather than "not train".
+ assert.match(
+ src,
+ page.includes("video")
+ ? /\/>\s*<\/div>\s*\)\}\s*\{restyleMounted && \(\s*<div className=\{pageMode === "restyle" \? "contents" : "hidden"\} inert=\{pageMode !== "restyle" \|\| undefined\}>\s*<VideoRestylePanel active=\{active\} \/>\s*<\/div>\s*\)\}\s*\{pageMode === "create" && \(/
+ : /\/>\s*<\/div>\s*\)\}\s*\{pageMode !== "train" && \(/,
+ );
assert.doesNotMatch(src, /\{pageMode === "train" \? \(\s*<DiffusionTrainPanel/);
});
}