pyquist 0.2.3__tar.gz → 0.2.5__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.
Files changed (33) hide show
  1. {pyquist-0.2.3/pyquist.egg-info → pyquist-0.2.5}/PKG-INFO +1 -1
  2. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/__init__.py +1 -1
  3. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/audio.py +87 -71
  4. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/cli.py +16 -4
  5. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/device.py +13 -6
  6. {pyquist-0.2.3 → pyquist-0.2.5/pyquist.egg-info}/PKG-INFO +1 -1
  7. {pyquist-0.2.3 → pyquist-0.2.5}/LICENSE +0 -0
  8. {pyquist-0.2.3 → pyquist-0.2.5}/README.md +0 -0
  9. {pyquist-0.2.3 → pyquist-0.2.5}/pyproject.toml +0 -0
  10. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/audio_test.py +0 -0
  11. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/device_test.py +0 -0
  12. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/helper.py +0 -0
  13. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/helper_test.py +0 -0
  14. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/paths.py +0 -0
  15. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/plot.py +0 -0
  16. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/plot_test.py +0 -0
  17. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/py.typed +0 -0
  18. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/score.py +0 -0
  19. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/score_test.py +0 -0
  20. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
  21. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
  22. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
  23. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/test_data/ATTRIBUTION.md +0 -0
  24. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/test_data/ravel_bolero.mid +0 -0
  25. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/web/__init__.py +0 -0
  26. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/web/freesound.py +0 -0
  27. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist/web/theorytab.py +0 -0
  28. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist.egg-info/SOURCES.txt +0 -0
  29. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist.egg-info/dependency_links.txt +0 -0
  30. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist.egg-info/entry_points.txt +0 -0
  31. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist.egg-info/requires.txt +0 -0
  32. {pyquist-0.2.3 → pyquist-0.2.5}/pyquist.egg-info/top_level.txt +0 -0
  33. {pyquist-0.2.3 → pyquist-0.2.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Barebones utilities for low-level computer music programming in Python and NumPy. Teaching library for CMU 15-322.
5
5
  Author: Chris Donahue
6
6
  License-Expression: MIT
@@ -1,4 +1,4 @@
1
- __version__ = "0.2.3"
1
+ __version__ = "0.2.5"
2
2
 
3
3
  from .audio import Audio
4
4
  from .device import (
@@ -25,12 +25,13 @@ in-place variants), all returning ``Audio``::
25
25
  mix = riff + drums[: len(riff)] # sum the overlapping region
26
26
  mix *= 0.5 # halve the amplitude in place
27
27
 
28
- On top of that it offers music-specific helpers that return new ``Audio``
29
- objects::
28
+ On top of that it offers music-specific helpers. Some derive a new ``Audio``
29
+ and leave the original alone; others (``normalize``, ``clip``, ``pan``) adjust
30
+ levels in place by default, with ``in_place=False`` to get a copy instead::
30
31
 
31
- clip = mix.as_mono().segment(offset=1.0, duration=3.0).resample(8000)
32
- clip.normalize(peak_dbfs=-1.0)
33
- clip.write("clip.wav")
32
+ excerpt = mix.as_mono().segment(offset=1.0, duration=3.0).resample(8000)
33
+ excerpt.normalize(peak_dbfs=-1.0) # in place
34
+ excerpt.write("excerpt.wav")
34
35
 
35
36
  See :meth:`Audio.zeros` for a silent destination buffer (or
36
37
  :meth:`Audio.empty` for an uninitialized one) and
@@ -69,6 +70,8 @@ class Audio:
69
70
  >>> pq.play(audio)
70
71
  """
71
72
 
73
+ # --- Construction -------------------------------------------------------
74
+
72
75
  def __init__(
73
76
  self,
74
77
  samples: np.ndarray,
@@ -191,6 +194,15 @@ class Audio:
191
194
  samples = np.concatenate([a.samples for a in audios], axis=0)
192
195
  return cls(samples, sample_rate=sample_rates.pop())
193
196
 
197
+ def copy(self) -> "Audio":
198
+ """Returns a deep copy of this ``Audio``.
199
+
200
+ The returned ``Audio`` owns a fresh copy of the sample array, so
201
+ in-place mutations of either one leave the other untouched.
202
+ ``sample_rate`` is carried over.
203
+ """
204
+ return Audio(self._samples.copy(), sample_rate=self._sample_rate)
205
+
194
206
  # --- Core attributes ----------------------------------------------------
195
207
 
196
208
  @property
@@ -261,7 +273,7 @@ class Audio:
261
273
  raise ValueError(f"sample_rate must be positive, got {value}.")
262
274
  self._sample_rate = int(value)
263
275
 
264
- # --- Shape-derived properties ------------------------------------------
276
+ # --- Derived properties -------------------------------------------------
265
277
 
266
278
  @property
267
279
  def num_samples(self) -> int:
@@ -297,7 +309,7 @@ class Audio:
297
309
  return 0.0
298
310
  return float(np.abs(self._samples).max())
299
311
 
300
- # --- Mutation methods ---------------------------------------------------
312
+ # --- In-place methods ---------------------------------------------------
301
313
 
302
314
  def clear(self) -> None:
303
315
  """Fills the audio with silence (zeros) in place.
@@ -306,41 +318,6 @@ class Audio:
306
318
  """
307
319
  self._samples.fill(0.0)
308
320
 
309
- def segment(
310
- self,
311
- *,
312
- offset: Optional[float] = None,
313
- duration: Optional[float] = None,
314
- ) -> "Audio":
315
- """Returns a new ``Audio`` containing a time-slice of this one.
316
-
317
- Both ``offset`` and ``duration`` are in seconds and require
318
- ``sample_rate`` to be set. Out-of-range values are clamped: a negative
319
- ``offset`` is treated as zero, and a ``duration`` that runs past the
320
- end is truncated. With both arguments ``None`` this is a no-op that
321
- returns ``self``.
322
-
323
- Args:
324
- offset: Start time in seconds. Defaults to the beginning.
325
- duration: Length in seconds. Defaults to the rest of the audio.
326
-
327
- Returns:
328
- A new ``Audio`` carrying the same ``sample_rate`` as ``self``.
329
- """
330
- if offset is None and duration is None:
331
- return self
332
- if self._sample_rate is None:
333
- raise ValueError("segment() requires a sample_rate.")
334
- start = max(0, int((offset or 0.0) * self._sample_rate))
335
- end = (
336
- self.num_samples
337
- if duration is None
338
- else start + int(duration * self._sample_rate)
339
- )
340
- start = min(start, self.num_samples)
341
- end = max(start, min(end, self.num_samples))
342
- return Audio(self._samples[start:end, :], sample_rate=self._sample_rate)
343
-
344
321
  def normalize(self, *, peak_dbfs: float = 0.0, in_place: bool = True) -> "Audio":
345
322
  """Scales the audio so its peak amplitude matches ``peak_dbfs``.
346
323
 
@@ -384,35 +361,6 @@ class Audio:
384
361
  return self
385
362
  return Audio(clipped, sample_rate=self._sample_rate)
386
363
 
387
- def as_mono(self) -> "Audio":
388
- """Returns a mono (1-channel) version of the audio.
389
-
390
- Multi-channel audio is mixed down by averaging across channels
391
- (mean, not sum), which preserves perceived loudness without risking
392
- clipping. If the audio is already mono, returns ``self`` (no copy).
393
- """
394
- if self.num_channels == 1:
395
- return self
396
- mono = self._samples.mean(axis=1, keepdims=True).astype(np.float32)
397
- return Audio(mono, sample_rate=self._sample_rate)
398
-
399
- def as_stereo(self) -> "Audio":
400
- """Returns a stereo (2-channel) version of the audio.
401
-
402
- Mono audio is duplicated across both channels (the same signal in
403
- L and R). Stereo audio is returned as ``self`` (no copy). Audio with
404
- 3 or more channels raises ``ValueError`` — this method does not try
405
- to guess a downmix.
406
- """
407
- if self.num_channels == 2:
408
- return self
409
- if self.num_channels == 1:
410
- stereo = np.repeat(self._samples, 2, axis=1)
411
- return Audio(stereo, sample_rate=self._sample_rate)
412
- raise ValueError(
413
- f"Cannot convert audio with {self.num_channels} channels to stereo."
414
- )
415
-
416
364
  def pan(self, position: float = 0.0, *, in_place: bool = True) -> "Audio":
417
365
  """Pans stereo audio to ``position`` using an equal-power pan law.
418
366
 
@@ -446,6 +394,72 @@ class Audio:
446
394
  return self
447
395
  return Audio(self._samples * gains, sample_rate=self._sample_rate)
448
396
 
397
+ # --- Derived audio ------------------------------------------------------
398
+
399
+ def segment(
400
+ self,
401
+ *,
402
+ offset: Optional[float] = None,
403
+ duration: Optional[float] = None,
404
+ ) -> "Audio":
405
+ """Returns a new ``Audio`` containing a time-slice of this one.
406
+
407
+ Both ``offset`` and ``duration`` are in seconds and require
408
+ ``sample_rate`` to be set. Out-of-range values are clamped: a negative
409
+ ``offset`` is treated as zero, and a ``duration`` that runs past the
410
+ end is truncated. With both arguments ``None`` this is a no-op that
411
+ returns ``self``.
412
+
413
+ Args:
414
+ offset: Start time in seconds. Defaults to the beginning.
415
+ duration: Length in seconds. Defaults to the rest of the audio.
416
+
417
+ Returns:
418
+ A new ``Audio`` carrying the same ``sample_rate`` as ``self``.
419
+ """
420
+ if offset is None and duration is None:
421
+ return self
422
+ if self._sample_rate is None:
423
+ raise ValueError("segment() requires a sample_rate.")
424
+ start = max(0, int((offset or 0.0) * self._sample_rate))
425
+ end = (
426
+ self.num_samples
427
+ if duration is None
428
+ else start + int(duration * self._sample_rate)
429
+ )
430
+ start = min(start, self.num_samples)
431
+ end = max(start, min(end, self.num_samples))
432
+ return Audio(self._samples[start:end, :], sample_rate=self._sample_rate)
433
+
434
+ def as_mono(self) -> "Audio":
435
+ """Returns a mono (1-channel) version of the audio.
436
+
437
+ Multi-channel audio is mixed down by averaging across channels
438
+ (mean, not sum), which preserves perceived loudness without risking
439
+ clipping. If the audio is already mono, returns ``self`` (no copy).
440
+ """
441
+ if self.num_channels == 1:
442
+ return self
443
+ mono = self._samples.mean(axis=1, keepdims=True).astype(np.float32)
444
+ return Audio(mono, sample_rate=self._sample_rate)
445
+
446
+ def as_stereo(self) -> "Audio":
447
+ """Returns a stereo (2-channel) version of the audio.
448
+
449
+ Mono audio is duplicated across both channels (the same signal in
450
+ L and R). Stereo audio is returned as ``self`` (no copy). Audio with
451
+ 3 or more channels raises ``ValueError`` — this method does not try
452
+ to guess a downmix.
453
+ """
454
+ if self.num_channels == 2:
455
+ return self
456
+ if self.num_channels == 1:
457
+ stereo = np.repeat(self._samples, 2, axis=1)
458
+ return Audio(stereo, sample_rate=self._sample_rate)
459
+ raise ValueError(
460
+ f"Cannot convert audio with {self.num_channels} channels to stereo."
461
+ )
462
+
449
463
  def resample(self, new_sample_rate: int, **kwargs) -> "Audio":
450
464
  """Returns a new ``Audio`` resampled to ``new_sample_rate``.
451
465
 
@@ -469,6 +483,8 @@ class Audio:
469
483
  )
