Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
bebc9d4
feat: add audio url class
Dec 14, 2022
6025c2f
fix: typos
Dec 14, 2022
9a599e5
test: add tests for audio and audio url
Dec 15, 2022
04abdae
feat: add audio url and audio predefined class
Dec 15, 2022
f8d700d
Merge remote-tracking branch 'origin/feat-rewrite-v2' into feat-add-a…
Dec 21, 2022
d58f804
chore: add types-request
Dec 22, 2022
bdf8e88
feat: add audio tensors torch and ndarray
Dec 22, 2022
6572df8
fix: mypy type hints
Dec 22, 2022
9cd4baa
test: empty test file
Dec 22, 2022
b3c1948
test: add more unit and integration tests
Dec 28, 2022
7774181
fix: update audio tensors and audio url
Dec 28, 2022
af840d4
fix: remove print statements
Dec 28, 2022
797f488
docs: add documentation
Dec 28, 2022
8b48a77
refactor: rename test audio py to test audio tensor py
Dec 28, 2022
e135438
fix: typo in torch tensor py
Dec 28, 2022
14fcf6b
feat: add proto stuff to audio tensors
Dec 28, 2022
c623a13
test: add tests for proto and set tensors
Dec 28, 2022
1be8e3f
fix: set tensor to tensor int, since no inplace change
Dec 28, 2022
17786eb
refactor: rename to save to wav file
Dec 28, 2022
97355f7
docs: fix typo
Dec 28, 2022
20e2344
docs: fix docs for save tensor to wav file
Dec 28, 2022
7fc06e1
Merge branch 'feat-rewrite-v2' into feat-add-audio-v2
Dec 28, 2022
b34d783
fix: apply suggestions from code review
Dec 28, 2022
130d8ab
fix: apply suggestions from code review
Dec 29, 2022
2954351
test: fix assertions
Dec 29, 2022
61cb103
fix: move max int multiplication to abstract class
Dec 29, 2022
5943c0f
feat: add ndim method to abstract tensor class and concrete classes
Dec 29, 2022
131c5ff
fix: ndim
Dec 29, 2022
83ef649
fix: revert ndim in abstract tensor and torch tensor and ndarray
Dec 29, 2022
eecca41
fix: mypy checks
Dec 29, 2022
4762c3c
docs: add docstring to n dim
Dec 29, 2022
6948122
refactor: move n dim to abstract tensor and subclasses
Dec 29, 2022
d174087
refactor: make to protobuf abstract, change node to protobuf signature
Dec 29, 2022
3a52303
fix: remove not needed methods
Dec 29, 2022
a0be12e
fix: change remote audio file to file from github
Dec 30, 2022
9623d29
fix: raw content from remote file
Dec 30, 2022
6efdcf2
fix: path to github remote file
Dec 30, 2022
5026543
refactor: tensor field name to proto field name
Jan 2, 2023
703de43
test: remove redundant test in test audio tensor
Jan 2, 2023
83ece31
fix: load audio url to audio ndarray instead of np ndarray
Jan 2, 2023
de079e2
refactor: move n dim to computational backend
Jan 2, 2023
2ef1350
docs: update docstrings for audio tensors
Jan 3, 2023
d51d38e
feat: make dtype in audiourl load optional
Jan 3, 2023
3901cfa
Merge branch 'feat-rewrite-v2' into feat-add-audio-v2
Jan 3, 2023
a571898
test: fix document refactor and ndarray import
Jan 3, 2023
71af630
fix: fix mypy check
Jan 3, 2023
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
Prev Previous commit
Next Next commit
feat: add audio url and audio predefined class
Signed-off-by: anna-charlotte <[email protected]>
  • Loading branch information
anna-charlotte committed Dec 15, 2022
commit 04abdae27bb4ad0fba42becb835b8b4240ee3665
12 changes: 10 additions & 2 deletions docarray/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

from docarray.array import DocumentArray
from docarray.document.document import BaseDocument as Document
from docarray.predefined_document import Image, Mesh3D, PointCloud3D, Text
from docarray.predefined_document import Audio, Image, Mesh3D, PointCloud3D, Text

