Signed-off-by: chickeyton <ngton2014@gmail.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
49 files changed
+3056
-1715
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Model-neutral helpers shared between model packages.
|
||||
|
||||
``audio`` and ``request_outputs`` carry no duplex vocabulary and may be used
|
||||
from any model. ``duplex`` builds on the duplex framework contracts and is
|
||||
imported only from a model's ``duplex`` package.
|
||||
"""
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Generic audio helpers shared between model packages."""
|
||||
@@ -0,0 +1,54 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Little-endian float32 PCM (``pcm_f32le``) helpers.
|
||||
|
||||
Plain audio plumbing every model that takes raw PCM needs: decode a base64
|
||||
chunk, check it is whole finite samples, count and materialise them. No
|
||||
duplex vocabulary lives here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
|
||||
import numpy as np
|
||||
import pybase64 as base64
|
||||
|
||||
PCM_F32LE_BYTES_PER_SAMPLE = 4
|
||||
|
||||
|
||||
def decode_pcm_f32le_base64(encoded: object, *, model: str = "audio") -> bytes:
|
||||
"""Decode base64 ``pcm_f32le`` into raw bytes, refusing partial or non-finite samples.
|
||||
|
||||
``model`` names the caller in error messages so a client sees which model
|
||||
rejected its audio.
|
||||
"""
|
||||
if not isinstance(encoded, str):
|
||||
raise ValueError(f"{model} audio must be base64 pcm_f32le")
|
||||
try:
|
||||
raw = base64.b64decode(encoded, validate=True)
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise ValueError(f"{model} audio is not valid base64") from exc
|
||||
if len(raw) % PCM_F32LE_BYTES_PER_SAMPLE:
|
||||
raise ValueError(f"{model} pcm_f32le byte length must be divisible by four")
|
||||
samples = np.frombuffer(raw, dtype="<f4")
|
||||
if samples.size and not bool(np.isfinite(samples).all()):
|
||||
raise ValueError(f"{model} pcm_f32le samples must be finite")
|
||||
return raw
|
||||
|
||||
|
||||
def pcm_f32le_sample_count(raw: bytes) -> int:
|
||||
return len(raw) // PCM_F32LE_BYTES_PER_SAMPLE
|
||||
|
||||
|
||||
def pcm_f32le_samples(raw: bytes) -> np.ndarray:
|
||||
"""The samples as a writable, contiguous float32 array (safe for zero-copy tensor views)."""
|
||||
return np.ascontiguousarray(np.frombuffer(raw, dtype="<f4"), dtype=np.float32).copy()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PCM_F32LE_BYTES_PER_SAMPLE",
|
||||
"decode_pcm_f32le_base64",
|
||||
"pcm_f32le_sample_count",
|
||||
"pcm_f32le_samples",
|
||||
]
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared building blocks for ``DuplexModelPlugin`` implementations.
|
||||
|
||||
Everything here depends on the duplex framework contracts
|
||||
(``vllm_omni.engine.duplex.plugin``), so it is imported only from a model's
|
||||
``duplex`` package, never from the turn-based stack.
|
||||
"""
|
||||
@@ -0,0 +1,135 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Data plane for models whose final stage streams cumulative audio and text.
|
||||
|
||||
The stage runner re-sends the whole waveform (and transcript) it has produced
|
||||
so far for one request; the session needs only what is new. This data plane
|
||||
keeps one cursor per request, slices the delta, encodes it for the wire and
|
||||
reports it as one internal ``response.output_audio.delta``-shaped result.
|
||||
Model-specific constants (stage role, runtime metadata, default rate) are
|
||||
class attributes for a subclass to set.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import duplex_resource_request_belongs_to_session
|
||||
from vllm_omni.engine.duplex.plugin import DuplexDataPlane, DuplexDataPlaneContext
|
||||
from vllm_omni.model_executor.common.request_outputs import (
|
||||
audio_sample_count,
|
||||
audio_value,
|
||||
multimodal_output,
|
||||
sample_rate_hz,
|
||||
slice_audio_delta,
|
||||
text_delta,
|
||||
text_value,
|
||||
unwrap_request_output,
|
||||
)
|
||||
|
||||
EncodeAudio = Callable[[object, int, str, float | None], str | None]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _RequestCursor:
|
||||
audio_samples: int = 0
|
||||
text: str = ""
|
||||
terminal: bool = False
|
||||
|
||||
|
||||
class CumulativeAudioTextDataPlane(DuplexDataPlane):
|
||||
"""Project cumulative staged audio/text output into per-request deltas."""
|
||||
|
||||
stage_role: str = "tts"
|
||||
runtime_impl: str = "scheduler_data_plane"
|
||||
uses_model_runner_scheduler: bool = True
|
||||
runner_kv_backed: bool = True
|
||||
owned_runtime: bool = False
|
||||
default_sample_rate_hz: int = 24000
|
||||
|
||||
def __init__(self, encode_audio: EncodeAudio) -> None:
|
||||
self._encode_audio = encode_audio
|
||||
self._requests: dict[str, _RequestCursor] = {}
|
||||
|
||||
# ---- request / session bookkeeping ----
|
||||
|
||||
def begin_request(self, request_id: str) -> None:
|
||||
self._requests.setdefault(request_id, _RequestCursor()).terminal = False
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
if request_id is None:
|
||||
return False
|
||||
state = self._requests.get(request_id)
|
||||
return state is not None and state.terminal
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
self._requests.setdefault(request_id, _RequestCursor()).terminal = True
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
self._requests.pop(request_id, None)
|
||||
|
||||
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
|
||||
if active_request_id is not None:
|
||||
self._requests.pop(active_request_id, None)
|
||||
for request_id in list(self._requests):
|
||||
if duplex_resource_request_belongs_to_session(request_id, session_id):
|
||||
self._requests.pop(request_id, None)
|
||||
|
||||
# ---- projection ----
|
||||
|
||||
def project(self, result: object, *, context: object | None = None) -> Iterator[dict[str, object]]:
|
||||
if not isinstance(result, dict):
|
||||
return
|
||||
outputs = result.get("data_plane_outputs")
|
||||
if not isinstance(outputs, list):
|
||||
return
|
||||
if not isinstance(context, DuplexDataPlaneContext):
|
||||
context = DuplexDataPlaneContext(response_format="wav", modalities=("audio", "text"))
|
||||
for output in outputs:
|
||||
projected = self._project_output(output, context=context)
|
||||
if projected is not None:
|
||||
yield projected
|
||||
|
||||
def _project_output(self, output: object, *, context: DuplexDataPlaneContext) -> dict[str, object] | None:
|
||||
output, completion = unwrap_request_output(output)
|
||||
request_id = getattr(output, "request_id", None)
|
||||
if not isinstance(request_id, str) or not request_id:
|
||||
request_id = None
|
||||
state = self._requests.setdefault(request_id, _RequestCursor()) if request_id is not None else _RequestCursor()
|
||||
multimodal = multimodal_output(output, completion)
|
||||
audio = audio_value(multimodal)
|
||||
audio_delta = slice_audio_delta(audio, state.audio_samples)
|
||||
total_samples = audio_sample_count(audio)
|
||||
if total_samples is not None:
|
||||
state.audio_samples = total_samples
|
||||
|
||||
text = text_value(multimodal, completion)
|
||||
delta_text = text_delta(text, state.text)
|
||||
if text:
|
||||
state.text = text
|
||||
|
||||
rate = sample_rate_hz(multimodal, default=self.default_sample_rate_hz)
|
||||
encoded = self._encode_audio(audio_delta, rate, context.response_format, context.speed)
|
||||
if not encoded and not delta_text:
|
||||
return None
|
||||
delta_samples = audio_sample_count(audio_delta) or 0
|
||||
return {
|
||||
"supported": True,
|
||||
"stage_role": self.stage_role,
|
||||
"is_listen": False,
|
||||
"data_plane_request_id": request_id,
|
||||
"text": delta_text,
|
||||
"audio_data": encoded or "",
|
||||
"audio_format": context.response_format,
|
||||
"sample_rate_hz": rate,
|
||||
"audio_duration_ms": round(delta_samples * 1000 / max(1, rate)),
|
||||
"end_of_turn": False,
|
||||
"uses_model_runner_scheduler": self.uses_model_runner_scheduler,
|
||||
"runner_kv_backed": self.runner_kv_backed,
|
||||
"runtime_impl": self.runtime_impl,
|
||||
"owned_runtime": self.owned_runtime,
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["CumulativeAudioTextDataPlane"]
|
||||
@@ -0,0 +1,63 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Validation of one duplex audio append payload.
|
||||
|
||||
The runner hands a plugin the append as a mapping ``{format, sample_rate_hz,
|
||||
audio}`` (``audio`` base64 ``pcm_f32le``). Models with a fixed input rate and
|
||||
frame size validate it here; the PCM itself is decoded by
|
||||
``vllm_omni.model_executor.common.audio.pcm``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
|
||||
from vllm_omni.model_executor.common.audio.pcm import (
|
||||
decode_pcm_f32le_base64,
|
||||
pcm_f32le_sample_count,
|
||||
)
|
||||
|
||||
|
||||
def payload_audio(payload: object) -> object | None:
|
||||
"""The encoded audio field of an append payload (``audio``, or the older ``data``)."""
|
||||
if not isinstance(payload, Mapping):
|
||||
return None
|
||||
return payload.get("audio") or payload.get("data")
|
||||
|
||||
|
||||
def decode_pcm_f32le_payload(
|
||||
payload: object,
|
||||
*,
|
||||
sample_rate_hz: int,
|
||||
exact_samples: int | None = None,
|
||||
model: str = "duplex",
|
||||
) -> bytes:
|
||||
"""Raw PCM of one append that must be ``pcm_f32le`` at ``sample_rate_hz``.
|
||||
|
||||
``exact_samples`` pins the unit length (a lockstep model takes exactly one
|
||||
frame per append); ``None`` accepts any whole number of samples.
|
||||
"""
|
||||
if not isinstance(payload, Mapping):
|
||||
raise ValueError(f"{model} duplex append payload must be a mapping")
|
||||
if payload.get("format") != "pcm_f32le":
|
||||
raise ValueError(f"{model} duplex append format must be pcm_f32le")
|
||||
if payload.get("sample_rate_hz") != sample_rate_hz:
|
||||
raise ValueError(f"{model} duplex append sample_rate_hz must be {sample_rate_hz}")
|
||||
raw = decode_pcm_f32le_base64(payload_audio(payload), model=model)
|
||||
if exact_samples is not None and pcm_f32le_sample_count(raw) != exact_samples:
|
||||
raise ValueError(f"{model} duplex append must contain exactly {exact_samples} samples")
|
||||
return raw
|
||||
|
||||
|
||||
def payload_sample_count(payload: object) -> int | None:
|
||||
"""Sample count of a ``pcm_f32le`` append, or ``None`` when it is not one (lenient, for budgeting)."""
|
||||
if not isinstance(payload, Mapping) or payload.get("format") != "pcm_f32le":
|
||||
return None
|
||||
try:
|
||||
raw = decode_pcm_f32le_base64(payload_audio(payload))
|
||||
except ValueError:
|
||||
return None
|
||||
return pcm_f32le_sample_count(raw)
|
||||
|
||||
|
||||
__all__ = ["decode_pcm_f32le_payload", "payload_audio", "payload_sample_count"]
|
||||
@@ -0,0 +1,194 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Transactional framing of client PCM into fixed model units.
|
||||
|
||||
A frame-locked model (PersonaPlex: 1920 samples every 80 ms at 24 kHz) takes
|
||||
exactly one frame per append. Clients send arbitrary chunks, so the session
|
||||
runner buffers them here and takes one whole frame out at a time as a
|
||||
*reservation*: committed once the stage accepted the append, rolled back
|
||||
(the bytes go back to the front of the buffer) when it did not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.plugin import PcmAppendBuffer, PcmAppendReservation
|
||||
from vllm_omni.model_executor.common.audio.pcm import (
|
||||
PCM_F32LE_BYTES_PER_SAMPLE,
|
||||
decode_pcm_f32le_base64,
|
||||
)
|
||||
|
||||
|
||||
class FixedFramePcmAppendReservation(PcmAppendReservation):
|
||||
__slots__ = ("_active", "_owner", "_raw", "operation_id", "payload")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
owner: FixedFramePcmAppendBuffer,
|
||||
operation_id: str,
|
||||
payload: dict[str, object] | None,
|
||||
raw: bytes,
|
||||
) -> None:
|
||||
self._owner = owner
|
||||
self.operation_id = operation_id
|
||||
self.payload = payload
|
||||
self._raw = raw
|
||||
self._active = True
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self._active
|
||||
|
||||
@property
|
||||
def byte_count(self) -> int:
|
||||
return len(self._raw)
|
||||
|
||||
def commit(self) -> None:
|
||||
self._owner._commit_reservation(self)
|
||||
|
||||
def rollback(self) -> None:
|
||||
self._owner._rollback_reservation(self)
|
||||
|
||||
|
||||
class FixedFramePcmAppendBuffer(PcmAppendBuffer):
|
||||
"""Frame ``pcm_f32le`` at one sample rate into ``frame_samples`` units, transactionally."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
sample_rate_hz: int,
|
||||
frame_samples: int,
|
||||
chunk_period_ms: int,
|
||||
model: str = "duplex",
|
||||
) -> None:
|
||||
if sample_rate_hz <= 0 or frame_samples <= 0 or chunk_period_ms <= 0:
|
||||
raise ValueError("FixedFramePcmAppendBuffer needs positive sample_rate_hz, frame_samples, chunk_period_ms")
|
||||
self.sample_rate_hz = int(sample_rate_hz)
|
||||
self.frame_samples = int(frame_samples)
|
||||
self.chunk_period_ms = int(chunk_period_ms)
|
||||
self.model = model
|
||||
self._buffer = bytearray()
|
||||
self._reservations: list[FixedFramePcmAppendReservation] = []
|
||||
|
||||
@property
|
||||
def frame_bytes(self) -> int:
|
||||
return self.frame_samples * PCM_F32LE_BYTES_PER_SAMPLE
|
||||
|
||||
@property
|
||||
def pending_byte_count(self) -> int:
|
||||
return len(self._buffer)
|
||||
|
||||
def has_pending(self) -> bool:
|
||||
return bool(self._buffer)
|
||||
|
||||
def has_reserved(self) -> bool:
|
||||
return any(reservation.active for reservation in self._reservations)
|
||||
|
||||
def clear_force_listen(self) -> None:
|
||||
return
|
||||
|
||||
def clear(self) -> None:
|
||||
for reservation in self._reservations:
|
||||
reservation._active = False
|
||||
self._reservations.clear()
|
||||
self._buffer.clear()
|
||||
|
||||
def prepare_append(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
allow_emit: bool,
|
||||
) -> FixedFramePcmAppendReservation | None:
|
||||
self._require_chunk_period(chunk_period_ms)
|
||||
if any(reservation.active and reservation.operation_id == operation_id for reservation in self._reservations):
|
||||
raise ValueError(f"{self.model} duplicate active operation_id: {operation_id}")
|
||||
self._buffer.extend(self._decode_payload(payload))
|
||||
if not allow_emit or len(self._buffer) < self.frame_bytes:
|
||||
return None
|
||||
return self._reserve_frame(payload, operation_id=operation_id, flush=False)
|
||||
|
||||
def prepare_commit(self, *, operation_id: str, chunk_period_ms: int) -> FixedFramePcmAppendReservation:
|
||||
self._require_chunk_period(chunk_period_ms)
|
||||
if not self._buffer:
|
||||
reservation = FixedFramePcmAppendReservation(owner=self, operation_id=operation_id, payload=None, raw=b"")
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
payload: dict[str, object] = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": self.sample_rate_hz,
|
||||
"audio": "",
|
||||
"final": True,
|
||||
}
|
||||
return self._reserve_frame(payload, operation_id=operation_id, flush=True)
|
||||
|
||||
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
|
||||
reservation = self.prepare_commit(operation_id=f"{self.model}-flush", chunk_period_ms=chunk_period_ms)
|
||||
payload = reservation.payload
|
||||
reservation.commit()
|
||||
return payload
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Internals #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _require_chunk_period(self, chunk_period_ms: int) -> None:
|
||||
if chunk_period_ms != self.chunk_period_ms:
|
||||
raise ValueError(f"{self.model} chunk_period_ms must be {self.chunk_period_ms}")
|
||||
|
||||
def _decode_payload(self, payload: dict[str, object]) -> bytes:
|
||||
if payload.get("format") != "pcm_f32le":
|
||||
raise ValueError(f"{self.model} input format must be pcm_f32le")
|
||||
if payload.get("sample_rate_hz") != self.sample_rate_hz:
|
||||
raise ValueError(f"{self.model} sample_rate_hz must be {self.sample_rate_hz}")
|
||||
return decode_pcm_f32le_base64(payload.get("audio"), model=self.model)
|
||||
|
||||
def _reserve_frame(
|
||||
self,
|
||||
source_payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
flush: bool,
|
||||
) -> FixedFramePcmAppendReservation:
|
||||
frame_bytes = self.frame_bytes
|
||||
consumed_bytes = min(len(self._buffer), frame_bytes) if flush else frame_bytes
|
||||
raw = bytes(self._buffer[:consumed_bytes])
|
||||
del self._buffer[:consumed_bytes]
|
||||
encoded_raw = raw + b"\x00" * (frame_bytes - consumed_bytes)
|
||||
payload = dict(source_payload)
|
||||
payload["type"] = "audio"
|
||||
payload["format"] = "pcm_f32le"
|
||||
payload["sample_rate_hz"] = self.sample_rate_hz
|
||||
payload["audio"] = base64.b64encode(encoded_raw).decode("ascii")
|
||||
reservation = FixedFramePcmAppendReservation(owner=self, operation_id=operation_id, payload=payload, raw=raw)
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
|
||||
def _commit_reservation(self, reservation: FixedFramePcmAppendReservation) -> None:
|
||||
if not reservation.active:
|
||||
return
|
||||
reservation._active = False
|
||||
self._reservations.remove(reservation)
|
||||
|
||||
def _rollback_reservation(self, reservation: FixedFramePcmAppendReservation) -> None:
|
||||
if not reservation.active:
|
||||
return
|
||||
try:
|
||||
index = self._reservations.index(reservation)
|
||||
except ValueError:
|
||||
reservation._active = False
|
||||
return
|
||||
# Later reservations were taken after this one: they go back too, in order.
|
||||
rolled_back = self._reservations[index:]
|
||||
restored = b"".join(item._raw for item in rolled_back if item.active)
|
||||
self._buffer[:0] = restored
|
||||
for item in rolled_back:
|
||||
item._active = False
|
||||
del self._reservations[index:]
|
||||
|
||||
|
||||
__all__ = ["FixedFramePcmAppendBuffer", "FixedFramePcmAppendReservation"]
|
||||
@@ -0,0 +1,172 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Reading a vLLM ``RequestOutput`` the way model-side projection code needs to.
|
||||
|
||||
Stage outputs arrive as duck-typed objects (a ``RequestOutput``, an
|
||||
``OmniRequestOutput`` wrapping one, or a test double): these helpers unwrap
|
||||
them, read the ``multimodal_output`` mapping, coerce tensor scalars, and turn
|
||||
cumulative audio/text into the delta since the last read. No duplex
|
||||
vocabulary lives here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def unwrap_request_output(output: object) -> tuple[object, object | None]:
|
||||
"""Return ``(request_output, first_completion)`` for a stage output or a wrapper around one."""
|
||||
inner = getattr(output, "request_output", None)
|
||||
if inner is not None and inner is not output:
|
||||
output = inner
|
||||
return output, first_completion(output)
|
||||
|
||||
|
||||
def first_completion(output: object) -> object | None:
|
||||
outputs = getattr(output, "outputs", None)
|
||||
return outputs[0] if isinstance(outputs, list) and outputs else None
|
||||
|
||||
|
||||
def multimodal_output(output: object, completion: object | None = None) -> dict[str, object]:
|
||||
"""The first non-empty ``multimodal_output`` mapping of the output or its completion, copied."""
|
||||
for candidate in (
|
||||
getattr(output, "multimodal_output", None),
|
||||
getattr(completion, "multimodal_output", None) if completion is not None else None,
|
||||
):
|
||||
if isinstance(candidate, Mapping) and candidate:
|
||||
return dict(candidate)
|
||||
return {}
|
||||
|
||||
|
||||
def coerce_int(value: object) -> int | None:
|
||||
"""``int(value)`` for scalars, one-element tensors/arrays and numeric strings; ``None`` otherwise."""
|
||||
detach = getattr(value, "detach", None)
|
||||
if callable(detach):
|
||||
try:
|
||||
flat = detach().cpu().reshape(-1)
|
||||
if flat.numel() == 0:
|
||||
return None
|
||||
value = flat[0].item()
|
||||
except (RuntimeError, TypeError, ValueError, IndexError):
|
||||
return None
|
||||
elif isinstance(value, np.ndarray):
|
||||
if value.size == 0:
|
||||
return None
|
||||
value = value.reshape(-1)[0].item()
|
||||
try:
|
||||
return int(cast(Any, value)) # Any: duck-typed scalar (int/float/str/tensor item)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def coerce_int_list(value: object) -> list[int]:
|
||||
if value is None:
|
||||
return []
|
||||
if hasattr(value, "detach"):
|
||||
try:
|
||||
value = value.detach().cpu().reshape(-1).tolist()
|
||||
except (RuntimeError, TypeError, ValueError):
|
||||
return []
|
||||
elif isinstance(value, np.ndarray):
|
||||
value = value.reshape(-1).tolist()
|
||||
if not isinstance(value, (list, tuple)):
|
||||
return []
|
||||
return [token_id for item in value if (token_id := coerce_int(item)) is not None]
|
||||
|
||||
|
||||
def audio_value(multimodal: Mapping[str, object]) -> object | None:
|
||||
"""The audio carried by a ``multimodal_output`` (``audio`` / ``model_outputs`` / ``latent``)."""
|
||||
value = next(
|
||||
(multimodal[key] for key in ("audio", "model_outputs", "latent") if key in multimodal),
|
||||
None,
|
||||
)
|
||||
if isinstance(value, list) and len(value) == 1:
|
||||
return value[0]
|
||||
return value
|
||||
|
||||
|
||||
def text_value(multimodal: Mapping[str, object], completion: object | None) -> str:
|
||||
for candidate in (
|
||||
multimodal.get("text"),
|
||||
multimodal.get("llm_output_text"),
|
||||
getattr(completion, "text", None) if completion is not None else None,
|
||||
):
|
||||
if isinstance(candidate, str) and candidate:
|
||||
return candidate
|
||||
return ""
|
||||
|
||||
|
||||
def text_delta(text: str, previous: str) -> str:
|
||||
"""What ``text`` adds over ``previous`` when outputs are cumulative; the whole text on a restart."""
|
||||
if not text:
|
||||
return ""
|
||||
if text == previous:
|
||||
return ""
|
||||
if previous and text.startswith(previous):
|
||||
return text[len(previous) :]
|
||||
return text
|
||||
|
||||
|
||||
def audio_sample_count(audio: object | None) -> int | None:
|
||||
if audio is None:
|
||||
return None
|
||||
try:
|
||||
import torch
|
||||
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return int(audio.numel())
|
||||
except ImportError:
|
||||
pass
|
||||
try:
|
||||
return int(np.asarray(audio, dtype=np.float32).size)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def slice_audio_delta(audio: object | None, offset: int) -> object | None:
|
||||
"""The samples of a cumulative ``audio`` past ``offset``; the whole audio when it restarted."""
|
||||
samples = audio_sample_count(audio)
|
||||
if samples is None or samples <= 0:
|
||||
return None
|
||||
if offset <= 0 or samples < offset:
|
||||
return audio
|
||||
if samples == offset:
|
||||
return None
|
||||
try:
|
||||
import torch
|
||||
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return audio.reshape(-1)[offset:].contiguous()
|
||||
except ImportError:
|
||||
pass
|
||||
return np.asarray(audio, dtype=np.float32).reshape(-1)[offset:]
|
||||
|
||||
|
||||
def sample_rate_hz(multimodal: Mapping[str, object], *, default: int) -> int:
|
||||
value = multimodal.get("sr", multimodal.get("sample_rate_hz", default))
|
||||
if isinstance(value, list) and value:
|
||||
value = value[0]
|
||||
if hasattr(value, "item"):
|
||||
try:
|
||||
value = value.item()
|
||||
except (RuntimeError, TypeError, ValueError):
|
||||
value = default
|
||||
return int(value) if isinstance(value, int | float) and value > 0 else default
|
||||
|
||||
|
||||
__all__ = [
|
||||
"audio_sample_count",
|
||||
"audio_value",
|
||||
"coerce_int",
|
||||
"coerce_int_list",
|
||||
"first_completion",
|
||||
"multimodal_output",
|
||||
"sample_rate_hz",
|
||||
"slice_audio_delta",
|
||||
"text_delta",
|
||||
"text_value",
|
||||
"unwrap_request_output",
|
||||
]
|
||||
Reference in new issue
Block a user