Skip to content

πŸŽ› πŸ”Š A Python library for audio.

fix: revert io/utils stubs to master (generator reformatted broke pyright)

Christopher Jacobybafe63a10b49
diff --git a/pedalboard_native/io/__init__.pyi b/pedalboard_native/io/__init__.pyi
index 471378c..c5f7e8d 100644
--- a/pedalboard_native/io/__init__.pyi
+++ b/pedalboard_native/io/__init__.pyi
@@ -7,30 +7,11 @@ import pedalboard_native.io
import typing
-original_overload = typing.overload
-__OVERLOADED_DOCSTRINGS = {}
-
-def patch_overload(func):
- original_overload(func)
- if func.__doc__:
- __OVERLOADED_DOCSTRINGS[func.__qualname__] = func.__doc__
- else:
- func.__doc__ = __OVERLOADED_DOCSTRINGS.get(func.__qualname__)
- if func.__doc__:
- # Work around the fact that pybind11-stubgen generates
- # duplicate docstrings sometimes, once for each overload:
- docstring = func.__doc__
- if docstring[len(docstring) // 2 :].strip() == docstring[: -len(docstring) // 2].strip():
- func.__doc__ = docstring[len(docstring) // 2 :].strip()
- return func
-
-typing.overload = patch_overload
-
from typing_extensions import Literal
-from enum import Enum
-import threading
-import numpy
+import numpy as np
import pedalboard_native.utils
+from numpy.typing import NDArray
+from numpy import float32
_Shape = typing.Tuple[int, ...]
@@ -46,6 +27,52 @@ __all__ = [
"get_supported_write_formats",
]
+class WriteableAudioFileFlag:
+ """
+ An enumeration of codec-specific options that can be passed when opening an
+ audio file for writing. These flags are used as keys in the ``codec_options``
+ dictionary parameter accepted by :class:`WriteableAudioFile` and
+ :class:`AudioFile`.
+
+ Not all flags are supported by all codecs. Passing an unsupported flag for
+ the selected codec will raise a ``ValueError``.
+
+ .. note::
+ These flags control low-level encoder behavior. Most users will not need
+ to use them. The ``quality`` parameter is usually sufficient for
+ controlling encoder output.
+
+ Members:
+
+ Mp3EnableBitReservoir :
+ When writing MP3 files, controls whether the LAME encoder's bit reservoir
+ is enabled. Defaults to ``True``.
+ """
+
+ Mp3EnableBitReservoir: typing.ClassVar[WriteableAudioFileFlag]
+ """
+ When writing MP3 files, controls whether the LAME encoder's bit reservoir
+ is enabled. The bit reservoir allows the encoder to use fewer bits on
+ simple frames and save them for complex frames, improving overall quality
+ at a given bitrate. Disabling it forces each frame to be independently
+ decodable at the cost of slightly lower quality.
+
+ Set to ``False`` for streaming or seeking applications where individual
+ frames need to be independently decodable.
+
+ Accepts a ``bool`` value. Defaults to ``True`` (bit reservoir enabled).
+ """
+
+ def __eq__(self, other: object) -> bool: ...
+ def __hash__(self) -> int: ...
+ def __index__(self) -> int: ...
+ def __int__(self) -> int: ...
+ def __ne__(self, other: object) -> bool: ...
+ @property
+ def name(self) -> str: ...
+ @property
+ def value(self) -> int: ...
+
class AudioFile:
"""
A base class for readable and writeable audio files.
@@ -142,54 +169,60 @@ class AudioFile:
those classes below for documentation.
"""
- @staticmethod
+ @classmethod
@typing.overload
- def __new__(
- cls: object, file_like: typing.Union[typing.BinaryIO, memoryview], mode: Literal["r"] = "r"
- ) -> ReadableAudioFile:
- """
- Open an audio file for reading.
+ def __new__(cls, filename: str) -> ReadableAudioFile:
+ """Open an audio file for reading (mode 'r' is implied)."""
+ ...
- Open a file-like object for reading. The provided object must have ``read``, ``seek``, ``tell``, and ``seekable`` methods, and must return binary data (i.e.: ``open(..., "w")`` or ``io.BytesIO``, etc.).
- """
+ @classmethod
+ @typing.overload
+ def __new__(cls, filename: str, mode: Literal["r"]) -> ReadableAudioFile:
+ """Open an audio file for reading with an explicit mode 'r'."""
+ ...
- @staticmethod
+ @classmethod
@typing.overload
def __new__(
- cls: object,
- file_like: typing.BinaryIO,
+ cls, file_like: typing.Union[typing.BinaryIO, memoryview], mode: Literal["r"] = "r"
+ ) -> ReadableAudioFile: ...
+
+ @classmethod
+ @typing.overload
+ def __new__(
+ cls,
+ filename: str,
mode: Literal["w"],
samplerate: typing.Optional[float] = None,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- format: typing.Optional[str] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
- @staticmethod
- @typing.overload
- def __new__(cls: object, filename: str, mode: Literal["r"] = "r") -> ReadableAudioFile: ...
- @staticmethod
+
+ @classmethod
@typing.overload
def __new__(
- cls: object,
- filename: str,
+ cls,
+ file_like: typing.BinaryIO,
mode: Literal["w"],
samplerate: typing.Optional[float] = None,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
+
@staticmethod
def encode(
- samples: numpy.ndarray,
+ samples: NDArray[typing.Union[np.int8, np.int16, np.int32, np.float32, np.float64]],
samplerate: float,
format: str,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
num_threads: int = 1,
) -> bytes:
"""
@@ -326,7 +359,7 @@ class AudioStream:
@staticmethod
def play(
- audio: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]],
+ audio: NDArray[float32],
sample_rate: float,
output_device_name: typing.Optional[str] = None,
) -> None:
@@ -334,7 +367,7 @@ class AudioStream:
Play audio data to the speaker, headphones, or other output device. This method will block until the audio is finished playing.
"""
- def read(self, num_samples: int = 0) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:
+ def read(self, num_samples: int = 0) -> NDArray[float32]:
"""
.. warning::
Recording audio is a **real-time** operation, so if your code doesn't call :py:meth:`read` quickly enough, some audio will be lost. To warn about this, :py:meth:`read` will throw an exception if audio data is dropped. This behavior can be disabled by setting :py:attr:`ignore_dropped_input` to :py:const:`True`. The number of dropped samples since the last call to :py:meth:`read` can be retrieved by accessing the :py:attr:`dropped_input_frame_count` property.
@@ -346,7 +379,7 @@ class AudioStream:
"""
def write(
- self, audio: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]], sample_rate: float
+ self, audio: NDArray[float32], sample_rate: float
) -> None:
"""
If the provided sample rate does not match the output device's sample rate, an error will be thrown. In this case, you can use :py:class:`StreamResampler` to resample the audio before calling :py:meth:`write`.
@@ -487,18 +520,23 @@ class ReadableAudioFile(AudioFile):
Stop using this :class:`ReadableAudioFile` as a context manager, close the file, release its resources.
"""
- @typing.overload
- def __init__(self, file_like: typing.BinaryIO) -> None: ...
@typing.overload
def __init__(self, filename: str) -> None: ...
- @staticmethod
@typing.overload
- def __new__(
- cls: object, file_like: typing.Union[typing.BinaryIO, memoryview]
- ) -> ReadableAudioFile: ...
- @staticmethod
+ def __init__(self, file_like: typing.Union[typing.BinaryIO, memoryview]) -> None: ...
+
+ # These don't exist, but Pyright assumes they do:
+ @typing.overload
+ def __init__(self, filename: str, mode: Literal["r"]) -> None: ...
+ @typing.overload
+ def __init__(self, file_like: typing.Union[typing.BinaryIO, memoryview], mode: Literal["r"]) -> None: ...
+
+ @classmethod
+ @typing.overload
+ def __new__(cls, filename: str) -> ReadableAudioFile: ...
+ @classmethod
@typing.overload
- def __new__(cls: object, filename: str) -> ReadableAudioFile: ...
+ def __new__(cls, file_like: typing.Union[typing.BinaryIO, memoryview]) -> ReadableAudioFile: ...
def __repr__(self) -> str: ...
def close(self) -> None:
"""
@@ -507,7 +545,7 @@ class ReadableAudioFile(AudioFile):
def read(
self, num_frames: typing.Union[float, int] = 0
- ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:
+ ) -> NDArray[float32]:
"""
Read the given number of frames (samples in each channel) from this audio file at its current position.
@@ -535,7 +573,9 @@ class ReadableAudioFile(AudioFile):
an exception will be thrown, as a fractional number of samples cannot be returned.
"""
- def read_raw(self, num_frames: typing.Union[float, int] = 0) -> numpy.ndarray:
+ def read_raw(
+ self, num_frames: typing.Union[float, int] = 0
+ ) -> NDArray[typing.Union[np.int8, np.int16, np.int32, np.float32]]:
"""
Read the given number of frames (samples in each channel) from this audio file at its current position.
@@ -763,9 +803,9 @@ class ResampledReadableAudioFile(AudioFile):
target_sample_rate: float,
resampling_quality: pedalboard_native.Resample.Quality = pedalboard_native.Resample.Quality.WindowedSinc32,
) -> None: ...
- @staticmethod
+ @classmethod
def __new__(
- cls: object,
+ cls,
audio_file: ReadableAudioFile,
target_sample_rate: float,
resampling_quality: pedalboard_native.Resample.Quality = pedalboard_native.Resample.Quality.WindowedSinc32,
@@ -778,7 +818,7 @@ class ResampledReadableAudioFile(AudioFile):
def read(
self, num_frames: typing.Union[float, int] = 0
- ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:
+ ) -> NDArray[float32]:
"""
Read the given number of frames (samples in each channel, at the target sample rate)
from this audio file at its current position, automatically resampling on-the-fly to
@@ -950,8 +990,8 @@ class StreamResampler:
def __repr__(self) -> str: ...
def process(
- self, input: typing.Optional[numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]] = None
- ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:
+ self, input: typing.Optional[NDArray[float32]] = None
+ ) -> NDArray[float32]:
"""
Resample a 32-bit floating-point audio buffer. The returned buffer may be smaller than the provided buffer depending on the quality method used. Call :meth:`process()` without any arguments to flush the internal buffers and return all remaining audio.
"""
@@ -1041,14 +1081,6 @@ class WriteableAudioFile(AudioFile):
may be passed as a string. The strings ``"best"``, ``"worst"``,
``"fastest"``, and ``"slowest"`` will also work for any codec.
- codec_options:
- An optional dictionary mapping :class:`WriteableAudioFileFlag` keys to
- values (``bool``, ``int``, ``float``, or ``str``). These flags control
- low-level, codec-specific encoder behavior. Not all flags are supported
- by all codecs; passing an unsupported flag will raise a ``ValueError``.
-
- See :class:`WriteableAudioFileFlag` for available options.
-
.. note::
You probably don't want to use this class directly: all of the parameters
accepted by the :class:`WriteableAudioFile` constructor will be accepted by
@@ -1061,47 +1093,77 @@ class WriteableAudioFile(AudioFile):
@typing.overload
def __init__(
self,
- file_like: typing.BinaryIO,
+ filename: str,
samplerate: float,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- format: typing.Optional[str] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
@typing.overload
def __init__(
self,
- filename: str,
+ file_like: typing.BinaryIO,
samplerate: float,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
- @staticmethod
+ @classmethod
+ @typing.overload
+ def __new__(
+ cls,
+ filename: str,
+ samplerate: typing.Optional[float] = None,
+ num_channels: int = 1,
+ bit_depth: int = 16,
+ quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
+ ) -> WriteableAudioFile: ...
+ @classmethod
@typing.overload
def __new__(
- cls: object,
+ cls,
file_like: typing.BinaryIO,
samplerate: typing.Optional[float] = None,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
format: typing.Optional[str] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
- @staticmethod
+
+ # This overload does not actually exist; just makes Pyright happy as
+ # it assumes that __init__ is called with the same arguments as __new__:
@typing.overload
- def __new__(
- cls: object,
+ def __init__(
+ self,
filename: str,
+ mode: Literal["w"],
+ samplerate: float,
+ num_channels: int = 1,
+ bit_depth: int = 16,
+ quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
+ ) -> None: ...
+
+ # This overload does not actually exist; just makes Pyright happy as
+ # it assumes that __init__ is called with the same arguments as __new__:
+ @typing.overload
+ def __init__(
+ self,
+ file_like: typing.BinaryIO,
+ mode: Literal["w"],
samplerate: typing.Optional[float] = None,
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
- codec_options: dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = {},
- ) -> WriteableAudioFile: ...
+ format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
+ ) -> None: ...
+
def __repr__(self) -> str: ...
def close(self) -> None:
"""
@@ -1201,36 +1263,6 @@ class WriteableAudioFile(AudioFile):
"""
pass
-class WriteableAudioFileFlag(Enum):
- """
- An enumeration of codec-specific options that can be passed when opening an
- audio file for writing. These flags are used as keys in the ``codec_options``
- dictionary parameter accepted by :class:`WriteableAudioFile` and
- :class:`AudioFile`.
-
- Not all flags are supported by all codecs. Passing an unsupported flag for
- the selected codec will raise a ``ValueError``.
-
- .. note::
- These flags control low-level encoder behavior. Most users will not need
- to use them. The ``quality`` parameter is usually sufficient for
- controlling encoder output.
- """
-
- Mp3EnableBitReservoir = 0 # fmt: skip
- """
- When writing MP3 files, controls whether the LAME encoder's bit reservoir
- is enabled. The bit reservoir allows the encoder to use fewer bits on
- simple frames and save them for complex frames, improving overall quality
- at a given bitrate. Disabling it forces each frame to be independently
- decodable at the cost of slightly lower quality.
-
- Set to ``False`` for streaming or seeking applications where individual
- frames need to be independently decodable.
-
- Accepts a ``bool`` value. Defaults to ``True`` (bit reservoir enabled).
- """
-
def get_supported_read_formats() -> typing.List[str]:
pass
diff --git a/pedalboard_native/utils/__init__.pyi b/pedalboard_native/utils/__init__.pyi
index b3acc54..af1b7fd 100644
--- a/pedalboard_native/utils/__init__.pyi
+++ b/pedalboard_native/utils/__init__.pyi
@@ -37,9 +37,9 @@ class Chain(pedalboard_native.PluginContainer, pedalboard_native.Plugin):
Run zero or more plugins as a plugin. Useful when used with the Mix plugin.
"""
- @typing.overload
@typing.overload
def __init__(self, plugins: typing.List[pedalboard_native.Plugin]) -> None: ...
+ @typing.overload
def __repr__(self) -> str: ...
pass
@@ -48,9 +48,9 @@ class Mix(pedalboard_native.PluginContainer, pedalboard_native.Plugin):
A utility plugin that allows running other plugins in parallel. All plugins provided will be mixed equally.
"""
- @typing.overload
@typing.overload
def __init__(self, plugins: typing.List[pedalboard_native.Plugin]) -> None: ...
+ @typing.overload
def __repr__(self) -> str: ...
pass