__all__ = ['Document', 'DocumentArray', 'Image', 'Text', 'Mesh3D', 'PointCloud3D']
__all__ = [
'Document',
'DocumentArray',
'Image',
'Audio',
'Text',
'Mesh3D',
'PointCloud3D',
]
3 changes: 2 additions & 1 deletion docarray/predefined_document/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from docarray.predefined_document.audio import Audio
from docarray.predefined_document.image import Image
from docarray.predefined_document.mesh import Mesh3D
from docarray.predefined_document.point_cloud import PointCloud3D
from docarray.predefined_document.text import Text

__all__ = ['Text', 'Image', 'Mesh3D', 'PointCloud3D']
__all__ = ['Text', 'Image', 'Audio', 'Mesh3D', 'PointCloud3D']
103 changes: 103 additions & 0 deletions docarray/predefined_document/audio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import wave
from typing import BinaryIO, Optional, TypeVar, Union

from docarray.document import BaseDocument
from docarray.typing import AudioUrl, Embedding, Tensor

T = TypeVar('T', bound='Audio')


class Audio(BaseDocument):
"""
Document for handling audios.

The Audio Document can contain an AudioUrl (`Audio.url`), a Tensor
(`Audio.tensor`), and an Embedding (`Audio.embedding`).

EXAMPLE USAGE:

You can use this Document directly:

.. code-block:: python

from docarray import Audio

# use it directly
audio = Audio(url='https://www.kozco.com/tech/piano2.wav')
audio.tensor = audio.url.load()
model = MyEmbeddingModel()
audio.embedding = model(audio.tensor)

You can extend this Document:

.. code-block:: python

from docarray import Audio
from docarray.typing import Embedding
from typing import Optional

# extend it
class MyAudio(Audio):
name: Optional[Text]


audio = MyAudio(url='https://www.kozco.com/tech/piano2.wav')
audio.tensor = audio.url.load()
model = MyEmbeddingModel()
audio.embedding = model(audio.tensor)
audio.name = 'my first audio'


You can use this Document for composition:

.. code-block:: python

from docarray import Document, Audio, Text

# compose it
class MultiModalDoc(Document):
audio: Audio
text: Text


mmdoc = MultiModalDoc(
audio=Audio(url='https://www.kozco.com/tech/piano2.wav'),
text=Text(text='hello world, how are you doing?'),
)
mmdoc.audio.tensor = mmdoc.audio.url.load()
"""

url: Optional[AudioUrl]
tensor: Optional[Tensor]
embedding: Optional[Embedding]

def save_audio_tensor_to_file(
self: 'T',
file_path: Union[str, BinaryIO],
sample_rate: int = 44100,
sample_width: int = 2,
) -> None:
"""Save :attr:`.tensor` into a .wav file. Mono/stereo is preserved.

:param file_path: if file is a string, open the file by that name, otherwise
treat it as a file-like object.
:param sample_rate: sampling frequency
:param sample_width: sample width in bytes
"""
if self.tensor is None:
raise ValueError(
'Audio.tensor has not been set, and therefore cannot be saved to file.'
)

# Convert to (little-endian) 16 bit integers.
max_int16 = 2**15
tensor = (self.tensor * max_int16).astype('<h')
n_channels = 2 if self.tensor.ndim > 1 else 1

with wave.open(file_path, 'w') as f:
# 2 Channels.
f.setnchannels(n_channels)
# 2 bytes per sample.
f.setsampwidth(sample_width)
f.setframerate(sample_rate)
f.writeframes(tensor.tobytes())
2 changes: 2 additions & 0 deletions docarray/proto/docarray.proto
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ message NodeProto {

string point_cloud_url = 13;

string audio_url = 14;


}

Expand Down
32 changes: 16 additions & 16 deletions docarray/proto/pb2/docarray_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion docarray/typing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
from docarray.typing.id import ID
from docarray.typing.tensor import NdArray, Tensor
from docarray.typing.tensor.embedding import Embedding
from docarray.typing.url import AnyUrl, ImageUrl, Mesh3DUrl, PointCloud3DUrl, TextUrl
from docarray.typing.url import (
AnyUrl,
AudioUrl,
ImageUrl,
Mesh3DUrl,
PointCloud3DUrl,
TextUrl,
)

