[Frontend] Add midway prompt update for streaming video generation (#4652)
Signed-off-by: Huang, Zeyu <11222265+fhfuih@users.noreply.github.com>
This commit is contained in:
1 parent
1f01d05603
commit
eaf90d8eff
28 files changed
+2615
-133
No files matched your search
@@ -50,7 +50,7 @@ if TYPE_CHECKING:
|
||||
DuplexSessionLifecycleMessage,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.request_client import DuplexRequestClient
|
||||
from vllm_omni.inputs.data import OmniPromptType
|
||||
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniPromptType
|
||||
|
||||
logger = init_logger(__name__)
|
||||
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
|
||||
@@ -1006,6 +1006,46 @@ class AsyncOmni(EngineClient, OmniBase):
|
||||
internal_ids = [s.request_id for s in self.request_states.values() if s.external_request_id in request_ids]
|
||||
await self._abort(internal_ids)
|
||||
|
||||
async def submit_interaction_async(
|
||||
self,
|
||||
request_id: str,
|
||||
*,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Apply a midway interaction to an active streaming diffusion request.
|
||||
|
||||
``request_id`` is the external id created by the server-side session,
|
||||
matching the value passed to :meth:`generate`.
|
||||
"""
|
||||
event = interaction.get("event")
|
||||
prompt = event.get("prompt") if isinstance(event, dict) else None
|
||||
if isinstance(event, dict) and "prompt" in event and (not isinstance(prompt, str) or not prompt):
|
||||
raise ValueError("prompt must be non-empty")
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
if transition_chunks is not None and transition_chunks < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
if self.num_stages != 1:
|
||||
raise ValueError("interaction requires single-stage diffusion")
|
||||
stage_meta = self.engine.get_stage_metadata(0)
|
||||
if stage_meta.stage_type != "diffusion":
|
||||
raise ValueError("interaction requires a diffusion stage")
|
||||
|
||||
internal_ids = [s.request_id for s in self.request_states.values() if s.external_request_id == request_id]
|
||||
if not internal_ids:
|
||||
raise ValueError(f"No active request for interaction: {request_id!r}")
|
||||
if len(internal_ids) > 1:
|
||||
raise ValueError(
|
||||
f"interaction requires exactly one active request for {request_id!r}, found {len(internal_ids)}"
|
||||
)
|
||||
|
||||
await self.engine.submit_interaction_async(
|
||||
internal_ids[0],
|
||||
interaction=interaction,
|
||||
)
|
||||
if self.log_stats:
|
||||
logger.info("[AsyncOmni] Queued interaction for request %s", request_id)
|
||||
|
||||
async def _abort_internal_requests(self, request_id: str | Iterable[str]):
|
||||
"""Abort request(s) via the Orchestrator given internal request IDs,
|
||||
which take the format <external_request_id>-<UUID>.
|
||||
|
||||
@@ -5,13 +5,22 @@
|
||||
Protocol:
|
||||
Client -> Server:
|
||||
{"type": "session.start", "model": "...", "prompt": "...", "format": "m4s", ...}
|
||||
{"type": "session.prompt_update", "prompt": "..."} # currently unsupported
|
||||
{
|
||||
"type": "session.interaction",
|
||||
"interaction": {
|
||||
"event_id": "...",
|
||||
"event": {"prompt": "..."},
|
||||
"transition_chunks": (optional, integer),
|
||||
},
|
||||
}
|
||||
{"type": "session.stop"}
|
||||
{"type": "session.ping"} # optional; refreshes stall clock
|
||||
|
||||
Server -> Client:
|
||||
{"type": "video.start", "request_id": "...", "config": {...}, "format": "m4s"}
|
||||
{"type": "video.chunk_metadata", ...}
|
||||
<binary frame: fragmented MP4 bytes>
|
||||
{"type": "session.interaction.queued", "request_id": "...", "event_id": "..."}
|
||||
{"type": "session.done", ...}
|
||||
{"type": "session.pong"} # reply to session.ping
|
||||
{"type": "error", "message": "..."}
|
||||
@@ -21,7 +30,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import inspect
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
@@ -29,19 +37,34 @@ from collections.abc import AsyncGenerator
|
||||
from http import HTTPStatus
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
|
||||
from PIL import Image
|
||||
from pydantic import ValidationError
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.entrypoints.openai.errors import InvalidInputReferenceError
|
||||
from vllm_omni.entrypoints.openai.protocol.videos import VideoGenerationRequest, VideoParams
|
||||
from vllm_omni.entrypoints.openai.stage_params import (
|
||||
build_stage_sampling_params_list,
|
||||
get_default_sampling_params_list,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.utils import get_stage_type, parse_lora_request
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import StreamingVideoFormat, create_streaming_video_encoder
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
|
||||
from vllm_omni.entrypoints.openai.video_api_utils import (
|
||||
StreamingVideoFormat,
|
||||
create_streaming_video_encoder,
|
||||
decode_input_reference,
|
||||
)
|
||||
from vllm_omni.inputs.data import (
|
||||
OmniDiffusionSamplingParams,
|
||||
OmniInteractionEvent,
|
||||
OmniInteractionPrompt,
|
||||
OmniTextPrompt,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.outputs.output_metadata import DiffusionPayloadValue
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -70,7 +93,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine_client: EngineClient,
|
||||
engine_client: AsyncOmni,
|
||||
model_name: str | None = None,
|
||||
stage_configs: list[Any] | None = None,
|
||||
stall_timeout: float = _DEFAULT_STALL_TIMEOUT,
|
||||
@@ -91,6 +114,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
control_task: asyncio.Task[None] | None = None
|
||||
stopped = False
|
||||
chunks_sent = 0
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt] = {}
|
||||
|
||||
try:
|
||||
start = await self._receive_start(websocket)
|
||||
@@ -112,13 +136,22 @@ class OmniStreamingVideoOutputHandler:
|
||||
progress.touch()
|
||||
|
||||
control_task = asyncio.create_task(
|
||||
self._control_loop(websocket, request_id, stop_event, send_lock, progress)
|
||||
self._control_loop(
|
||||
websocket,
|
||||
request_id,
|
||||
stop_event,
|
||||
send_lock,
|
||||
progress,
|
||||
interaction_payloads_by_id,
|
||||
)
|
||||
)
|
||||
async for chunk in self._stream_video_bytes(request, request_id, output_format, progress):
|
||||
async for chunk, metadata in self._stream_video_bytes(request, request_id, output_format, progress):
|
||||
if stop_event.is_set():
|
||||
stopped = True
|
||||
break
|
||||
async with send_lock:
|
||||
metadata["transport_chunk_index"] = chunks_sent
|
||||
await websocket.send_json(metadata)
|
||||
await websocket.send_bytes(chunk)
|
||||
chunks_sent += 1
|
||||
progress.touch()
|
||||
@@ -234,6 +267,7 @@ class OmniStreamingVideoOutputHandler:
|
||||
stop_event: asyncio.Event,
|
||||
send_lock: asyncio.Lock,
|
||||
progress: _SessionProgress,
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt],
|
||||
) -> None:
|
||||
while not stop_event.is_set():
|
||||
if progress.stalled_for(self._stall_timeout):
|
||||
@@ -282,34 +316,151 @@ class OmniStreamingVideoOutputHandler:
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
if msg_type == "session.prompt_update":
|
||||
await self._send_error(
|
||||
if msg_type == "session.interaction":
|
||||
await self._handle_interaction(
|
||||
websocket,
|
||||
"session.prompt_update is not supported by this backend yet",
|
||||
msg,
|
||||
request_id=request_id,
|
||||
send_lock=send_lock,
|
||||
interaction_payloads_by_id=interaction_payloads_by_id,
|
||||
)
|
||||
continue
|
||||
await self._send_error(websocket, f"Unknown message type: {msg_type}", send_lock=send_lock)
|
||||
|
||||
async def _abort_request(self, request_id: str) -> None:
|
||||
try:
|
||||
abort = getattr(self._engine_client, "abort", None)
|
||||
if callable(abort):
|
||||
result = abort(request_id)
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
await self._engine_client.abort(request_id)
|
||||
except Exception:
|
||||
logger.debug("Failed to abort streaming video request %s", request_id, exc_info=True)
|
||||
|
||||
async def _handle_interaction(
|
||||
self,
|
||||
websocket: WebSocket,
|
||||
msg: dict[str, Any],
|
||||
*,
|
||||
request_id: str,
|
||||
send_lock: asyncio.Lock,
|
||||
interaction_payloads_by_id: dict[str, OmniInteractionPrompt],
|
||||
) -> None:
|
||||
interaction = msg.get("interaction")
|
||||
if not isinstance(interaction, dict):
|
||||
await self._send_error(websocket, "session.interaction requires an interaction object", send_lock=send_lock)
|
||||
return
|
||||
|
||||
event_id = interaction.get("event_id")
|
||||
if event_id is None:
|
||||
event_id = uuid.uuid4().hex
|
||||
elif not isinstance(event_id, str) or not event_id:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction event_id must be a non-empty string",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
event = interaction.get("event")
|
||||
if not isinstance(event, dict):
|
||||
await self._send_error(websocket, "session.interaction requires event object", send_lock=send_lock)
|
||||
return
|
||||
|
||||
prompt = event.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt.strip():
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction requires a non-empty event.prompt",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
if "negative_prompt" in event and event["negative_prompt"] is not None:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction negative_prompt is not supported in this release",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
normalized: OmniInteractionPrompt = {
|
||||
"event_id": event_id,
|
||||
"event": cast(OmniInteractionEvent, event),
|
||||
}
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
if transition_chunks is not None:
|
||||
try:
|
||||
if (
|
||||
isinstance(transition_chunks, bool)
|
||||
or not isinstance(transition_chunks, (int, float))
|
||||
or (isinstance(transition_chunks, float) and not transition_chunks.is_integer())
|
||||
):
|
||||
raise ValueError
|
||||
normalized["transition_chunks"] = int(transition_chunks)
|
||||
except (TypeError, ValueError):
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction transition_chunks must be an integer",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
if normalized["transition_chunks"] < 0:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"session.interaction transition_chunks must be >= 0",
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
if event_id in interaction_payloads_by_id:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"event_id_conflict",
|
||||
code="event_id_conflict",
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
interaction_payloads_by_id[event_id] = normalized
|
||||
|
||||
try:
|
||||
await self._engine_client.submit_interaction_async(
|
||||
request_id,
|
||||
interaction=normalized,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to apply interaction for request %s", request_id, exc_info=True)
|
||||
interaction_payloads_by_id.pop(event_id, None)
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"Failed to apply interaction",
|
||||
code="interaction_failed",
|
||||
request_id=request_id,
|
||||
event_id=event_id,
|
||||
send_lock=send_lock,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
async with send_lock:
|
||||
await websocket.send_json(
|
||||
{
|
||||
"type": "session.interaction.queued",
|
||||
"request_id": request_id,
|
||||
"event_id": event_id,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to send interaction acknowledgement for %s", request_id, exc_info=True)
|
||||
|
||||
async def _stream_video_bytes(
|
||||
self,
|
||||
request: VideoGenerationRequest,
|
||||
request_id: str,
|
||||
output_format: StreamingVideoFormat,
|
||||
progress: _SessionProgress,
|
||||
) -> AsyncGenerator[bytes, None]:
|
||||
) -> AsyncGenerator[tuple[bytes, dict[str, Any]], None]:
|
||||
"""Yield encoded video bytes from diffusion streaming outputs."""
|
||||
prompt, gen_params, vp = self._build_prompt_and_sampling_params(request)
|
||||
prompt, gen_params, vp = await self._build_prompt_and_sampling_params(request)
|
||||
video_codec_options = {"preset": "ultrafast", "threads": "0", "tune": "zerolatency"}
|
||||
if isinstance(request.extra_params, dict) and "video_codec_options" in request.extra_params:
|
||||
video_codec_options = request.extra_params["video_codec_options"]
|
||||
@@ -323,23 +474,41 @@ class OmniStreamingVideoOutputHandler:
|
||||
completed = False
|
||||
try:
|
||||
async for result in self._iter_generation_outputs(prompt, gen_params, request_id, progress):
|
||||
if error := getattr(result, "error", None):
|
||||
raise RuntimeError(str(error))
|
||||
if result.error:
|
||||
raise RuntimeError(str(result.error))
|
||||
videos = self._extract_video_outputs(result)
|
||||
for video in videos:
|
||||
chunk = encoder.encode(video)
|
||||
if chunk:
|
||||
yield chunk
|
||||
yield (
|
||||
chunk,
|
||||
self._build_chunk_metadata(
|
||||
request_id=request_id,
|
||||
kind="media",
|
||||
byte_length=len(chunk),
|
||||
num_frames=self._num_video_frames(video),
|
||||
stream_metadata=self._extract_stream_metadata(result),
|
||||
),
|
||||
)
|
||||
|
||||
completed = True
|
||||
final_chunk = encoder.close()
|
||||
if final_chunk:
|
||||
yield final_chunk
|
||||
yield (
|
||||
final_chunk,
|
||||
self._build_chunk_metadata(
|
||||
request_id=request_id,
|
||||
kind="trailer",
|
||||
byte_length=len(final_chunk),
|
||||
num_frames=0,
|
||||
stream_metadata={},
|
||||
),
|
||||
)
|
||||
finally:
|
||||
if not completed:
|
||||
encoder.close()
|
||||
|
||||
def _build_prompt_and_sampling_params(
|
||||
async def _build_prompt_and_sampling_params(
|
||||
self,
|
||||
request: VideoGenerationRequest,
|
||||
) -> tuple[OmniTextPrompt, OmniDiffusionSamplingParams, VideoParams]:
|
||||
@@ -350,6 +519,10 @@ class OmniStreamingVideoOutputHandler:
|
||||
|
||||
gen_params = self._resolve_default_sampling_params()
|
||||
vp = request.resolve_video_params()
|
||||
input_image = await self._decode_image_reference(request)
|
||||
if input_image is not None:
|
||||
prompt["multi_modal_data"] = {"image": input_image}
|
||||
|
||||
if vp.width is not None and vp.height is not None:
|
||||
gen_params.width = vp.width
|
||||
gen_params.height = vp.height
|
||||
@@ -386,12 +559,28 @@ class OmniStreamingVideoOutputHandler:
|
||||
self._apply_lora(request.lora, gen_params)
|
||||
return prompt, gen_params, vp
|
||||
|
||||
@staticmethod
|
||||
async def _decode_image_reference(request: VideoGenerationRequest) -> Image.Image | None:
|
||||
try:
|
||||
media_data = await decode_input_reference(
|
||||
request.image_reference,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
except InvalidInputReferenceError as exc:
|
||||
raise HTTPException(HTTPStatus.BAD_REQUEST.value, detail=str(exc)) from exc
|
||||
if media_data is not None and not isinstance(media_data, Image.Image):
|
||||
raise HTTPException(
|
||||
HTTPStatus.BAD_REQUEST.value,
|
||||
detail="image_reference must resolve to an image.",
|
||||
)
|
||||
return media_data
|
||||
|
||||
def _resolve_default_sampling_params(self) -> OmniDiffusionSamplingParams:
|
||||
default_sampling_params_list = getattr(self._engine_client, "default_sampling_params_list", None)
|
||||
if default_sampling_params_list:
|
||||
for params in default_sampling_params_list:
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
return copy.deepcopy(params)
|
||||
default_sampling_params_list = self._engine_client.default_sampling_params_list
|
||||
for params in default_sampling_params_list:
|
||||
if isinstance(params, OmniDiffusionSamplingParams):
|
||||
return copy.deepcopy(params)
|
||||
return OmniDiffusionSamplingParams()
|
||||
|
||||
@staticmethod
|
||||
@@ -417,8 +606,8 @@ class OmniStreamingVideoOutputHandler:
|
||||
gen_params: OmniDiffusionSamplingParams,
|
||||
request_id: str,
|
||||
progress: _SessionProgress,
|
||||
) -> AsyncGenerator[Any, None]:
|
||||
stage_configs = self._stage_configs or getattr(self._engine_client, "stage_configs", None)
|
||||
) -> AsyncGenerator[OmniRequestOutput, None]:
|
||||
stage_configs = self._stage_configs or self._engine_client.stage_configs
|
||||
if not stage_configs:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.SERVICE_UNAVAILABLE.value,
|
||||
@@ -433,15 +622,14 @@ class OmniStreamingVideoOutputHandler:
|
||||
detail=f"Video generation only supports diffusion stages, found '{stage_type}' stage.",
|
||||
)
|
||||
|
||||
engine_client = cast(Any, self._engine_client)
|
||||
sampling_params_list = build_stage_sampling_params_list(
|
||||
list(stage_configs),
|
||||
get_default_sampling_params_list(engine_client),
|
||||
get_default_sampling_params_list(self._engine_client),
|
||||
diffusion_params=gen_params,
|
||||
replace_diffusion_params=True,
|
||||
)
|
||||
|
||||
async for output in engine_client.generate(
|
||||
async for output in self._engine_client.generate(
|
||||
prompt=prompt,
|
||||
request_id=request_id,
|
||||
sampling_params_list=sampling_params_list,
|
||||
@@ -450,44 +638,49 @@ class OmniStreamingVideoOutputHandler:
|
||||
yield output
|
||||
|
||||
@staticmethod
|
||||
def _normalize_video_outputs(videos: Any) -> list[Any]:
|
||||
def _normalize_video_outputs(videos: DiffusionPayloadValue | None) -> list[DiffusionPayloadValue]:
|
||||
if videos is None:
|
||||
return []
|
||||
if hasattr(videos, "ndim") and videos.ndim == 5:
|
||||
if isinstance(videos, (torch.Tensor, np.ndarray)) and videos.ndim == 5:
|
||||
return [videos[i] for i in range(videos.shape[0])]
|
||||
if isinstance(videos, list):
|
||||
if not videos:
|
||||
return []
|
||||
first = videos[0]
|
||||
if hasattr(first, "ndim") and first.ndim == 5:
|
||||
flattened: list[Any] = []
|
||||
if isinstance(first, (torch.Tensor, np.ndarray)) and first.ndim == 5:
|
||||
flattened: list[DiffusionPayloadValue] = []
|
||||
for item in videos:
|
||||
if hasattr(item, "ndim") and item.ndim == 5:
|
||||
if isinstance(item, (torch.Tensor, np.ndarray)) and item.ndim == 5:
|
||||
flattened.extend([item[i] for i in range(item.shape[0])])
|
||||
else:
|
||||
flattened.append(item)
|
||||
return flattened
|
||||
if isinstance(first, list):
|
||||
return videos
|
||||
if hasattr(first, "ndim") and first.ndim == 3:
|
||||
if isinstance(first, (torch.Tensor, np.ndarray)) and first.ndim == 3:
|
||||
return [videos]
|
||||
if isinstance(first, Image.Image):
|
||||
return [videos]
|
||||
return videos
|
||||
return [videos]
|
||||
|
||||
def _extract_video_outputs(self, result: Any) -> list[Any]:
|
||||
videos = None
|
||||
if hasattr(result, "images") and result.images:
|
||||
videos = result.images
|
||||
elif hasattr(result, "request_output"):
|
||||
def _extract_video_outputs(self, result: OmniRequestOutput) -> list[DiffusionPayloadValue]:
|
||||
videos: DiffusionPayloadValue | None = None
|
||||
if result.images:
|
||||
# Video frames may be list[list[Image.Image]] despite images: list[Image.Image].
|
||||
videos = result.images # type: ignore[assignment]
|
||||
elif result.request_output is not None:
|
||||
request_output = result.request_output
|
||||
if isinstance(request_output, dict) and request_output.get("images"):
|
||||
videos = request_output["images"]
|
||||
elif not isinstance(request_output, dict):
|
||||
if hasattr(request_output, "images") and request_output.images:
|
||||
videos = request_output.images
|
||||
elif hasattr(request_output, "multimodal_output") and request_output.multimodal_output:
|
||||
videos = request_output.multimodal_output.get("video")
|
||||
if videos is None and hasattr(result, "multimodal_output") and result.multimodal_output:
|
||||
elif isinstance(request_output, OmniRequestOutput):
|
||||
if request_output.images:
|
||||
# Same nested-frames mismatch as result.images above.
|
||||
videos = request_output.images # type: ignore[assignment]
|
||||
else:
|
||||
request_multimodal_output = request_output.multimodal_output
|
||||
videos = request_multimodal_output.get("video")
|
||||
if videos is None:
|
||||
videos = result.multimodal_output.get("video")
|
||||
|
||||
normalized = self._normalize_video_outputs(videos)
|
||||
@@ -498,18 +691,64 @@ class OmniStreamingVideoOutputHandler:
|
||||
)
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _extract_stream_metadata(result: OmniRequestOutput) -> dict[str, Any]:
|
||||
multimodal_output = result.multimodal_output
|
||||
if not isinstance(multimodal_output, dict):
|
||||
return {}
|
||||
metadata = multimodal_output.get("metadata")
|
||||
if not isinstance(metadata, dict):
|
||||
return {}
|
||||
stream = metadata.get("stream")
|
||||
return dict(stream) if isinstance(stream, dict) else {}
|
||||
|
||||
@staticmethod
|
||||
def _num_video_frames(video: DiffusionPayloadValue) -> int:
|
||||
if isinstance(video, (torch.Tensor, np.ndarray)) and len(video.shape) > 0:
|
||||
return int(video.shape[0])
|
||||
if isinstance(video, list):
|
||||
return len(video)
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def _build_chunk_metadata(
|
||||
*,
|
||||
request_id: str,
|
||||
kind: str,
|
||||
byte_length: int,
|
||||
num_frames: int,
|
||||
stream_metadata: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"type": "video.chunk_metadata",
|
||||
"request_id": request_id,
|
||||
"kind": kind,
|
||||
"num_frames": num_frames,
|
||||
"byte_length": byte_length,
|
||||
"generation_chunk_index": (stream_metadata.get("generation_chunk_index") if kind == "media" else None),
|
||||
"started_event_ids": stream_metadata.get("started_event_ids", []),
|
||||
"active_event_ids": stream_metadata.get("active_event_ids", []),
|
||||
"completed_event_ids": stream_metadata.get("completed_event_ids", []),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def _send_error(
|
||||
websocket: WebSocket,
|
||||
message: str,
|
||||
code: int | None = None,
|
||||
code: int | str | None = None,
|
||||
*,
|
||||
request_id: str | None = None,
|
||||
event_id: str | None = None,
|
||||
send_lock: asyncio.Lock | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
payload: dict[str, Any] = {"type": "error", "message": message}
|
||||
if code is not None:
|
||||
payload["code"] = code
|
||||
if request_id is not None:
|
||||
payload["request_id"] = request_id
|
||||
if event_id is not None:
|
||||
payload["event_id"] = event_id
|
||||
if send_lock is None:
|
||||
await websocket.send_json(payload)
|
||||
else:
|
||||
|
||||
Reference in new issue
Block a user