hum 1.0.6__tar.gz → 1.0.8__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.8
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
@@ -17,11 +17,14 @@ def estimate_chunk_frequency(chk: Iterable, sr: int):
17
17
  # Find peaks in the FFT result
18
18
  peaks, _ = find_peaks(np.abs(yf[: N // 2]), height=0)
19
19
 
20
- # Get the frequencies of the peaks
21
- peak_freqs = xf[peaks]
22
-
23
- # Return the frequency with the highest amplitude
24
- return peak_freqs[np.argmax(np.abs(yf[peaks]))]
20
+ if len(peaks) > 0:
21
+ # Get the frequencies of the peaks
22
+ peak_freqs = xf[peaks]
23
+
24
+ # Return the frequency with the highest amplitude
25
+ return peak_freqs[np.argmax(np.abs(yf[peaks]))]
26
+ else:
27
+ return None
25
28
 
26
29
 
27
30
  def estimate_frequencies(wf: Iterable, sr: int, chunker: int | Callable):
@@ -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,10 @@ 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
+ before_v = v
774
+ v = self._value_trans[k](v)
775
+ print(f"{before_v} -> {v}")
757
776
  if k in self._dials:
758
777
  live_updates[k] = v
759
778
  elif k in self._settings:
@@ -939,11 +958,11 @@ class Synth(MutableMapping):
939
958
  f"Failed to initialize synth function '{self._synth_func.__name__}'.\n"
940
959
  f"Perhaps some arguments were wrongly wrapped into SigTo.\n"
941
960
  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"
961
+ f" * using the dials argument to control which parameters are live.\n"
962
+ f" * using the settings argument to control which parameters are not live.\n"
944
963
  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"
964
+ f" * using the @add_default_dials decorator to control which parameters are live.\n"
965
+ f" * using the @add_default_settings decorator to control which parameters are not live.\n"
947
966
  f"Original error: {e}"
948
967
  ) from e
949
968
 
@@ -1084,6 +1103,14 @@ class Synth(MutableMapping):
1084
1103
 
1085
1104
  for key, val in updates.items():
1086
1105
  target = raw_params[key] if raw_params else self.knobs[key]
1106
+
1107
+ if self._has_value_trans:
1108
+ if not isinstance(val, dict):
1109
+ val = self._value_trans[key](val)
1110
+ else:
1111
+ if "value" in val:
1112
+ val["value"] = self._value_trans[key](val["value"])
1113
+
1087
1114
  if isinstance(target, SigTo):
1088
1115
  if isinstance(val, dict):
1089
1116
  for attr in ["value", "time", "mul", "add"]:
hum-1.0.8/hum/util.py ADDED
@@ -0,0 +1,320 @@
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
+ # ----------------------------------------------------------------------------------
117
+ # Frequency snappers
118
+ # ----------------------------------------------------------------------------------
119
+
120
+ from bisect import bisect_left
121
+ from math import log2
122
+
123
+
124
+ class ListSnapper:
125
+ """
126
+ Snap to the nearest value in a list.
127
+
128
+ >>> snapper = ListSnapper([0, 1, 2, 3, 4, 5])
129
+ >>> snapper(2.3)
130
+ 2
131
+ >>> snapper(2.7)
132
+ 3
133
+ >>> snapper(2.5) # exactly the middle of 2 and 3; snaps to 2
134
+ 2
135
+
136
+ """
137
+
138
+ def __init__(self, snap_values):
139
+ self.snap_values = sorted(snap_values)
140
+
141
+ def __call__(self, x):
142
+ pos = bisect_left(self.snap_values, x)
143
+ if pos == 0:
144
+ return self.snap_values[0]
145
+ if pos == len(self.snap_values):
146
+ return self.snap_values[-1]
147
+ before = self.snap_values[pos - 1]
148
+ after = self.snap_values[pos]
149
+ return before if abs(x - before) <= abs(after - x) else after
150
+
151
+
152
+ class SnapToChromatic:
153
+ """
154
+ Snap to the nearest chromatic note in a tempered scale.
155
+ """
156
+
157
+ def __init__(self, base_tuning=440):
158
+ self.base_tuning = base_tuning
159
+
160
+ def __call__(self, x):
161
+ if x <= 0:
162
+ raise ValueError("Frequency must be positive")
163
+ midi_note = round(69 + 12 * log2(x / 440))
164
+ return 440 * 2 ** ((midi_note - 69) / 12)
165
+
166
+
167
+ DFLT_OCTAVE_RANGE = (0, 10)
168
+ DFLT_TUNING = 440.0 # A4 tuning frequency
169
+ DFLT_SCALE_MIDI_NOTES = (0, 2, 4, 5, 7, 9, 11) # C major scale
170
+
171
+
172
+ def tempered_semitone_frequencies(
173
+ tuning=DFLT_TUNING, octave_range=DFLT_OCTAVE_RANGE, digits=5
174
+ ):
175
+ """
176
+ Get a sorted list of frequencies for a given tuning and octave range.
177
+
178
+ :param tuning: The tuning frequency (default is 440 Hz).
179
+ It corresponds to A4 (that is, the 69th MIDI note).
180
+ :param octave_range: A tuple of two integers representing the range of octaves.
181
+
182
+ The first integer is the starting octave (inclusive), and the second integer is the ending octave (exclusive).
183
+ For example, (0, 10) will generate frequencies from C0 to B9.
184
+ The default is (0, 10), which covers a wide range of frequencies.
185
+ :return: A sorted list of frequencies in the specified octave range. The first (i.e. .[0]) frequency will correspond to a C.
186
+
187
+ >>> frequencies = tempered_semitone_frequencies()
188
+ >>> len(frequencies)
189
+ 120
190
+ >>> frequencies # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
191
+ [8.1758, 8.66196, 9.17702, 9.72272, ..., 7040.0, 7458.62018, 7902.13282]
192
+
193
+ """
194
+
195
+ assert len(octave_range) == 2, "octave_range must be a tuple of two integers"
196
+ n_octave_divisions = 12
197
+
198
+ def gen_freqs():
199
+ for octave in range(*octave_range):
200
+ base_midi = n_octave_divisions * octave
201
+ for st in range(n_octave_divisions):
202
+ midi_note = base_midi + st
203
+ freq = tuning * 2 ** ((midi_note - 69) / n_octave_divisions)
204
+ yield round(freq, digits)
205
+
206
+ return sorted(gen_freqs())
207
+
208
+
209
+ def scale_frequencies(
210
+ scale: Iterable[Union[float, int]] = DFLT_SCALE_MIDI_NOTES,
211
+ *,
212
+ tuning=DFLT_TUNING,
213
+ octave_range=DFLT_OCTAVE_RANGE,
214
+ ):
215
+ """
216
+ Get frequencies for a given scale.
217
+
218
+ :param scale: A list of integers representing the scale.
219
+ For example, (0, 2, 4, 5, 7, 9, 11) corresponds to the C major scale.
220
+ :param tuning: The tuning frequency (default is 440 Hz).
221
+ :param octave_range: A tuple of two integers representing the range of octaves.
222
+ :return: A list of frequencies corresponding to the notes in the given scale.
223
+ """
224
+ chromatic_scale = tempered_semitone_frequencies(
225
+ tuning=tuning, octave_range=octave_range
226
+ )
227
+ return [chromatic_scale[i] for i in range(len(chromatic_scale)) if i % 12 in scale]
228
+
229
+
230
+ # TODO: Add string_to_scale_map argument to convert string to midi note array scale
231
+ def scale_snapper(
232
+ scale: Iterable[Union[float, int]] = DFLT_SCALE_MIDI_NOTES,
233
+ *,
234
+ tuning=DFLT_TUNING,
235
+ octave_range=DFLT_OCTAVE_RANGE,
236
+ ):
237
+ """
238
+ Snap frequency to the nearest midi note of the midi_nodes list, modulo 12.
239
+
240
+ :param scale: A list of integers representing the scale.
241
+ For example, (0, 2, 4, 5, 7, 9, 11) (the default) corresponds to the C major scale.
242
+ :param tuning: The tuning frequency (default is 440 Hz).
243
+ It corresponds to A4 (that is, the 69th MIDI note).
244
+ :param octave_range: A tuple of two integers representing the range of octaves.
245
+ The first integer is the starting octave (inclusive), and the second integer is the ending octave (exclusive).
246
+ For example, (0, 10) will generate frequencies from C0 to B9.
247
+ The default is (0, 10), which covers a wide range of frequencies.
248
+
249
+ :return: A ListSnapper object that can be used to snap frequencies to the nearest note in the scale.
250
+
251
+ >>> snapper = scale_snapper()
252
+ >>> snapper(440.0) # A4
253
+ 440.0
254
+
255
+ If you're near that A4, `snapper` will snap to it:
256
+
257
+ >>> snapper(441.0)
258
+ 440.0
259
+ >>> snapper(439.0)
260
+ 440.0
261
+
262
+ But even if you're, say at A#, you'll still snap to A4 (since it's the closest note
263
+ of C major scale):
264
+
265
+ >>> snapper(466.16) # A#4
266
+ 440.0
267
+
268
+ If you are slightly higher than A#, you'll snap to B4
269
+
270
+ >>> snapper(467) # doctest: +ELLIPSIS
271
+ 493.8833...
272
+
273
+ """
274
+ _scale_frequencies = scale_frequencies(
275
+ scale=scale, tuning=tuning, octave_range=octave_range
276
+ )
277
+ # create a ListSnapper object
278
+ return ListSnapper(_scale_frequencies)
279
+
280
+
281
+ # ----------------------------------------------------------------------------------
282
+
283
+
284
+ def getmodulename(obj, default=""):
285
+ """Get name of module of object"""
286
+ return getattr(getmodule(obj), "__name__", default)
287
+
288
+
289
+ class ModuleNotFoundErrorNiceMessage:
290
+ def __init__(self, msg=None):
291
+ self.msg = msg
292
+
293
+ def __enter__(self):
294
+ pass
295
+
296
+ def __exit__(self, exc_type, exc_val, exc_tb):
297
+ if exc_type is ModuleNotFoundError:
298
+ msg = (
299
+ self.msg
300
+ or f"""
301
+ It seems you don't have required `{exc_val.name}` package for this Store.
302
+ Try installing it by running:
303
+
304
+ pip install {exc_val.name}
305
+
306
+ in your terminal.
307
+ For more information: https://pypi.org/project/{exc_val.name}
308
+ """
309
+ )
310
+ warn(msg)
311
+
312
+
313
+ class ModuleNotFoundIgnore:
314
+ def __enter__(self):
315
+ pass
316
+
317
+ def __exit__(self, exc_type, exc_val, exc_tb):
318
+ if exc_type is ModuleNotFoundError:
319
+ pass
320
+ 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.8
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.8
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