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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add the OpenAI videos API on /v1/videos (#9891)
Nilay7872208456ca
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.pyindex 24254ea79fe..6a2e9c5d9ed 100644--- a/studio/backend/core/inference/llama_keepwarm.py+++ b/studio/backend/core/inference/llama_keepwarm.py@@ -100,6 +100,12 @@ _INFERENCE_SUFFIXES = ("/video/generate", # /api/inference/video/generate)+# Matched WHOLE, not by suffix. The suffix tuple above is an endswith test, so a bare+# "/videos" entry would also class an unrouted /v1/anything/videos as inference: that+# 404s before any auth dependency, and this middleware only excludes 401/403, so each+# such probe would refresh the chat model's idle timer and keep it resident for free.+_INFERENCE_EXACT_PATHS = frozenset({"/v1/videos", "/api/inference/videos"})+# Tracked above (they hold the GPU, so the in-flight count must see them) but served by the# diffusion/video engines, never the llama slot. A successful one therefore did NOT run against# the resident chat model and must not adopt it for Unsloth: clearing the marker on an image or@@ -109,6 +115,10 @@ _NON_LLM_SLOT_SUFFIXES = ("/images/generate","/images/generations","/video/generate",+ # The OpenAI videos route (/v1/videos + /api/inference/videos) runs the video+ # backend only, exactly like /video/generate. It is tracked as an inference path,+ # so without this it would claim the slot and clear preview ownership.+ "/videos",)@@ -119,6 +129,8 @@ def _is_preview_path(path: str) -> bool:def _is_inference_path(path: str) -> bool:+ if path in _INFERENCE_EXACT_PATHS:+ return Trueif path.startswith(_INFERENCE_PREFIXES) and path.endswith(_INFERENCE_SUFFIXES):return Truereturn _is_preview_path(path)diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.pyindex 16122aa7006..dbd77e3b1ee 100644--- a/studio/backend/core/inference/media_auto_switch.py+++ b/studio/backend/core/inference/media_auto_switch.py@@ -103,6 +103,20 @@ def _resident_answers_exactly(resident: dict[str, Any], name: str) -> bool:)+def resident_answers_media_request(+ resident: dict[str, Any], requested_model: Optional[str], *, owner: str+) -> bool:+ """Whether one exact resident state still answers an auto-switch request."""+ if not isinstance(requested_model, str) or not requested_model.strip():+ return False+ name = requested_model.strip()+ if _resident_answers_exactly(resident, name):+ return True+ task = IMAGE_TASK if owner == DIFFUSION else VIDEO_TASK+ pick = resolve_local_media_model(name, task = task)+ return pick is not None and satisfied_by(resident, name, pick)++async def _require_local(owner: str,pick: MediaModelPick,@@ -518,5 +532,6 @@ __all__ = ["available_media_model_ids","invalidate_index","maybe_auto_switch_media_model",+ "resident_answers_media_request","resolve_local_media_model",]diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.pyindex d5150dcf05c..1188514eb03 100644--- a/studio/backend/core/inference/media_keepwarm.py+++ b/studio/backend/core/inference/media_keepwarm.py@@ -204,6 +204,8 @@ _TRACKED_PATHS = {# The OpenAI-compatible route is on inference_router, mounted at both prefixes."/api/inference/images/generations": DIFFUSION,"/v1/images/generations": DIFFUSION,+ "/api/inference/videos": VIDEO,+ "/v1/videos": VIDEO,}diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 89d5ac27033..a619ae3be6f 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -121,6 +121,7 @@ from .diffusion_precision import (from .video_families import (VIDEO_CANCELLED_MSG,VIDEO_GENERATION_BUSY_MSG,+ VIDEO_MODEL_CHANGED_MSG,VIDEO_NOT_LOADED_MSG,VideoFamily,default_video_generation_params,@@ -1058,6 +1059,8 @@ class VideoBackend:# Which job the flag belongs to. The flag alone cannot tell "my job" from "the job that# replaced mine", so finalising is keyed on this. Compared by identity.self._generate_job_token: Optional[object] = None+ # The OpenAI /v1/videos job id this run was started under, or None for a Studio-page run.+ self._gen_video_id: Optional[str] = Nonedef _device_target(self, ordinal: Optional[int] = None) -> DiffusionDeviceTarget:"""The device target for ``ordinal``, pinned onto the calling thread.@@ -4936,6 +4939,36 @@ class VideoBackend:state = self._statereturn getattr(state, "family", None) if state is not None else None+ def generation_snapshot(self) -> tuple[dict[str, Any], Optional[object]]:+ """Return the route-facing generation fields and their exact resident-state token."""+ from hub.utils.gguf import extract_quant_token+ with self._lock:+ state = self._state+ if state is None:+ return {"loaded": False, "repo_id": None, "defaults": None}, None+ fam = state.family+ status = {+ "loaded": True,+ "repo_id": getattr(state, "repo_id", None),+ "dtype": getattr(state, "dtype", None),+ "model_kind": getattr(state, "kind", None),+ "gguf_variant": (+ extract_quant_token(state.gguf_filename)+ if getattr(state, "kind", None) == "gguf"+ and getattr(state, "gguf_filename", None)+ else None+ ),+ "h3_task": getattr(state, "h3_task", None),+ "defaults": {+ "num_frames": fam.default_num_frames,+ "fps": fam.default_fps,+ "frame_step": fam.frame_step,+ "frame_offset": fam.frame_offset,+ "resolution_presets": [list(p) for p in fam.resolution_presets],+ },+ }+ return status, state+@staticmethoddef _reset_step_cache(pipe: Any) -> None:"""Clear FBCache residuals on the resident DiT(s) before a generation.@@ -4965,11 +4998,13 @@ class VideoBackend:width: Optional[int] = None,height: Optional[int] = None,num_frames: Optional[int] = None,+ duration_s: Optional[float] = None,fps: Optional[int] = None,steps: Optional[int] = None,guidance: Optional[float] = None,guidance_2: Optional[float] = None,seed: Optional[int] = None,+ input_reference: Optional[str] = None,first_frame: Optional[str] = None,last_frame: Optional[str] = None,reference_images: Optional[list[str]] = None,@@ -4978,7 +5013,9 @@ class VideoBackend:reference_image_size: Optional[str] = None,flow_shift: Optional[float] = None,audio_flow_shift: Optional[float] = None,- ) -> None:+ video_id: Optional[str] = None,+ expected_state: Optional[object] = None,+ ) -> dict[str, int]:"""Validate cheaply, then run generate + gallery persist on a daemon thread.Returns at once, mirroring begin_load: a clip takes minutes to denoise, and@@ -4990,24 +5027,37 @@ class VideoBackend:Raises RuntimeError with VIDEO_NOT_LOADED_MSG / VIDEO_GENERATION_BUSY_MSGsentinels the route maps to 409."""+ if input_reference is not None and (first_frame is not None or reference_images):+ raise ValueError(+ "input_reference cannot be combined with explicit conditioning inputs."+ )cancel = threading.Event()job_token = object() # this reservation's identity; only its own worker may finalise itwhile True:# Resolve outside the lock, then retry if the resident state changed.with self._lock:state = self._state+ if expected_state is not None and state is not expected_state:+ raise RuntimeError(VIDEO_MODEL_CHANGED_MSG)if state is None:raise RuntimeError(VIDEO_NOT_LOADED_MSG)if self._generate_job_active:raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)+ resolved_first_frame = first_frame+ resolved_reference_images = reference_images+ if input_reference is not None:+ if state.h3_task == H3_TASK_REFERENCES:+ resolved_reference_images = [input_reference]+ else:+ resolved_first_frame = input_referencefirst_pil, last_pil, canvas_w, canvas_h, conditioning = self._resolve_keyframes(- state.family, state.h3_task, first_frame, last_frame, width, height+ state.family, state.h3_task, resolved_first_frame, last_frame, width, height)references = self._resolve_references(state.family,state.h3_task,state.engine,- reference_images,+ resolved_reference_images,reference_videos,reference_audios,reference_image_size,@@ -5017,6 +5067,14 @@ class VideoBackend:shift, audio_shift = self._resolve_flow_shifts(state.family, state.engine, flow_shift, audio_flow_shift)+ run_num_frames = num_frames+ if duration_s is not None:+ run_fps = int(fps or state.family.default_fps or 24)+ step = max(1, int(state.family.frame_step))+ offset = max(1, int(state.family.frame_offset))+ wanted = max(offset, int(round(float(duration_s) * run_fps)))+ k = max(1, int(round((wanted - offset) / step)))+ run_num_frames = k * step + offsetif references:conditioning = h3_conditioning_mode(has_references = True)resolved_inputs = _VideoResolvedInputs(@@ -5036,12 +5094,13 @@ class VideoBackend:if self._generate_job_active:raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)validate_video_request_shape(- state.family, width = width, height = height, num_frames = num_frames+ state.family, width = width, height = height, num_frames = run_num_frames)self._generate_job_active = Trueself._generate_job_token = job_token# Register before the worker starts so cancellation covers the spawn window.self._active_generate_cancel = cancel+ self._gen_video_id = video_idself._gen = {"active": True,"phase": "queued",@@ -5051,15 +5110,15 @@ class VideoBackend:}breakworker = threading.Thread(- # The token rides on the target rather than in kwargs: those kwargs are also a- # valid generate() call, and callers replay them as one.- target = functools.partial(self._run_generate, job_token = job_token),+ # The token and the /v1/videos job id ride on the target rather than in kwargs:+ # those kwargs are also a valid generate() call, and callers replay them as one.+ target = functools.partial(self._run_generate, job_token = job_token, video_id = video_id),kwargs = dict(prompt = prompt,negative_prompt = negative_prompt,width = width,height = height,- num_frames = num_frames,+ num_frames = run_num_frames,fps = fps,steps = steps,guidance = guidance,@@ -5086,12 +5145,32 @@ class VideoBackend:error = "Video generation could not start.",)raise+ # What this run actually reserved, read off the same state the lock committed.+ # A caller that describes the job from an earlier status() read can be wrong on+ # every one of these: a load committing in between swaps the family, so the+ # frame count it computed belongs to the old fps and the model it reports is+ # already gone. The canvas is here for the same reason -- with a keyframe it+ # follows the source aspect, not the family's first preset.+ state = resolved_inputs.state+ fam = getattr(state, "family", None)+ return {+ "width": resolved_inputs.width,+ "height": resolved_inputs.height,+ "num_frames": (+ run_num_frames+ if run_num_frames is not None+ else getattr(fam, "default_num_frames", None)+ ),+ "fps": fps if fps is not None else getattr(fam, "default_fps", None),+ "model": getattr(state, "repo_id", None),+ }def _run_generate(self,*,cancel_event: threading.Event,job_token: Optional[object] = None,+ video_id: Optional[str] = None,**gen_kwargs: Any,) -> None:"""Backstop around the worker body, so a reservation cannot outlive its thread.@@ -5103,7 +5182,9 @@ class VideoBackend:Still the thread target: begin_generate resolves it by name and doubles subclass it."""try:- self._run_generate_body(cancel_event = cancel_event, job_token = job_token, **gen_kwargs)+ self._run_generate_body(+ cancel_event = cancel_event, job_token = job_token, video_id = video_id, **gen_kwargs+ )finally:if job_token is not None:# Only begin_generate makes a reservation, so only it can leave one dangling.@@ -5120,6 +5201,7 @@ class VideoBackend:*,cancel_event: threading.Event,job_token: Optional[object] = None,+ video_id: Optional[str] = None,**gen_kwargs: Any,) -> None:"""begin_generate's worker: generate, persist to the gallery, record the@@ -5130,9 +5212,20 @@ class VideoBackend:internals (CUDA state, paths) never reach the client."""from . import video_gallery+ def _record_outcome(error: Optional[str] = None) -> None:+ if video_id is None:+ return+ try:+ video_gallery.record_job_outcome(+ video_id, completed_at = int(time.time()), error = error+ )+ except Exception as exc: # noqa: BLE001 -- job persistence must not strand the backend busy+ logger.warning("video.persist_job_outcome_failed: %s", exc)+try:result = self.generate(cancel_event = cancel_event, **gen_kwargs)except ValueError as exc:+ _record_outcome(str(exc))self._finish_generate_job(job_token = job_token, cancel_event = cancel_event, error = str(exc))@@ -5142,10 +5235,12 @@ class VideoBackend:if msg not in (VIDEO_NOT_LOADED_MSG, VIDEO_CANCELLED_MSG):logger.error("video.generate_failed: %s", exc, exc_info = True)msg = "Video generation failed."+ _record_outcome(msg)self._finish_generate_job(job_token = job_token, cancel_event = cancel_event, error = msg)returnexcept Exception as exc: # noqa: BLE001 -- worker thread: never propagatelogger.error("video.generate_failed: %s", exc, exc_info = True)+ _record_outcome("Video generation failed.")self._finish_generate_job(job_token = job_token,cancel_event = cancel_event,@@ -5190,15 +5285,18 @@ class VideoBackend:"offload_policy": result.get("offload_policy"),"created_at": created_at,},+ **({"video_id": video_id} if video_id is not None else {}),)except Exception as exc: # noqa: BLE001 -- disk failure must reach the pollerlogger.error("video.persist_failed: %s", exc)+ _record_outcome("Failed to save the generated video.")self._finish_generate_job(job_token = job_token,cancel_event = cancel_event,error = "Failed to save the generated video.",)return+ _record_outcome()self._finish_generate_job(job_token = job_token,cancel_event = cancel_event,@@ -6089,6 +6187,8 @@ class VideoBackend:# generate() swaps in a bare {"active": False} before the worker records the terminal dict; report active across that gap.if self._generate_job_active:gen["active"] = True+ if self._gen_video_id is not None:+ gen["video_id"] = self._gen_video_idgen.setdefault("active", False)# Mirror the image endpoint field names (total_steps / fraction) alongside the native "total": the two generate-progress APIs used to disagree.total = int(gen.get("total") or 0)@@ -6118,9 +6218,11 @@ class VideoBackend:self._gen = {"active": False}return True- def cancel_generate(self) -> bool:+ def cancel_generate(self, expected_video_id: Optional[str] = None) -> bool:"""Signal the in-flight generation to stop at its next step callback."""with self._lock:+ if expected_video_id is not None and self._gen_video_id != expected_video_id:+ return Falsecancel = self._active_generate_cancelif cancel is None:return Falsediff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex 8ac81af880a..8d8cc691cc8 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -30,6 +30,7 @@ MAX_VIDEO_NUM_FRAMES = 1024VIDEO_NOT_LOADED_MSG = "No video model is loaded."VIDEO_CANCELLED_MSG = "Video generation was cancelled."VIDEO_GENERATION_BUSY_MSG = "A video generation is already in progress."+VIDEO_MODEL_CHANGED_MSG = "The requested video model changed before generation was reserved."@dataclass(frozen = True)diff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.pyindex 742f7f8af46..0c3f2de95f3 100644--- a/studio/backend/core/inference/video_gallery.py+++ b/studio/backend/core/inference/video_gallery.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport jsonimport osimport re+import threadingimport uuidfrom collections.abc import Callablefrom pathlib import Path@@ -26,15 +27,115 @@ logger = get_logger(__name__)# Video ids are file stems; restrict to safe chars so a crafted id can't escape the directory._ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")+_JOB_OUTCOME_KEY = "_worker_outcome"+_job_lock = threading.Lock()def gallery_dir() -> Path:return ensure_dir(studio_root() / "videos")-def save(mp4_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:+def _job_dir() -> Path:+ return ensure_dir(gallery_dir() / ".jobs")+++def _job_path(video_id: str) -> Optional[Path]:+ if not _ID_RE.match(video_id):+ return None+ return _job_dir() / f"{video_id}.json"+++def _read_job(path: Path, video_id: str) -> Optional[dict[str, Any]]:+ try:+ raw = json.loads(path.read_text(encoding = "utf-8"))+ except (OSError, UnicodeError, ValueError, TypeError):+ return None+ return raw if isinstance(raw, dict) and raw.get("id") == video_id else None+++def _write_job(path: Path, job: dict[str, Any]) -> None:+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ tmp.write_text(json.dumps(job), encoding = "utf-8")+ os.replace(tmp, path)+ finally:+ tmp.unlink(missing_ok = True)+++def save_job(video_id: str, job: dict[str, Any]) -> None:+ """Atomically persist an OpenAI job, preserving any worker outcome that raced it."""+ path = _job_path(video_id)+ if path is None:+ raise ValueError("Invalid video id.")+ with _job_lock:+ existing = _read_job(path, video_id) or {}+ stored = dict(job)+ if isinstance(existing.get(_JOB_OUTCOME_KEY), dict):+ stored[_JOB_OUTCOME_KEY] = existing[_JOB_OUTCOME_KEY]+ _write_job(path, stored)+++def record_job_outcome(+ video_id: str,+ *,+ completed_at: int,+ error: Optional[str] = None,+) -> None:+ """Persist a worker result by id before the backend can accept another generation."""+ path = _job_path(video_id)+ if path is None:+ raise ValueError("Invalid video id.")+ with _job_lock:+ stored = _read_job(path, video_id) or {"id": video_id}+ stored[_JOB_OUTCOME_KEY] = {"completed_at": completed_at, "error": error}+ _write_job(path, stored)+++def get_job(video_id: str) -> Optional[dict[str, Any]]:+ path = _job_path(video_id)+ if path is None:+ return None+ with _job_lock:+ return _read_job(path, video_id)+++def list_jobs() -> list[dict[str, Any]]:+ try:+ paths = list(_job_dir().glob("*.json"))+ except OSError:+ return []+ jobs = []+ for path in paths:+ job = get_job(path.stem)+ if job is not None:+ jobs.append(job)+ return jobs+++def forget_job(video_id: str) -> bool:+ """Remove a persisted OpenAI job; missing state already satisfies the request."""+ path = _job_path(video_id)+ if path is None:+ return False+ with _job_lock:+ try:+ path.unlink(missing_ok = True)+ except OSError as exc:+ logger.warning("video_gallery.forget_job_failed: %s", exc)+ return False+ return True+++def save(+ mp4_bytes: bytes,+ meta: dict[str, Any],+ video_id: Optional[str] = None,+) -> dict[str, Any]:"""Persist encoded MP4 bytes plus their recipe sidecar; return the record."""- video_id = uuid.uuid4().hex+ if video_id is None:+ video_id = uuid.uuid4().hex+ elif not _ID_RE.match(video_id):+ raise ValueError("Invalid video id.")directory = gallery_dir()mp4_path = directory / f"{video_id}.mp4"mp4_tmp = directory / f".{video_id}.mp4.tmp"@@ -86,6 +187,36 @@ def video_path(video_id: str) -> Optional[Path]:return path if path.is_file() else None+def thumbnail(video_id: str) -> Optional[bytes]:+ """Encode the first frame of an owned clip as the OpenAI-compatible WebP preview."""+ path = owned_video_path(video_id)+ if path is None:+ return None+ return _thumbnail_webp(path)+++def _thumbnail_webp(path: Path) -> bytes:+ import io+ try:+ import av+ except Exception as exc: # noqa: BLE001 -- no PyAV -> no thumbnail+ raise RuntimeError("Thumbnail generation needs the 'av' package (PyAV).") from exc+ try:+ with av.open(str(path)) as src:+ if not src.streams.video:+ raise RuntimeError("Thumbnail generation failed: the clip has no video stream.")+ frame = next(src.decode(src.streams.video[0]), None)+ if frame is None:+ raise RuntimeError("Thumbnail generation failed: the clip has no decodable frames.")+ buf = io.BytesIO()+ frame.to_image().save(buf, format = "WEBP", quality = 85, method = 4)+ return buf.getvalue()+ except RuntimeError:+ raise+ except Exception as exc: # noqa: BLE001 -- surface decoder / WebP encoder failures+ raise RuntimeError(f"Thumbnail generation failed to decode the clip: {exc}") from exc++def transcode_to_file(video_id: str, fmt: str) -> Optional[Path]:"""Re-encode a stored MP4 for the Download menu into a TEMP FILE and return its path, or Nonewhen the id doesn't resolve. Raises RuntimeError on missing codec/deps (route 501s). The caller@@ -300,6 +431,15 @@ def _read_meta(sidecar: Path) -> Optional[dict[str, Any]]:return meta+def get_record(video_id: str) -> Optional[dict[str, Any]]:+ if owned_video_path(video_id) is None:+ return None+ meta = _read_meta(_sidecar_path(video_id))+ if meta is None:+ return None+ return _record(video_id, meta)++def owned_video_path(video_id: str) -> Optional[Path]:"""Resolve an id to its MP4 only when it is an Unsloth-owned clip (a readable sidecar), elseNone. The serve and export routes use this instead of video_path() so a guessed stem for a@@ -409,8 +549,8 @@ def delete(video_id: str) -> bool:return True-def clear(include_archived: bool = False) -> int:- """Delete Unsloth-owned gallery pairs (readable sidecar); return how many were removed.+def clear(include_archived: bool = False, *, return_ids: bool = False) -> int | list[str]:+ """Delete owned gallery pairs and return their count, or their ids when requested.Archived clips are SPARED by default: archiving is how a user sets something aside, so a"clear the gallery" action that destroyed the archive would defeat it. Pass@@ -432,7 +572,7 @@ def clear(include_archived: bool = False) -> int:try:paths = list(directory.glob("*.mp4"))except OSError:- return 0+ return [] if return_ids else 0cleared: list[str] = []for path in paths:if _read_meta(_sidecar_path(path.stem)) is None: # orphan / not ours@@ -456,4 +596,4 @@ def clear(include_archived: bool = False) -> int:gallery_flags.reset_locked(directory)else:gallery_flags.forget_locked(directory, cleared)- return removed+ return cleared if return_ids else removeddiff --git a/studio/backend/main.py b/studio/backend/main.pyindex 71b188a8e10..ee9676a5e2c 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -313,6 +313,7 @@ from routes import (training_history_router,training_router,video_router,+ video_openai_router,youtube_router,)from routes.llama import router as llama_router@@ -1096,13 +1097,15 @@ from utils.upload_limits import ( # noqa: E402STT_AUDIO_JSON_MAX_BYTES,STT_AUDIO_RAW_MAX_BYTES,UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ VIDEO_INPUT_REFERENCE_MAX_BYTES,default_request_body_limit_bytes,upload_request_limit_bytes,)_BODY_PROTECTED_PREFIXES = (# Blanket-protect the whole /v1 surface, like /api/inference: every /v1 POST buffers a JSON- # body and none is a multipart passthrough, so one prefix caps them all.+ # body (the multipart routes are listed as exact passthroughs below), so one prefix caps them all."/v1","/p/","/api/inference",@@ -1130,6 +1133,10 @@ _STT_MULTIPART_UPLOAD_PATHS = ("/v1/audio/transcriptions","/api/inference/audio/transcriptions",)+_VIDEO_MULTIPART_UPLOAD_PATHS = (+ "/v1/videos",+ "/api/inference/videos",+)_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (*_DATASET_UPLOAD_PASSTHROUGH_PREFIXES,_DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX,@@ -1138,7 +1145,14 @@ _BODY_UPLOAD_PASSTHROUGH_PREFIXES = (_BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (_DIFFUSION_DATASET_UPLOAD_PATH,*_STT_MULTIPART_UPLOAD_PATHS,+ *_VIDEO_MULTIPART_UPLOAD_PATHS,)+# Which of those may arrive with no Content-Length and be counted instead of refused.+# Deliberately NOT the whole set above: this middleware runs before authentication, and+# a counted body is a held body, so the dataset path (whose cap is the configurable+# upload limit, up to 8 GB) and the 25 MB stt paths keep their 411. The videos+# reference image is bounded at 32 MB, the same order as the default protected cap.+_CHUNKED_UPLOAD_EXACT_PATHS = _VIDEO_MULTIPART_UPLOAD_PATHSdef _get_upload_passthrough_request_max_bytes(path: str) -> int:@@ -1146,6 +1160,11 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:return upload_request_limit_bytes(UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES)if path.rstrip("/") in _STT_MULTIPART_UPLOAD_PATHS:return upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)+ if path.rstrip("/") in _VIDEO_MULTIPART_UPLOAD_PATHS:+ return max(+ upload_request_limit_bytes(VIDEO_INPUT_REFERENCE_MAX_BYTES),+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ )# The trailing-slash variant reaches this middleware BEFORE the router's redirect_slashes# 307, so it must resolve to the same cap. JSON sub-routes keep extra path components.if (@@ -1164,6 +1183,11 @@ def _get_request_body_max_bytes(path: str) -> int:# multipart headroom over the raw stt cap for the openai transcription route on both mountsif path.rstrip("/") in _STT_MULTIPART_UPLOAD_PATHS:return upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)+ if path.rstrip("/") in _VIDEO_MULTIPART_UPLOAD_PATHS:+ return max(+ upload_request_limit_bytes(VIDEO_INPUT_REFERENCE_MAX_BYTES),+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ )return default_request_body_limit_bytes()@@ -1213,6 +1237,7 @@ class MaxBodyMiddleware:upload_passthrough_prefixes: tuple = (),upload_passthrough_max_bytes_getter = None,upload_passthrough_exact_paths: tuple = (),+ chunked_upload_exact_paths: tuple = (),):self.app = appself.max_bytes_getter = max_bytes_getter@@ -1222,6 +1247,8 @@ class MaxBodyMiddleware:self.upload_passthrough_max_bytes_getter = upload_passthrough_max_bytes_getter# Exact path, not prefix: sibling JSON sub-routes must keep the normal (small) body cap.self.upload_passthrough_exact_paths = upload_passthrough_exact_paths+ # The subset of those allowed to omit Content-Length; the rest still get a 411.+ self.chunked_upload_exact_paths = chunked_upload_exact_pathsdef _is_upload_passthrough(self, path: str) -> bool:# Exact paths also match their trailing-slash variant (this runs before redirect_slashes).@@ -1274,14 +1301,16 @@ class MaxBodyMiddleware:if self._is_upload_passthrough(path):upload_max_bytes = self._upload_passthrough_max_bytes(path)- if declared is None:- await _send_411(send)+ if declared is not None:+ if declared > upload_max_bytes:+ await _send_413(send, declared, upload_max_bytes)+ return+ await self.app(scope, receive, send)return- if declared > upload_max_bytes:- await _send_413(send, declared, upload_max_bytes)+ if path.rstrip("/") not in self.chunked_upload_exact_paths:+ await _send_411(send)return- await self.app(scope, receive, send)- return+ max_bytes = upload_max_bytesif declared is not None and declared > max_bytes:await _send_413(send, declared, max_bytes)@@ -1331,6 +1360,7 @@ app.add_middleware(upload_passthrough_prefixes = _BODY_UPLOAD_PASSTHROUGH_PREFIXES,upload_passthrough_max_bytes_getter = _get_upload_passthrough_request_max_bytes,upload_passthrough_exact_paths = _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS,+ chunked_upload_exact_paths = _CHUNKED_UPLOAD_EXACT_PATHS,)# Tracks in-flight inference requests for idle auto-unload; off -> passthrough.@@ -1413,6 +1443,8 @@ 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_openai_router, prefix = "/v1", tags = ["openai-compat"])# OpenAI-compatible: mount the inference router at /v1 for external tools.app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 9b2addd5b70..6575c58de82 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4207,6 +4207,62 @@ class AudioGalleryListResponse(BaseModel):next_before_id: Optional[str] = None+# ── OpenAI-compatible videos API (/v1/videos) ──+++class VideoJobCreateRequest(BaseModel):+ prompt: str = Field(..., min_length = 1)+ model: Optional[str] = None+ seconds: Optional[str] = Field(+ None, description = "Clip duration in seconds, snapped to the loaded family's frame lattice."+ )+ size: Optional[str] = Field(+ None, description = "'<width>x<height>', a resolution preset of the loaded family."+ )++ @field_validator("model", "seconds", "size", mode = "before")+ @classmethod+ def _blank_means_default(cls, value):+ if value is None:+ return None+ return str(value).strip() or None+++class VideoJobError(BaseModel):+ code: str+ message: str+++class VideoJob(BaseModel):+ id: str+ object: Literal["video"] = "video"+ model: str+ status: Literal["queued", "in_progress", "completed", "failed"]+ progress: int = Field(0, ge = 0, le = 100)+ created_at: int+ completed_at: Optional[int] = None+ expires_at: Optional[int] = None+ prompt: Optional[str] = None+ size: str+ seconds: str+ error: Optional[VideoJobError] = None+ remixed_from_video_id: Optional[str] = None+++class VideoJobListResponse(BaseModel):+ object: Literal["list"] = "list"+ data: List[VideoJob] = Field(default_factory = list)+ first_id: Optional[str] = None+ last_id: Optional[str] = None+ has_more: bool = False+++class VideoJobDeleteResponse(BaseModel):+ id: str+ object: Literal["video.deleted"] = "video.deleted"+ deleted: bool = True++# ── Video (local text-to-video) ──diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.pyindex 875d1aad62b..e4772c1b9d2 100644--- a/studio/backend/routes/__init__.py+++ b/studio/backend/routes/__init__.py@@ -10,6 +10,7 @@ from routes.models import router as models_routerfrom routes.inference import router as inference_routerfrom routes.inference import studio_router as inference_studio_routerfrom routes.video import router as video_router+from routes.video import openai_router as video_openai_routerfrom routes.datasets import router as datasets_routerfrom routes.auth import router as auth_routerfrom routes.data_recipe import router as data_recipe_router@@ -31,6 +32,7 @@ __all__ = ["inference_router","inference_studio_router","video_router",+ "video_openai_router","datasets_router","auth_router","data_recipe_router",@@ -47,4 +49,11 @@ __all__ = []# Bind the re-export so the import-hoist verifier counts it as used.-_ = (rag_router, video_router, research_runs_router, chat_generation_runs_router, youtube_router)+_ = (+ rag_router,+ video_router,+ video_openai_router,+ research_runs_router,+ chat_generation_runs_router,+ youtube_router,+)diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 6e417607c92..318e3ded6d9 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -18,16 +18,24 @@ here.from __future__ import annotationsimport asyncio+import base64import hashlib as _hashlibimport hmac as _hmac+import re as _reimport secrets as _secrets+import threadingimport time as _time-from typing import Annotated, Optional+import uuid+from dataclasses import asdict, dataclass+from datetime import datetime, timezone+from typing import Annotated, Any, Literal, Optional-from fastapi import APIRouter, Depends, HTTPException, Query, Response+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Responsefrom pydantic import ValidationError+from starlette.datastructures import UploadFilefrom auth.authentication import get_current_subject, request_admitted_without_credential+from core.inference.model_ids import public_model_idfrom hub.dependencies import get_hf_tokenfrom loggers import get_loggerfrom models.inference import (@@ -38,14 +46,22 @@ from models.inference import (VideoGenerateProgressResponse,VideoGenerateRequest,VideoGenerateResponse,+ VideoJob,+ VideoJobCreateRequest,+ VideoJobDeleteResponse,+ VideoJobError,+ VideoJobListResponse,VideoLoadProgressResponse,VideoLoadRequest,VideoStatusResponse,)+from utils.api_errors import openai_error_body+from utils.upload_limits import VIDEO_INPUT_REFERENCE_MAX_BYTESlogger = get_logger(__name__)router = APIRouter()+openai_router = APIRouter()def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True):@@ -741,6 +757,8 @@ async def delete_gallery_video(video_id: str, current_subject: str = Depends(getif not deleted:raise HTTPException(status_code = 404, detail = "Video not found.")_forget_terminal_video(video_id)+ if not await asyncio.to_thread(_forget_openai_job, video_id):+ raise HTTPException(status_code = 500, detail = "Could not delete the video job.")return {"deleted": True}@@ -750,7 +768,7 @@ async def clear_gallery_videos(current_subject: str = Depends(get_current_subjecfrom core.inference.gallery_flags import FlagsUnavailabletry:- removed = await asyncio.to_thread(video_gallery.clear)+ cleared = await asyncio.to_thread(video_gallery.clear, return_ids = True)except FlagsUnavailable as exc:# Refuse rather than delete the archive we cannot prove is archived.logger.warning("video_gallery.clear_blocked: %s", exc)@@ -761,4 +779,831 @@ async def clear_gallery_videos(current_subject: str = Depends(get_current_subjec)# Clear-all takes the terminal record's clip with it whatever its id._forget_terminal_video(None)- return {"removed": removed}+ failed = await asyncio.to_thread(_forget_openai_jobs, cleared)+ if failed:+ raise HTTPException(status_code = 500, detail = "Could not delete every video job.")+ return {"removed": len(cleared)}+++# ── OpenAI-compatible videos API (/v1/videos) ──++_VIDEO_SIZE_RE = _re.compile(r"^(\d{1,5})\s*x\s*(\d{1,5})$")+_VIDEO_SECONDS_MAX = 120.0+_VIDEO_JOB_ID_PREFIX = "video_"+_MAX_REMEMBERED_JOBS = 256+_VIDEO_POLL_AFTER_MS = "2000"+_NO_VIDEO_MODEL_MSG = "No video model loaded. Load a video model first."+_VIDEO_FAILED_CODE = "video_generation_failed"+_VIDEO_CREATE_FIELDS = ("prompt", "model", "seconds", "size")+# Upper bound on how long DELETE waits for a cancelled run to stop writing.+_DELETE_SETTLE_TIMEOUT_S = 10.0+++@dataclass+class _VideoJob:+ id: str+ created_at: int+ prompt: str+ model: str+ size: str+ seconds: str+ status: str = "queued"+ progress: int = 0+ completed_at: Optional[int] = None+ error: Optional[dict] = None++ @property+ def terminal(self) -> bool:+ return self.status in ("completed", "failed")+++_jobs: dict[str, _VideoJob] = {}+_jobs_lock = threading.Lock()+++def _forget_openai_job(video_id: str) -> bool:+ """Forget disk and memory state without letting a stale poll save between them."""+ from core.inference import video_gallery++ with _jobs_lock:+ if not video_gallery.forget_job(video_id):+ return False+ _jobs.pop(video_id, None)+ return True+++def _forget_openai_jobs(video_ids: list[str]) -> list[str]:+ failed = []+ for video_id in video_ids:+ if not _forget_openai_job(video_id):+ failed.append(video_id)+ return failed+++def _openai_video_error(+ status: int,+ message: str,+ *,+ code: Optional[str] = None,+ param: Optional[str] = None,+) -> HTTPException:+ return HTTPException(+ status_code = status,+ detail = openai_error_body(message, status = status, code = code, param = param),+ )+++def _not_found(video_id: str) -> HTTPException:+ return _openai_video_error(+ 404, f"No video found with id '{video_id[:128]}'.", code = "video_not_found", param = "video_id"+ )+++def _parse_openai_video_size(size: Optional[str]) -> Optional[tuple[int, int]]:+ text = (size or "").strip().lower()+ if text in ("", "auto"):+ return None+ match = _VIDEO_SIZE_RE.match(text)+ if not match:+ raise ValueError("size must be '<width>x<height>', e.g. '768x512'.")+ width, height = int(match.group(1)), int(match.group(2))+ for label, value in (("width", width), ("height", height)):+ if not 32 <= value <= 2048:+ raise ValueError(f"size {label} must be between 32 and 2048.")+ return width, height+++def _parse_openai_video_seconds(seconds: Optional[str]) -> Optional[float]:+ text = (seconds or "").strip().lower()+ if text in ("", "auto"):+ return None+ try:+ value = float(text)+ except ValueError:+ raise ValueError("seconds must be a number of seconds, e.g. '4'.") from None+ if value != value or not 0 < value <= _VIDEO_SECONDS_MAX:+ raise ValueError(f"seconds must be between 0 and {_VIDEO_SECONDS_MAX:g}.")+ return value+++def _frames_for_seconds(seconds: float, defaults: dict) -> int:+ fps = int(defaults.get("fps") or 24)+ step = max(1, int(defaults.get("frame_step") or 1))+ offset = max(1, int(defaults.get("frame_offset") or 1))+ wanted = max(offset, int(round(seconds * fps)))+ k = max(1, int(round((wanted - offset) / step)))+ return k * step + offset+++def _format_seconds(value: float) -> str:+ return f"{round(float(value), 2):g}"+++def _record_epoch(record: dict) -> int:+ raw = record.get("created_at")+ if isinstance(raw, (int, float)):+ return int(raw)+ if isinstance(raw, str):+ try:+ parsed = datetime.fromisoformat(raw.strip().replace("Z", "+00:00"))+ except ValueError:+ return 0+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo = timezone.utc)+ return int(parsed.timestamp())+ return 0+++_IMAGE_MAGIC = (+ (b"\x89PNG\r\n\x1a\n", "image/png"),+ (b"\xff\xd8\xff", "image/jpeg"),+ (b"GIF87a", "image/gif"),+ (b"GIF89a", "image/gif"),+ (b"BM", "image/bmp"),+)+++def _sniff_image_type(data: bytes) -> Optional[str]:+ for magic, mime in _IMAGE_MAGIC:+ if data.startswith(magic):+ return mime+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":+ return "image/webp"+ return None+++def _valid_gallery_video_record(record: dict) -> bool:+ try:+ GalleryVideo(**record)+ except ValidationError:+ return False+ return True+++def _record_to_job(record: dict, job: Optional[_VideoJob] = None) -> VideoJob:+ saved_at = _record_epoch(record)+ created = job.created_at if job is not None else saved_at+ completed = (job.completed_at if job is not None else None) or saved_at or created+ return VideoJob(+ id = record["id"],+ model = public_model_id(+ str(record.get("model") or (job.model if job is not None else "") or "video")+ ),+ status = "completed",+ progress = 100,+ created_at = created,+ completed_at = completed,+ prompt = record.get("prompt"),+ size = f"{record.get('width')}x{record.get('height')}",+ seconds = _format_seconds(record.get("duration_s") or 0.0),+ )+++def _job_to_openai(job: _VideoJob) -> VideoJob:+ return VideoJob(+ id = job.id,+ model = job.model,+ status = job.status, # type: ignore[arg-type]+ progress = job.progress,+ created_at = job.created_at,+ completed_at = job.completed_at,+ prompt = job.prompt,+ size = job.size,+ seconds = job.seconds,+ error = VideoJobError(**job.error) if job.error else None,+ )+++def _remember_job(job: _VideoJob) -> None:+ from core.inference import video_gallery++ with _jobs_lock:+ pending = [existing for existing in _jobs.values() if not existing.terminal]+ for existing in pending:+ persisted = _job_from_record(video_gallery.get_job(existing.id) or {})+ if persisted is not None and persisted.terminal:+ with _jobs_lock:+ if _jobs.get(existing.id) is existing:+ _jobs[existing.id] = persisted+ with _jobs_lock:+ _jobs[job.id] = job+ excess = len(_jobs) - _MAX_REMEMBERED_JOBS+ if excess > 0:+ for stale in [j for j in _jobs.values() if j.terminal][:excess]:+ _jobs.pop(stale.id, None)+ try:+ video_gallery.save_job(job.id, asdict(job))+ except OSError as exc:+ logger.warning("openai_videos.persist_job_failed: %s", exc)+++def _job_from_record(record: dict) -> Optional[_VideoJob]:+ from core.inference.video_families import VIDEO_CANCELLED_MSG+ try:+ stored = dict(record)+ outcome = stored.pop("_worker_outcome", None)+ job = _VideoJob(**stored)+ if isinstance(outcome, dict):+ message = outcome.get("error")+ job.completed_at = int(outcome.get("completed_at") or job.completed_at or 0) or None+ if message is None:+ job.status, job.progress, job.error = "completed", 100, None+ else:+ message = str(message)+ job.status, job.progress = "failed", 0+ job.error = {+ "code": "cancelled" if message == VIDEO_CANCELLED_MSG else _VIDEO_FAILED_CODE,+ "message": message,+ }+ if job.status not in ("queued", "in_progress", "completed", "failed"):+ return None+ _job_to_openai(job)+ except (TypeError, ValueError, OverflowError, ValidationError):+ return None+ return job+++def _hydrate_job(video_id: str) -> None:+ from core.inference import video_gallery+ with _jobs_lock:+ if video_id in _jobs:+ return+ job = _job_from_record(video_gallery.get_job(video_id) or {})+ if job is not None:+ _jobs.setdefault(job.id, job)+++def _hydrate_jobs() -> list[_VideoJob]:+ from core.inference import video_gallery+ with _jobs_lock:+ jobs = [+ job for raw in video_gallery.list_jobs() if (job := _job_from_record(raw)) is not None+ ]+ jobs.sort(key = lambda job: job.created_at, reverse = True)+ for job in jobs[:_MAX_REMEMBERED_JOBS]:+ _jobs.setdefault(job.id, job)+ return jobs+++def _sync_jobs() -> None:+ from core.inference import video_gallery+ from core.inference.video import get_video_backend+ from core.inference.video_families import VIDEO_CANCELLED_MSG++ with _jobs_lock:+ open_jobs = [job for job in _jobs.values() if not job.terminal]+ if not open_jobs:+ return+ gen = get_video_backend().generate_progress()+ now = int(_time.time())+ for job in open_jobs:+ persisted_job = _job_from_record(video_gallery.get_job(job.id) or {})+ if persisted_job is not None and persisted_job.terminal:+ with _jobs_lock:+ if _jobs.get(job.id) is job:+ _jobs[job.id] = persisted_job+ continue+ status: Optional[str] = None+ progress = 0+ completed_at: Optional[int] = None+ error: Optional[dict] = None+ if gen.get("video_id") == job.id:+ phase = gen.get("phase")+ if phase == "queued":+ status = "queued"+ elif phase in ("denoise", "export") or gen.get("active"):+ fraction = float(gen.get("fraction") or 0.0)+ status = "in_progress"+ progress = 99 if phase == "export" else max(0, min(99, int(fraction * 100)))+ elif phase == "completed":+ status, progress, completed_at = "completed", 100, now+ elif phase == "failed":+ message = str(gen.get("error") or "Video generation failed.")+ status = "failed"+ error = {+ "code": "cancelled" if message == VIDEO_CANCELLED_MSG else _VIDEO_FAILED_CODE,+ "message": message,+ }+ if status is None:+ if video_gallery.owned_video_path(job.id) is not None:+ status, progress, completed_at = "completed", 100, now+ else:+ status = "failed"+ error = {+ "code": _VIDEO_FAILED_CODE,+ "message": "The generation ended before a clip was saved.",+ }+ with _jobs_lock:+ if _jobs.get(job.id) is not job:+ continue+ if job.terminal:+ continue+ if job.status == "in_progress" and status == "queued":+ continue+ if job.status == "in_progress" and status == "in_progress":+ progress = max(job.progress, progress)+ job.status = status+ job.progress = progress+ if completed_at is not None:+ job.completed_at = completed_at+ if error is not None:+ job.error = error+ persisted = asdict(job)+ try:+ video_gallery.save_job(job.id, persisted)+ except OSError as exc:+ logger.warning("openai_videos.persist_job_failed: %s", exc)+++def _await_generate_settled(video_id: str, timeout: float = _DELETE_SETTLE_TIMEOUT_S) -> bool:+ """Block until the run started for ``video_id`` is no longer in flight.++ Bounded, so a wedged backend cannot hold the request open. Returns False when the+ wait expired with the run still live: the caller must not report a deletion it+ could not observe, or the worker commits its sidecar afterwards and the clip+ reappears through retrieve/list.+ """+ from core.inference.video import get_video_backend++ backend = get_video_backend()+ deadline = _time.monotonic() + timeout+ while _time.monotonic() < deadline:+ gen = backend.generate_progress()+ if gen.get("video_id") != video_id or not gen.get("active"):+ return True+ _time.sleep(0.05)+ return False+++def _lookup_video(video_id: str) -> Optional[VideoJob]:+ from core.inference import video_gallery++ _hydrate_job(video_id)+ _sync_jobs()+ with _jobs_lock:+ job = _jobs.get(video_id)+ if job is not None and job.status != "completed":+ return _job_to_openai(job)+ record = video_gallery.get_record(video_id)+ if record is None:+ return None+ return _record_to_job(record, job)+++def _all_videos() -> list[VideoJob]:+ from core.inference import video_gallery++ persisted_jobs = _hydrate_jobs()+ _sync_jobs()+ with _jobs_lock:+ jobs = {job.id: job for job in persisted_jobs}+ jobs.update(_jobs)+ records = video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record)+ records.extend(+ video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record, archived = True)+ )+ listed = [_record_to_job(record, jobs.get(record["id"])) for record in records]+ seen = {video.id for video in listed}+ listed.extend(+ _job_to_openai(job)+ for job in jobs.values()+ if job.id not in seen and job.status != "completed"+ )+ return listed+++async def _read_video_create_body(request: Request) -> tuple[dict, Any]:+ ctype = (request.headers.get("content-type") or "").lower()+ if ctype.startswith(("multipart/form-data", "application/x-www-form-urlencoded")):+ try:+ form = await request.form()+ except Exception: # noqa: BLE001+ raise _openai_video_error(400, "Could not parse the multipart form body.")+ fields = {key: form.get(key) for key in _VIDEO_CREATE_FIELDS if key in form}+ reference = form.get("input_reference")+ if reference is None:+ nested_reference = {+ key: form.get(f"input_reference[{key}]")+ for key in ("image_url", "file_id")+ if f"input_reference[{key}]" in form+ }+ reference = nested_reference or None+ return fields, reference+ try:+ data = await request.json()+ except Exception: # noqa: BLE001+ raise _openai_video_error(400, "Request body must be JSON or multipart/form-data.")+ if not isinstance(data, dict):+ raise _openai_video_error(400, "Request body must be a JSON object.")+ return {key: data.get(key) for key in _VIDEO_CREATE_FIELDS if key in data}, data.get(+ "input_reference"+ )+++def _validate_create_fields(fields: dict) -> VideoJobCreateRequest:+ try:+ return VideoJobCreateRequest(**fields)+ except ValidationError as exc:+ errors = exc.errors()+ first = errors[0] if errors else {}+ loc = first.get("loc") or ()+ param = str(loc[0]) if loc else None+ message = str(first.get("msg") or "Invalid request.")+ raise _openai_video_error(400, f"{param}: {message}" if param else message, param = param)+++async def _reference_to_data_url(reference: Any) -> Optional[str]:+ if reference is None:+ return None+ if isinstance(reference, dict):+ if reference.get("file_id"):+ raise _openai_video_error(+ 400,+ "input_reference.file_id is not supported; send the image as a file upload or a base64 data URL.",+ param = "input_reference",+ )+ reference = reference.get("image_url")+ if reference is None:+ return None+ if isinstance(reference, UploadFile):+ data = await reference.read()+ if not data:+ raise _openai_video_error(400, "input_reference is empty.", param = "input_reference")+ if len(data) > VIDEO_INPUT_REFERENCE_MAX_BYTES:+ raise _openai_video_error(+ 400,+ f"input_reference is too large; the limit is {VIDEO_INPUT_REFERENCE_MAX_BYTES // (1024 * 1024)} MB.",+ param = "input_reference",+ )+ content_type = (reference.content_type or "").split(";")[0].strip().lower()+ sniffed = _sniff_image_type(data)+ if not content_type.startswith("image/"):+ if sniffed is None:+ raise _openai_video_error(+ 400, "input_reference must be an image.", param = "input_reference"+ )+ content_type = sniffed+ encoded = base64.b64encode(data).decode("ascii")+ return f"data:{content_type};base64,{encoded}"+ if isinstance(reference, str):+ text = reference.strip()+ if not text:+ return None+ if text.lower().startswith(("http://", "https://")):+ raise _openai_video_error(+ 400,+ "Remote input_reference URLs are not fetched; send the image as a file upload or a base64 data URL.",+ param = "input_reference",+ )+ return text+ raise _openai_video_error(+ 400, "input_reference must be an image file or a base64 data URL.", param = "input_reference"+ )+++@openai_router.post("/videos", response_model = VideoJob)+async def openai_create_video(+ request: Request,+ current_subject: str = Depends(get_current_subject),+ hf_token: Optional[str] = Depends(get_hf_token),+):+ # The body has to be read before the row can name a model and prompt, so the parse+ # sits out here and the rest of the handler runs inside the monitor context.+ from routes.inference import _monitored_media_request++ fields, raw_reference = await _read_video_create_body(request)+ body = _validate_create_fields(fields)+ reference = await _reference_to_data_url(raw_reference)+ from core.inference.api_monitor import api_monitor++ async with _monitored_media_request(+ request,+ model = public_model_id(body.model) or body.model or "",+ prompt = body.prompt,+ subject = current_subject,+ ) as monitor_id:+ job = await _create_openai_video(body, reference, current_subject, hf_token)+ api_monitor.relabel(monitor_id, job.model)+ return job+++# Split out so the API monitor row can wrap the whole handler without reindenting it,+# exactly as the OpenAI image route does.+async def _create_openai_video(+ body: VideoJobCreateRequest,+ reference: Optional[str],+ current_subject: str,+ hf_token: Optional[str],+):+ from core.inference.gpu_arbiter import VIDEO+ from core.inference.media_auto_switch import (+ maybe_auto_switch_media_model,+ resident_answers_media_request,+ )+ from core.inference.video import get_video_backend+ from core.inference.video_families import (+ VIDEO_GENERATION_BUSY_MSG,+ VIDEO_MODEL_CHANGED_MSG,+ VIDEO_NOT_LOADED_MSG,+ VideoShapeError,+ )+ from utils.openai_auto_switch_settings import get_media_auto_switch_enabled++ try:+ size = _parse_openai_video_size(body.size)+ except ValueError as exc:+ raise _openai_video_error(400, str(exc), param = "size")+ try:+ seconds = _parse_openai_video_seconds(body.seconds)+ except ValueError as exc:+ raise _openai_video_error(400, str(exc), param = "seconds")+ width, height = size if size is not None else (None, None)+ if reference is not None:+ # Check readability before a model switch. The conditioning path applies its own+ # keyframe or Ref2VA limit later, so this uses the broadest bounded source policy.+ from core.inference.diffusion import decode_b64_image+ from core.inference.video_minimax_h3 import (+ H3_REF_IMAGE_SOURCE_MAX_PIXELS,+ H3_REF_IMAGE_SOURCE_MAX_SIDE,+ )+ try:+ await asyncio.to_thread(+ decode_b64_image,+ reference,+ mode = "RGB",+ max_side = H3_REF_IMAGE_SOURCE_MAX_SIDE,+ max_pixels = H3_REF_IMAGE_SOURCE_MAX_PIXELS,+ )+ except Exception: # noqa: BLE001 -- any decode failure is client input feedback+ raise _openai_video_error(+ 400, "input_reference is not a readable image.", param = "input_reference"+ )++ def _refuse_unservable_request(pick) -> None:+ from core.inference.media_model_index import expected_partition+ from core.inference.video import _detect_load_family+ from core.inference.video_families import (+ validate_video_keyframe_conditioning,+ validate_video_reference_conditioning,+ validate_video_request_shape,+ )+ from core.inference.video_minimax_h3 import H3_TASK_REFERENCES++ fam = _detect_load_family(pick.model_path, pick.gguf_filename, None)+ if fam is None:+ return+ # Judge the duration against the family being switched TO, using its own lattice.+ # Passing None here accepted any seconds and only refused it in begin_generate --+ # after the resident pipeline had been evicted and the target fully loaded.+ want_frames = (+ _frames_for_seconds(+ seconds,+ {+ "fps": fam.default_fps,+ "frame_step": fam.frame_step,+ "frame_offset": fam.frame_offset,+ },+ )+ if seconds is not None+ else None+ )+ validate_video_request_shape(fam, width, height, want_frames)+ h3_task = expected_partition(pick)+ ref2va = h3_task == H3_TASK_REFERENCES+ validate_video_keyframe_conditioning(+ fam, h3_task, has_keyframes = reference is not None and not ref2va+ )+ validate_video_reference_conditioning(+ fam,+ h3_task,+ has_references = reference is not None and ref2va,+ )++ pin_requested_model = bool(+ isinstance(body.model, str) and body.model.strip() and get_media_auto_switch_enabled()+ )+ try:+ await maybe_auto_switch_media_model(+ body.model,+ owner = VIDEO,+ current_subject = current_subject,+ openai_errors = True,+ hf_token = hf_token,+ before_switch = _refuse_unservable_request,+ )+ except VideoShapeError as exc:+ raise _openai_video_error(+ 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"+ )+ except ValueError as exc:+ raise _openai_video_error(400, str(exc), param = "input_reference")++ backend = get_video_backend()+ expected_state = None+ if pin_requested_model:+ status, expected_state = await asyncio.to_thread(backend.generation_snapshot)+ if not await asyncio.to_thread(+ resident_answers_media_request, status, body.model, owner = VIDEO+ ):+ raise _openai_video_error(+ 409,+ VIDEO_MODEL_CHANGED_MSG,+ code = "model_changed",+ param = "model",+ )+ else:+ status = await asyncio.to_thread(backend.status)+ if not status.get("loaded"):+ raise HTTPException(status_code = 503, detail = _NO_VIDEO_MODEL_MSG)+ defaults = status.get("defaults") or {}+ num_frames = _frames_for_seconds(seconds, defaults) if seconds is not None else None+ video_id = _VIDEO_JOB_ID_PREFIX + uuid.uuid4().hex+ try:+ generate_kwargs = dict(+ prompt = body.prompt,+ width = width,+ height = height,+ duration_s = seconds,+ input_reference = reference,+ video_id = video_id,+ )+ if expected_state is not None:+ generate_kwargs["expected_state"] = expected_state+ resolved = await asyncio.to_thread(backend.begin_generate, **generate_kwargs)+ except VideoShapeError as exc:+ raise _openai_video_error(+ 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"+ )+ except ValueError as exc:+ raise _openai_video_error(+ 400, str(exc), param = "input_reference" if reference is not None else None+ )+ except RuntimeError as exc:+ msg = str(exc)+ if msg == VIDEO_NOT_LOADED_MSG:+ raise HTTPException(status_code = 503, detail = _NO_VIDEO_MODEL_MSG)+ if msg == VIDEO_GENERATION_BUSY_MSG:+ raise _openai_video_error(409, msg)+ if msg == VIDEO_MODEL_CHANGED_MSG:+ raise _openai_video_error(409, msg, code = "model_changed", param = "model")+ logger.error("openai_videos.generate_failed: %s", exc, exc_info = True)+ raise HTTPException(status_code = 500, detail = "Video generation failed.")++ # begin_generate hands back the canvas it resolved. Without it a reference-image+ # request reported the family's first preset while the clip rendered at the source+ # aspect, so the job advertised one size and the finished record another.+ if isinstance(resolved, dict) and resolved.get("width") and resolved.get("height"):+ width, height = int(resolved["width"]), int(resolved["height"])+ else:+ presets = defaults.get("resolution_presets") or []+ if size is None and presets:+ width, height = int(presets[0][0]), int(presets[0][1])+ # Describe the job from what begin_generate reserved, falling back to the status()+ # snapshot only where it said nothing. A load committing between that snapshot and+ # the reservation swaps the family underneath, and the snapshot's fps would then+ # date a frame count the new model never used.+ reserved = resolved if isinstance(resolved, dict) else {}+ run_frames = reserved.get("num_frames") or num_frames+ fps = reserved.get("fps") or defaults.get("fps")+ if run_frames and fps:+ seconds_text = _format_seconds(int(run_frames) / float(fps))+ elif seconds is None and defaults.get("num_frames") and fps:+ seconds_text = _format_seconds(int(defaults["num_frames"]) / float(fps))+ else:+ seconds_text = body.seconds or "auto"+ job = _VideoJob(+ id = video_id,+ created_at = int(_time.time()),+ prompt = body.prompt,+ model = public_model_id(+ str(reserved.get("model") or status.get("repo_id") or body.model or "video")+ ),+ size = f"{width}x{height}" if width and height else "auto",+ seconds = seconds_text,+ )+ _remember_job(job)+ return _job_to_openai(job)+++@openai_router.get("/videos", response_model = VideoJobListResponse)+async def openai_list_videos(+ limit: int = Query(20, ge = 1, le = 100),+ after: Optional[str] = None,+ order: Literal["asc", "desc"] = "desc",+ current_subject: str = Depends(get_current_subject),+):+ videos = await asyncio.to_thread(_all_videos)+ videos.sort(key = lambda video: (video.created_at, video.id), reverse = order == "desc")+ if after:+ index = next((i for i, video in enumerate(videos) if video.id == after), None)+ if index is None:+ raise _openai_video_error(+ 400, f"No video found with id '{after[:128]}'.", param = "after"+ )+ videos = videos[index + 1 :]+ page = videos[:limit]+ return VideoJobListResponse(+ data = page,+ first_id = page[0].id if page else None,+ last_id = page[-1].id if page else None,+ has_more = len(videos) > limit,+ )+++@openai_router.get("/videos/{video_id}", response_model = VideoJob)+async def openai_retrieve_video(+ video_id: str,+ response: Response,+ current_subject: str = Depends(get_current_subject),+):+ video = await asyncio.to_thread(_lookup_video, video_id)+ if video is None:+ raise _not_found(video_id)+ if video.status in ("queued", "in_progress"):+ response.headers["openai-poll-after-ms"] = _VIDEO_POLL_AFTER_MS+ return video+++@openai_router.get("/videos/{video_id}/content")+async def openai_download_video_content(+ video_id: str,+ variant: str = "video",+ current_subject: str = Depends(get_current_subject),+):+ from core.inference import video_gallery++ normalized_variant = (variant or "video").strip().lower()+ if normalized_variant not in ("video", "thumbnail"):+ raise _openai_video_error(+ 400, "Unsupported variant. Use 'video' or 'thumbnail'.", param = "variant"+ )+ path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)+ if path is None:+ video = await asyncio.to_thread(_lookup_video, video_id)+ if video is None:+ raise _not_found(video_id)+ if video.status == "failed":+ raise _openai_video_error(+ 400,+ video.error.message if video.error else "Video generation failed.",+ code = video.error.code if video.error else _VIDEO_FAILED_CODE,+ )+ raise _openai_video_error(+ 400,+ "Video is still generating; retrieve it until its status is 'completed'.",+ code = "video_not_ready",+ )+ if normalized_variant == "thumbnail":+ try:+ thumbnail = await asyncio.to_thread(video_gallery.thumbnail, video_id)+ except RuntimeError as exc:+ raise _openai_video_error(501, str(exc), code = "video_thumbnail_unavailable") from exc+ if thumbnail is None: # The clip was deleted between the ownership check and decode.+ raise _not_found(video_id)+ return Response(+ content = thumbnail,+ media_type = "image/webp",+ headers = {+ "Cache-Control": "private, max-age=31536000, immutable",+ "Content-Disposition": f'attachment; filename="{video_id}.webp"',+ },+ )+ from fastapi.responses import FileResponse++ return FileResponse(+ path,+ media_type = "video/mp4",+ filename = f"{video_id}.mp4",+ headers = {"Cache-Control": "private, max-age=31536000, immutable"},+ )+++@openai_router.delete("/videos/{video_id}", response_model = VideoJobDeleteResponse)+async def openai_delete_video(video_id: str, current_subject: str = Depends(get_current_subject)):+ from core.inference import video_gallery+ from core.inference.video import get_video_backend++ video = await asyncio.to_thread(_lookup_video, video_id)+ if video is None:+ raise _not_found(video_id)+ if video.status in ("queued", "in_progress"):+ await asyncio.to_thread(get_video_backend().cancel_generate, video_id)+ # The run can reach its terminal state between the lookup and the cancel, so a+ # refused cancellation is not proof that nothing was written. Let the worker+ # settle, then fall through to the same delete the completed branch performs --+ # otherwise the clip persists and the "deleted" job reappears through+ # retrieve/list on the very next call.+ if not await asyncio.to_thread(_await_generate_settled, video_id):+ raise _openai_video_error(+ 409,+ "The video is still being written; retry the delete once it is no longer generating.",+ code = "video_not_ready",+ )+ deleted = await asyncio.to_thread(video_gallery.delete, video_id)+ if deleted:+ _forget_terminal_video(video_id)+ elif await asyncio.to_thread(video_gallery.get_record, video_id) is not None:+ raise _openai_video_error(500, "Could not delete the video; retry the request.")+ if not await asyncio.to_thread(_forget_openai_job, video_id):+ raise _openai_video_error(500, "Could not delete the video job; retry the request.")+ return VideoJobDeleteResponse(id = video_id)diff --git a/studio/backend/tests/test_media_keepwarm.py b/studio/backend/tests/test_media_keepwarm.pyindex ef04cf29b39..2f39b576625 100644--- a/studio/backend/tests/test_media_keepwarm.py+++ b/studio/backend/tests/test_media_keepwarm.py@@ -564,6 +564,8 @@ def test_a_path_that_is_not_a_mounted_route_is_not_tracked():# The Unsloth routes are mounted under /api/inference only; /v1 carries the OpenAI shape.assert mk.owner_for_path("/v1/images/generate") is Noneassert mk.owner_for_path("/v1/video/load") is None+ assert mk.owner_for_path("/v1/videos/video_abc") is None+ assert mk.owner_for_path("/v1/videos/video_abc/content") is Nonedef test_every_tracked_path_is_a_route_that_is_actually_mounted():@@ -572,6 +574,7 @@ def test_every_tracked_path_is_a_route_that_is_actually_mounted():# list to the routers main.py mounts, in both directions.from routes.inference import router as inference_routerfrom routes.inference import studio_router+ from routes.video import openai_router as video_openai_routerfrom routes.video import router as video_routermounted = {@@ -580,11 +583,15 @@ def test_every_tracked_path_is_a_route_that_is_actually_mounted():(inference_router, ("/api/inference", "/v1")),(studio_router, ("/api/inference",)),(video_router, ("/api/inference",)),+ (video_openai_router, ("/api/inference", "/v1")),)for route in router.routesfor prefix in prefixes}assert not set(mk._TRACKED_PATHS) - mounted+ for path in ("/v1/videos", "/api/inference/videos"):+ assert path in mounted, path+ assert mk.owner_for_path(path) == arb.VIDEO, pathfor path in mounted:if ("/images/" in path or "/video/" in path) and path.rsplit("/", 1)[-1] in ("generate",@@ -778,3 +785,24 @@ def test_an_authenticated_request_is_still_counted_before_its_body(media, monkey_step()_stalled_media_request("/api/inference/images/generate", _BEARER)assert media[arb.DIFFUSION].unloads == 0+++def test_the_openai_videos_route_never_claims_the_llama_slot():+ """/v1/videos runs the video backend, exactly like /video/generate.++ Adding "/videos" to the inference suffixes made it a tracked path; without the+ matching non-LLM entry its completion called _claim_non_preview_slot(), clearing+ preview ownership so the next preview of a different checkpoint 503s on the guard.+ """+ from core.inference import llama_keepwarm as kw++ for path in ("/v1/videos", "/api/inference/videos"):+ assert kw._is_inference_path(path), path+ assert path.endswith(kw._NON_LLM_SLOT_SUFFIXES), path+ # Matched whole. As an endswith suffix it also caught unrouted paths, and those+ # 404 before auth -- which this middleware does not exclude -- so each probe would+ # have refreshed the chat model's idle timer and kept it resident for free.+ for path in ("/v1/anything/videos", "/api/inference/nope/videos", "/v1/videosx"):+ assert not kw._is_inference_path(path), path+ for path in ("/v1/videos/", "/api/inference/videos/"):+ assert not kw._is_inference_path(path), pathdiff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex eb57be9ac54..ac23c84c5d9 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -39,6 +39,7 @@ def _make_protected_app(upload_passthrough_prefixes: tuple = (),upload_passthrough_max_bytes_getter = None,upload_passthrough_exact_paths: tuple = (),+ chunked_upload_exact_paths: tuple = (),):app = FastAPI()app.add_middleware(@@ -54,6 +55,7 @@ def _make_protected_app(upload_passthrough_prefixes = upload_passthrough_prefixes,upload_passthrough_max_bytes_getter = upload_passthrough_max_bytes_getter,upload_passthrough_exact_paths = upload_passthrough_exact_paths,+ chunked_upload_exact_paths = chunked_upload_exact_paths,)@app.post("/v1/chat/completions")@@ -159,6 +161,26 @@ class TestMaxBodyMiddleware:assert main_module._get_upload_passthrough_request_max_bytes(path + "/") == (upload_request_limit_bytes(STT_AUDIO_RAW_MAX_BYTES)), path+ from utils.upload_limits import (+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ VIDEO_INPUT_REFERENCE_MAX_BYTES,+ )++ for path in ("/v1/videos", "/api/inference/videos"):+ expected = max(+ upload_request_limit_bytes(VIDEO_INPUT_REFERENCE_MAX_BYTES),+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ )+ assert main_module._get_request_body_max_bytes(path) == expected, path+ assert path in main_module._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS, path+ assert main_module._get_upload_passthrough_request_max_bytes(path) == expected, path+ assert VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES > (+ 4 * ((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) // 3)+ )+ assert "/v1/videos/video_abc" not in main_module._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS+ assert main_module._get_request_body_max_bytes("/v1/videos/video_abc") == (+ main_module.default_request_body_limit_bytes()+ )def test_settings_put_body_over_cap_rejected(self, main_module):app = _make_protected_app(1024, main_module)@@ -360,6 +382,64 @@ class TestMaxBodyMiddleware:assert r.status_code == 411assert "Content-Length" in r.json()["detail"]+ def test_exact_path_passthrough_without_content_length_is_capped_not_refused(self, main_module):+ app = _make_protected_app(+ 128,+ main_module,+ upload_passthrough_exact_paths = ("/api/train/upload",),+ chunked_upload_exact_paths = ("/api/train/upload",),+ upload_passthrough_max_bytes_getter = lambda path: 1024,+ )+ c = TestClient(app)++ def small():+ yield b"x" * 256+ yield b"y" * 256++ r = c.post(+ "/api/train/upload",+ content = small(),+ headers = {"content-type": "application/octet-stream"},+ )+ assert r.status_code == 200++ def large():+ yield b"x" * 1024+ yield b"y" * 1024++ r = c.post(+ "/api/train/upload",+ content = large(),+ headers = {"content-type": "application/octet-stream"},+ )+ assert r.status_code == 413++ def test_a_passthrough_outside_the_chunked_set_still_demands_a_length(self, main_module):+ """Counting a body means holding it, and this runs before authentication.++ Only paths explicitly opted in may omit Content-Length; the big ones (the+ dataset cap reaches 8 GB) keep their 411 so an unauthenticated chunked POST+ cannot make the server retain the whole allowance.+ """+ app = _make_protected_app(+ 128,+ main_module,+ upload_passthrough_exact_paths = ("/api/train/upload",),+ chunked_upload_exact_paths = (),+ upload_passthrough_max_bytes_getter = lambda path: 1024,+ )+ c = TestClient(app)++ def body():+ yield b"x" * 256++ r = c.post(+ "/api/train/upload",+ content = body(),+ headers = {"content-type": "application/octet-stream"},+ )+ assert r.status_code == 411+def test_exact_path_passthrough_does_not_cover_subroutes(self, main_module):# The exact-path passthrough lifts the cap for the upload path itself, but a sibling sub-path under the same prefix stays capped.app = FastAPI()diff --git a/studio/backend/tests/test_openai_videos_route.py b/studio/backend/tests/test_openai_videos_route.pynew file mode 100644index 00000000000..c1d5a200ce5--- /dev/null+++ b/studio/backend/tests/test_openai_videos_route.py@@ -0,0 +1,1313 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import sys+import threading+import time+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import core.inference.gpu_arbiter as gpu_arbiter+import core.inference.video as video_module+import core.inference.video_gallery as gallery_module+import routes.video as video_routes+from auth.authentication import get_current_subject+from core.inference.video_families import VIDEO_CANCELLED_MSG+from routes.video import (+ _format_seconds,+ _frames_for_seconds,+ _parse_openai_video_seconds,+ _parse_openai_video_size,+)+from routes.video import openai_router, router as video_router+from utils.api_errors import install_api_error_handlers++_TESTS_DIR = Path(__file__).resolve().parent+if str(_TESTS_DIR) not in sys.path:+ sys.path.insert(0, str(_TESTS_DIR))++from test_video_routes import _FakeBackend # noqa: E402+++ "size, expected",+ [+ (None, None),+ ("", None),+ ("auto", None),+ ("768x512", (768, 512)),+ (" 1216 X 704 ", (1216, 704)),+ ],+)+def test_parse_video_size_ok(size, expected):+ assert _parse_openai_video_size(size) == expected++[email protected]("size", ["abc", "768", "x512", "16x16", "4096x4096"])+def test_parse_video_size_rejects(size):+ with pytest.raises(ValueError):+ _parse_openai_video_size(size)+++ "seconds, expected", [(None, None), ("", None), ("4", 4.0), ("2.5", 2.5), ("12", 12.0)]+)+def test_parse_video_seconds_ok(seconds, expected):+ assert _parse_openai_video_seconds(seconds) == expected++[email protected]("seconds", ["abc", "0", "-1", "nan", "inf", "1000"])+def test_parse_video_seconds_rejects(seconds):+ with pytest.raises(ValueError):+ _parse_openai_video_seconds(seconds)+++def test_frames_for_seconds_snaps_to_the_lattice():+ ltx = {"fps": 24, "frame_step": 8, "frame_offset": 1}+ assert _frames_for_seconds(5.0, ltx) == 121+ assert _frames_for_seconds(4.0, ltx) == 97+ assert _frames_for_seconds(0.01, ltx) == 9+ assert _frames_for_seconds(0.2, ltx) == 9+ h3 = {"fps": 24, "frame_step": 17, "frame_offset": 5}+ assert (_frames_for_seconds(5.0, h3) - 5) % 17 == 0+++class _GatedBackend(_FakeBackend):+ def __init__(self) -> None:+ super().__init__()+ self.gate = threading.Event()+ self.gate.set()+ self.fail_with: str | None = None+ self.last_generate_kwargs: dict = {}++ def generate(+ self,+ *,+ prompt,+ seed = None,+ cancel_event = None,+ **kwargs,+ ):+ self.last_generate_kwargs = {"prompt": prompt, "seed": seed, **kwargs}+ if self.fail_with is not None:+ raise ValueError(self.fail_with)+ while not self.gate.wait(timeout = 0.01):+ if cancel_event is not None and cancel_event.is_set():+ raise RuntimeError(VIDEO_CANCELLED_MSG)+ return super().generate(prompt = prompt, seed = seed, cancel_event = cancel_event, **kwargs)++[email protected](autouse = True)+def _healthy_diffusers(healthy_diffusers):+ pass+++def backend(monkeypatch, tmp_path):+ backend = _GatedBackend()+ backend.loaded = True+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.VIDEO, lambda: None)+ monkeypatch.setattr(gallery_module, "gallery_dir", lambda: tmp_path)+ monkeypatch.setattr(video_routes, "_jobs", {})+ return backend+++def client(backend):+ app = FastAPI()+ install_api_error_handlers(app)+ app.include_router(openai_router, prefix = "/v1")+ app.include_router(openai_router, prefix = "/api/inference")+ app.include_router(video_router, prefix = "/api/inference")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app)+++def _multipart(fields: dict, files: dict | None = None) -> tuple[bytes, str]:+ boundary = "----unsloth-test-boundary"+ parts = []+ for name, value in fields.items():+ parts.append(+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()+ )+ for name, (filename, data, content_type) in (files or {}).items():+ parts.append(+ (+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\n'+ f"Content-Type: {content_type}\r\n\r\n"+ ).encode()+ + data+ + b"\r\n"+ )+ parts.append(f"--{boundary}--\r\n".encode())+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"+++def _create(+ client,+ fields: dict,+ files: dict | None = None,+):+ body, content_type = _multipart(fields, files)+ return client.post("/v1/videos", content = body, headers = {"Content-Type": content_type})+++def _wait_terminal(+ client,+ video_id: str,+ timeout = 5.0,+) -> dict:+ deadline = time.monotonic() + timeout+ video: dict = {}+ while time.monotonic() < deadline:+ resp = client.get(f"/v1/videos/{video_id}")+ assert resp.status_code == 200, resp.json()+ video = resp.json()+ if video["status"] in ("completed", "failed"):+ return video+ time.sleep(0.01)+ raise AssertionError(f"job never reached a terminal state: {video}")+++def _reference_image_bytes(fmt: str, size: tuple[int, int] = (8, 8)) -> bytes:+ """A real, decodable image. The route decodes the reference before any model+ switch, so a magic-byte stub is refused before it can reach begin_generate."""+ import io++ from PIL import Image++ buf = io.BytesIO()+ Image.new("RGB", size, (10, 20, 30)).save(buf, format = fmt)+ return buf.getvalue()+++def _reference_data_url(fmt: str, mime: str) -> str:+ import base64+ return f"data:{mime};base64," + base64.b64encode(_reference_image_bytes(fmt)).decode("ascii")+++def _save_clip(+ prompt: str,+ created_at: str,+ video_id: str | None = None,+ model: str = "unsloth/LTX-2.3-GGUF",+) -> dict:+ return gallery_module.save(+ b"OLD-MP4",+ {+ "prompt": prompt,+ "negative_prompt": None,+ "width": 768,+ "height": 512,+ "num_frames": 121,+ "fps": 24,+ "duration_s": 5.0,+ "steps": 40,+ "guidance": 4.0,+ "seed": 7,+ "has_audio": True,+ "model": model,+ "created_at": created_at,+ },+ video_id = video_id,+ )+++def test_create_like_the_sdk_poll_download_list_delete(client, backend):+ resp = _create(+ client,+ {"prompt": "a red fox in snow", "model": "sora-2", "seconds": "4", "size": "768x512"},+ )+ assert resp.status_code == 200, resp.json()+ job = resp.json()+ assert job["object"] == "video"+ assert job["id"].startswith("video_")+ assert job["status"] in ("queued", "in_progress")+ assert job["progress"] < 100 and job["completed_at"] is None and job["error"] is None+ assert job["prompt"] == "a red fox in snow"+ assert job["size"] == "768x512"+ assert job["seconds"] == "4.04"+ assert job["model"] == "unsloth/LTX-2.3-GGUF"++ done = _wait_terminal(client, job["id"])+ assert done["status"] == "completed" and done["progress"] == 100+ assert done["completed_at"] >= done["created_at"] == job["created_at"]+ assert done["id"] == job["id"]+ assert backend.last_generate_kwargs["width"] == 768+ assert backend.last_generate_kwargs["height"] == 512+ assert backend.last_generate_kwargs["num_frames"] == 97+ # begin_generate resolves keyframes up front and hands the worker _resolved_inputs.+ assert backend.last_generate_kwargs["_resolved_inputs"].first_frame is None++ assert gallery_module.owned_video_path(job["id"]) is not None+ content = client.get(f"/v1/videos/{job['id']}/content")+ assert content.status_code == 200+ assert content.headers["content-type"].startswith("video/mp4")+ assert content.content == b"MP4-FAKE-BYTES"+ assert (+ client.get(f"/v1/videos/{job['id']}/content", params = {"variant": "video"}).status_code+ == 200+ )++ listing = client.get("/v1/videos").json()+ assert listing["object"] == "list"+ assert [v["id"] for v in listing["data"]] == [job["id"]]+ assert listing["first_id"] == listing["last_id"] == job["id"]+ assert listing["has_more"] is False++ deleted = client.delete(f"/v1/videos/{job['id']}")+ assert deleted.status_code == 200+ assert deleted.json() == {"id": job["id"], "object": "video.deleted", "deleted": True}+ assert gallery_module.owned_video_path(job["id"]) is None+ gone = client.get(f"/v1/videos/{job['id']}")+ assert gone.status_code == 404+ assert gone.json()["error"]["code"] == "video_not_found"+ assert client.get("/v1/videos").json()["data"] == []+++def test_json_body_and_the_studio_mount_work_too(client, backend):+ resp = client.post("/api/inference/videos", json = {"prompt": "a cat", "seconds": 5})+ assert resp.status_code == 200, resp.json()+ job = resp.json()+ assert job["seconds"] == "5.04" and job["size"] == "768x512"+ done = _wait_terminal(client, job["id"])+ assert done["status"] == "completed"+ assert backend.last_generate_kwargs["num_frames"] == 121+ assert backend.last_generate_kwargs["width"] is None+++def test_omitted_seconds_and_size_use_the_family_defaults(client, backend):+ resp = client.post("/v1/videos", json = {"prompt": "a cat"})+ assert resp.status_code == 200, resp.json()+ assert resp.json()["seconds"] == "5.04"+ _wait_terminal(client, resp.json()["id"])+ assert backend.last_generate_kwargs["num_frames"] is None+++def test_in_progress_job_reports_progress_and_the_poll_hint(client, backend):+ backend.gate.clear()+ job = _create(client, {"prompt": "slow"}).json()+ resp = client.get(f"/v1/videos/{job['id']}")+ assert resp.status_code == 200+ assert resp.json()["status"] in ("queued", "in_progress")+ assert resp.headers["openai-poll-after-ms"] == "2000"+ content = client.get(f"/v1/videos/{job['id']}/content")+ assert content.status_code == 400+ assert content.json()["error"]["code"] == "video_not_ready"+ busy = _create(client, {"prompt": "another"})+ assert busy.status_code == 409+ assert "error" in busy.json()+ backend.gate.set()+ done = _wait_terminal(client, job["id"])+ assert done["status"] == "completed"+ assert "openai-poll-after-ms" not in client.get(f"/v1/videos/{job['id']}").headers+++def test_a_job_outcome_survives_the_next_job(client, backend):+ first = _create(client, {"prompt": "first"}).json()+ assert _wait_terminal(client, first["id"])["status"] == "completed"+ backend.gate.clear()+ second = _create(client, {"prompt": "second"}).json()+ assert client.get(f"/v1/videos/{first['id']}").json()["status"] == "completed"+ assert client.get(f"/v1/videos/{second['id']}").json()["status"] in ("queued", "in_progress")+ ids = [v["id"] for v in client.get("/v1/videos").json()["data"]]+ assert set(ids) == {first["id"], second["id"]}+ backend.gate.set()+ assert _wait_terminal(client, second["id"])["status"] == "completed"+++def test_a_failed_job_reports_its_error_and_keeps_it_after_the_next_job(client, backend):+ backend.fail_with = "Prompt rejected by the model."+ job = _create(client, {"prompt": "bad"}).json()+ failed = _wait_terminal(client, job["id"])+ assert failed["status"] == "failed" and failed["progress"] == 0+ assert failed["error"] == {+ "code": "video_generation_failed",+ "message": "Prompt rejected by the model.",+ }+ content = client.get(f"/v1/videos/{job['id']}/content")+ assert content.status_code == 400+ assert content.json()["error"]["code"] == "video_generation_failed"+ assert gallery_module.owned_video_path(job["id"]) is None+ assert [v["status"] for v in client.get("/v1/videos").json()["data"]] == ["failed"]++ # Polling can cross a Studio restart. Replacing the process-local cache must rehydrate+ # the terminal error instead of turning the ID into a 404.+ video_routes._jobs = {}+ reloaded = client.get(f"/v1/videos/{job['id']}")+ assert reloaded.status_code == 200+ assert reloaded.json()["status"] == "failed" and reloaded.json()["error"] == failed["error"]++ backend.fail_with = None+ later = _create(client, {"prompt": "good"}).json()+ assert _wait_terminal(client, later["id"])["status"] == "completed"+ assert client.get(f"/v1/videos/{job['id']}").json()["status"] == "failed"+ assert client.delete(f"/v1/videos/{job['id']}").json()["deleted"] is True+ assert gallery_module.get_job(job["id"]) is None+ assert client.get(f"/v1/videos/{job['id']}").status_code == 404+++def test_an_unpolled_failure_keeps_its_error_after_the_next_job(client, backend):+ backend.fail_with = "Prompt rejected before polling."+ failed_job = _create(client, {"prompt": "bad"}).json()+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if backend.generate_progress().get("phase") == "failed":+ break+ time.sleep(0.01)+ else:+ raise AssertionError("the first generation never failed")++ backend.fail_with = None+ later = _create(client, {"prompt": "good"})+ assert later.status_code == 200, later.json()+ failed = client.get(f"/v1/videos/{failed_job['id']}").json()+ assert failed["status"] == "failed"+ assert failed["error"]["message"] == "Prompt rejected before polling."+++def test_unpolled_terminal_jobs_still_obey_the_memory_cap(client, backend, monkeypatch):+ monkeypatch.setattr(video_routes, "_MAX_REMEMBERED_JOBS", 2)+ ids = []+ for prompt in ("first", "second", "third"):+ job = _create(client, {"prompt": prompt}).json()+ ids.append(job["id"])+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if backend.generate_progress().get("phase") == "completed":+ break+ time.sleep(0.01)+ else:+ raise AssertionError(f"{prompt} never completed")+ assert len(video_routes._jobs) == 2+ assert ids[0] not in video_routes._jobs+ assert gallery_module.get_job(ids[0]) is not None+++def test_listing_keeps_persisted_failures_beyond_the_memory_cap(client, backend, monkeypatch):+ monkeypatch.setattr(video_routes, "_MAX_REMEMBERED_JOBS", 2)+ ids = []+ for index in range(3):+ job = video_routes._VideoJob(+ id = f"video_failed_{index}",+ created_at = index + 1,+ prompt = f"failed {index}",+ model = "model",+ size = "768x512",+ seconds = "5",+ status = "failed",+ completed_at = index + 1,+ error = {"code": "video_generation_failed", "message": f"failure {index}"},+ )+ gallery_module.save_job(job.id, vars(job))+ ids.append(job.id)++ video_routes._jobs = {}+ listed = client.get("/v1/videos").json()+ assert [video["id"] for video in listed["data"]] == list(reversed(ids))+ assert listed["has_more"] is False+++def test_a_worker_outcome_that_arrives_before_the_job_record_is_not_overwritten(client, backend):+ video_id = "video_worker_won_the_race"+ gallery_module.record_job_outcome(+ video_id, completed_at = 123, error = "Failed before the create response."+ )+ video_routes._remember_job(+ video_routes._VideoJob(+ id = video_id,+ created_at = 100,+ prompt = "fast failure",+ model = "model",+ size = "768x512",+ seconds = "5",+ )+ )+ video_routes._jobs = {}+ failed = client.get(f"/v1/videos/{video_id}").json()+ assert failed["status"] == "failed"+ assert failed["completed_at"] == 123+ assert failed["error"]["message"] == "Failed before the create response."+++def test_an_overflowing_worker_timestamp_is_ignored():+ job = video_routes._VideoJob(+ id = "video_overflowing_timestamp",+ created_at = 100,+ prompt = "bad persisted timestamp",+ model = "model",+ size = "768x512",+ seconds = "5",+ )+ record = {**vars(job), "_worker_outcome": {"completed_at": float("inf"), "error": None}}++ assert video_routes._job_from_record(record) is None+++def test_completed_job_keeps_its_submission_time_after_restart(client, backend, monkeypatch):+ monkeypatch.setattr(video_routes._time, "time", lambda: 100)+ job = _create(client, {"prompt": "slow timestamp"}).json()+ assert _wait_terminal(client, job["id"])["created_at"] == 100+ video_routes._jobs = {}+ restarted = client.get(f"/v1/videos/{job['id']}").json()+ assert restarted["status"] == "completed"+ assert restarted["created_at"] == job["created_at"] == 100+++def test_studio_delete_and_clear_remove_unpolled_openai_jobs(client, backend):+ first = _create(client, {"prompt": "delete in Studio"}).json()+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if backend.generate_progress().get("phase") == "completed":+ break+ time.sleep(0.01)+ assert client.delete(f"/api/inference/video/gallery/{first['id']}").status_code == 200+ assert gallery_module.get_job(first["id"]) is None+ assert client.get(f"/v1/videos/{first['id']}").status_code == 404++ second = _create(client, {"prompt": "clear in Studio"}).json()+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if backend.generate_progress().get("phase") == "completed":+ break+ time.sleep(0.01)+ cleared = client.delete("/api/inference/video/gallery")+ assert cleared.status_code == 200 and cleared.json()["removed"] == 1+ assert gallery_module.get_job(second["id"]) is None+ assert client.get(f"/v1/videos/{second['id']}").status_code == 404+++def test_deleting_a_running_job_cancels_it(client, backend):+ backend.gate.clear()+ job = _create(client, {"prompt": "slow"}).json()+ assert client.get(f"/v1/videos/{job['id']}").json()["status"] in ("queued", "in_progress")+ resp = client.delete(f"/v1/videos/{job['id']}")+ assert resp.status_code == 200 and resp.json()["deleted"] is True+ assert client.get(f"/v1/videos/{job['id']}").status_code == 404+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ progress = client.get("/api/inference/video/generate-progress").json()+ if progress.get("phase") in ("completed", "failed"):+ break+ time.sleep(0.01)+ assert progress["phase"] == "failed" and progress["error"] == VIDEO_CANCELLED_MSG+ assert gallery_module.owned_video_path(job["id"]) is None+ backend.gate.set()+++def test_cancelled_content_keeps_the_cancelled_error_code(client, backend):+ backend.gate.clear()+ job = _create(client, {"prompt": "cancel through Studio"}).json()+ cancelled = client.post("/api/inference/video/generate/cancel")+ assert cancelled.status_code == 200 and cancelled.json()["cancelled"] is True+ failed = _wait_terminal(client, job["id"])+ assert failed["error"]["code"] == "cancelled"+ content = client.get(f"/v1/videos/{job['id']}/content")+ assert content.status_code == 400+ assert content.json()["error"]["code"] == "cancelled"+ backend.gate.set()+++def test_deleting_a_stale_job_does_not_cancel_its_successor(client, backend, monkeypatch):+ successor_cancel = threading.Event()+ with backend._lock:+ backend._gen_video_id = "video_successor"+ backend._active_generate_cancel = successor_cancel+ monkeypatch.setattr(+ video_routes,+ "_lookup_video",+ lambda video_id: type("Video", (), {"status": "queued"})()+ if video_id == "video_target"+ else None,+ )++ resp = client.delete("/v1/videos/video_target")+ assert resp.status_code == 200, resp.json()+ assert successor_cancel.is_set() is False+++def test_clips_made_before_this_process_list_and_retrieve_as_completed(client, backend):+ older = _save_clip("older", "2026-01-01T00:00:00Z")+ newer = _save_clip("newer", "2026-01-02T00:00:00Z")+ resp = client.get(f"/v1/videos/{older['id']}")+ assert resp.status_code == 200+ video = resp.json()+ assert video["status"] == "completed" and video["progress"] == 100+ assert video["created_at"] == video["completed_at"] == 1767225600+ assert video["size"] == "768x512" and video["seconds"] == "5" and video["prompt"] == "older"+ assert video["model"] == "unsloth/LTX-2.3-GGUF"++ page = client.get("/v1/videos", params = {"limit": 1}).json()+ assert [v["id"] for v in page["data"]] == [newer["id"]]+ assert page["has_more"] is True and page["last_id"] == newer["id"]+ rest = client.get("/v1/videos", params = {"limit": 1, "after": page["last_id"]}).json()+ assert [v["id"] for v in rest["data"]] == [older["id"]]+ assert rest["has_more"] is False+ ascending = client.get("/v1/videos", params = {"order": "asc"}).json()+ assert [v["id"] for v in ascending["data"]] == [older["id"], newer["id"]]+ unknown = client.get("/v1/videos", params = {"after": "nope"})+ assert unknown.status_code == 400 and unknown.json()["error"]["param"] == "after"++ assert client.get(f"/v1/videos/{older['id']}/content").content == b"OLD-MP4"+++def test_archived_clips_remain_in_the_openai_listing(client, backend):+ clip = _save_clip("archived", "2026-01-01T00:00:00Z")+ archived = client.patch(f"/api/inference/video/gallery/{clip['id']}", json = {"archived": True})+ assert archived.status_code == 200, archived.json()+ listed = client.get("/v1/videos").json()["data"]+ assert [video["id"] for video in listed] == [clip["id"]]+ assert client.get(f"/v1/videos/{clip['id']}").status_code == 200+++def test_completed_delete_does_not_confirm_when_the_clip_remains(client, backend, monkeypatch):+ clip = _save_clip("kept", "2026-01-01T00:00:00Z")+ monkeypatch.setattr(gallery_module, "delete", lambda _video_id: False)++ resp = client.delete(f"/v1/videos/{clip['id']}")+ assert resp.status_code == 500+ assert gallery_module.get_record(clip["id"]) is not None+ assert client.get(f"/v1/videos/{clip['id']}").status_code == 200+++def test_missing_prompt_is_a_400_naming_the_param(client, backend):+ resp = client.post("/v1/videos", json = {})+ assert resp.status_code == 400+ assert resp.json()["error"]["param"] == "prompt"+ resp = _create(client, {"model": "sora-2"})+ assert resp.status_code == 400 and resp.json()["error"]["param"] == "prompt"+ resp = client.post(+ "/v1/videos", content = b"not json", headers = {"Content-Type": "application/json"}+ )+ assert resp.status_code == 400 and "error" in resp.json()+++ "fields, param",+ [+ ({"prompt": "x", "size": "abc"}, "size"),+ ({"prompt": "x", "size": "640x480"}, "size"),+ ({"prompt": "x", "seconds": "abc"}, "seconds"),+ ({"prompt": "x", "seconds": "0"}, "seconds"),+ ],+)+def test_unservable_shapes_are_400s_naming_the_param(client, backend, fields, param):+ resp = _create(client, fields)+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == param+ assert client.get("/v1/videos").json()["data"] == []+++def test_not_loaded_is_a_503_in_the_openai_envelope(client, backend):+ backend.loaded = False+ resp = _create(client, {"prompt": "x"})+ assert resp.status_code == 503+ assert "No video model loaded" in resp.json()["error"]["message"]+++def test_unknown_ids_are_404s(client, backend):+ for path in ("/v1/videos/video_nope", "/v1/videos/video_nope/content"):+ resp = client.get(path)+ assert resp.status_code == 404, path+ assert resp.json()["error"]["code"] == "video_not_found"+ assert client.delete("/v1/videos/video_nope").status_code == 404+ assert client.get("/v1/videos/../etc/passwd/content").status_code in (404, 400)+++def test_thumbnail_variant_returns_webp(client, backend, monkeypatch):+ clip = _save_clip("x", "2026-01-01T00:00:00Z")+ thumbnail = b"RIFF\x04\x00\x00\x00WEBP"+ monkeypatch.setattr(gallery_module, "thumbnail", lambda video_id: thumbnail)+ resp = client.get(f"/v1/videos/{clip['id']}/content", params = {"variant": "thumbnail"})+ assert resp.status_code == 200+ assert resp.headers["content-type"].startswith("image/webp")+ assert resp.headers["content-disposition"] == f'attachment; filename="{clip["id"]}.webp"'+ assert resp.content == thumbnail+++def test_unsupported_content_variant_names_the_param(client, backend):+ clip = _save_clip("x", "2026-01-01T00:00:00Z")+ resp = client.get(f"/v1/videos/{clip['id']}/content", params = {"variant": "spritesheet"})+ assert resp.status_code == 400 and resp.json()["error"]["param"] == "variant"+++def test_input_reference_upload_reaches_the_backend_unclassified(client, backend, monkeypatch):+ captured: dict = {}+ monkeypatch.setattr(backend, "begin_generate", lambda **kwargs: captured.update(kwargs))+ png = _reference_image_bytes("PNG")+ resp = _create(+ client, {"prompt": "animate this"}, {"input_reference": ("frame.png", png, "image/png")}+ )+ assert resp.status_code == 200, resp.json()+ assert captured["input_reference"].startswith("data:image/png;base64,")+ assert captured["video_id"] == resp.json()["id"]+ jpeg_url = _reference_data_url("JPEG", "image/jpeg")+ resp = _create(client, {"prompt": "x", "input_reference[image_url]": jpeg_url})+ assert resp.status_code == 200 and captured["input_reference"] == jpeg_url+ png_url = _reference_data_url("PNG", "image/png")+ resp = client.post(+ "/v1/videos",+ json = {"prompt": "x", "input_reference": {"image_url": png_url}},+ )+ assert resp.status_code == 200 and captured["input_reference"] == png_url+++def test_input_reference_refusals(client, backend):+ png = b"\x89PNG\r\n\x1a\nfake"+ resp = _create(client, {"prompt": "x"}, {"input_reference": ("frame.png", png, "image/png")})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "input_reference"+ resp = client.post(+ "/v1/videos",+ json = {"prompt": "x", "input_reference": {"image_url": "https://example.com/a.png"}},+ )+ assert resp.status_code == 400 and "not fetched" in resp.json()["error"]["message"]+ resp = client.post(+ "/v1/videos", json = {"prompt": "x", "input_reference": {"file_id": "file_123"}}+ )+ assert resp.status_code == 400 and resp.json()["error"]["param"] == "input_reference"+ resp = _create(client, {"prompt": "x", "input_reference[file_id]": "file_123"})+ assert resp.status_code == 400 and resp.json()["error"]["param"] == "input_reference"+ resp = _create(client, {"prompt": "x"}, {"input_reference": ("a.txt", b"hello", "text/plain")})+ assert resp.status_code == 400 and "must be an image" in resp.json()["error"]["message"]+ assert client.get("/v1/videos").json()["data"] == []+++def test_octet_stream_uploads_are_sniffed(client, backend, monkeypatch):+ captured: dict = {}+ monkeypatch.setattr(backend, "begin_generate", lambda **kwargs: captured.update(kwargs))+ jpeg = _reference_image_bytes("JPEG")+ resp = _create(+ client,+ {"prompt": "x"},+ {"input_reference": ("frame.bin", jpeg, "application/octet-stream")},+ )+ assert resp.status_code == 200, resp.json()+ assert captured["input_reference"].startswith("data:image/jpeg;base64,")+ webp = _reference_image_bytes("WEBP")+ resp = _create(+ client, {"prompt": "x"}, {"input_reference": ("frame", webp, "application/octet-stream")}+ )+ assert resp.status_code == 200 and captured["input_reference"].startswith(+ "data:image/webp;base64,"+ )+ resp = _create(+ client,+ {"prompt": "x"},+ {"input_reference": ("blob.bin", b"not an image", "application/octet-stream")},+ )+ assert resp.status_code == 400 and resp.json()["error"]["param"] == "input_reference"+++def test_model_never_leaks_a_host_path(client, backend, monkeypatch):+ monkeypatch.setattr(+ backend,+ "status",+ lambda: {**_FakeBackend.status(backend), "repo_id": "/srv/models/ltx-2.3-Q4_K_M.gguf"},+ )+ job = _create(client, {"prompt": "x"}).json()+ assert job["model"] == "ltx-2.3-Q4_K_M"+ clip = _save_clip("old", "2026-01-01T00:00:00Z", model = "/srv/models/ltx-2.3-Q4_K_M.gguf")+ assert client.get(f"/v1/videos/{clip['id']}").json()["model"] == "ltx-2.3-Q4_K_M"+ assert "/srv/" not in client.get("/v1/videos").text+++def test_create_hands_the_model_to_auto_switch(client, backend, monkeypatch):+ import core.inference.media_auto_switch as mas++ calls: list = []++ async def _record(model, **kwargs):+ calls.append(+ (+ model,+ kwargs["owner"],+ kwargs["openai_errors"],+ kwargs["hf_token"],+ kwargs["before_switch"] is not None,+ )+ )++ monkeypatch.setattr(mas, "maybe_auto_switch_media_model", _record)+ resp = client.post(+ "/v1/videos",+ json = {"prompt": "x", "model": "unsloth/LTX-2.3-GGUF"},+ headers = {"X-Unsloth-HF-Token": "hf_abc"},+ )+ assert resp.status_code == 200, resp.json()+ assert calls == [("unsloth/LTX-2.3-GGUF", gpu_arbiter.VIDEO, True, "hf_abc", True)]+++ "created_at, expected",+ [+ ("2026-01-01T00:00:00Z", 1767225600),+ ("2026-01-01T00:00:00+00:00", 1767225600),+ ("2026-01-01T01:00:00+01:00", 1767225600),+ ("2026-01-01T00:00:00", 1767225600),+ (1767225600.7, 1767225600),+ ("garbage", 0),+ (None, 0),+ ],+)+def test_record_epoch_accepts_old_and_new_sidecar_timestamps(created_at, expected):+ assert video_routes._record_epoch({"created_at": created_at}) == expected+++def test_an_unservable_duration_is_refused_before_the_model_switch(client, backend, monkeypatch):+ """The preflight judged size but passed None for the frame count.++ A duration no family can serve was therefore only refused inside begin_generate --+ after the resident pipeline had been evicted and the target model fully loaded.+ """+ import types++ from core.inference import media_auto_switch++ switched = {"completed": False}++ async def _fake_switch(+ model,+ *,+ before_switch = None,+ **_kwargs,+ ):+ pick = types.SimpleNamespace(model_path = "Lightricks/LTX-2", gguf_filename = None)+ if before_switch is not None:+ before_switch(pick)+ switched["completed"] = True++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)++ # 120s is inside the route's own bound but ~2880 frames, over the 1024 global ceiling.+ resp = _create(client, {"prompt": "x", "model": "Lightricks/LTX-2", "seconds": "120"})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "seconds"+ assert switched["completed"] is False, "the model was switched before the refusal"+++def test_a_reference_only_checkpoint_is_refused_before_the_model_switch(+ client, backend, monkeypatch+):+ import types++ from core.inference import media_auto_switch++ switched = {"completed": False}++ async def _fake_switch(+ model,+ *,+ before_switch = None,+ **_kwargs,+ ):+ pick = types.SimpleNamespace(+ model_path = "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_ref2va-Q4_K_M.gguf",+ model_kind = "gguf",+ )+ if before_switch is not None:+ before_switch(pick)+ switched["completed"] = True++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)+ resp = _create(client, {"prompt": "text only", "model": "MiniMax-H3-Ref2VA"})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "input_reference"+ assert "Ref2VA partition" in resp.json()["error"]["message"]+ assert switched["completed"] is False, "the model was switched before the refusal"++[email protected]("reference_size", [(8, 8), (5000, 1000)])+def test_ref2va_routes_the_input_image_as_a_reference(client, backend, monkeypatch, reference_size):+ import types++ from core.inference import media_auto_switch+ from core.inference.video_minimax_h3 import H3_TASK_REFERENCES++ switched = {"completed": False}+ captured = {}++ async def _fake_switch(+ model,+ *,+ before_switch = None,+ **_kwargs,+ ):+ pick = types.SimpleNamespace(+ model_path = "MiniMaxAI/MiniMax-H3",+ gguf_filename = "minimax_h3_ref2va-Q4_K_M.gguf",+ model_kind = "gguf",+ )+ if before_switch is not None:+ before_switch(pick)+ switched["completed"] = True++ def _status():+ return {+ **_FakeBackend.status(backend),+ "repo_id": "MiniMaxAI/MiniMax-H3",+ "h3_task": H3_TASK_REFERENCES,+ }++ def _begin(**kwargs):+ captured.update(kwargs)+ return {"width": 768, "height": 512}++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)+ monkeypatch.setattr(backend, "status", _status)+ monkeypatch.setattr(backend, "begin_generate", _begin)++ resp = _create(+ client,+ {"prompt": "follow this subject", "model": "MiniMax-H3-Ref2VA"},+ {+ "input_reference": (+ "subject.png",+ _reference_image_bytes("PNG", reference_size),+ "image/png",+ )+ },+ )+ assert resp.status_code == 200, resp.json()+ assert switched["completed"] is True+ assert captured["input_reference"].startswith("data:image/png;base64,")+ assert "first_frame" not in captured+ assert "reference_images" not in captured+++def test_reference_conditioning_follows_the_state_reserved_by_begin_generate(+ client, backend, monkeypatch+):+ import types++ from core.inference.video_families import detect_video_family+ from core.inference.video_minimax_h3 import H3_TASK_REFERENCES++ real_begin = backend.begin_generate++ def _racing_begin(**kwargs):+ with backend._lock:+ backend._state = types.SimpleNamespace(+ **{+ **vars(backend._state),+ "family": detect_video_family("MiniMaxAI/MiniMax-H3", None),+ "h3_task": H3_TASK_REFERENCES,+ "repo_id": "MiniMaxAI/MiniMax-H3",+ }+ )+ return real_begin(**kwargs)++ monkeypatch.setattr(backend, "begin_generate", _racing_begin)+ response = _create(+ client,+ {"prompt": "follow the newly reserved partition"},+ {"input_reference": ("subject.png", _reference_image_bytes("PNG"), "image/png")},+ )++ assert response.status_code == 200, response.json()+ deadline = time.monotonic() + 5.0+ while "_resolved_inputs" not in backend.last_generate_kwargs and time.monotonic() < deadline:+ time.sleep(0.01)+ resolved = backend.last_generate_kwargs["_resolved_inputs"]+ assert resolved.first_frame is None+ assert len(resolved.references.images) == 1+++def test_the_created_job_reports_the_canvas_the_backend_resolved(client, backend, monkeypatch):+ """With a reference image and no size the canvas follows the source aspect.++ The route used to record the family's first resolution preset regardless, so the+ create response advertised one size while the clip rendered at another, and the+ same job's size changed once it was read back from the gallery.+ """+ real = backend.begin_generate++ def _begin(**kwargs):+ real(**kwargs)+ return {"width": 704, "height": 1216}++ monkeypatch.setattr(backend, "begin_generate", _begin)+ job = _create(client, {"prompt": "a tall portrait"}).json()+ assert job["size"] == "704x1216"+++def test_deleting_a_job_that_finishes_mid_cancel_removes_the_clip(client, backend, monkeypatch):+ """Cancellation losing the race is not proof that nothing was written.++ The handler used to cancel and return deleted:true without ever deleting the pair,+ so a clip persisted in that window came straight back through retrieve and list.+ """+ backend.gate.clear()+ job = _create(client, {"prompt": "racy"}).json()+ assert client.get(f"/v1/videos/{job['id']}").json()["status"] in ("queued", "in_progress")++ def _cancel_after_it_finishes(expected_video_id):+ assert expected_video_id == job["id"]+ backend.gate.set()+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if gallery_module.owned_video_path(job["id"]) is not None:+ break+ time.sleep(0.01)+ else:+ raise AssertionError("the clip was never persisted")+ return False++ monkeypatch.setattr(backend, "cancel_generate", _cancel_after_it_finishes)++ resp = client.delete(f"/v1/videos/{job['id']}")+ assert resp.status_code == 200, resp.json()+ assert resp.json()["deleted"] is True+ assert gallery_module.owned_video_path(job["id"]) is None+ assert client.get(f"/v1/videos/{job['id']}").status_code == 404+ assert [v["id"] for v in client.get("/v1/videos").json()["data"]] == []+++def test_a_stale_poller_cannot_recreate_a_deleted_job(client, backend, monkeypatch):+ video_id = "video_delete_poll_race"+ job = video_routes._VideoJob(+ id = video_id,+ created_at = 1,+ prompt = "racy poll",+ model = "model",+ size = "768x512",+ seconds = "5",+ )+ video_routes._jobs[video_id] = job+ gallery_module.save_job(video_id, vars(job))++ save_started = threading.Event()+ release_save = threading.Event()+ forget_started = threading.Event()+ delete_done = threading.Event()+ real_save = gallery_module.save_job+ real_forget = gallery_module.forget_job++ def _delayed_save(saved_id, record):+ save_started.set()+ assert release_save.wait(timeout = 5.0)+ real_save(saved_id, record)++ def _observed_forget(forgotten_id):+ result = real_forget(forgotten_id)+ forget_started.set()+ return result++ monkeypatch.setattr(gallery_module, "save_job", _delayed_save)+ monkeypatch.setattr(gallery_module, "forget_job", _observed_forget)+ monkeypatch.setattr(+ video_routes,+ "_lookup_video",+ lambda requested_id: video_routes._job_to_openai(job) if requested_id == video_id else None,+ )+ monkeypatch.setattr(video_routes, "_await_generate_settled", lambda _video_id: True)++ poller = threading.Thread(target = video_routes._sync_jobs)+ poller.start()+ assert save_started.wait(timeout = 5.0)++ responses = []++ def _delete():+ responses.append(client.delete(f"/v1/videos/{video_id}"))+ delete_done.set()++ deleter = threading.Thread(target = _delete)+ deleter.start()+ if forget_started.wait(timeout = 0.5):+ assert delete_done.wait(timeout = 5.0)+ release_save.set()+ poller.join(timeout = 5.0)+ deleter.join(timeout = 5.0)++ assert not poller.is_alive() and not deleter.is_alive()+ assert responses[0].status_code == 200, responses[0].json()+ assert gallery_module.get_job(video_id) is None+ assert video_id not in video_routes._jobs+++def test_terminal_hydration_cannot_restore_a_deleted_job(client, backend, monkeypatch):+ video_id = "video_delete_hydration_race"+ job = video_routes._VideoJob(+ id = video_id,+ created_at = 1,+ prompt = "racy hydration",+ model = "model",+ size = "768x512",+ seconds = "5",+ )+ video_routes._jobs[video_id] = job+ gallery_module.save_job(+ video_id,+ {+ **vars(job),+ "status": "failed",+ "error": {"code": "video_generation_failed", "message": "failed"},+ },+ )++ terminal_read = threading.Event()+ release_read = threading.Event()+ real_get = gallery_module.get_job++ def _delayed_get(requested_id):+ record = real_get(requested_id)+ terminal_read.set()+ assert release_read.wait(timeout = 5.0)+ return record++ monkeypatch.setattr(gallery_module, "get_job", _delayed_get)+ monkeypatch.setattr(+ video_routes,+ "_lookup_video",+ lambda requested_id: video_routes._job_to_openai(job) if requested_id == video_id else None,+ )+ monkeypatch.setattr(video_routes, "_await_generate_settled", lambda _video_id: True)++ poller = threading.Thread(target = video_routes._sync_jobs)+ poller.start()+ assert terminal_read.wait(timeout = 5.0)+ deleted = client.delete(f"/v1/videos/{video_id}")+ assert deleted.status_code == 200, deleted.json()+ release_read.set()+ poller.join(timeout = 5.0)++ assert not poller.is_alive()+ assert real_get(video_id) is None+ assert video_id not in video_routes._jobs+++def test_concurrent_pollers_cannot_move_progress_backward(backend, monkeypatch):+ video_id = "video_monotonic_progress"+ job = video_routes._VideoJob(+ id = video_id,+ created_at = 1,+ prompt = "concurrent polls",+ model = "model",+ size = "768x512",+ seconds = "5",+ status = "in_progress",+ progress = 10,+ )+ video_routes._jobs[video_id] = job+ gallery_module.save_job(video_id, vars(job))++ older_waiting = threading.Event()+ release_older = threading.Event()+ real_get = gallery_module.get_job++ def _delayed_get(requested_id):+ if threading.current_thread().name == "older-video-poll":+ older_waiting.set()+ assert release_older.wait(timeout = 5.0)+ return real_get(requested_id)++ def _progress():+ fraction = 0.2 if threading.current_thread().name == "older-video-poll" else 0.3+ return {+ "video_id": video_id,+ "phase": "denoise",+ "active": True,+ "fraction": fraction,+ }++ monkeypatch.setattr(gallery_module, "get_job", _delayed_get)+ monkeypatch.setattr(backend, "generate_progress", _progress)+ older = threading.Thread(target = video_routes._sync_jobs, name = "older-video-poll")+ older.start()+ assert older_waiting.wait(timeout = 5.0)+ video_routes._sync_jobs()+ release_older.set()+ older.join(timeout = 5.0)++ assert not older.is_alive()+ assert job.status == "in_progress"+ assert job.progress == 30+ assert gallery_module.get_job(video_id)["progress"] == 30+++def test_an_undecodable_reference_is_refused_before_the_model_switch(client, backend, monkeypatch):+ """A well-formed content type is not a readable image.++ _resolve_keyframes only decodes inside begin_generate, which runs after the auto+ switch, so bad bytes used to evict the resident pipeline and load the target first.+ """+ import types++ from core.inference import media_auto_switch++ switched = {"completed": False}++ async def _fake_switch(+ model,+ *,+ before_switch = None,+ **_kwargs,+ ):+ pick = types.SimpleNamespace(model_path = "Lightricks/LTX-2", gguf_filename = None)+ if before_switch is not None:+ before_switch(pick)+ switched["completed"] = True++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)++ resp = _create(+ client,+ {"prompt": "x", "model": "Lightricks/LTX-2"},+ {"input_reference": ("frame.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png")},+ )+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "input_reference"+ # The message matters: without the eager decode this path still 400s, but only via+ # the keyframe-conditioning check, leaving real decode failures to run post-switch.+ assert "not a readable image" in resp.json()["error"]["message"], resp.json()+ assert switched["completed"] is False, "the model was switched before the refusal"+++def test_a_delete_that_cannot_observe_the_settle_does_not_confirm(client, backend, monkeypatch):+ """Returning deleted:true on a timed-out wait let the worker commit afterwards.++ The clip then reappeared through retrieve/list, so the caller was told a deletion+ happened that had not. Report 409 instead and let them retry.+ """+ monkeypatch.setattr(video_routes, "_DELETE_SETTLE_TIMEOUT_S", 0.05)+ backend.gate.clear()+ try:+ job = _create(client, {"prompt": "still writing"}).json()+ assert client.get(f"/v1/videos/{job['id']}").json()["status"] in (+ "queued",+ "in_progress",+ )+ monkeypatch.setattr(backend, "cancel_generate", lambda expected_video_id: False)+ resp = client.delete(f"/v1/videos/{job['id']}")+ assert resp.status_code == 409, resp.json()+ assert resp.json()["error"]["code"] == "video_not_ready"+ finally:+ backend.gate.set()+++def test_the_create_call_opens_an_api_monitor_row(client, backend, monkeypatch):+ """The OpenAI image and audio routes open a row; videos never did.++ Without it the newly supported API is invisible to the API Monitor and its usage+ receipts, so per-subject history silently undercounts video generation.+ """+ from core.inference.api_monitor import api_monitor++ started: list[dict] = []+ relabeled: list[str] = []+ real_start = api_monitor.start+ real_relabel = api_monitor.relabel++ def _spy(**kwargs):+ started.append(kwargs)+ return real_start(**kwargs)++ def _relabel(entry_id, model):+ relabeled.append(model)+ return real_relabel(entry_id, model)++ monkeypatch.setattr(api_monitor, "start", _spy)+ monkeypatch.setattr(api_monitor, "relabel", _relabel)+ resp = _create(client, {"prompt": "a monitored clip"})+ assert resp.status_code == 200, resp.json()+ rows = [r for r in started if r.get("endpoint") == "/v1/videos"]+ assert rows, started+ assert rows[0]["prompt"] == "a monitored clip"+ assert rows[0]["method"] == "POST"+ assert relabeled == [resp.json()["model"]]+++def test_the_job_describes_the_run_the_backend_reserved(client, backend, monkeypatch):+ """A load committing between status() and the reservation swaps the family.++ The job used to be described from the earlier snapshot, so it advertised the model+ that had just been replaced and a duration computed against that model's fps.+ """+ real = backend.begin_generate++ def _begin(**kwargs):+ real(**kwargs)+ # What the reservation actually committed to, different from the snapshot.+ return {+ "width": 704,+ "height": 1216,+ "num_frames": 121,+ "fps": 24,+ "model": "unsloth/Some-Other-Video-Model",+ }++ monkeypatch.setattr(backend, "begin_generate", _begin)+ job = _create(client, {"prompt": "swapped underneath", "seconds": "4"}).json()+ assert job["model"] == "unsloth/Some-Other-Video-Model"+ assert job["size"] == "704x1216"+ assert job["seconds"] == _format_seconds(121 / 24)++[email protected]("swap_before_snapshot", [True, False])+def test_requested_model_cannot_change_before_the_generation_reservation(+ client, backend, monkeypatch, swap_before_snapshot+):+ import types++ from core.inference import media_auto_switch+ from utils import openai_auto_switch_settings++ requested = backend.status()["repo_id"]++ def _swap_model():+ with backend._lock:+ backend._state = types.SimpleNamespace(+ **{+ **vars(backend._state),+ "repo_id": "unsloth/Replacement-Video-Model",+ }+ )++ async def _resident_fast_path(*_args, **_kwargs):+ if swap_before_snapshot:+ _swap_model()+ return None++ real_begin = backend.begin_generate++ def _racing_begin(**kwargs):+ if not swap_before_snapshot:+ _swap_model()+ return real_begin(**kwargs)++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _resident_fast_path)+ monkeypatch.setattr(openai_auto_switch_settings, "get_media_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(backend, "begin_generate", _racing_begin)++ response = _create(client, {"prompt": "keep the requested model", "model": requested})++ assert response.status_code == 409, response.json()+ assert response.json()["error"]["code"] == "model_changed"+++def test_requested_duration_is_recomputed_for_the_reserved_family(client, backend, monkeypatch):+ real_status = backend.status++ def _stale_status():+ status = real_status()+ status["defaults"] = {+ **status["defaults"],+ "fps": 16,+ "frame_step": 4,+ "frame_offset": 1,+ }+ return status++ monkeypatch.setattr(backend, "status", _stale_status)+ job = _create(client, {"prompt": "five seconds", "seconds": "5"}).json()+ assert backend.last_generate_kwargs["num_frames"] == 121+ assert job["seconds"] == _format_seconds(121 / 24)diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex d6eeab2926b..4ed76b578ea 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -6683,6 +6683,38 @@ def test_h3_begin_generate_reuses_preflight_resolved_references(monkeypatch):assert len(resolve_calls) == 2+def test_a_v1_videos_job_id_stays_out_of_the_replayable_worker_kwargs(monkeypatch):+ """begin_generate's worker kwargs must stay a valid generate() call.++ The /v1/videos job id is worker bookkeeping, not a generation input, so it rides on the+ thread target beside job_token. Putting it in kwargs made every caller that replays them+ -- the H3 preflight reuse path does -- raise TypeError on an unexpected keyword."""+ import core.inference.video as video_mod++ backend = _h3_ref_backend(monkeypatch, [])+ expected = object()+ captured = {}++ class _DeferredThread:+ def __init__(self, *, target, kwargs, daemon):+ captured.update(target = target, kwargs = kwargs, daemon = daemon)++ def start(self):+ return None++ monkeypatch.setattr(backend, "_resolve_references", lambda *a, **k: expected)+ monkeypatch.setattr(backend, "_state_device_target", lambda _state: None)+ monkeypatch.setattr(video_mod.threading, "Thread", _DeferredThread)+ monkeypatch.setattr(backend, "_generate_h3_native", lambda **kwargs: kwargs["references"])++ backend.begin_generate(prompt = "p", video_id = "video_abc123")++ assert "video_id" not in captured["kwargs"]+ assert captured["target"].keywords["video_id"] == "video_abc123"+ # The replay the H3 preflight path performs must still be accepted.+ assert backend.generate(**captured["kwargs"]) is expected++def test_h3_native_refuses_a_later_video_soundtrack_after_a_silent_video(monkeypatch):pytest.importorskip("av")backend = _h3_ref_backend(monkeypatch, [])diff --git a/studio/backend/tests/test_video_gallery.py b/studio/backend/tests/test_video_gallery.pyindex a29ca3e67b5..cea584f90b0 100644--- a/studio/backend/tests/test_video_gallery.py+++ b/studio/backend/tests/test_video_gallery.py@@ -474,6 +474,27 @@ def test_transcode_gif_and_webm_produce_real_containers():assert webm is not None and webm[:4] == b"\x1a\x45\xdf\xa3"+def test_thumbnail_produces_a_webp_from_the_video():+ import io++ Image = pytest.importorskip("PIL.Image")+ record = gallery.save(_real_mp4_bytes(frames = 3, size = 64), _meta())+ thumbnail = gallery.thumbnail(record["id"])++ assert thumbnail is not None+ assert thumbnail[:4] == b"RIFF" and thumbnail[8:12] == b"WEBP"+ with Image.open(io.BytesIO(thumbnail)) as image:+ assert image.format == "WEBP"+ assert image.size == (64, 64)+++def test_thumbnail_rejects_unowned_and_invalid_videos():+ assert gallery.thumbnail("does-not-exist") is None+ record = gallery.save(_mp4(), _meta())+ with pytest.raises(RuntimeError, match = "Thumbnail generation failed"):+ gallery.thumbnail(record["id"])++def test_transcode_unknown_id_and_bad_format():assert gallery.transcode("does-not-exist", "gif") is Nonerecord = gallery.save(_real_mp4_bytes(), _meta())diff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.pyindex 662af0f1dd2..932a802146d 100644--- a/studio/backend/utils/upload_limits.py+++ b/studio/backend/utils/upload_limits.py@@ -15,8 +15,11 @@ MAX_UPLOAD_LIMIT_MB = 8192_BYTES_PER_MB = 1024 * 1024MULTIPART_OVERHEAD_BYTES = 10 * _BYTES_PER_MBSTT_AUDIO_RAW_MAX_BYTES = 25 * _BYTES_PER_MB+VIDEO_INPUT_REFERENCE_MAX_BYTES = 32 * _BYTES_PER_MBSTT_AUDIO_B64_MAX_CHARS = ((STT_AUDIO_RAW_MAX_BYTES + 2) // 3) * 4STT_AUDIO_JSON_MAX_BYTES = STT_AUDIO_B64_MAX_CHARS + 64 * 1024+VIDEO_INPUT_REFERENCE_B64_MAX_CHARS = ((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) // 3) * 4+VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES = VIDEO_INPUT_REFERENCE_B64_MAX_CHARS + 64 * 1024LOCAL_SEED_UPLOAD_MAX_BYTES = 100 * _BYTES_PER_MBLOCAL_SEED_UPLOAD_MAX_LABEL = "100MB"