hum 1.0.6__tar.gz → 1.0.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.6
3
+ Version: 1.0.7
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -16,6 +16,7 @@ from typing import (
16
16
  Set,
17
17
  Tuple,
18
18
  TypeVar,
19
+ Mapping,
19
20
  runtime_checkable,
20
21
  )
21
22
  from collections.abc import MutableMapping
@@ -675,10 +676,12 @@ class Synth(MutableMapping):
675
676
  settings: Optional[Set[str]] = None,
676
677
  sr=DFLT_PYO_SR,
677
678
  nchnls=DFLT_PYO_NCHNLS,
679
+ value_trans: Optional[Dict[str, Callable]] = None,
678
680
  record_on_start: bool = True,
679
681
  event_log_factory: RecordFactory = list, # No argument factory that makes an Appendable
680
682
  audio="portaudio",
681
683
  verbosity=DFLT_PYO_VERBOSITY,
684
+ synth_func_kwargs=None,
682
685
  **server_kwargs,
683
686
  ):
684
687
  """
@@ -711,11 +714,23 @@ class Synth(MutableMapping):
711
714
  self._server_kwargs = dict(
712
715
  server_kwargs, sr=sr, nchnls=nchnls, verbosity=verbosity, audio=audio
713
716
  )
717
+ if synth_func_kwargs:
718
+ synth_func_attributes = synth_func.__dict__.copy()
719
+ synth_func = partial(synth_func, **synth_func_kwargs)
720
+ synth_func.__dict__.update(synth_func_attributes)
721
+ self._synth_func_kwargs = synth_func_kwargs
714
722
  self._synth_func = synth_func
715
723
  self._server = None
716
724
  self.output = None
717
725
  self._synth_func_params = synth_func_defaults(synth_func)
718
726
 
727
+ assert value_trans is None or (
728
+ isinstance(value_trans, Mapping)
729
+ and all(map(callable, value_trans.values()))
730
+ ), f"value_trans must be a dict of callables. Was: {value_trans}"
731
+ self._has_value_trans = value_trans is not None
732
+ self._value_trans = value_trans
733
+
719
734
  # if function has some default dials or settings, use them if not specified in Synth arguments
720
735
  dials = dials or getattr(synth_func, "_default_dials", None)
721
736
  settings = settings or getattr(synth_func, "_default_settings", None)
@@ -754,6 +769,8 @@ class Synth(MutableMapping):
754
769
  rebuild_updates = {}
755
770
 
756
771
  for k, v in updates.items():
772
+ if self._has_value_trans and k in self._value_trans:
773
+ v = self._value_trans[k](v)
757
774
  if k in self._dials:
758
775
  live_updates[k] = v
759
776
  elif k in self._settings:
@@ -939,11 +956,11 @@ class Synth(MutableMapping):
939
956
  f"Failed to initialize synth function '{self._synth_func.__name__}'.\n"
940
957
  f"Perhaps some arguments were wrongly wrapped into SigTo.\n"
941
958
  f"Consider :\n"
942
- f" * using the sigto_include argument to control which parameters are live.\n"
943
- f" * using the sigto_exclude argument to control which parameters are not live.\n"
959
+ f" * using the dials argument to control which parameters are live.\n"
960
+ f" * using the settings argument to control which parameters are not live.\n"
944
961
  f"Alternatively, at function definition time, you can control this by:\n"
945
- f" * using the @knob_params decorator to control which parameters are live.\n"
946
- f" * using the @knob_exclude decorator to control which parameters are not live.\n"
962
+ f" * using the @add_default_dials decorator to control which parameters are live.\n"
963
+ f" * using the @add_default_settings decorator to control which parameters are not live.\n"
947
964
  f"Original error: {e}"
948
965
  ) from e
949
966
 
hum-1.0.7/hum/util.py ADDED
@@ -0,0 +1,295 @@
1
+ """
2
+ A few general utils
3
+ """
4
+
5
+ from warnings import warn
6
+ from inspect import getmodule
7
+ from typing import Iterable, Iterator, Tuple, TypeVar, Callable, Iterable, Union
8
+ from itertools import zip_longest
9
+ from functools import partial
10
+
11
+ import numpy as np
12
+
13
+
14
+ T = TypeVar("T")
15
+
16
+
17
+ def simple_chunker(
18
+ a: Iterable[T], chk_size: int, *, include_tail: bool = True
19
+ ) -> Iterator[Tuple[T, ...]]:
20
+ """
21
+ Chunks an iterable into non-overlapping chunks of size `chk_size`.
22
+
23
+ Note: This chunker is simpler, but also less efficient than `chunk_iterable`.
24
+ It does have the extra `include_tail` argument, though.
25
+ Though note that you can get the effect of `include_tail=False` in `chunk_iterable`
26
+ by using `filter(lambda x: len(x) == chk_size, chunk_iterable(...))`.
27
+
28
+ Args:
29
+ a: The iterable to be chunked.
30
+ chk_size: The size of each chunk.
31
+ include_tail: If True, includes the remaining elements as the last chunk
32
+ even if they are fewer than `chk_size`. Defaults to True.
33
+
34
+ Returns:
35
+ An iterator of tuples, where each tuple is a chunk of size `chk_size`
36
+ (or fewer elements if `include_tail` is True).
37
+
38
+ Examples:
39
+ >>> list(simple_chunker(range(8), 3))
40
+ [(0, 1, 2), (3, 4, 5), (6, 7)]
41
+ >>> list(simple_chunker(range(8), 3, include_tail=False))
42
+ [(0, 1, 2), (3, 4, 5)]
43
+ """
44
+ it = iter(a)
45
+ if include_tail:
46
+ sentinel = object()
47
+ for chunk in zip_longest(*([it] * chk_size), fillvalue=sentinel):
48
+ yield tuple(item for item in chunk if item is not sentinel)
49
+ else:
50
+ yield from zip(*([it] * chk_size))
51
+
52
+
53
+ def round_number(number, round_to=0.001):
54
+ """
55
+ Round a number to the nearest multiple of round_to.
56
+
57
+ Parameters:
58
+ - number: float, the number to round.
59
+ - round_to: float, the value to round to.
60
+
61
+ Returns:
62
+ - float, the rounded number.
63
+
64
+ >>> round_number(1.234567, 0.01)
65
+ 1.23
66
+
67
+ Note, the rounder rounds to nearest multiple of round_to, not to the nearest decimal place.
68
+
69
+ >>> round_number(1.234567, 0.001)
70
+ 1.235
71
+
72
+
73
+ """
74
+ digits = len(str(round_to).split(".")[-1])
75
+ return round(round(number / round_to) * round_to, digits)
76
+
77
+
78
+ def round_numbers(items, round_to=0.001, *, index_of_item_number=None, egress=None):
79
+ """
80
+ Round numbers in an iterable, optionally extracting the number to round from an index.
81
+
82
+ Parameters:
83
+ - items: iterable of numbers or iterable of tuples/lists containing numbers.
84
+ - round_to: float, round to the nearest multiple of this value.
85
+ - index_of_item_number: int or None. If None, round the item directly;
86
+ otherwise, round the item at this index in each iterable element.
87
+
88
+ Returns:
89
+ - generator yielding items with rounded numbers.
90
+
91
+ Examples:
92
+ >>> list(round_numbers([1.23, 3.14159], round_to=0.1))
93
+ [1.2, 3.1]
94
+
95
+ >>> items = [(1.234, 'one'), (3.14159, 'three')]
96
+ >>> list(round_numbers(items, round_to=0.1, index_of_item_number=0))
97
+ [[1.2, 'one'], [3.1, 'three']]
98
+ """
99
+ digits = len(str(round_to).split(".")[-1])
100
+
101
+ for item in items:
102
+ if index_of_item_number is None:
103
+ yield round(round(item / round_to) * round_to, digits)
104
+ else:
105
+ val = item[index_of_item_number]
106
+ rounded_val = round(round(val / round_to) * round_to, digits)
107
+ item = list(item)
108
+ item[index_of_item_number] = rounded_val
109
+
110
+ if egress is None:
111
+ yield item
112
+ else:
113
+ yield egress(item)
114
+
115
+
116
+ from bisect import bisect_left
117
+ from math import log2
118
+
119
+
120
+ class ListSnapper:
121
+ """
122
+ Snap to the nearest value in a list.
123
+
124
+ >>> snapper = ListSnapper([0, 1, 2, 3, 4, 5])
125
+ >>> snapper(2.3)
126
+ 2
127
+ >>> snapper(2.7)
128
+ 3
129
+ >>> snapper(2.5) # exactly the middle of 2 and 3; snaps to 2
130
+ 2
131
+
132
+ """
133
+
134
+ def __init__(self, snap_values):
135
+ self.snap_values = sorted(snap_values)
136
+
137
+ def __call__(self, x):
138
+ pos = bisect_left(self.snap_values, x)
139
+ if pos == 0:
140
+ return self.snap_values[0]
141
+ if pos == len(self.snap_values):
142
+ return self.snap_values[-1]
143
+ before = self.snap_values[pos - 1]
144
+ after = self.snap_values[pos]
145
+ return before if abs(x - before) <= abs(after - x) else after
146
+
147
+
148
+ class SnapToChromatic:
149
+ """
150
+ Snap to the nearest chromatic note in a tempered scale.
151
+ """
152
+
153
+ def __init__(self, base_tuning=440):
154
+ self.base_tuning = base_tuning
155
+
156
+ def __call__(self, x):
157
+ if x <= 0:
158
+ raise ValueError("Frequency must be positive")
159
+ midi_note = round(69 + 12 * log2(x / 440))
160
+ return 440 * 2 ** ((midi_note - 69) / 12)
161
+
162
+
163
+ DFLT_OCTAVE_RANGE = (0, 10)
164
+ DFLT_TUNING = 440.0 # A4 tuning frequency
165
+
166
+
167
+ def tempered_semitone_frequencies(
168
+ tuning=DFLT_TUNING, octave_range=DFLT_OCTAVE_RANGE, digits=5
169
+ ):
170
+ """
171
+ Get a sorted list of frequencies for a given tuning and octave range.
172
+
173
+ :param tuning: The tuning frequency (default is 440 Hz).
174
+ It corresponds to A4 (that is, the 69th MIDI note).
175
+ :param octave_range: A tuple of two integers representing the range of octaves.
176
+
177
+ The first integer is the starting octave (inclusive), and the second integer is the ending octave (exclusive).
178
+ For example, (0, 10) will generate frequencies from C0 to B9.
179
+ The default is (0, 10), which covers a wide range of frequencies.
180
+ :return: A sorted list of frequencies in the specified octave range. The first (i.e. .[0]) frequency will correspond to a C.
181
+
182
+ >>> frequencies = tempered_semitone_frequencies()
183
+ >>> len(frequencies)
184
+ 120
185
+ >>> frequencies # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
186
+ [8.1758, 8.66196, 9.17702, 9.72272, ..., 7040.0, 7458.62018, 7902.13282]
187
+
188
+ """
189
+
190
+ assert len(octave_range) == 2, "octave_range must be a tuple of two integers"
191
+ n_octave_divisions = 12
192
+
193
+ def gen_freqs():
194
+ for octave in range(*octave_range):
195
+ base_midi = n_octave_divisions * octave
196
+ for st in range(n_octave_divisions):
197
+ midi_note = base_midi + st
198
+ freq = tuning * 2 ** ((midi_note - 69) / n_octave_divisions)
199
+ yield round(freq, digits)
200
+
201
+ return sorted(gen_freqs())
202
+
203
+
204
+ # TODO: Add string_to_scale_map argument to convert string to midi note array scale
205
+ def scale_snapper(
206
+ scale: Iterable[Union[float, int]] = (0, 2, 4, 5, 7, 9, 11),
207
+ *,
208
+ tuning=DFLT_TUNING,
209
+ octave_range=DFLT_OCTAVE_RANGE,
210
+ ):
211
+ """
212
+ Snap frequency to the nearest midi note of the midi_nodes list, modulo 12.
213
+
214
+ :param scale: A list of integers representing the scale.
215
+ For example, (0, 2, 4, 5, 7, 9, 11) (the default) corresponds to the C major scale.
216
+ :param tuning: The tuning frequency (default is 440 Hz).
217
+ It corresponds to A4 (that is, the 69th MIDI note).
218
+ :param octave_range: A tuple of two integers representing the range of octaves.
219
+ The first integer is the starting octave (inclusive), and the second integer is the ending octave (exclusive).
220
+ For example, (0, 10) will generate frequencies from C0 to B9.
221
+ The default is (0, 10), which covers a wide range of frequencies.
222
+
223
+ :return: A ListSnapper object that can be used to snap frequencies to the nearest note in the scale.
224
+
225
+ >>> snapper = scale_snapper()
226
+ >>> snapper(440.0) # A4
227
+ 440.0
228
+
229
+ If you're near that A4, `snapper` will snap to it:
230
+
231
+ >>> snapper(441.0)
232
+ 440.0
233
+ >>> snapper(439.0)
234
+ 440.0
235
+
236
+ But even if you're, say at A#, you'll still snap to A4 (since it's the closest note
237
+ of C major scale):
238
+
239
+ >>> snapper(466.16) # A#4
240
+ 440.0
241
+
242
+ If you are slightly higher than A#, you'll snap to B4
243
+
244
+ >>> snapper(467) # doctest: +ELLIPSIS
245
+ 493.8833...
246
+
247
+ """
248
+ chromatic_scale = tempered_semitone_frequencies(
249
+ tuning=tuning, octave_range=octave_range
250
+ )
251
+ # keep all elements of chromatic_scale that have index in midi_notes module 12
252
+ scale_frequencies = [
253
+ chromatic_scale[i] for i in range(len(chromatic_scale)) if i % 12 in scale
254
+ ]
255
+ # create a ListSnapper object
256
+ return ListSnapper(scale_frequencies)
257
+
258
+
259
+ def getmodulename(obj, default=""):
260
+ """Get name of module of object"""
261
+ return getattr(getmodule(obj), "__name__", default)
262
+
263
+
264
+ class ModuleNotFoundErrorNiceMessage:
265
+ def __init__(self, msg=None):
266
+ self.msg = msg
267
+
268
+ def __enter__(self):
269
+ pass
270
+
271
+ def __exit__(self, exc_type, exc_val, exc_tb):
272
+ if exc_type is ModuleNotFoundError:
273
+ msg = (
274
+ self.msg
275
+ or f"""
276
+ It seems you don't have required `{exc_val.name}` package for this Store.
277
+ Try installing it by running:
278
+
279
+ pip install {exc_val.name}
280
+
281
+ in your terminal.
282
+ For more information: https://pypi.org/project/{exc_val.name}
283
+ """
284
+ )
285
+ warn(msg)
286
+
287
+
288
+ class ModuleNotFoundIgnore:
289
+ def __enter__(self):
290
+ pass
291
+
292
+ def __exit__(self, exc_type, exc_val, exc_tb):
293
+ if exc_type is ModuleNotFoundError:
294
+ pass
295
+ return True
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.6
3
+ Version: 1.0.7
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = hum
3
- version = 1.0.6
3
+ version = 1.0.7
4
4
  url = https://github.com/thorwhalen/hum
5
5
  platforms = any
6
6
  description_file = README.md
hum-1.0.6/hum/util.py DELETED
@@ -1,131 +0,0 @@
1
- """
2
- A few general utils
3
- """
4
-
5
- from warnings import warn
6
- from inspect import getmodule
7
- from typing import Iterable, Iterator, Tuple, TypeVar, Callable
8
- from itertools import zip_longest
9
- from functools import partial
10
-
11
- import numpy as np
12
-
13
-
14
- T = TypeVar("T")
15
-
16
-
17
- def simple_chunker(
18
- a: Iterable[T], chk_size: int, *, include_tail: bool = True
19
- ) -> Iterator[Tuple[T, ...]]:
20
- """
21
- Chunks an iterable into non-overlapping chunks of size `chk_size`.
22
-
23
- Note: This chunker is simpler, but also less efficient than `chunk_iterable`.
24
- It does have the extra `include_tail` argument, though.
25
- Though note that you can get the effect of `include_tail=False` in `chunk_iterable`
26
- by using `filter(lambda x: len(x) == chk_size, chunk_iterable(...))`.
27
-
28
- Args:
29
- a: The iterable to be chunked.
30
- chk_size: The size of each chunk.
31
- include_tail: If True, includes the remaining elements as the last chunk
32
- even if they are fewer than `chk_size`. Defaults to True.
33
-
34
- Returns:
35
- An iterator of tuples, where each tuple is a chunk of size `chk_size`
36
- (or fewer elements if `include_tail` is True).
37
-
38
- Examples:
39
- >>> list(simple_chunker(range(8), 3))
40
- [(0, 1, 2), (3, 4, 5), (6, 7)]
41
- >>> list(simple_chunker(range(8), 3, include_tail=False))
42
- [(0, 1, 2), (3, 4, 5)]
43
- """
44
- it = iter(a)
45
- if include_tail:
46
- sentinel = object()
47
- for chunk in zip_longest(*([it] * chk_size), fillvalue=sentinel):
48
- yield tuple(item for item in chunk if item is not sentinel)
49
- else:
50
- yield from zip(*([it] * chk_size))
51
-
52
-
53
- from functools import partial
54
- from collections.abc import Iterable
55
-
56
-
57
- def round_numbers(items, round_to=0.001, *, index_of_item_number=None, egress=None):
58
- """
59
- Round numbers in an iterable, optionally extracting the number to round from an index.
60
-
61
- Parameters:
62
- - items: iterable of numbers or iterable of tuples/lists containing numbers.
63
- - round_to: float, round to the nearest multiple of this value.
64
- - index_of_item_number: int or None. If None, round the item directly;
65
- otherwise, round the item at this index in each iterable element.
66
-
67
- Returns:
68
- - generator yielding items with rounded numbers.
69
-
70
- Examples:
71
- >>> list(round_numbers([1.23, 3.14159], round_to=0.1))
72
- [1.2, 3.1]
73
-
74
- >>> items = [(1.234, 'one'), (3.14159, 'three')]
75
- >>> list(round_numbers(items, round_to=0.1, index_of_item_number=0))
76
- [[1.2, 'one'], [3.1, 'three']]
77
- """
78
- digits = len(str(round_to).split(".")[-1])
79
-
80
- for item in items:
81
- if index_of_item_number is None:
82
- yield round(round(item / round_to) * round_to, digits)
83
- else:
84
- val = item[index_of_item_number]
85
- rounded_val = round(round(val / round_to) * round_to, digits)
86
- item = list(item)
87
- item[index_of_item_number] = rounded_val
88
-
89
- if egress is None:
90
- yield item
91
- else:
92
- yield egress(item)
93
-
94
-
95
- def getmodulename(obj, default=""):
96
- """Get name of module of object"""
97
- return getattr(getmodule(obj), "__name__", default)
98
-
99
-
100
- class ModuleNotFoundErrorNiceMessage:
101
- def __init__(self, msg=None):
102
- self.msg = msg
103
-
104
- def __enter__(self):
105
- pass
106
-
107
- def __exit__(self, exc_type, exc_val, exc_tb):
108
- if exc_type is ModuleNotFoundError:
109
- msg = (
110
- self.msg
111
- or f"""
112
- It seems you don't have required `{exc_val.name}` package for this Store.
113
- Try installing it by running:
114
-
115
- pip install {exc_val.name}
116
-
117
- in your terminal.
118
- For more information: https://pypi.org/project/{exc_val.name}
119
- """
120
- )
121
- warn(msg)
122
-
123
-
124
- class ModuleNotFoundIgnore:
125
- def __enter__(self):
126
- pass
127
-
128
- def __exit__(self, exc_type, exc_val, exc_tb):
129
- if exc_type is ModuleNotFoundError:
130
- pass
131
- return True
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes