Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix: pad audio arrays to same shape if sample rates differ
  • Loading branch information
chrisammon3000 committed Apr 3, 2024
commit 7cc0cc7c8f9777e2a47c04391cb2cd6f4e8dde78
18 changes: 18 additions & 0 deletions docarray/typing/bytes/video_bytes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import warnings
from io import BytesIO
from typing import TYPE_CHECKING, List, NamedTuple, TypeVar

Expand Down Expand Up @@ -80,6 +81,11 @@ class MyDoc(BaseDoc):

video_frames.append(frame.to_ndarray(format='rgb24'))

# Pad audio arrays to same shape if sample rates differ
if len({arr.shape for arr in audio_frames}) > 1:
warnings.warn('Audio frames have different sample rates')
audio_frames = self._pad_arrays_to_same_shape(audio_frames)

if len(audio_frames) == 0:
audio = parse_obj_as(AudioNdArray, np.array(audio_frames))
else:
Expand All @@ -89,3 +95,15 @@ class MyDoc(BaseDoc):
indices = parse_obj_as(NdArray, keyframe_indices)

return VideoLoadResult(video=video, audio=audio, key_frame_indices=indices)

@staticmethod
def _pad_arrays_to_same_shape(arrays: List[np.ndarray]) -> List[np.ndarray]:
# Calculate the maximum number of samples in any array
max_samples = max(arr.shape[1] for arr in arrays)

# Pad arrays with fewer samples
for i, arr in enumerate(arrays):
if arr.shape[1] < max_samples:
arrays[i] = np.pad(arr, ((0, 0), (0, max_samples - arr.shape[1])))

return arrays