-
Notifications
You must be signed in to change notification settings - Fork 234
feat(v2): add video support #972
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
a452268
feat: add video url and tensors to proto
3ccb697
feat: add video url and video ndarray
dc957d1
feat: add video torch tensor and tests
fc86920
fix: mypy checks
8a55e0b
chore: add av to video extra
5cb098a
fix: allow dim 3
3ba1f78
test: wip video load and save
be63926
refactor: move to numpy to computational backend
395a495
fix: video load and save
406ec80
test: adjust tests
091e79a
fix: video load and save and add docstrings
dee1146
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-v…
e4106a8
fix: fix some imports after merging
23ee930
docs: add doc strings and fix example urls
7ab8dbd
docs: small fixes in docs
ecf01d8
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-v…
5295dd1
refactor: rename save to mp4 file to save
b3f2ccb
feat: add shape method to comp backend
20ecf2c
refactor: move validate shape to video tensor mixin
711d105
refactor: extract private load and make separate methods for frames
0c9c1fd
fix: use torch shape instead of size method
e3a465c
fix: add typehint to shape in comp backend
40eac93
docs: add supported strings for skip type
a700f30
fix: apply suggestions from code review
94572fd
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-v…
07ceae8
fix: small change to trigger ci again
c2e129d
fix: extract shape var
d50ae67
fix: introduce compbackendinterface
2e365e6
fix: revert previous pr and fix for mypy
c44a035
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-v…
95b0b81
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-v…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: add video torch tensor and tests
Signed-off-by: anna-charlotte <[email protected]>
- Loading branch information
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| from typing import Optional, TypeVar | ||
|
|
||
| from docarray.document import BaseDocument | ||
| from docarray.typing import AnyTensor, Embedding | ||
| from docarray.typing.tensor.video.video_tensor import VideoTensor | ||
| from docarray.typing.url.video_url import VideoUrl | ||
|
|
||
| T = TypeVar('T', bound='Video') | ||
|
|
||
|
|
||
| class Video(BaseDocument): | ||
| """ | ||
| Document for handling video. | ||
| The Video Document can contain a VideoUrl (`Video.url`), a VideoTensor | ||
| (`Video.tensor`), an AnyTensor ('Video.key_frame_indices), and an Embedding | ||
| (`Video.embedding`). | ||
|
|
||
| EXAMPLE USAGE: | ||
|
|
||
| You can use this Document directly: | ||
|
|
||
| You can extend this Document: | ||
|
|
||
| You can use this Document for composition: | ||
|
|
||
| """ | ||
|
|
||
| url: Optional[VideoUrl] | ||
| tensor: Optional[VideoTensor] | ||
| key_frame_indices: Optional[AnyTensor] | ||
| embedding: Optional[Embedding] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| from docarray.typing.tensor.video.video_ndarray import VideoNdArray | ||
|
|
||
| __all__ = ['VideoNdArray'] | ||
|
|
||
| try: | ||
| import torch # noqa: F401 | ||
| except ImportError: | ||
| pass | ||
| else: | ||
| from docarray.typing.tensor.video.video_torch_tensor import VideoTorchTensor # noqa | ||
|
|
||
| __all__.extend(['VideoTorchTensor']) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| from abc import ABC, abstractmethod | ||
| from typing import BinaryIO, Dict, Generator, Optional, Tuple, Type, TypeVar, Union | ||
|
|
||
| import numpy as np | ||
|
|
||
| from docarray.typing.tensor.abstract_tensor import AbstractTensor | ||
|
|
||
| T = TypeVar('T', bound='AbstractVideoTensor') | ||
|
|
||
|
|
||
| class AbstractVideoTensor(AbstractTensor, ABC): | ||
| @abstractmethod | ||
| def to_numpy(self) -> np.ndarray: | ||
| """ | ||
| Convert video tensor to numpy.ndarray. | ||
| """ | ||
| ... | ||
|
|
||
| def save_to_file( | ||
| self: 'T', | ||
| file_path: Union[str, BinaryIO], | ||
| frame_rate: int = 30, | ||
| codec: str = 'h264', | ||
| ) -> None: | ||
| """ | ||
| Save video tensor to a .wav file. Mono/stereo is preserved. | ||
|
|
||
|
|
||
| :param file_path: path to a .wav file. If file is a string, open the file by | ||
| that name, otherwise treat it as a file-like object. | ||
| :param frame_rate: frames per second. | ||
| :param codec: the name of a decoder/encoder. | ||
| """ | ||
| np_tensor = self.to_numpy() | ||
|
|
||
| video_tensor = np.moveaxis(np.clip(np_tensor, 0, 255), 1, 2).astype('uint8') | ||
|
|
||
| import av | ||
|
|
||
| with av.open(file_path, mode='w') as container: | ||
| stream = container.add_stream(codec, rate=frame_rate) | ||
| stream.width = np_tensor.shape[1] | ||
| stream.height = np_tensor.shape[2] | ||
| stream.pix_fmt = 'yuv420p' | ||
|
|
||
| for b in video_tensor: | ||
| frame = av.VideoFrame.from_ndarray(b, format='rgb24') | ||
| for packet in stream.encode(frame): | ||
| container.mux(packet) | ||
|
|
||
| for packet in stream.encode(): | ||
| container.mux(packet) | ||
|
|
||
| @classmethod | ||
| def generator_from_webcam( | ||
| cls: Type['T'], | ||
| height_width: Optional[Tuple[int, int]] = None, | ||
| show_window: bool = True, | ||
| window_title: str = 'webcam', | ||
| fps: int = 30, | ||
| exit_key: int = 27, | ||
| exit_event=None, | ||
| tags: Optional[Dict] = None, | ||
| ) -> Generator['T', None, None]: | ||
| ... | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| from typing import Union | ||
|
|
||
| from docarray.typing.tensor.video.video_ndarray import VideoNdArray | ||
|
|
||
| try: | ||
| import torch # noqa: F401 | ||
| except ImportError: | ||
| VideoTensor = VideoNdArray | ||
|
|
||
| else: | ||
| from docarray.typing.tensor.video.video_torch_tensor import VideoTorchTensor | ||
|
|
||
| VideoTensor = Union[VideoNdArray, VideoTorchTensor] # type: ignore |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| from typing import TYPE_CHECKING, Any, List, Tuple, Type, TypeVar, Union | ||
|
|
||
| import numpy as np | ||
|
|
||
| from docarray.typing.tensor.torch_tensor import TorchTensor, metaTorchAndNode | ||
| from docarray.typing.tensor.video.abstract_video_tensor import AbstractVideoTensor | ||
|
|
||
| T = TypeVar('T', bound='VideoTorchTensor') | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pydantic import BaseConfig | ||
| from pydantic.fields import ModelField | ||
|
|
||
|
|
||
| class VideoTorchTensor(AbstractVideoTensor, TorchTensor, metaclass=metaTorchAndNode): | ||
| """ | ||
| Subclass of TorchTensor, to represent a video tensor. | ||
| Adds video-specific features to the tensor. | ||
|
|
||
| EXAMPLE USAGE | ||
|
|
||
| """ | ||
|
|
||
| _PROTO_FIELD_NAME = 'video_torch_tensor' | ||
|
|
||
| @classmethod | ||
| def validate( | ||
| cls: Type[T], | ||
| value: Union[T, np.ndarray, List[Any], Tuple[Any], Any], | ||
| field: 'ModelField', | ||
| config: 'BaseConfig', | ||
| ) -> T: | ||
| tensor = super().validate(value=value, field=field, config=config) | ||
| if tensor.ndim not in [3, 4] or tensor.shape[-1] != 3: | ||
| raise ValueError( | ||
| f'Expects tensor with 3 or 4 dimensions and the last dimension equal ' | ||
| f'to 3, but received {tensor.shape} in {tensor.dtype}' | ||
| ) | ||
| else: | ||
| return tensor | ||
|
|
||
| def to_numpy(self) -> np.ndarray: | ||
| return self.cpu().detach().numpy() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import os | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from docarray import Video | ||
| from docarray.typing import VideoNdArray | ||
| from tests import TOYDATA_DIR | ||
|
|
||
| LOCAL_VIDEO_FILE = str(TOYDATA_DIR / 'mov_bbb.mp4') | ||
| REMOTE_VIDEO_FILE = 'https://github.com/docarray/docarray/blob/feat-rewrite-v2/tests/toydata/mov_bbb.mp4?raw=true' # noqa: E501 | ||
|
|
||
|
|
||
| @pytest.mark.slow | ||
| @pytest.mark.internet | ||
| @pytest.mark.parametrize('file_url', [LOCAL_VIDEO_FILE, REMOTE_VIDEO_FILE]) | ||
| def test_video(file_url): | ||
| video = Video(url=file_url) | ||
| video.tensor, video.key_frame_indices = video.url.load() | ||
|
|
||
| assert isinstance(video.tensor, np.ndarray) | ||
| assert isinstance(video.tensor, VideoNdArray) | ||
| assert isinstance(video.key_frame_indices, np.ndarray) | ||
|
|
||
|
|
||
| @pytest.mark.slow | ||
| @pytest.mark.internet | ||
| @pytest.mark.parametrize('file_url', [LOCAL_VIDEO_FILE, REMOTE_VIDEO_FILE]) | ||
| def test_save_video_ndarray(file_url, tmpdir): | ||
| tmp_file = str(tmpdir / 'tmp.mp4') | ||
|
|
||
| video = Video(url=file_url) | ||
| video.tensor, _ = video.url.load() | ||
|
|
||
| assert isinstance(video.tensor, np.ndarray) | ||
| assert isinstance(video.tensor, VideoNdArray) | ||
|
|
||
| video.tensor.save_to_file(tmp_file) | ||
| assert os.path.isfile(tmp_file) | ||
|
|
||
| video_from_file = Video(url=tmp_file) | ||
| video_from_file.tensor = video_from_file.url.load() | ||
| assert np.allclose(video.tensor, video_from_file.tensor) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.