π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Remove syntactic sugar experiment.
Peter Sobotd9db0e88b93a
diff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.pyindex e31bfa7..8ee6070 100644--- a/pedalboard/pedalboard.py+++ b/pedalboard/pedalboard.py@@ -28,86 +28,16 @@ from pedalboard_native import Plugin, process, _AudioProcessorParameterfrom pedalboard_native.utils import Mix, Chain-# A concrete type for all ways to define a Pedalboard with zero or more plugins:-PedalboardDefinition = Union[- # The standard Pedalboard is a list of plugins,- # although nested lists will be unpacked.- List[Union[Plugin, 'PedalboardDefinition']],- # Tuples can be used in place of lists when necessary,- # if putting a chain inside of a mix plugin.- Tuple[Union[Plugin, 'PedalboardDefinition']],- # Pedalboards can be nested, and the contained- # pedalboard's plugins will be treated as a list:- 'Pedalboard',- # Passing a set of plugins will result in them being processed in parallel- # (i.e: they will all accept the same input and their outputs will be mixed)- Set[Union[Plugin, 'PedalboardDefinition']],-]---def _coalesce_plugin_definitions(- _input: Optional[PedalboardDefinition], level: int = 0-) -> List[Plugin]:- """- Given a PedalboardDefinition, return a concrete list of plugins that can be executed.- Basically: remove the syntactic sugar and add the appropriate Mix() and Chain() plugins.- """- if isinstance(_input, Plugin):- return _input- elif hasattr(_input, "plugins"):- return _coalesce_plugin_definitions(_input.plugins, level + 1)- elif isinstance(_input, List) or isinstance(_input, Tuple):- plugins = [- _coalesce_plugin_definitions(element, level + 1)- for element in _input- if element is not None- ]- if level > 0:- return Chain(plugins)- else:- return plugins- elif isinstance(_input, Set):- return Mix(- [- _coalesce_plugin_definitions(element, level + 1)- for element in _input- if element is not None- ]- )- else:- raise TypeError(- "Pedalboard(...) expected a list (or set) of plugins (or lists or sets of plugins),"- " but found an element of type: {}".format(type(_input))- )---def _flatten_all_plugins(_input: Optional[PedalboardDefinition]) -> List[Plugin]:- """- Given a PedalboardDefinition, return a concrete list of plugins that can be executed.- Basically: remove the syntactic sugar and add the appropriate Mix() and Chain() plugins.- """- if hasattr(_input, "plugins"):- return _input.plugins- elif isinstance(_input, Plugin):- return [_input]- elif isinstance(_input, List) or isinstance(_input, List) or isinstance(_input, Tuple):- return sum([_flatten_all_plugins(element) for element in _input if element is not None], [])- return []--class Pedalboard(Chain):"""A container for a chain of plugins, to use for processing audio."""- def __init__(self, plugins: Optional[PedalboardDefinition] = None):- plugins = _coalesce_plugin_definitions(plugins)- if not isinstance(plugins, list):- plugins = [plugins]- super().__init__(plugins)+ def __init__(self, plugins: Optional[List[Plugin]] = None):+ super().__init__(plugins or [])def __repr__(self) -> str:- return "<{} plugins={}>".format(self.__class__.__name__, list(self))+ return "<{} with {} plugins: {}>".format(self.__class__.__name__, len(self), list(self))FLOAT_SUFFIXES_TO_IGNORE = set(["x", "%", "*", ",", ".", "hz"])diff --git a/pedalboard/plugins/Chain.h b/pedalboard/plugins/Chain.hindex 33c1080..871172b 100644--- a/pedalboard/plugins/Chain.h+++ b/pedalboard/plugins/Chain.h@@ -77,6 +77,7 @@ inline void init_chain(py::module &m) {return new Chain(plugins);}),py::arg("plugins"))+ .def(py::init([]() { return new Chain({}); })).def("__repr__",[](Chain &plugin) {std::ostringstream ss;diff --git a/pedalboard/plugins/Mix.h b/pedalboard/plugins/Mix.hindex 40e828b..9efc830 100644--- a/pedalboard/plugins/Mix.h+++ b/pedalboard/plugins/Mix.h@@ -162,6 +162,7 @@ inline void init_mix(py::module &m) {return new Mix(plugins);}),py::arg("plugins"))+ .def(py::init([]() { return new Mix({}); })).def("__repr__", [](Mix &plugin) {std::ostringstream ss;ss << "<pedalboard.Mix with " << plugin.getPlugins().size()diff --git a/tests/test_mix_and_chain.py b/tests/test_mix_and_chain.pyindex 3e1c345..c87585f 100644--- a/tests/test_mix_and_chain.py+++ b/tests/test_mix_and_chain.py@@ -34,12 +34,11 @@ from pedalboard_native._internal import AddLatencyNUM_SECONDS = 4-def test_chain_syntactic_sugar():+def test_nested_chain():sr = 44100_input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)- # Nested chains should work fine when passed as lists:- pb = Pedalboard([Gain(6), [Gain(-6), Gain(1)], Gain(-1)])+ pb = Pedalboard([Gain(6), Chain([Gain(-6), Gain(1)]), Gain(-1)])output = pb(_input, sr)assert isinstance(pb[0], Gain)@@ -55,12 +54,16 @@ def test_chain_syntactic_sugar():np.testing.assert_allclose(_input, output, rtol=0.01)-def test_mix_syntactic_sugar():+def test_nested_list_raises_error():+ with pytest.raises(TypeError):+ Pedalboard([Gain(6), [Gain(-6), Gain(1)], Gain(-1)])+++def test_nested_mix():sr = 44100_input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)- # Nested mixes should work fine when passed as sets:- pb = Pedalboard([Gain(6), {Gain(-6), Gain(-6)}, Gain(-6)])+ pb = Pedalboard([Gain(6), Mix([Gain(-6), Gain(-6)]), Gain(-6)])output = pb(_input, sr)assert isinstance(pb[0], Gain)@@ -83,10 +86,10 @@ def test_deep_nesting():[# This parallel chain should boost by 6dB, but due to# there being 2 outputs, the result will be +12dB.- {tuple([Gain(1) for _ in range(6)]), tuple([Gain(1) for _ in range(6)])},+ Mix([Chain([Gain(1) for _ in range(6)]), Chain([Gain(1) for _ in range(6)])]),# This parallel chain should cut by -24dB, but due to# there being 2 outputs, the result will be -18dB.- {tuple([Gain(-1) for _ in range(24)]), tuple([Gain(-1) for _ in range(24)])},+ Mix([Chain([Gain(-1) for _ in range(24)]), Chain([Gain(-1) for _ in range(24)])]),])output = pb(_input, sr)@@ -101,10 +104,15 @@ def test_nesting_pedalboards():[# This parallel chain should boost by 6dB, but due to# there being 2 outputs, the result will be +12dB.- {Pedalboard([Gain(1) for _ in range(6)]), Pedalboard([Gain(1) for _ in range(6)])},+ Mix([Pedalboard([Gain(1) for _ in range(6)]), Pedalboard([Gain(1) for _ in range(6)])]),# This parallel chain should cut by -24dB, but due to# there being 2 outputs, the result will be -18dB.- {Pedalboard([Gain(-1) for _ in range(24)]), Pedalboard([Gain(-1) for _ in range(24)])},+ Mix(+ [+ Pedalboard([Gain(-1) for _ in range(24)]),+ Pedalboard([Gain(-1) for _ in range(24)]),+ ]+ ),])output = pb(_input, sr)@@ -119,10 +127,10 @@ def test_chain_latency_compensation():[# This parallel chain should boost by 6dB, but due to# there being 2 outputs, the result will be +12dB.- {tuple([Gain(1) for _ in range(6)]), tuple([Gain(1) for _ in range(6)])},+ Mix([Chain([Gain(1) for _ in range(6)]), Chain([Gain(1) for _ in range(6)])]),# This parallel chain should cut by -24dB, but due to# there being 2 outputs, the result will be -18dB.- {tuple([Gain(-1) for _ in range(24)]), tuple([Gain(-1) for _ in range(24)])},+ Mix([Chain([Gain(-1) for _ in range(24)]), Chain([Gain(-1) for _ in range(24)])]),])output = pb(_input, sr)@@ -137,10 +145,12 @@ def test_mix_latency_compensation(sample_rate, buffer_size, latency_a_seconds, lnoise = np.random.rand(int(NUM_SECONDS * sample_rate))pb = Pedalboard([- {- AddLatency(int(latency_a_seconds * sample_rate)),- AddLatency(int(latency_b_seconds * sample_rate)),- },+ Mix(+ [+ AddLatency(int(latency_a_seconds * sample_rate)),+ AddLatency(int(latency_b_seconds * sample_rate)),+ ]+ ),])output = pb(noise, sample_rate, buffer_size=buffer_size)@@ -157,14 +167,14 @@ def test_chain_latency_compensation(sample_rate, buffer_size, latency_a_seconds,noise = np.random.rand(int(NUM_SECONDS * sample_rate))pb = Pedalboard([- [+ Chain([AddLatency(int(latency_a_seconds * sample_rate)),AddLatency(int(latency_b_seconds * sample_rate)),- ],- [+ ]),+ Chain([AddLatency(int(latency_a_seconds * sample_rate)),AddLatency(int(latency_b_seconds * sample_rate)),- ],+ ]),])output = pb(noise, sample_rate, buffer_size=buffer_size)@@ -195,7 +205,7 @@ def test_readme_example_does_not_crash(sample_rate, buffer_size):)original_plus_delayed_harmonies = Pedalboard(- {passthrough, delay_and_pitch_shift, delay_longer_and_more_pitch_shift}+ Mix([passthrough, delay_and_pitch_shift, delay_longer_and_more_pitch_shift]))# TODO: Allow passing a Pedalboard into Mix (which will require Pedalboard to be a subclass of Plugin)original_plus_delayed_harmonies(noise, sample_rate=sample_rate, buffer_size=buffer_size)@@ -206,11 +216,11 @@ def test_readme_example_does_not_crash(sample_rate, buffer_size):# Put a compressor at the front of the chain:Compressor(),# Split the chain and mix three different effects equally:- {- (passthrough, Distortion(drive_db=36)),- (delay_and_pitch_shift, Reverb(room_size=1)),+ Mix([+ Pedalboard([passthrough, Distortion(drive_db=36)]),+ Pedalboard([delay_and_pitch_shift, Reverb(room_size=1)]),delay_longer_and_more_pitch_shift,- },+ ]),# Add a reverb on the final mix:Reverb(),]@@ -264,3 +274,14 @@ def test_pedalboard_is_a_plugin(sample_rate, buffer_size):])original_plus_delayed_harmonies(noise, sample_rate=sample_rate, buffer_size=buffer_size)++[email protected]("cls", [Mix, Chain, Pedalboard])+def test_empty_list_is_valid_constructor_arg(cls):+ assert len(cls([])) == 0+++[email protected]("cls", [Mix, Chain, Pedalboard])+def test_no_arg_constructor(cls):+ assert len(cls()) == 0