Support Audio Extraction from MP4 Video for Nemotron Nano VL (#35539)
Signed-off-by: Netanel Haber <58652339+netanel-haber@users.noreply.github.com> Signed-off-by: Andrii Skliar <askliar@nvidia.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Signed-off-by: Matthew Bonanni <mbonanni@redhat.com> Signed-off-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com> Signed-off-by: wangxiyuan <wangxiyuan1007@gmail.com> Signed-off-by: Andrii <askliar@nvidia.com> Co-authored-by: Netanel Haber <58652339+netanel-haber@users.noreply.github.com> Co-authored-by: Andrii Skliar <askliar@oci-nrt-cs-001-vscode-01.cm.cluster> Co-authored-by: Andrii <askliar@nvidia.com> Co-authored-by: root <root@pool0-03748.cm.cluster> Co-authored-by: Roger Wang <hey@rogerw.io> Co-authored-by: root <root@pool0-02416.cm.cluster> Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com> Co-authored-by: Matthew Bonanni <mbonanni@redhat.com> Co-authored-by: Tyler Michael Smith <tyler@neuralmagic.com> Co-authored-by: wangxiyuan <wangxiyuan1007@gmail.com> Co-authored-by: root <root@pool0-04880.cm.cluster>
This commit is contained in:
co-authored by
Netanel Haber
Andrii Skliar
Andrii
root
Roger Wang
root
Lucas Wilkinson
Matthew Bonanni
Tyler Michael Smith
wangxiyuan
root
parent
9e0f44bec4
commit
5d199ac8f2
@@ -4,6 +4,7 @@ import base64
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
import pybase64
|
||||
import torch
|
||||
@@ -23,6 +24,63 @@ try:
|
||||
except ImportError:
|
||||
soundfile = PlaceholderModule("soundfile") # type: ignore[assignment]
|
||||
|
||||
try:
|
||||
import av
|
||||
except ImportError:
|
||||
av = PlaceholderModule("av") # type: ignore[assignment]
|
||||
|
||||
|
||||
def extract_audio_from_video_bytes(
|
||||
data: bytes,
|
||||
) -> tuple[npt.NDArray, float]:
|
||||
"""Extract the audio track from raw video bytes using PyAV.
|
||||
|
||||
PyAV wraps FFmpeg's C libraries in-process — no subprocess is
|
||||
spawned, which is critical to avoid crashing CUDA-active vLLM
|
||||
worker processes.
|
||||
|
||||
The returned waveform is at the native sample rate of the video's
|
||||
audio stream. Resampling to a model-specific rate is left to the
|
||||
downstream :class:`AudioResampler` in the parsing pipeline.
|
||||
|
||||
Args:
|
||||
data: Raw video file bytes (e.g. from an mp4 file).
|
||||
|
||||
Returns:
|
||||
A tuple of ``(waveform, sample_rate)`` suitable for use as an
|
||||
:class:`AudioItem`.
|
||||
"""
|
||||
if data is None or len(data) == 0:
|
||||
raise ValueError(
|
||||
"Cannot extract audio: video bytes are missing or empty. "
|
||||
"Ensure video was loaded with keep_video_bytes=True for "
|
||||
"audio-in-video extraction."
|
||||
)
|
||||
try:
|
||||
with av.open(BytesIO(data)) as container:
|
||||
if not container.streams.audio:
|
||||
raise ValueError("No audio stream found in the video.")
|
||||
stream = container.streams.audio[0]
|
||||
native_sr = stream.rate
|
||||
|
||||
chunks: list[npt.NDArray] = []
|
||||
for frame in container.decode(audio=0):
|
||||
arr = frame.to_ndarray()
|
||||
chunks.append(arr.mean(axis=0) if arr.ndim > 1 else arr)
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise ValueError(
|
||||
"Invalid or corrupted video data when extracting audio. "
|
||||
"Ensure the input is valid video bytes (e.g. a complete MP4)."
|
||||
) from e
|
||||
|
||||
if not chunks:
|
||||
raise ValueError("No audio found in the video.")
|
||||
|
||||
audio = np.concatenate(chunks).astype(np.float32)
|
||||
return audio, float(native_sr)
|
||||
|
||||
|
||||
class AudioMediaIO(MediaIO[tuple[npt.NDArray, float]]):
|
||||
def __init__(self, **kwargs) -> None:
|
||||
|
||||
@@ -749,6 +749,33 @@ class Molmo2VideoBackend(VideoLoader):
|
||||
return out
|
||||
|
||||
|
||||
@VIDEO_LOADER_REGISTRY.register("nemotron_vl")
|
||||
class NemotronVLVideoBackend(OpenCVVideoBackend):
|
||||
@classmethod
|
||||
def load_bytes(
|
||||
cls,
|
||||
data: bytes,
|
||||
num_frames: int = -1,
|
||||
fps: int = -1,
|
||||
max_duration: int = 300,
|
||||
frame_recovery: bool = False,
|
||||
**kwargs,
|
||||
) -> tuple[npt.NDArray, dict[str, Any]]:
|
||||
frames, metadata = OpenCVVideoBackend.load_bytes(
|
||||
data,
|
||||
num_frames=num_frames,
|
||||
fps=fps,
|
||||
max_duration=max_duration,
|
||||
frame_recovery=frame_recovery,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
metadata = dict(metadata)
|
||||
metadata["original_video_bytes"] = data
|
||||
|
||||
return frames, metadata
|
||||
|
||||
|
||||
@VIDEO_LOADER_REGISTRY.register("openpangu")
|
||||
class OpenCVDynamicOpenPanguVideoBackend(OpenCVVideoBackend):
|
||||
@classmethod
|
||||
|
||||
Reference in New Issue
Block a user