Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

tests: mo.audio (#4268)

Myles Scolnick10bf7fc7be1a
diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.py
index 934dfc2640..26be7225fa 100644
--- a/marimo/_plugins/stateless/audio.py
+++ b/marimo/_plugins/stateless/audio.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import io
import os
import wave
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING, Any, Optional, Union
import marimo._output.data.data as mo_data
from marimo._dependencies.dependencies import DependencyManager
@@ -59,7 +59,9 @@ def convert_numpy_to_wav(
def get_resolved_src(
- src: Union[str, io.BytesIO], rate: Optional[int], normalize: bool
+ src: Union[str, io.BytesIO, NDArray[Any]],
+ rate: Optional[int],
+ normalize: bool,
) -> Optional[str]:
"""Determines the correct URL for the given audio source."""
@@ -94,7 +96,7 @@ def get_resolved_src(
@mddoc
def audio(
- src: Union[str, io.BytesIO],
+ src: Union[str, io.BytesIO, NDArray[Any]],
rate: Optional[int] = None,
normalize: bool = True,
) -> Html:
diff --git a/tests/_plugins/stateless/test_audio.py b/tests/_plugins/stateless/test_audio.py
new file mode 100644
index 0000000000..7b6c989377
--- /dev/null
+++ b/tests/_plugins/stateless/test_audio.py
@@ -0,0 +1,156 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.stateless.audio import audio
+from marimo._runtime.context import get_context
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+HAS_NUMPY = DependencyManager.numpy.has()
+
+
+async def test_audio_url() -> None:
+ result = audio("https://example.com/test.wav")
+ assert (
+ result.text
+ == "<audio src='https://example.com/test.wav' controls></audio>"
+ )
+
+
+async def test_audio_filename(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import os
+ with open("test_audio.wav", "wb") as f:
+ f.write(b"hello")
+ audio = mo.audio("test_audio.wav")
+ # Delete the file
+ os.remove("test_audio.wav")
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".wav")
+
+
+async def test_audio_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ bytestream = io.BytesIO(b"hello")
+ audio = mo.audio(bytestream)
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".wav")
+
+
+async def test_audio_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ audio = mo.audio(b"hello")
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".wav")
+
+
[email protected](not HAS_NUMPY, reason="numpy not installed")
+async def test_audio_numpy_mono(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import numpy as np
+ data = np.random.rand(1000) * 2 - 1 # Random values between -1 and 1
+ audio = mo.audio(data, rate=44100)
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".wav")
+
+
[email protected](not HAS_NUMPY, reason="numpy not installed")
+async def test_audio_numpy_normalize(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import numpy as np
+ data = np.random.rand(1000) * 10 # Values > 1
+ audio = mo.audio(data, rate=44100, normalize=True)
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".wav")
+
+
[email protected](not HAS_NUMPY, reason="numpy not installed")
+async def test_audio_numpy_constructor() -> None:
+ import numpy as np
+
+ # Rate
+ data = np.random.rand(1000) * 2 - 1 # Random values between -1 and 1
+ res = audio(data, rate=44100, normalize=False)
+ assert res.text.startswith("<audio src='data:audio/")
+
+ # Don't normalize out of range
+ data = np.random.rand(1000) * 10 # Values > 1
+ with pytest.raises(ValueError):
+ res = audio(data, rate=44100, normalize=False)
+
+ # Normalize in range
+ data = np.random.rand(1000) * 10 # Values > 1
+ res = audio(data, rate=44100, normalize=True)
+
+ # No rate
+ with pytest.raises(ValueError):
+ res = audio(data)
+
+
[email protected](sys.platform == "win32", reason="Failing on Windows CI")
+async def test_audio_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:
+ with open(__file__, encoding="utf-8") as f: # noqa: ASYNC101 ASYNC230
+ await k.run(
+ [
+ exec_req.get(
+ f"""
+ import marimo as mo
+ audio = mo.audio('{f.name}')
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1