470
484
  return Audio(resampled, sample_rate=new_sample_rate)
471
485
 
486
+ # --- File I/O -----------------------------------------------------------
487
+
472
488
  def write(self, file: Union[str, IO], **kwargs) -> None:
473
489
  """Writes the audio to a file via ``soundfile``.
474
490
 
@@ -22,9 +22,11 @@ from .web.freesound import fetch_freesound
22
22
 
23
23
 
24
24
  def _cmd_devices(args: argparse.Namespace) -> None:
25
- del args
26
- set_input_device(update_default=True)
27
- set_output_device(update_default=True)
25
+ # No kind given means both, one after the other.
26
+ if args.kind in (None, "in"):
27
+ set_input_device(update_default=True)
28
+ if args.kind in (None, "out"):
29
+ set_output_device(update_default=True)
28
30
  print("Saved as default for future pyquist sessions.")
29
31
 
30
32
 
@@ -32,7 +34,7 @@ def _cmd_play(args: argparse.Namespace) -> None:
32
34
  # "test" is a shorthand for the bundled sample, so users can check that
33
35
  # audio output works without having an audio file on hand.
34
36
  if args.input.strip().lower() == "test":
35
- audio = Audio.from_file(TEST_SOUND).segment(duration=1.0)
37
+ audio = Audio.from_file(TEST_SOUND).as_mono().segment(duration=1.0)
36
38
  audio *= np.linspace(1.0, 0.0, audio.num_samples)[:, np.newaxis]
37
39
  else:
38
40
  audio = Audio.from_file(args.input)
@@ -71,6 +73,16 @@ def _build_parser() -> argparse.ArgumentParser:
71
73
  p_devices = subparsers.add_parser(
72
74
  "devices", help="Interactively select default input and output devices."
73
75
  )
76
+ p_devices.add_argument(
77
+ "kind",
78
+ nargs="?",
79
+ type=lambda s: {"input": "in", "output": "out"}.get(s.lower(), s.lower()),
80
+ choices=["in", "out"],
81
+ help=(
82
+ "Select only the input ('in' / 'input') or only the output "
83
+ "('out' / 'output') device. Omit to select both."
84
+ ),
85
+ )
74
86
  p_devices.set_defaults(func=_cmd_devices)
75
87
 
76
88
  p_play = subparsers.add_parser("play", help="Play an audio file.")
@@ -15,12 +15,16 @@ import sounddevice as sd
15
15
  import tqdm
16
16
 
17
17
  from .audio import Audio
18
+ from .helper import db_to_amplitude
18
19
  from .paths import CACHE_DIR
19
20
 
20
21
  _DEFAULTS_PATH = CACHE_DIR / "device_defaults.json"
21
22
 
22
23
  DeviceRef = Union[int, str]
23
24
 
25
+ # Peak ceiling applied by ``play(safe=True)``.
26
+ _SAFE_PEAK_DBFS = -18.0
27
+
24
28
 
25
29
  def set_input_device(
26
30
  device_id_or_name: Optional[DeviceRef] = None,
@@ -124,8 +128,8 @@ def play(
124
128
 
125
129
  Args:
126
130
  audio: The audio to play. Must have a ``sample_rate``.
127
- safe: If True (default), attenuates the audio to -18 dBFS before
128
- playback to protect ears against accidentally hot signals.
131
+ safe: If True (default), limits the peak amplitude to -18 dBFS
132
+ before playback to protect ears against accidentally hot signals.
129
133
  normalize: If True, normalizes the audio to 0 dBFS before playback.
130
134
  force_sounddevice: If True, always use sounddevice playback, even
131
135
  when called from a notebook. Useful when you want the audio
@@ -138,11 +142,14 @@ def play(
138
142
  if audio.sample_rate is None:
139
143
  raise ValueError("sample_rate is None; cannot play audio.")
140
144
 
145
+ # Copy up front so the caller's Audio is never touched, then do every
146
+ # level adjustment in place on that copy.
147
+ audio = audio.copy()
141
148
  if normalize:
142
- audio = audio.normalize(in_place=False)
143
- audio = audio.clip(in_place=False)
144
- if safe:
145
- audio = audio.normalize(peak_dbfs=-18.0, in_place=False)
149
+ audio.normalize()
150
+ audio.clip()
151
+ if safe and audio.peak_amplitude > db_to_amplitude(_SAFE_PEAK_DBFS):
152
+ audio.normalize(peak_dbfs=_SAFE_PEAK_DBFS)
146
153
 
147
154
  if not force_sounddevice and _in_ipython_notebook():
148
155
  # Imported lazily so headless / non-notebook usage doesn't need IPython.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Barebones utilities for low-level computer music programming in Python and NumPy. Teaching library for CMU 15-322.
5
5
  Author: Chris Donahue
6
6
  License-Expression: MIT
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