๐ ๐ A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add type hinting and stub files for editor autocomplete. (#117)
Peter Sobotc3a7c7861e17
diff --git a/.github/workflows/all.yml b/.github/workflows/all.ymlindex 0b58248..c53bb09 100644--- a/.github/workflows/all.yml+++ b/.github/workflows/all.yml@@ -37,7 +37,7 @@ jobs:- name: Lint Python coderun: flake8 . --count --ignore=W503,E203 --exclude .git,dist,doc,build,vendors --show-source --statistics --max-line-length 100- name: Check Python formatting- run: black pedalboard tests --line-length 100 --experimental-string-processing --diff --check+ run: black pedalboard tests --line-length 100 --preview --diff --checklint-cpp:runs-on: ubuntu-latest@@ -99,6 +99,14 @@ jobs:if: runner.os == 'Windows'- name: Build pedalboard locallyrun: python setup.py install+ - name: Generate native type stubs+ run: pybind11-stubgen -o stubs_output pedalboard pedalboard_native --no-setup-py+ - name: Validate type stubs match postprocessing+ run: python3 -m scripts.postprocess_type_hints stubs_output pedalboard --check+ - name: Validate type stubs match runtime+ # Numpy doesn't have typing support for 3.6. Also, 3.6 is deprecated.+ if: matrix.python-version != '3.6'+ run: python3 -m mypy.stubtest pedalboard --allowlist stubtest.allowlist --ignore-missing-stub --ignore-unused-allowlist- name: Install VSTs for testingenv:GCS_ASSET_BUCKET_NAME: ${{ secrets.GCS_ASSET_BUCKET_NAME }}diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex fd400c5..1541606 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -26,8 +26,19 @@ Then, you can `import pedalboard` from Python (or run the tests with `tox`) to t> ```> Note that `ccache` may or may not work out-of-the-box on other platforms - see https://github.com/spotify/pedalboard/issues/62 for more information.-By default, [all `.cpp` and `.mm` files in the `pedalboard` directory (or subdirectories)](https://github.com/spotify/pedalboard/blob/master/setup.py#L129)-will be automatically compiled by `setup.py`.+By default, [all `.cpp` and `.mm` files in the `pedalboard` directory (or subdirectories)](https://github.com/spotify/pedalboard/blob/master/setup.py#L129) will be automatically compiled by `setup.py`.++While `pedalboard` is mostly C++ code, it ships with `.pyi` files to allow for type hints in text editors and via MyPy. To update the type hint files, use the following commands:++```shell+# Use pybind11-stubgen to create intermediate stub files:+pybind11-stubgen -o stubs_output pedalboard pedalboard_native --no-setup-py+# Post-process the stub files into more human-readable, usable ones:+python3 -m scripts.postprocess_type_hints stubs_output pedalboard --check+# Run mypy.stubtest to ensure the resulting stubs are valid+python3 -m mypy.stubtest pedalboard --allowlist stubtest.allowlist+# If all looks good, commit the resulting stubs to Git.+```## Workflowdiff --git a/pedalboard/PluginContainer.h b/pedalboard/PluginContainer.hindex 239e1af..989786a 100644--- a/pedalboard/PluginContainer.h+++ b/pedalboard/PluginContainer.h@@ -61,71 +61,83 @@ inline void init_plugin_container(py::module &m) {m, "PluginContainer","A generic audio processing plugin that contains zero or more other ""plugins. Not intended for direct use.")- .def(py::init([](std::vector<std::shared_ptr<Plugin>> plugins) {- throw py::type_error(- "PluginContainer is an abstract base class - don't instantiate "- "this directly, use its subclasses instead.");- // This will never be hit, but is required to provide a non-void- // type to return from this lambda or else the compiler can't do- // type inference.- return nullptr;- }))+ .def(+ py::init([](std::vector<std::shared_ptr<Plugin>> plugins) {+ throw py::type_error(+ "PluginContainer is an abstract base class - don't instantiate "+ "this directly, use its subclasses instead.");+ // This will never be hit, but is required to provide a non-void+ // type to return from this lambda or else the compiler can't do+ // type inference.+ return nullptr;+ }),+ py::arg("plugins"))// Implement the Sequence protocol:- .def("__getitem__",- [](PluginContainer &s, int i) {- if (i < 0)- i = s.getPlugins().size() + i;- if (i < 0)- throw py::index_error("index out of range");- if (i >= s.getPlugins().size())- throw py::index_error("index out of range");- return s.getPlugins()[i];- })- .def("__setitem__",- [](PluginContainer &s, int i, std::shared_ptr<Plugin> plugin) {- if (i < 0)- i = s.getPlugins().size() + i;- if (i < 0)- throw py::index_error("index out of range");- if (i >= s.getPlugins().size())- throw py::index_error("index out of range");- s.getPlugins()[i] = plugin;- })- .def("__delitem__",- [](PluginContainer &s, int i) {- if (i < 0)- i = s.getPlugins().size() + i;- if (i < 0)- throw py::index_error("index out of range");- if (i >= s.getPlugins().size())- throw py::index_error("index out of range");- auto &plugins = s.getPlugins();- plugins.erase(plugins.begin() + i);- })+ .def(+ "__getitem__",+ [](PluginContainer &s, int i) {+ if (i < 0)+ i = s.getPlugins().size() + i;+ if (i < 0)+ throw py::index_error("index out of range");+ if (i >= s.getPlugins().size())+ throw py::index_error("index out of range");+ return s.getPlugins()[i];+ },+ py::arg("index"))+ .def(+ "__setitem__",+ [](PluginContainer &s, int i, std::shared_ptr<Plugin> plugin) {+ if (i < 0)+ i = s.getPlugins().size() + i;+ if (i < 0)+ throw py::index_error("index out of range");+ if (i >= s.getPlugins().size())+ throw py::index_error("index out of range");+ s.getPlugins()[i] = plugin;+ },+ py::arg("index"), py::arg("plugin"))+ .def(+ "__delitem__",+ [](PluginContainer &s, int i) {+ if (i < 0)+ i = s.getPlugins().size() + i;+ if (i < 0)+ throw py::index_error("index out of range");+ if (i >= s.getPlugins().size())+ throw py::index_error("index out of range");+ auto &plugins = s.getPlugins();+ plugins.erase(plugins.begin() + i);+ },+ py::arg("index")).def("__len__", [](PluginContainer &s) { return s.getPlugins().size(); })- .def("insert",- [](PluginContainer &s, int i, std::shared_ptr<Plugin> plugin) {- if (i < 0)- i = s.getPlugins().size() + i;- if (i < 0)- throw py::index_error("index out of range");- if (i > s.getPlugins().size())- throw py::index_error("index out of range");- auto &plugins = s.getPlugins();- plugins.insert(plugins.begin() + i, plugin);- })+ .def(+ "insert",+ [](PluginContainer &s, int i, std::shared_ptr<Plugin> plugin) {+ if (i < 0)+ i = s.getPlugins().size() + i;+ if (i < 0)+ throw py::index_error("index out of range");+ if (i > s.getPlugins().size())+ throw py::index_error("index out of range");+ auto &plugins = s.getPlugins();+ plugins.insert(plugins.begin() + i, plugin);+ },+ py::arg("index"), py::arg("plugin")).def("append",[](PluginContainer &s, std::shared_ptr<Plugin> plugin) {s.getPlugins().push_back(plugin);})- .def("remove",- [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {- auto &plugins = s.getPlugins();- auto position = std::find(plugins.begin(), plugins.end(), plugin);- if (position == plugins.end())- throw py::value_error("remove(x): x not in list");- plugins.erase(position);- })+ .def(+ "remove",+ [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {+ auto &plugins = s.getPlugins();+ auto position = std::find(plugins.begin(), plugins.end(), plugin);+ if (position == plugins.end())+ throw py::value_error("remove(x): x not in list");+ plugins.erase(position);+ },+ py::arg("plugin")).def("__iter__",[](PluginContainer &s) {@@ -133,12 +145,14 @@ inline void init_plugin_container(py::module &m) {s.getPlugins().end());},py::keep_alive<0, 1>())- .def("__contains__",- [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {- auto &plugins = s.getPlugins();- return std::find(plugins.begin(), plugins.end(), plugin) !=- plugins.end();- });+ .def(+ "__contains__",+ [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {+ auto &plugins = s.getPlugins();+ return std::find(plugins.begin(), plugins.end(), plugin) !=+ plugins.end();+ },+ py::arg("plugin"));}} // namespace Pedalboarddiff --git a/pedalboard/__init__.py b/pedalboard/__init__.pyindex 9b3b804..e577410 100644--- a/pedalboard/__init__.py+++ b/pedalboard/__init__.py@@ -17,8 +17,8 @@from pedalboard_native import * # noqa: F403, F401from pedalboard_native.utils import * # noqa: F403, F401-from .pedalboard import Pedalboard, AVAILABLE_PLUGIN_CLASSES, load_plugin # noqa: F401+from .pedalboard import Pedalboard, _AVAILABLE_PLUGIN_CLASSES, load_plugin # noqa: F401from .version import __version__ # noqa: F401-for klass in AVAILABLE_PLUGIN_CLASSES:+for klass in _AVAILABLE_PLUGIN_CLASSES:vars()[klass.__name__] = klassdiff --git a/pedalboard/__init__.pyi b/pedalboard/__init__.pyinew file mode 100644index 0000000..8e28a17--- /dev/null+++ b/pedalboard/__init__.pyi@@ -0,0 +1,1057 @@+from __future__ import annotations+import pedalboard_native # type: ignore+import typing+import typing_extensions+import numpy++_Shape = typing.Tuple[int, ...]++__all__ = [+ "Bitcrush",+ "Chorus",+ "Compressor",+ "Convolution",+ "Delay",+ "Distortion",+ "GSMFullRateCompressor",+ "Gain",+ "HighShelfFilter",+ "HighpassFilter",+ "Invert",+ "LadderFilter",+ "Limiter",+ "LowShelfFilter",+ "LowpassFilter",+ "MP3Compressor",+ "NoiseGate",+ "PeakFilter",+ "Phaser",+ "PitchShift",+ "Plugin",+ "PluginContainer",+ "Resample",+ "Reverb",+ "io",+ "process",+ "utils",+]++class Plugin:+ """+ A generic audio processing plugin. Base class of all Pedalboard plugins.+ """++ def __init__(self) -> None: ...+ @typing.overload+ def process(+ self,+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]],+ sample_rate: float,+ buffer_size: int = 8192,+ reset: bool = True,+ ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ """+ Run a 32-bit floating point audio buffer through this plugin.(Note: if calling this multiple times with multiple plugins, consider using pedalboard.process(...) instead.)++ Run a 64-bit floating point audio buffer through this plugin.(Note: if calling this multiple times with multiple plugins, consider using pedalboard.process(...) instead.) The buffer will be converted to 32-bit for processing.+ """+ @typing.overload+ def process(+ self,+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]],+ sample_rate: float,+ buffer_size: int = 8192,+ reset: bool = True,+ ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]: ...+ def reset(self) -> None:+ """+ Clear any internal state kept by this plugin (e.g.: reverb tails). The values of plugin parameters will remain unchanged. For most plugins, this is a fast operation; for some, this will cause a full re-instantiation of the plugin.+ """+ pass++class Chorus(Plugin):+ """+ A basic chorus effect. This audio effect can be controlled via the speed and depth of the LFO controlling the frequency response, a mix control, a feedback control, and the centre delay of the modulation.+ Note: To get classic chorus sounds try to use a centre delay time around 7-8 ms with a low feeback volume and a low depth. This effect can also be used as a flanger with a lower centre delay time and a lot of feedback, and as a vibrato effect if the mix value is 1.+ """++ def __init__(+ self,+ rate_hz: float = 1.0,+ depth: float = 0.25,+ centre_delay_ms: float = 7.0,+ feedback: float = 0.0,+ mix: float = 0.5,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def centre_delay_ms(self) -> float:+ """+ :type: float+ """+ @centre_delay_ms.setter+ def centre_delay_ms(self, arg1: float) -> None:+ pass+ @property+ def depth(self) -> float:+ """+ :type: float+ """+ @depth.setter+ def depth(self, arg1: float) -> None:+ pass+ @property+ def feedback(self) -> float:+ """+ :type: float+ """+ @feedback.setter+ def feedback(self, arg1: float) -> None:+ pass+ @property+ def mix(self) -> float:+ """+ :type: float+ """+ @mix.setter+ def mix(self, arg1: float) -> None:+ pass+ @property+ def rate_hz(self) -> float:+ """+ :type: float+ """+ @rate_hz.setter+ def rate_hz(self, arg1: float) -> None:+ pass+ pass++class Compressor(Plugin):+ """+ A dynamic range compressor, used to amplify quiet sounds and reduce the volume of loud sounds.+ """++ def __init__(+ self,+ threshold_db: float = 0,+ ratio: float = 1,+ attack_ms: float = 1.0,+ release_ms: float = 100,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def attack_ms(self) -> float:+ """+ :type: float+ """+ @attack_ms.setter+ def attack_ms(self, arg1: float) -> None:+ pass+ @property+ def ratio(self) -> float:+ """+ :type: float+ """+ @ratio.setter+ def ratio(self, arg1: float) -> None:+ pass+ @property+ def release_ms(self) -> float:+ """+ :type: float+ """+ @release_ms.setter+ def release_ms(self, arg1: float) -> None:+ pass+ @property+ def threshold_db(self) -> float:+ """+ :type: float+ """+ @threshold_db.setter+ def threshold_db(self, arg1: float) -> None:+ pass+ pass++class Convolution(Plugin):+ """+ An audio convolution, suitable for things like speaker simulation or reverb modeling.+ """++ def __init__(self, impulse_response_filename: str, mix: float = 1.0) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def impulse_response_filename(self) -> str:+ """+ :type: str+ """+ @property+ def mix(self) -> float:+ """+ :type: float+ """+ @mix.setter+ def mix(self, arg1: float) -> None:+ pass+ pass++class Delay(Plugin):+ """+ A digital delay plugin with controllable delay time, feedback percentage, and dry/wet mix.+ """++ def __init__(+ self, delay_seconds: float = 0.5, feedback: float = 0.0, mix: float = 0.5+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def delay_seconds(self) -> float:+ """+ :type: float+ """+ @delay_seconds.setter+ def delay_seconds(self, arg1: float) -> None:+ pass+ @property+ def feedback(self) -> float:+ """+ :type: float+ """+ @feedback.setter+ def feedback(self, arg1: float) -> None:+ pass+ @property+ def mix(self) -> float:+ """+ :type: float+ """+ @mix.setter+ def mix(self, arg1: float) -> None:+ pass+ pass++class Distortion(Plugin):+ """+ Apply soft distortion with a tanh waveshaper.+ """++ def __init__(self, drive_db: float = 25) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def drive_db(self) -> float:+ """+ :type: float+ """+ @drive_db.setter+ def drive_db(self, arg1: float) -> None:+ pass+ pass++class GSMFullRateCompressor(Plugin):+ """+ Apply an GSM Full Rate compressor to emulate the sound of a GSM Full Rate ("2G") cellular phone connection. This plugin internally resamples the input audio to 8kHz.+ """++ def __init__(self, quality: Resample.Quality = Resample.Quality.WindowedSinc) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def quality(self) -> Resample.Quality:+ """+ :type: Resample.Quality+ """+ @quality.setter+ def quality(self, arg1: Resample.Quality) -> None:+ pass+ pass++class Gain(Plugin):+ """+ Increase or decrease the volume of a signal by applying a gain value (in decibels). No distortion or other effects are applied.+ """++ def __init__(self, gain_db: float = 1.0) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def gain_db(self) -> float:+ """+ :type: float+ """+ @gain_db.setter+ def gain_db(self, arg1: float) -> None:+ pass+ pass++class HighShelfFilter(Plugin):+ """+ Apply a high shelf filter with variable Q and gain. Frequencies above the cutoff frequency will be boosted (or cut) by the provided gain value.+ """++ def __init__(+ self, cutoff_frequency_hz: float = 440, gain_db: float = 0.0, q: float = 0.7071067690849304+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_frequency_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_frequency_hz.setter+ def cutoff_frequency_hz(self, arg1: float) -> None:+ pass+ @property+ def gain_db(self) -> float:+ """+ :type: float+ """+ @gain_db.setter+ def gain_db(self, arg1: float) -> None:+ pass+ @property+ def q(self) -> float:+ """+ :type: float+ """+ @q.setter+ def q(self, arg1: float) -> None:+ pass+ pass++class HighpassFilter(Plugin):+ """+ Apply a first-order high-pass filter with a roll-off of 6dB/octave. The cutoff frequency will be attenuated by -3dB (i.e.: 0.707x as loud).+ """++ def __init__(self, cutoff_frequency_hz: float = 50) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_frequency_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_frequency_hz.setter+ def cutoff_frequency_hz(self, arg1: float) -> None:+ pass+ pass++class Invert(Plugin):+ """+ Flip the polarity of the signal. This effect is not audible on its own.+ """++ def __init__(self) -> None: ...+ def __repr__(self) -> str: ...+ pass++class LadderFilter(Plugin):+ """+ Multi-mode audio filter based on the classic Moog synthesizer ladder filter.+ """++ class Mode:+ """+ Members:++ LPF12 : low-pass 12 dB/octave++ HPF12 : high-pass 12 dB/octave++ BPF12 : band-pass 12 dB/octave++ LPF24 : low-pass 24 dB/octave++ HPF24 : high-pass 24 dB/octave++ BPF24 : band-pass 24 dB/octave+ """++ def __eq__(self, other: object) -> bool: ...+ def __getstate__(self) -> int: ...+ def __hash__(self) -> int: ...+ def __index__(self) -> int: ...+ def __init__(self, value: int) -> None: ...+ def __int__(self) -> int: ...+ def __ne__(self, other: object) -> bool: ...+ def __repr__(self) -> str: ...+ def __setstate__(self, state: int) -> None: ...+ @property+ def name(self) -> str:+ """+ :type: str+ """+ @property+ def value(self) -> int:+ """+ :type: int+ """+ BPF12: LadderFilter.Mode # value = <Mode.BPF12: 2>+ BPF24: LadderFilter.Mode # value = <Mode.BPF24: 5>+ HPF12: LadderFilter.Mode # value = <Mode.HPF12: 1>+ HPF24: LadderFilter.Mode # value = <Mode.HPF24: 4>+ LPF12: LadderFilter.Mode # value = <Mode.LPF12: 0>+ LPF24: LadderFilter.Mode # value = <Mode.LPF24: 3>+ __members__: dict # value = {'LPF12': <Mode.LPF12: 0>, 'HPF12': <Mode.HPF12: 1>, 'BPF12': <Mode.BPF12: 2>, 'LPF24': <Mode.LPF24: 3>, 'HPF24': <Mode.HPF24: 4>, 'BPF24': <Mode.BPF24: 5>}+ pass+ def __init__(+ self,+ mode: LadderFilter.Mode = Mode.LPF12,+ cutoff_hz: float = 200,+ resonance: float = 0,+ drive: float = 1.0,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_hz.setter+ def cutoff_hz(self, arg1: float) -> None:+ pass+ @property+ def drive(self) -> float:+ """+ :type: float+ """+ @drive.setter+ def drive(self, arg1: float) -> None:+ pass+ @property+ def mode(self) -> LadderFilter.Mode:+ """+ :type: LadderFilter.Mode+ """+ @mode.setter+ def mode(self, arg1: LadderFilter.Mode) -> None:+ pass+ @property+ def resonance(self) -> float:+ """+ :type: float+ """+ @resonance.setter+ def resonance(self, arg1: float) -> None:+ pass+ BPF12: LadderFilter.Mode # value = <Mode.BPF12: 2>+ BPF24: LadderFilter.Mode # value = <Mode.BPF24: 5>+ HPF12: LadderFilter.Mode # value = <Mode.HPF12: 1>+ HPF24: LadderFilter.Mode # value = <Mode.HPF24: 4>+ LPF12: LadderFilter.Mode # value = <Mode.LPF12: 0>+ LPF24: LadderFilter.Mode # value = <Mode.LPF24: 3>+ pass++class Limiter(Plugin):+ """+ A simple limiter with standard threshold and release time controls, featuring two compressors and a hard clipper at 0 dB.+ """++ def __init__(self, threshold_db: float = -10.0, release_ms: float = 100.0) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def release_ms(self) -> float:+ """+ :type: float+ """+ @release_ms.setter+ def release_ms(self, arg1: float) -> None:+ pass+ @property+ def threshold_db(self) -> float:+ """+ :type: float+ """+ @threshold_db.setter+ def threshold_db(self, arg1: float) -> None:+ pass+ pass++class LowShelfFilter(Plugin):+ """+ Apply a low shelf filter with variable Q and gain. Frequencies below the cutoff frequency will be boosted (or cut) by the provided gain value.+ """++ def __init__(+ self, cutoff_frequency_hz: float = 440, gain_db: float = 0.0, q: float = 0.7071067690849304+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_frequency_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_frequency_hz.setter+ def cutoff_frequency_hz(self, arg1: float) -> None:+ pass+ @property+ def gain_db(self) -> float:+ """+ :type: float+ """+ @gain_db.setter+ def gain_db(self, arg1: float) -> None:+ pass+ @property+ def q(self) -> float:+ """+ :type: float+ """+ @q.setter+ def q(self, arg1: float) -> None:+ pass+ pass++class LowpassFilter(Plugin):+ """+ Apply a first-order low-pass filter with a roll-off of 6dB/octave. The cutoff frequency will be attenuated by -3dB (i.e.: 0.707x as loud).+ """++ def __init__(self, cutoff_frequency_hz: float = 50) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_frequency_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_frequency_hz.setter+ def cutoff_frequency_hz(self, arg1: float) -> None:+ pass+ pass++class MP3Compressor(Plugin):+ """+ Apply an MP3 compressor to the audio to reduce its quality.+ """++ def __init__(self, vbr_quality: float = 2.0) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def vbr_quality(self) -> float:+ """+ :type: float+ """+ @vbr_quality.setter+ def vbr_quality(self, arg1: float) -> None:+ pass+ pass++class NoiseGate(Plugin):+ """+ A simple noise gate with standard threshold, ratio, attack time and release time controls. Can be used as an expander if the ratio is low.+ """++ def __init__(+ self,+ threshold_db: float = -100.0,+ ratio: float = 10,+ attack_ms: float = 1.0,+ release_ms: float = 100.0,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def attack_ms(self) -> float:+ """+ :type: float+ """+ @attack_ms.setter+ def attack_ms(self, arg1: float) -> None:+ pass+ @property+ def ratio(self) -> float:+ """+ :type: float+ """+ @ratio.setter+ def ratio(self, arg1: float) -> None:+ pass+ @property+ def release_ms(self) -> float:+ """+ :type: float+ """+ @release_ms.setter+ def release_ms(self, arg1: float) -> None:+ pass+ @property+ def threshold_db(self) -> float:+ """+ :type: float+ """+ @threshold_db.setter+ def threshold_db(self, arg1: float) -> None:+ pass+ pass++class PeakFilter(Plugin):+ """+ Apply a peak (or notch) filter with variable Q and gain. Frequencies around the cutoff frequency will be boosted (or cut) by the provided gain value.+ """++ def __init__(+ self, cutoff_frequency_hz: float = 440, gain_db: float = 0.0, q: float = 0.7071067690849304+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def cutoff_frequency_hz(self) -> float:+ """+ :type: float+ """+ @cutoff_frequency_hz.setter+ def cutoff_frequency_hz(self, arg1: float) -> None:+ pass+ @property+ def gain_db(self) -> float:+ """+ :type: float+ """+ @gain_db.setter+ def gain_db(self, arg1: float) -> None:+ pass+ @property+ def q(self) -> float:+ """+ :type: float+ """+ @q.setter+ def q(self, arg1: float) -> None:+ pass+ pass++class Phaser(Plugin):+ """+ A 6 stage phaser that modulates first order all-pass filters to create sweeping notches in the magnitude frequency response. This audio effect can be controlled with standard phaser parameters: the speed and depth of the LFO controlling the frequency response, a mix control, a feedback control, and the centre frequency of the modulation.+ """++ def __init__(+ self,+ rate_hz: float = 1.0,+ depth: float = 0.5,+ centre_frequency_hz: float = 1300.0,+ feedback: float = 0.0,+ mix: float = 0.5,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def centre_frequency_hz(self) -> float:+ """+ :type: float+ """+ @centre_frequency_hz.setter+ def centre_frequency_hz(self, arg1: float) -> None:+ pass+ @property+ def depth(self) -> float:+ """+ :type: float+ """+ @depth.setter+ def depth(self, arg1: float) -> None:+ pass+ @property+ def feedback(self) -> float:+ """+ :type: float+ """+ @feedback.setter+ def feedback(self, arg1: float) -> None:+ pass+ @property+ def mix(self) -> float:+ """+ :type: float+ """+ @mix.setter+ def mix(self, arg1: float) -> None:+ pass+ @property+ def rate_hz(self) -> float:+ """+ :type: float+ """+ @rate_hz.setter+ def rate_hz(self, arg1: float) -> None:+ pass+ pass++class PitchShift(Plugin):+ """+ Shift pitch without affecting audio duration.+ """++ def __init__(self, semitones: float = 0.0) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def semitones(self) -> float:+ """+ :type: float+ """+ @semitones.setter+ def semitones(self, arg1: float) -> None:+ pass+ pass++class Bitcrush(Plugin):+ """+ A plugin that reduces the signal to a given bit depth, giving the audio a lo-fi, digitized sound. Floating-point bit depths are supported.+ """++ def __init__(self, bit_depth: float = 8) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def bit_depth(self) -> float:+ """+ :type: float+ """+ @bit_depth.setter+ def bit_depth(self, arg1: float) -> None:+ pass+ pass++class PluginContainer(Plugin):+ """+ A generic audio processing plugin that contains zero or more other plugins. Not intended for direct use.+ """++ def __contains__(self, plugin: Plugin) -> bool: ...+ def __delitem__(self, index: int) -> None: ...+ def __getitem__(self, index: int) -> Plugin: ...+ def __init__(self, plugins: typing.List[Plugin]) -> None: ...+ def __iter__(self) -> typing.Iterator: ...+ def __len__(self) -> int: ...+ def __setitem__(self, index: int, plugin: Plugin) -> None: ...+ def append(self, arg0: Plugin) -> None: ...+ def insert(self, index: int, plugin: Plugin) -> None: ...+ def remove(self, plugin: Plugin) -> None: ...+ pass++class Resample(Plugin):+ """+ A plugin that downsamples the input audio to the given sample rate, then upsamples it back to the original sample rate. Various quality settings will produce audible distortion and aliasing effects.+ """++ class Quality:+ """+ Members:++ ZeroOrderHold : The lowest quality and fastest resampling method, with lots of audible artifacts.++ Linear : A resampling method slightly less noisy than the simplest method, but not by much.++ CatmullRom : A moderately good-sounding resampling method which is fast to run.++ Lagrange : A moderately good-sounding resampling method which is slow to run.++ WindowedSinc : The highest quality and slowest resampling method, with no audible artifacts.+ """++ def __eq__(self, other: object) -> bool: ...+ def __getstate__(self) -> int: ...+ def __hash__(self) -> int: ...+ def __index__(self) -> int: ...+ def __init__(self, value: int) -> None: ...+ def __int__(self) -> int: ...+ def __ne__(self, other: object) -> bool: ...+ def __repr__(self) -> str: ...+ def __setstate__(self, state: int) -> None: ...+ @property+ def name(self) -> str:+ """+ :type: str+ """+ @property+ def value(self) -> int:+ """+ :type: int+ """+ CatmullRom: Resample.Quality # value = <Quality.CatmullRom: 2>+ Lagrange: Resample.Quality # value = <Quality.Lagrange: 3>+ Linear: Resample.Quality # value = <Quality.Linear: 1>+ WindowedSinc: Resample.Quality # value = <Quality.WindowedSinc: 4>+ ZeroOrderHold: Resample.Quality # value = <Quality.ZeroOrderHold: 0>+ __members__: dict # value = {'ZeroOrderHold': <Quality.ZeroOrderHold: 0>, 'Linear': <Quality.Linear: 1>, 'CatmullRom': <Quality.CatmullRom: 2>, 'Lagrange': <Quality.Lagrange: 3>, 'WindowedSinc': <Quality.WindowedSinc: 4>}+ pass+ def __init__(+ self,+ target_sample_rate: float = 8000.0,+ quality: Resample.Quality = Resample.Quality.WindowedSinc,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def quality(self) -> Resample.Quality:+ """+ :type: Resample.Quality+ """+ @quality.setter+ def quality(self, arg1: Resample.Quality) -> None:+ pass+ @property+ def target_sample_rate(self) -> float:+ """+ :type: float+ """+ @target_sample_rate.setter+ def target_sample_rate(self, arg1: float) -> None:+ pass+ CatmullRom: Resample.Quality # value = <Quality.CatmullRom: 2>+ Lagrange: Resample.Quality # value = <Quality.Lagrange: 3>+ Linear: Resample.Quality # value = <Quality.Linear: 1>+ WindowedSinc: Resample.Quality # value = <Quality.WindowedSinc: 4>+ ZeroOrderHold: Resample.Quality # value = <Quality.ZeroOrderHold: 0>+ pass++class Reverb(Plugin):+ """+ Performs a simple reverb effect on a stream of audio data. This is a simple stereo reverb, based on the technique and tunings used in FreeVerb.+ """++ def __init__(+ self,+ room_size: float = 0.5,+ damping: float = 0.5,+ wet_level: float = 0.33,+ dry_level: float = 0.4,+ width: float = 1.0,+ freeze_mode: float = 0.0,+ ) -> None: ...+ def __repr__(self) -> str: ...+ @property+ def damping(self) -> float:+ """+ :type: float+ """+ @damping.setter+ def damping(self, arg1: float) -> None:+ pass+ @property+ def dry_level(self) -> float:+ """+ :type: float+ """+ @dry_level.setter+ def dry_level(self, arg1: float) -> None:+ pass+ @property+ def freeze_mode(self) -> float:+ """+ :type: float+ """+ @freeze_mode.setter+ def freeze_mode(self, arg1: float) -> None:+ pass+ @property+ def room_size(self) -> float:+ """+ :type: float+ """+ @room_size.setter+ def room_size(self, arg1: float) -> None:+ pass+ @property+ def wet_level(self) -> float:+ """+ :type: float+ """+ @wet_level.setter+ def wet_level(self, arg1: float) -> None:+ pass+ @property+ def width(self) -> float:+ """+ :type: float+ """+ @width.setter+ def width(self, arg1: float) -> None:+ pass+ pass++class _AudioProcessorParameter:+ """+ An abstract base class for parameter objects that can be added to an AudioProcessor.+ """++ def __repr__(self) -> str: ...+ def get_name(self, maximum_string_length: int) -> str:+ """+ Returns the name to display for this parameter, which is made to fit within the given string length+ """+ def get_raw_value_for_text(self, string_value: str) -> float:+ """+ Returns the raw value of the supplied text. Plugins may handle errors however they see fit, but will likely not raise exceptions.+ """+ def get_text_for_raw_value(self, raw_value: float, maximum_string_length: int = 512) -> str:+ """+ Returns a textual version of the supplied normalised parameter value.+ """+ @property+ def default_raw_value(self) -> float:+ """+ The default internal value of this parameter. Convention is that this parameter should be between 0 and 1.0. This may or may not correspond with the value shown to the user.++ :type: float+ """+ @property+ def index(self) -> int:+ """+ The index of this parameter in its plugin's parameter list.++ :type: int+ """+ @property+ def is_automatable(self) -> bool:+ """+ Returns true if this parameter can be automated (i.e.: scheduled to change over time, in real-time, in a DAW).++ :type: bool+ """+ @property+ def is_boolean(self) -> bool:+ """+ Returns whether the parameter represents a boolean switch, typically with "On" and "Off" states.++ :type: bool+ """+ @property+ def is_discrete(self) -> bool:+ """+ Returns whether the parameter uses discrete values, based on the result of getNumSteps, or allows the host to select values continuously.++ :type: bool+ """+ @property+ def is_meta_parameter(self) -> bool:+ """+ A meta-parameter is a parameter that changes other parameters.++ :type: bool+ """+ @property+ def is_orientation_inverted(self) -> bool:+ """+ If true, this parameter operates in the reverse direction. (Not all plugin formats will actually use this information).++ :type: bool+ """+ @property+ def label(self) -> str:+ """+ Some parameters may be able to return a label string for their units. For example "Hz" or "%".++ :type: str+ """+ @property+ def name(self) -> str:+ """+ Returns the name to display for this parameter at its longest.++ :type: str+ """+ @property+ def num_steps(self) -> int:+ """+ Returns the number of steps that this parameter's range should be quantised into. See also: is_discrete, is_boolean.++ :type: int+ """+ @property+ def raw_value(self) -> float:+ """+ The internal value of this parameter. Convention is that this parameter should be between 0 and 1.0. This may or may not correspond with the value shown to the user.++ :type: float+ """+ @raw_value.setter+ def raw_value(self, arg1: float) -> None:+ """+ The internal value of this parameter. Convention is that this parameter should be between 0 and 1.0. This may or may not correspond with the value shown to the user.+ """+ @property+ def string_value(self) -> str:+ """+ Returns the current value of the parameter as a string.++ :type: str+ """+ pass++class _VST3Plugin(Plugin):+ """+ A wrapper around any Steinbergยฎ VST3 audio effect plugin. Note that plugins must already support the operating system currently in use (i.e.: if you're running Linux but trying to open a VST that does not support Linux, this will fail).+ """++ def __init__(+ self, path_to_plugin_file: str, plugin_name: typing.Optional[str] = None+ ) -> None: ...+ def __repr__(self) -> str: ...+ def _get_parameter(self, arg0: str) -> _AudioProcessorParameter: ...+ @staticmethod+ def get_plugin_names_for_file(arg0: str) -> typing.List[str]:+ """+ Return a list of plugin names contained within a given VST3 plugin (i.e.: a ".vst3"). If the provided file cannot be scanned, an ImportError will be raised.+ """+ def load_preset(self, preset_file_path: str) -> None:+ """+ Load a VST3 preset file in .vstpreset format.+ """+ def show_editor(self) -> None:+ """+ Show the UI of this plugin as a native window. This method will block until the window is closed or a KeyboardInterrupt is received.+ """+ @property+ def _parameters(self) -> typing.List[_AudioProcessorParameter]:+ """+ :type: typing.List[_AudioProcessorParameter]+ """+ @property+ def name(self) -> str:+ """+ The name of this plugin.++ :type: str+ """+ pass++def process(+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]],+ sample_rate: float,+ plugin: Plugin,+ buffer_size: int = 8192,+ reset: bool = True,+) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ """+ Run a 32-bit floating point audio buffer through a list of Pedalboard plugins.++ Run a 64-bit floating point audio buffer through a list of Pedalboard plugins. The buffer will be converted to 32-bit for processing.++ Run a 32-bit floating point audio buffer through a single Pedalboard plugin. (Note: if calling this multiple times with multiple plugins, consider passing a list of plugins instead.)++ Run a 64-bit floating point audio buffer through a single Pedalboard plugin. (Note: if calling this multiple times with multiple plugins, consider passing a list of plugins instead.) The buffer will be converted to 32-bit for processing.+ """++def process(+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]],+ sample_rate: float,+ plugins: typing.List[Plugin],+ buffer_size: int = 8192,+ reset: bool = True,+) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ pass++def process(+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]],+ sample_rate: float,+ plugin: Plugin,+ buffer_size: int = 8192,+ reset: bool = True,+) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ pass++def process(+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]],+ sample_rate: float,+ plugins: typing.List[Plugin],+ buffer_size: int = 8192,+ reset: bool = True,+) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ passdiff --git a/pedalboard/io/AudioFileInit.h b/pedalboard/io/AudioFileInit.hindex 2a518db..e363bd7 100644--- a/pedalboard/io/AudioFileInit.h+++ b/pedalboard/io/AudioFileInit.h@@ -33,14 +33,26 @@ namespace py = pybind11;namespace Pedalboard {-inline void init_audio_file(py::module &m) {+// For pybind11-stubgen to properly parse the docstrings,+// we have to delcare all of the AudioFile subclasses first before using+// their types (i.e.: as return types from `__new__`).+// See:+// https://pybind11.readthedocs.io/en/latest/advanced/misc.html#avoiding-cpp-types-in-docstrings+inline py::class_<AudioFile, std::shared_ptr<AudioFile>>+declare_audio_file(py::module &m) {+ return py::class_<AudioFile, std::shared_ptr<AudioFile>>(+ m, "AudioFile", "A base class for readable and writeable audio files.");+}++inline void init_audio_file(+ py::class_<AudioFile, std::shared_ptr<AudioFile>> &pyAudioFile) {/*** Important note: any changes made to the function signatures here should* also be made to the constructor signatures of ReadableAudioFile and* WriteableAudioFile to keep a consistent interface!*/- py::class_<AudioFile, std::shared_ptr<AudioFile>>(- m, "AudioFile", "A base class for readable and writeable audio files.")++ pyAudioFile.def(py::init<>()) // Make this class effectively abstract; we can only// instantiate subclasses via __new__..def_static(diff --git a/pedalboard/io/ReadableAudioFile.h b/pedalboard/io/ReadableAudioFile.hindex cf86aab..f02902d 100644--- a/pedalboard/io/ReadableAudioFile.h+++ b/pedalboard/io/ReadableAudioFile.h@@ -473,14 +473,24 @@ private:int currentPosition = 0;};-inline void init_readable_audio_file(py::module &m) {- py::class_<ReadableAudioFile, AudioFile, std::shared_ptr<ReadableAudioFile>>(+inline py::class_<ReadableAudioFile, AudioFile,+ std::shared_ptr<ReadableAudioFile>>+declare_readable_audio_file(py::module &m) {+ return py::class_<ReadableAudioFile, AudioFile,+ std::shared_ptr<ReadableAudioFile>>(m, "ReadableAudioFile","An audio file reader interface, with native support for Ogg Vorbis, ""MP3, WAV, FLAC, and AIFF files on all operating systems. On some ""platforms, other formats may also be readable. (Use ""pedalboard.io.get_supported_read_formats() to see which formats are "- "supported on the current platform.)")+ "supported on the current platform.)");+}++inline void init_readable_audio_file(+ py::module &m,+ py::class_<ReadableAudioFile, AudioFile, std::shared_ptr<ReadableAudioFile>>+ &pyReadableAudioFile) {+ pyReadableAudioFile.def(py::init([](std::string filename) -> ReadableAudioFile * {// This definition is only here to provide nice docstrings.throw std::runtime_error(diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.hindex 2b6ee39..6cf242f 100644--- a/pedalboard/io/WriteableAudioFile.h+++ b/pedalboard/io/WriteableAudioFile.h@@ -698,14 +698,23 @@ private:int framesWritten = 0;};-inline void init_writeable_audio_file(py::module &m) {- py::class_<WriteableAudioFile, AudioFile,- std::shared_ptr<WriteableAudioFile>>(+inline py::class_<WriteableAudioFile, AudioFile,+ std::shared_ptr<WriteableAudioFile>>+declare_writeable_audio_file(py::module &m) {+ return py::class_<WriteableAudioFile, AudioFile,+ std::shared_ptr<WriteableAudioFile>>(m, "WriteableAudioFile","An audio file writer interface, with native support for Ogg Vorbis, ""WAV, FLAC, and AIFF files on all operating systems. (Use ""pedalboard.io.get_supported_write_formats() to see which additional "- "formats are supported on the current platform.)")+ "formats are supported on the current platform.)");+}++inline void init_writeable_audio_file(+ py::module &m,+ py::class_<WriteableAudioFile, AudioFile,+ std::shared_ptr<WriteableAudioFile>> &pyWriteableAudioFile) {+ pyWriteableAudioFile.def(py::init([](std::string filename, double sampleRate, int numChannels,int bitDepth,std::optional<std::variant<std::string, float>> quality)diff --git a/pedalboard/io/__init__.pyi b/pedalboard/io/__init__.pyinew file mode 100644index 0000000..998e8af--- /dev/null+++ b/pedalboard/io/__init__.pyi@@ -0,0 +1,276 @@+from __future__ import annotations+import pedalboard_native.io # type: ignore+import typing+import typing_extensions+import numpy++_Shape = typing.Tuple[int, ...]++__all__ = [+ "AudioFile",+ "ReadableAudioFile",+ "WriteableAudioFile",+ "get_supported_read_formats",+ "get_supported_write_formats",+]++class AudioFile:+ """+ A base class for readable and writeable audio files.+ """++ def __init__(self) -> None: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object, file_like: typing.BinaryIO, mode: typing_extensions.Literal["r"] = "r"+ ) -> ReadableAudioFile: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object,+ file_like: typing.BinaryIO,+ mode: typing_extensions.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,+ ) -> WriteableAudioFile: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object, filename: str, mode: typing_extensions.Literal["r"] = "r"+ ) -> ReadableAudioFile: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object,+ filename: str,+ mode: typing_extensions.Literal["w"],+ samplerate: typing.Optional[float] = None,+ num_channels: int = 1,+ bit_depth: int = 16,+ quality: typing.Optional[typing.Union[str, float]] = None,+ ) -> WriteableAudioFile: ...+ pass++class ReadableAudioFile(AudioFile):+ """+ An audio file reader interface, with native support for Ogg Vorbis, MP3, WAV, FLAC, and AIFF files on all operating systems. On some platforms, other formats may also be readable. (Use pedalboard.io.get_supported_read_formats() to see which formats are supported on the current platform.)+ """++ def __enter__(self) -> ReadableAudioFile: ...+ def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ...+ @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.BinaryIO) -> ReadableAudioFile: ...+ @staticmethod+ @typing.overload+ def __new__(cls: object, filename: str) -> ReadableAudioFile: ...+ def __repr__(self) -> str: ...+ def close(self) -> None:+ """+ Close this file, rendering this object unusable.+ """+ def read(self, num_frames: int = 0) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ """+ Read the given number of frames (samples in each channel) from this audio file at the current position. Audio samples are returned in the shape (channels, samples); i.e.: a stereo audio file will have shape (2, <length>). Returned data is always in float32 format.+ """+ def read_raw(self, num_frames: int = 0) -> numpy.ndarray:+ """+ Read the given number of frames (samples in each channel) from this audio file at the current position. Audio samples are returned in the shape (channels, samples); i.e.: a stereo audio file will have shape (2, <length>). Returned data is in the raw format stored by the underlying file (one of int8, int16, int32, or float32).+ """+ def seek(self, position: int) -> None:+ """+ Seek this file to the provided location in frames.+ """+ def seekable(self) -> bool:+ """+ Returns True if this file is currently open and calls to seek() will work.+ """+ def tell(self) -> int:+ """+ Fetch the position in this audio file, in frames.+ """+ @property+ def closed(self) -> bool:+ """+ If this file has been closed, this property will be True.++ :type: bool+ """+ @property+ def duration(self) -> float:+ """+ The duration of this file (frames divided by sample rate).++ :type: float+ """+ @property+ def file_dtype(self) -> str:+ """+ The data type stored natively by this file. Note that read(...) will always return a float32 array, regardless of the value of this property.++ :type: str+ """+ @property+ def frames(self) -> int:+ """+ The total number of frames (samples per channel) in this file.++ :type: int+ """+ @property+ def name(self) -> str:+ """+ The name of this file.++ :type: str+ """+ @property+ def num_channels(self) -> int:+ """+ The number of channels in this file.++ :type: int+ """+ @property+ def samplerate(self) -> float:+ """+ The sample rate of this file in samples (per channel) per second (Hz).++ :type: float+ """+ pass++class WriteableAudioFile(AudioFile):+ """+ An audio file writer interface, with native support for Ogg Vorbis, WAV, FLAC, and AIFF files on all operating systems. (Use pedalboard.io.get_supported_write_formats() to see which additional formats are supported on the current platform.)+ """++ def __enter__(self) -> WriteableAudioFile: ...+ def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ...+ @typing.overload+ def __init__(+ self,+ file_like: typing.BinaryIO,+ samplerate: float,+ num_channels: int = 1,+ bit_depth: int = 16,+ quality: typing.Optional[typing.Union[str, float]] = None,+ format: typing.Optional[str] = None,+ ) -> None: ...+ @typing.overload+ def __init__(+ self,+ filename: str,+ samplerate: float,+ num_channels: int = 1,+ bit_depth: int = 16,+ quality: typing.Optional[typing.Union[str, float]] = None,+ ) -> None: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object,+ 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,+ ) -> WriteableAudioFile: ...+ @staticmethod+ @typing.overload+ def __new__(+ cls: object,+ filename: str,+ samplerate: typing.Optional[float] = None,+ num_channels: int = 1,+ bit_depth: int = 16,+ quality: typing.Optional[typing.Union[str, float]] = None,+ ) -> WriteableAudioFile: ...+ def __repr__(self) -> str: ...+ def close(self) -> None:+ """+ Close this file, flushing its contents to disk and rendering this object unusable for further writing.+ """+ def flush(self) -> None:+ """+ Attempt to flush this audio file's contents to disk. Not all formats support flushing, so this may throw a RuntimeError. (If this happens, closing the file will reliably force a flush to occur.)+ """+ @typing.overload+ def write(self, samples: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]) -> None:+ """+ Encode an array of int8 (8-bit signed integer) audio data and write it to this file. The number of channels in the array must match the number of channels used to open the file. The array may contain audio in any shape. If the file's bit depth or format does not match this data type, the audio will be automatically converted.++ Encode an array of int16 (16-bit signed integer) audio data and write it to this file. The number of channels in the array must match the number of channels used to open the file. The array may contain audio in any shape. If the file's bit depth or format does not match this data type, the audio will be automatically converted.++ Encode an array of int32 (32-bit signed integer) audio data and write it to this file. The number of channels in the array must match the number of channels used to open the file. The array may contain audio in any shape. If the file's bit depth or format does not match this data type, the audio will be automatically converted.++ Encode an array of float32 (32-bit floating-point) audio data and write it to this file. The number of channels in the array must match the number of channels used to open the file. The array may contain audio in any shape. If the file's bit depth or format does not match this data type, the audio will be automatically converted.++ Encode an array of float64 (64-bit floating-point) audio data and write it to this file. The number of channels in the array must match the number of channels used to open the file. The array may contain audio in any shape. No supported formats support float64 natively, so the audio will be converted automatically.+ """+ @typing.overload+ def write(self, samples: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]) -> None: ...+ @typing.overload+ def write(self, samples: numpy.ndarray[typing.Any, numpy.dtype[numpy.int16]]) -> None: ...+ @typing.overload+ def write(self, samples: numpy.ndarray[typing.Any, numpy.dtype[numpy.int32]]) -> None: ...+ @typing.overload+ def write(self, samples: numpy.ndarray[typing.Any, numpy.dtype[numpy.int8]]) -> None: ...+ @property+ def closed(self) -> bool:+ """+ If this file has been closed, this property will be True.++ :type: bool+ """+ @property+ def file_dtype(self) -> str:+ """+ The data type stored natively by this file. Note that write(...) will accept multiple datatypes, regardless of the value of this property.++ :type: str+ """+ @property+ def frames(self) -> int:+ """+ The total number of frames (samples per channel) written to this file so far.++ :type: int+ """+ @property+ def num_channels(self) -> int:+ """+ The number of channels in this file.++ :type: int+ """+ @property+ def quality(self) -> typing.Optional[str]:+ """+ The quality setting used to write this file. For many formats, this may be None.++ :type: typing.Optional[str]+ """+ @property+ def samplerate(self) -> float:+ """+ The sample rate of this file in samples (per channel) per second (Hz).++ :type: float+ """+ pass++def get_supported_read_formats() -> typing.List[str]:+ pass++def get_supported_write_formats() -> typing.List[str]:+ passdiff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.pyindex 403fd5e..3f45838 100644--- a/pedalboard/pedalboard.py+++ b/pedalboard/pedalboard.py@@ -16,13 +16,13 @@import reimport platform+import weakref-from functools import update_wrapperfrom contextlib import contextmanager-from typing import List, Optional, Dict, Tuple, Iterable, Union+from typing import List, Optional, Dict, Tuple, Iterable, Type, Union-from pedalboard_native import Plugin, _AudioProcessorParameter-from pedalboard_native.utils import Chain+from pedalboard_native import Plugin, _AudioProcessorParameter # type: ignore+from pedalboard_native.utils import Chain # type: ignoreclass Pedalboard(Chain):@@ -45,7 +45,10 @@ class Pedalboard(Chain):FLOAT_SUFFIXES_TO_IGNORE = set(["x", "%", "*", ",", ".", "hz"])-def strip_common_float_suffixes(s: str) -> str:+def strip_common_float_suffixes(s: Union[float, str]) -> Union[float, str]:+ if isinstance(s, float):+ return s+s = s.strip()# Handle certain plugins that report "Hz" and "kHz" suffixes:@@ -63,7 +66,10 @@ def strip_common_float_suffixes(s: str) -> str:return s-def looks_like_float(s: str) -> bool:+def looks_like_float(s: Union[float, str]) -> bool:+ if isinstance(s, float):+ return True+try:float(strip_common_float_suffixes(s))return True@@ -197,8 +203,8 @@ class AudioProcessorParameter(object):self.ranges: Dict[Tuple[float, float], Union[str, float, bool]] = {}with self.__get_cpp_parameter() as cpp_parameter:- start_of_range = 0- text_value = None+ start_of_range: float = 0+ text_value: Optional[str] = Nonefor x in range(0, search_steps + 1):raw_value = x / search_stepsx_text_value = cpp_parameter.get_text_for_raw_value(raw_value)@@ -209,6 +215,11 @@ class AudioProcessorParameter(object):self.ranges[(start_of_range, raw_value)] = text_valuetext_value = x_text_valuestart_of_range = raw_value+ if text_value is None:+ raise NotImplementedError(+ f"Plugin parameter '{parameter_name}' failed to return a valid string for its"+ " value."+ )self.ranges[(start_of_range, 1)] = text_valueself.python_name = to_python_parameter_name(cpp_parameter)@@ -217,15 +228,17 @@ class AudioProcessorParameter(object):self.max_value = Noneself.step_size = Noneself.approximate_step_size = None- self.type = str+ self.type: Type = strif all(looks_like_float(v) for v in self.ranges.values()):self.type = float- self.ranges = {k: float(strip_common_float_suffixes(v)) for k, v in self.ranges.items()}- self.min_value = min(self.ranges.values())- self.max_value = max(self.ranges.values())+ float_ranges = {+ k: float(strip_common_float_suffixes(v)) for k, v in self.ranges.items()+ }+ self.min_value = min(float_ranges.values())+ self.max_value = max(float_ranges.values())- sorted_values = sorted(self.ranges.values())+ sorted_values = sorted(float_ranges.values())first_derivative_steps = set([round(abs(b - a), 8) for a, b in zip(sorted_values, sorted_values[1:])])@@ -235,9 +248,15 @@ class AudioProcessorParameter(object):self.approximate_step_size = sum(first_derivative_steps) / len(first_derivative_steps)- elif len(self.ranges) == 2 and (TRUE_BOOLEANS & {v.lower() for v in self.ranges.values()}):+ self.ranges = dict(float_ranges)+ elif len(self.ranges) == 2 and (+ TRUE_BOOLEANS & {(v.lower() if isinstance(v, str) else v) for v in self.ranges.values()}+ ):self.type = bool- self.ranges = {k: v.lower() in TRUE_BOOLEANS for k, v in self.ranges.items()}+ self.ranges = {+ k: (v.lower() if isinstance(v, str) else v) in TRUE_BOOLEANS+ for k, v in self.ranges.items()+ }self.min_value = Falseself.max_value = Trueself.step_size = 1@@ -307,7 +326,7 @@ class AudioProcessorParameter(object):except RuntimeError:passif hasattr(super(), "__getattr__"):- return super().__getattr__(name)+ return super().__getattr__(name) # type: ignoreraise AttributeError("'{}' has no attribute '{}'".format(self.__class__.__name__, name))def __setattr__(self, name: str, value):@@ -344,24 +363,24 @@ class AudioProcessorParameter(object):plugin_reported_raw_value = self.get_raw_value_for_text(str(new_value))closest_diff = None- closest_range_value = None+ closest_range_value: Optional[Tuple[float, float]] = Nonefor value, raw_value_range in self._value_to_raw_value_ranges.items():diff = new_value - valueif closest_diff is None or abs(diff) < abs(closest_diff):closest_range_value = raw_value_rangeclosest_diff = diff- expected_low, expected_high = closest_range_value- if (- plugin_reported_raw_value < expected_low- or plugin_reported_raw_value > expected_high- ):- # The plugin might have bad code in it when trying- # to parse one of the string values it gave to us.- # Let's use the range we had before:- return expected_low- else:- return plugin_reported_raw_value+ if closest_range_value is not None:+ expected_low, expected_high = closest_range_value+ if (+ plugin_reported_raw_value < expected_low+ or plugin_reported_raw_value > expected_high+ ):+ # The plugin might have bad code in it when trying+ # to parse one of the string values it gave to us.+ # Let's use the range we had before:+ return expected_low+ return plugin_reported_raw_valueelif self.type is str:if isinstance(new_value, (str, int, float, bool)):@@ -421,18 +440,40 @@ def normalize_python_parameter_name(name: str) -> str:# Special case: some plugins expose parameters with "#"/"โฏ" or "b"/"โญ" in their names.name = name.replace("#", "_sharp").replace("โฏ", "_sharp").replace("โญ", "_flat")# Replace all non-alphanumeric characters with underscores- name = [+ name_chars = [c if (c.isalpha() or c.isnumeric()) and c.isprintable() and ord(c) < 128 else "_"for c in name]# Remove any double-underscores:- name = [a for a, b in zip(name, name[1:]) if a != b or b != "_"] + [name[-1]]+ name_chars = [a for a, b in zip(name_chars, name_chars[1:]) if a != b or b != "_"] + [+ name_chars[-1]+ ]# Remove any leading or trailing underscores:- name = "".join(name).strip("_")+ name = "".join(name_chars).strip("_")return nameclass ExternalPlugin(object):+ # Don't actually define this here; this is only to appease MyPy.+ def __init__(+ self,+ path_to_plugin_file: str,+ parameter_values: Dict[str, Union[str, int, float, bool]] = {},+ plugin_name: Optional[str] = None,+ ) -> None:+ ...++ @classmethod+ def get_plugin_names_for_file(cls, filename: str) -> List[str]:+ ...++ def show_editor(self) -> None:+ ...++ @property+ def name(self) -> str:+ ...+def __set_initial_parameter_values__(self, parameter_values: Dict[str, Union[str, int, float, bool]] = {}):@@ -472,7 +513,7 @@ class ExternalPlugin(object):self.__python_to_cpp_names__[parameter.python_name] = cpp_parameter.namereturn parameters- def _get_parameter_by_python_name(self, python_name: str) -> AudioProcessorParameter:+ def _get_parameter_by_python_name(self, python_name: str) -> Optional[AudioProcessorParameter]:if not hasattr(self, "__python_parameter_cache__"):self.__python_parameter_cache__ = {}if not hasattr(self, "__python_to_cpp_names__"):@@ -545,10 +586,9 @@ try:f" {type(parameter_values).__name__}. (If passing a plugin name, pass"' "plugin_name=..." as a keyword argument instead.)')- super().__init__(path_to_plugin_file, plugin_name)+ _VST3Plugin.__init__(self, path_to_plugin_file, plugin_name)self.__set_initial_parameter_values__(parameter_values)-except ImportError:# We may be on a system that doesn't have native VST3Plugin support.pass@@ -569,38 +609,45 @@ try:f" {type(parameter_values).__name__}. (If passing a plugin name, pass"' "plugin_name=..." as a keyword argument instead.)')- super().__init__(path_to_plugin_file, plugin_name)+ _AudioUnitPlugin.__init__(self, path_to_plugin_file, plugin_name)self.__set_initial_parameter_values__(parameter_values)-except ImportError:# We may be on a system that doesn't have native AudioUnitPlugin support.# (i.e.: any platform that's not macOS.)pass-AVAILABLE_PLUGIN_CLASSES = list(ExternalPlugin.__subclasses__())+_AVAILABLE_PLUGIN_CLASSES: List[Type[ExternalPlugin]] = list(ExternalPlugin.__subclasses__())-def load_plugin(*args, **kwargs):- if not AVAILABLE_PLUGIN_CLASSES:+def load_plugin(+ path_to_plugin_file: str,+ parameter_values: Dict[str, Union[str, int, float, bool]] = {},+ plugin_name: Union[str, None] = None,+) -> ExternalPlugin:+ if not _AVAILABLE_PLUGIN_CLASSES:raise ImportError("Pedalboard found no supported external plugin types in this installation ({}).".format(platform.system()))exceptions = []- for plugin_class in AVAILABLE_PLUGIN_CLASSES:+ for plugin_class in _AVAILABLE_PLUGIN_CLASSES:try:- return plugin_class(*args, **kwargs)+ return plugin_class(+ path_to_plugin_file=path_to_plugin_file,+ parameter_values=parameter_values,+ plugin_name=plugin_name,+ )except ImportError as e:exceptions.append(e)except Exception:raiseelse:- tried_plugins = ", ".join([c.__name__ for c in AVAILABLE_PLUGIN_CLASSES])+ tried_plugins = ", ".join([c.__name__ for c in _AVAILABLE_PLUGIN_CLASSES])# Good error messages are important, okay?- if len(AVAILABLE_PLUGIN_CLASSES) > 2:+ if len(_AVAILABLE_PLUGIN_CLASSES) > 2:tried_plugins = ", or ".join(tried_plugins.rsplit(", ", 1))else:tried_plugins = " or ".join(tried_plugins.rsplit(", ", 1))@@ -610,12 +657,8 @@ def load_plugin(*args, **kwargs):"\n\t".join(["{}: {}".format(klass.__name__, exception)- for klass, exception in zip(AVAILABLE_PLUGIN_CLASSES, exceptions)+ for klass, exception in zip(_AVAILABLE_PLUGIN_CLASSES, exceptions)]),))---if AVAILABLE_PLUGIN_CLASSES:- update_wrapper(load_plugin, AVAILABLE_PLUGIN_CLASSES[0].__init__)diff --git a/pedalboard/py.typed b/pedalboard/py.typednew file mode 100644index 0000000..e69de29diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cppindex f33aaca..ec4c4b9 100644--- a/pedalboard/python_bindings.cpp+++ b/pedalboard/python_bindings.cpp@@ -68,6 +68,11 @@ namespace py = pybind11;using namespace Pedalboard;PYBIND11_MODULE(pedalboard_native, m) {+ auto plugin = py::class_<Plugin, std::shared_ptr<Plugin>>(+ m, "Plugin",+ "A generic audio processing plugin. Base class of all "+ "Pedalboard plugins.");+m.def("process", process<float>,"Run a 32-bit floating point audio buffer through a list of Pedalboard ""plugins.",@@ -95,58 +100,51 @@ PYBIND11_MODULE(pedalboard_native, m) {py::arg("input_array"), py::arg("sample_rate"), py::arg("plugin"),py::arg("buffer_size") = DEFAULT_BUFFER_SIZE, py::arg("reset") = true);- auto plugin =- py::class_<Plugin, std::shared_ptr<Plugin>>(- m, "Plugin",- "A generic audio processing plugin. Base class of all "- "Pedalboard plugins.")- .def(py::init([]() {- throw py::type_error(- "Plugin is an abstract base class - don't instantiate this "- "directly, use its subclasses instead.");- // This will never be hit, but is required to provide a non-void- // type to return from this lambda or else the compiler can't do- // type inference.- return nullptr;- }))- .def(- "reset", &Plugin::reset,- "Clear any internal state kept by this plugin (e.g.: reverb "- "tails). The values of plugin parameters will remain unchanged. "- "For most plugins, this is a fast operation; for some, this will "- "cause a full re-instantiation of the plugin.")- .def(- "process",- [](std::shared_ptr<Plugin> self,- const py::array_t<float, py::array::c_style> inputArray,- double sampleRate, unsigned int bufferSize, bool reset) {- return process(inputArray, sampleRate, {self}, bufferSize,- reset);- },- "Run a 32-bit floating point audio buffer through this plugin."- "(Note: if calling this multiple times with multiple plugins, "- "consider using pedalboard.process(...) instead.)",- py::arg("input_array"), py::arg("sample_rate"),- py::arg("buffer_size") = DEFAULT_BUFFER_SIZE,- py::arg("reset") = true)-- .def(- "process",- [](std::shared_ptr<Plugin> self,- const py::array_t<double, py::array::c_style> inputArray,- double sampleRate, unsigned int bufferSize, bool reset) {- const py::array_t<float, py::array::c_style> float32InputArray =- inputArray.attr("astype")("float32");- return process(float32InputArray, sampleRate, {self},- bufferSize, reset);- },- "Run a 64-bit floating point audio buffer through this plugin."- "(Note: if calling this multiple times with multiple plugins, "- "consider using pedalboard.process(...) instead.) The buffer "- "will be converted to 32-bit for processing.",- py::arg("input_array"), py::arg("sample_rate"),- py::arg("buffer_size") = DEFAULT_BUFFER_SIZE,- py::arg("reset") = true);+ plugin+ .def(py::init([]() {+ throw py::type_error(+ "Plugin is an abstract base class - don't instantiate this "+ "directly, use its subclasses instead.");+ // This will never be hit, but is required to provide a non-void+ // type to return from this lambda or else the compiler can't do+ // type inference.+ return nullptr;+ }))+ .def("reset", &Plugin::reset,+ "Clear any internal state kept by this plugin (e.g.: reverb "+ "tails). The values of plugin parameters will remain unchanged. "+ "For most plugins, this is a fast operation; for some, this will "+ "cause a full re-instantiation of the plugin.")+ .def(+ "process",+ [](std::shared_ptr<Plugin> self,+ const py::array_t<float, py::array::c_style> inputArray,+ double sampleRate, unsigned int bufferSize, bool reset) {+ return process(inputArray, sampleRate, {self}, bufferSize, reset);+ },+ "Run a 32-bit floating point audio buffer through this plugin."+ "(Note: if calling this multiple times with multiple plugins, "+ "consider using pedalboard.process(...) instead.)",+ py::arg("input_array"), py::arg("sample_rate"),+ py::arg("buffer_size") = DEFAULT_BUFFER_SIZE, py::arg("reset") = true)++ .def(+ "process",+ [](std::shared_ptr<Plugin> self,+ const py::array_t<double, py::array::c_style> inputArray,+ double sampleRate, unsigned int bufferSize, bool reset) {+ const py::array_t<float, py::array::c_style> float32InputArray =+ inputArray.attr("astype")("float32");+ return process(float32InputArray, sampleRate, {self}, bufferSize,+ reset);+ },+ "Run a 64-bit floating point audio buffer through this plugin."+ "(Note: if calling this multiple times with multiple plugins, "+ "consider using pedalboard.process(...) instead.) The buffer "+ "will be converted to 32-bit for processing.",+ py::arg("input_array"), py::arg("sample_rate"),+ py::arg("buffer_size") = DEFAULT_BUFFER_SIZE,+ py::arg("reset") = true);plugin.attr("__call__") = plugin.attr("process");init_plugin_container(m);@@ -193,7 +191,12 @@ PYBIND11_MODULE(pedalboard_native, m) {// I/O helpers and utilities:py::module io = m.def_submodule("io");- init_audio_file(io);- init_readable_audio_file(io);- init_writeable_audio_file(io);++ auto pyAudioFile = declare_audio_file(io);+ auto pyReadableAudioFile = declare_readable_audio_file(io);+ auto pyWriteableAudioFile = declare_writeable_audio_file(io);++ init_audio_file(pyAudioFile);+ init_readable_audio_file(io, pyReadableAudioFile);+ init_writeable_audio_file(io, pyWriteableAudioFile);};diff --git a/pedalboard/utils/__init__.pyi b/pedalboard/utils/__init__.pyinew file mode 100644index 0000000..3636722--- /dev/null+++ b/pedalboard/utils/__init__.pyi@@ -0,0 +1,55 @@+from __future__ import annotations+import pedalboard_native.utils # type: ignore+import typing+import typing_extensions+import numpy+import pedalboard_native # type: ignore++_Shape = typing.Tuple[int, ...]++__all__ = ["Chain", "Mix"]++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+ def __init__(self) -> None: ...+ @typing.overload+ def __init__(self, plugins: typing.List[pedalboard_native.Plugin]) -> None: ...+ def __repr__(self) -> str: ...+ @typing.overload+ def process(+ self,+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]],+ sample_rate: float,+ buffer_size: int = 8192,+ reset: bool = True,+ ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]:+ """+ Run a 32-bit floating point audio buffer through this plugin.(Note: if calling this multiple times with multiple plugins, consider using pedalboard.process(...) instead.)++ Run a 64-bit floating point audio buffer through this plugin.(Note: if calling this multiple times with multiple plugins, consider using pedalboard.process(...) instead.) The buffer will be converted to 32-bit for processing.+ """+ @typing.overload+ def process(+ self,+ input_array: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]],+ sample_rate: float,+ buffer_size: int = 8192,+ reset: bool = True,+ ) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float32]]: ...+ pass++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+ def __init__(self) -> None: ...+ @typing.overload+ def __init__(self, plugins: typing.List[pedalboard_native.Plugin]) -> None: ...+ def __repr__(self) -> str: ...+ passdiff --git a/pedalboard/version/__init__.pyi b/pedalboard/version/__init__.pyinew file mode 100644index 0000000..add833a--- /dev/null+++ b/pedalboard/version/__init__.pyi@@ -0,0 +1,11 @@+from __future__ import annotations+import pedalboard.version+import typing+import typing_extensions++__all__ = ["MAJOR", "MINOR", "PATCH"]++MAJOR = 0+MINOR = 5+PATCH = 5+__version__ = "0.5.5"diff --git a/scripts/postprocess_type_hints.py b/scripts/postprocess_type_hints.pynew file mode 100644index 0000000..4138b60--- /dev/null+++ b/scripts/postprocess_type_hints.py@@ -0,0 +1,171 @@+"""+This script is intended to postprocess type hint (.pyi) files produced by pybind11-stubgen.++A number of changes must be made to produce valid type hint files out-of-the-box.+Think of this as a more intelligent (or less intelligent) application of `git patch`.+"""++import os+import io+import re+import difflib+from pathlib import Path+from collections import defaultdict+import black+import argparse++REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))++OMIT_FILES = [+ os.path.join("pedalboard-stubs", "__init__.pyi"),+ os.path.join("pedalboard-stubs", "pedalboard", "__init__.pyi"),+ os.path.join("pedalboard_native-stubs", "_internal", "__init__.pyi"),+]++# Any lines containing any of these substrings will be omitted from the pedalboard_native stubs:+OMIT_LINES_CONTAINING = [+ "installed_plugins = [",+ "typing._GenericAlias",+ "typing._VariadicGenericAlias",+ "typing._SpecialForm",+ "__annotations__: dict",+ "_AVAILABLE_PLUGIN_CLASSES: list",+]++REPLACEMENTS = [+ # object is a superclass of `str`, which would make these declarations ambiguous:+ ("file_like: object", "file_like: typing.BinaryIO"),+ # "r" is the default file open/reading mode:+ ("mode: str = 'r'", r'mode: typing_extensions.Literal["r"] = "r"'),+ # ... but when using "w", "w" needs to be specified explicitly (no default):+ ("mode: str = 'w'", r'mode: typing_extensions.Literal["w"]'),+ # ndarrays need to be corrected as well:+ (r"numpy\.ndarray\[(.*?)\]", r"numpy.ndarray[typing.Any, numpy.dtype[\1]]"),+ # We return an ndarray with indeterminate type from read_raw,+ # which is represented by a py::handle object.+ # Type this as a numpy.ndarray with no type arguments:+ ("-> handle:", "-> numpy.ndarray:"),+ # None of our enums are properly detected by pybind11-stubgen:+ (r"Resample\.Quality = Quality\.", "Resample.Quality = Resample.Quality."),+ (r": pedalboard_native\.Resample\.Quality", ": Resample.Quality"),+ (r": pedalboard_native\.LadderFilter\.Mode", ": LadderFilter.Mode"),+ (r"import pedalboard_native(\.?.*)$", r"import pedalboard_native\1 # type: ignore"),+ (+ # For Python 3.6 compatibility:+ r"import typing",+ "\n".join(["import typing", "import typing_extensions"]),+ ),+]++REMOVE_INDENTED_BLOCKS_STARTING_WITH = [+ # TODO(psobot): Add a conditional to _AudioUnitPlugin+ # to ensure type stubs only show up on macOS:+ "class _AudioUnitPlugin(Plugin):"+]++LINES_TO_IGNORE_FOR_MATCH = {"from __future__ import annotations"}+++def stub_files_match(a: str, b: str) -> bool:+ a = "".join(+ [x for x in a.split("\n") if x.strip() and x.strip() not in LINES_TO_IGNORE_FOR_MATCH]+ )+ b = "".join(+ [x for x in b.split("\n") if x.strip() and x.strip() not in LINES_TO_IGNORE_FOR_MATCH]+ )+ return a == b+++def main():+ parser = argparse.ArgumentParser(+ description="Post-process type hint files produced by pybind11-stubgen for Pedalboard."+ )+ parser.add_argument(+ "source_directory",+ default=os.path.join(REPO_ROOT, "pybind11-stubgen-output"),+ )+ parser.add_argument(+ "target_directory",+ default=os.path.join(REPO_ROOT, "pedalboard"),+ )+ parser.add_argument(+ "--check",+ action="store_true",+ help=(+ "Return a non-zero exit code if files on disk don't match what this script would"+ " generate."+ ),+ )+ args = parser.parse_args()++ output_file_to_source_files = defaultdict(list)+ for source_path in Path(args.source_directory).rglob("*.pyi"):+ source_path = str(source_path)+ if any(x in source_path for x in OMIT_FILES):+ print(f"Skipping possible source file '{source_path}'...")+ continue+ output_module_path = os.path.join(*(["pedalboard"] + source_path.split(os.path.sep)[2:-1]))+ if not source_path.endswith("__init__.pyi"):+ raise NotImplementedError("Not sure how to create stubs not at the module level.")+ output_file_name = os.path.join(output_module_path, "__init__.pyi")+ output_file_to_source_files[output_file_name].append(source_path)++ for output_file_name, source_files in output_file_to_source_files.items():+ os.makedirs(os.path.dirname(output_file_name), exist_ok=True)++ print(f"Writing stub file {output_file_name}...")++ file_contents = io.StringIO()+ for source_file in source_files:+ with open(source_file) as f:+ in_excluded_indented_block = False+ for line in f:+ if all(x not in line for x in OMIT_LINES_CONTAINING):+ if any(line.startswith(x) for x in REMOVE_INDENTED_BLOCKS_STARTING_WITH):+ in_excluded_indented_block = True+ continue++ if line.strip() and not line.startswith(" "):+ in_excluded_indented_block = False++ if in_excluded_indented_block:+ continue++ for find, replace in REPLACEMENTS:+ if re.findall(find, line):+ print(f"\tReplacing {repr(find)} with {repr(replace)}...")+ line = re.sub(find, replace, line)+ file_contents.write(line)+ print(f"\tRead {f.tell():,} bytes of stubs from {source_file}.")++ # Run black:+ try:+ output = black.format_file_contents(+ file_contents.getvalue(),+ fast=False,+ mode=black.FileMode(is_pyi=True, line_length=100),+ )+ except black.report.NothingChanged:+ output = file_contents.getvalue()++ if args.check:+ with open(output_file_name, "r") as f:+ existing = f.read()+ if not stub_files_match(existing, output):+ error = f"File that would be generated ({output_file_name}) "+ error += "does not match existing file!\n"+ error += f"Existing file had {len(existing):,} bytes, "+ error += f"expected {len(output):,} bytes.\nDiff was:\n"+ diff = difflib.context_diff(existing.split("\n"), output.split("\n"))+ error += "\n".join([x.strip() for x in diff])+ raise ValueError(error)+ else:+ with open(output_file_name, "w") as o:+ o.write(output)+ print(f"\tWrote {o.tell():,} bytes of stubs to {output_file_name}.")++ print("Done!")+++if __name__ == "__main__":+ main()diff --git a/setup.py b/setup.pyindex 4d99ee4..c86d4d6 100644--- a/setup.py+++ b/setup.py@@ -326,5 +326,8 @@ setup(ext_modules=[pedalboard_cpp],install_requires=['numpy'],packages=['pedalboard', 'pedalboard.io'],+ package_data={+ 'pedalboard': ['py.typed', '*.pyi', '**/*.pyi']+ },cmdclass={"build_ext": BuildC_CxxExtensions},)diff --git a/stubtest.allowlist b/stubtest.allowlistnew file mode 100644index 0000000..789a74d--- /dev/null+++ b/stubtest.allowlist@@ -0,0 +1,14 @@+pedalboard.Plugin.__call__+pedalboard.__all__+pedalboard.io.__all__+pedalboard.pedalboard.Dict+pedalboard.pedalboard.Iterable+pedalboard.pedalboard.List+pedalboard.pedalboard.Plugin.__call__+pedalboard.pedalboard.WeakTypeWrapper@91+pedalboard.pedalboard._AudioProcessorParameter.__init__+pedalboard.utils.Chain+pedalboard.utils.Mix+pedalboard.utils.__all__+pedalboard.version.__all__+.*?AudioUnitPlugin.*\ No newline at end of filediff --git a/test-requirements.txt b/test-requirements.txtindex 0841a95..36666ab 100644--- a/test-requirements.txt+++ b/test-requirements.txt@@ -6,13 +6,15 @@ pybind11>=2.6.0setuptools>=42wheelflake8-black==21.7b0+black==22.6.0click==8.0.4interrogatenumpysox-tensorflow~=2.6.2; python_version < '3.10' and platform.machine != 'arm64'+tensorflow~=2.8; python_version < '3.10' and python_version > '3.6' and platform.machine != 'arm64'google-cloud-storagetqdmpsutil+pybind11-stubgen+mypydiff --git a/tests/test_bitcrush.py b/tests/test_bitcrush.pyindex 81f542f..d3674f6 100644--- a/tests/test_bitcrush.py+++ b/tests/test_bitcrush.py@@ -35,5 +35,5 @@ def test_bitcrush(bit_depth: float, fundamental_hz: float, sample_rate: float, nassert np.all(np.isfinite(output))- expected_output = np.around(sine_wave.astype(np.float64) * (2 ** bit_depth)) / (2 ** bit_depth)+ expected_output = np.around(sine_wave.astype(np.float64) * (2**bit_depth)) / (2**bit_depth)np.testing.assert_allclose(output, expected_output, atol=0.01)diff --git a/tests/test_external_plugins.py b/tests/test_external_plugins.pyindex 42ef97d..23238ec 100644--- a/tests/test_external_plugins.py+++ b/tests/test_external_plugins.py@@ -55,7 +55,7 @@ if os.getenv("CIBW_TEST_REQUIRES") or os.getenv("CI"):def is_container_plugin(filename: str):- for klass in pedalboard.AVAILABLE_PLUGIN_CLASSES:+ for klass in pedalboard._AVAILABLE_PLUGIN_CLASSES:try:return len(klass.get_plugin_names_for_file(filename)) > 1except ImportError:@@ -146,7 +146,7 @@ atexit.register(delete_installed_plugins)# Allow testing with all of the plugins on the local machine:if os.environ.get("ENABLE_TESTING_WITH_LOCAL_PLUGINS", False):- for plugin_class in pedalboard.AVAILABLE_PLUGIN_CLASSES:+ for plugin_class in pedalboard._AVAILABLE_PLUGIN_CLASSES:for plugin_path in plugin_class.installed_plugins:try:load_test_plugin(plugin_path)@@ -188,6 +188,8 @@ def test_at_least_one_plugin_is_available_for_testing():("123.45 Hz", "123.45"),("123.45 kHz", "123450.0"),("kHz", "kHz"),+ (1.23, 1.23),+ ("one thousand kHz", "one thousand kHz"),],)def test_strip_common_float_suffixes(value, expected):@@ -271,7 +273,7 @@ def test_initial_parameter_validation_missing(plugin_filename: str):load_test_plugin(plugin_filename, parameter_values={"missing_parameter": 123})[email protected]("loader", [pedalboard.load_plugin] + pedalboard.AVAILABLE_PLUGIN_CLASSES)[email protected]("loader", [pedalboard.load_plugin] + pedalboard._AVAILABLE_PLUGIN_CLASSES)def test_import_error_on_missing_path(loader):with pytest.raises(ImportError):loader("./")diff --git a/tests/test_filters.py b/tests/test_filters.pyindex 5abbc28..38917ff 100644--- a/tests/test_filters.py+++ b/tests/test_filters.py@@ -23,7 +23,7 @@ from .utils import generate_sine_atdef rms(x: np.ndarray) -> float:if len(x.shape) == 1:- return np.sqrt(np.mean(x ** 2))+ return np.sqrt(np.mean(x**2))else:return np.array([rms(channel) for channel in x])diff --git a/tests/test_io.py b/tests/test_io.pyindex 889bd2d..295593f 100644--- a/tests/test_io.py+++ b/tests/test_io.py@@ -63,7 +63,7 @@ def get_tolerance_for_format_and_bit_depth(extension: str, input_format, file_dtif np.issubdtype(input_format, np.signedinteger):input_bit_depth = np.dtype(input_format).itemsize * 8return 4 / (2 ** min(file_bit_depth, input_bit_depth))- return 4 / (2 ** file_bit_depth)+ return 4 / (2**file_bit_depth)# These formats offset the waveform substantially, and these tests don't do any realignment.if extension in {".m4a", ".ac3", ".adts", ".mp4", ".mp2", ".mp3"}:@@ -578,7 +578,7 @@ def test_basic_write_int32_to_16_bit_wav(tmp_path: pathlib.Path):original = np.linspace(0, 1, 11)# As per AES17: the integer value -(2^31) should never show up in the stream.- signal = (original * (2 ** 31 - 1)).astype(np.int32)+ signal = (original * (2**31 - 1)).astype(np.int32)with pedalboard.io.WriteableAudioFile(filename,@@ -596,7 +596,7 @@ def test_basic_write_int32_to_16_bit_wav(tmp_path: pathlib.Path):with pedalboard.io.ReadableAudioFile(filename) as af:as_written = af.read(len(signal))[0]- np.testing.assert_allclose(original, as_written, atol=2 / (2 ** 15))+ np.testing.assert_allclose(original, as_written, atol=2 / (2**15))@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())diff --git a/tests/test_tensorflow.py b/tests/test_tensorflow.pyindex f78009f..f1ba4af 100644--- a/tests/test_tensorflow.py+++ b/tests/test_tensorflow.py@@ -21,6 +21,9 @@ import numpy as npimport pedalboard+ sys.version_info.minor <= 6, reason="TensorFlow not supported on Python 3.6 anymore."+)@pytest.mark.skipif(sys.version_info.minor >= 10, reason="TensorFlow not supported on Python 3.10+ yet.")