__all__ = [
'NdArray',
'Embedding',
'ImageUrl',
'AudioUrl',
'TextUrl',
'Mesh3DUrl',
'PointCloud3DUrl',
Expand Down
3 changes: 2 additions & 1 deletion docarray/typing/url/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from docarray.typing.url.any_url import AnyUrl
from docarray.typing.url.audio_url import AudioUrl
from docarray.typing.url.image_url import ImageUrl
from docarray.typing.url.text_url import TextUrl
from docarray.typing.url.url_3d.mesh_url import Mesh3DUrl
from docarray.typing.url.url_3d.point_cloud_url import PointCloud3DUrl

__all__ = ['ImageUrl', 'AnyUrl', 'TextUrl', 'Mesh3DUrl', 'PointCloud3DUrl']
__all__ = ['ImageUrl', 'AudioUrl', 'AnyUrl', 'TextUrl', 'Mesh3DUrl', 'PointCloud3DUrl']
92 changes: 91 additions & 1 deletion docarray/typing/url/audio_url.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,98 @@
from docarray.typing import AnyUrl
import wave
from typing import TYPE_CHECKING, TypeVar

import numpy as np

from docarray.typing.url.any_url import AnyUrl

if TYPE_CHECKING:
from docarray.proto import NodeProto

T = TypeVar('T', bound='AudioUrl')


class AudioUrl(AnyUrl):
"""
URL to a .wav file.
Can be remote (web) URL, or a local file path.
"""

def _to_node_protobuf(self: T) -> 'NodeProto':
"""Convert Document into a NodeProto protobuf message. This function should
be called when the Document is nested into another Document that needs to
be converted into a protobuf

:return: the nested item protobuf message
"""
from docarray.proto import NodeProto

return NodeProto(audio_url=str(self))

def load(self: T) -> np.ndarray:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samsja Should I return a np.ndarray here, or rather AudioNdArray or AudioTorchTensor?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say AudioNdArray.
Normally we just load the np.ndarray, bc the framework specific conversion can happen when putting it back into the document, and having it as np.ndarray makes the least assumptions about the sorrounding code.
In this case, since there are actual audio features that come with the array, I would go with AudioNdArray. It can still be treated like a normal np.ndarray, but bring the aforementioned features.

But just verify in a test that setting a AudioNdArray to a field with type AudioTorchArray actually works without issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But just verify in a test that setting a AudioNdArray to a field with type AudioTorchArray actually works without issue

Do you mean like this?

def test_load_audio_url_to_audio_torch_tensor(file_url):
    class MyAudioDoc(Document):
        audio_url: AudioUrl
        tensor: Optional[AudioTorchTensor]

    doc = MyAudioDoc(audio_url=file_url)
    doc.tensor = doc.audio_url.load()

    assert isinstance(doc.tensor, np.ndarray)
    assert isinstance(doc.tensor, AudioNdArray)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I moved it to the computational backends

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great I like it better like this

"""
Load the data from the url into a numpy.ndarray audio tensor.

EXAMPLE USAGE

.. code-block:: python

from docarray import Document
import numpy as np

from docarray.typing import AudioUrl


class MyDoc(Document):
audio_url: AudioUrl


doc = MyDoc(mesh_url="toydata/hello.wav")

audio_tensor = doc.audio_url.load()
assert isinstance(audio_tensor, np.ndarray)

:return: np.ndarray representing the audio file content
"""

if self.startswith('http'):
import io

import requests

resp = requests.get(self)
resp.raise_for_status()
file = io.BytesIO()
file.write(resp.content)
file.seek(0)
else:
file = self

# note wave is Python built-in mod. https://docs.python.org/3/library/wave.html
with wave.open(file) as ifile:
samples = ifile.getnframes()
audio = ifile.readframes(samples)

# Convert buffer to float32 using NumPy
audio_as_np_int16 = np.frombuffer(audio, dtype=np.int16)
audio_as_np_float32 = audio_as_np_int16.astype(np.float32)

# Normalise float32 array so that values are between -1.0 and +1.0
max_int16 = 2**15
audio_normalised = audio_as_np_float32 / max_int16

channels = ifile.getnchannels()
if channels == 2:
# 1 for mono, 2 for stereo
audio_stereo = np.empty(
(int(len(audio_normalised) / channels), channels)
)
audio_stereo[:, 0] = audio_normalised[
range(0, len(audio_normalised), 2)
]
audio_stereo[:, 1] = audio_normalised[
range(1, len(audio_normalised), 2)
]

return audio_stereo
else:
return audio_normalised