pyquist 0.1.0__py3-none-any.whl

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.
pyquist/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from .audio import Audio
4
+ from .device import (
5
+ play,
6
+ record,
7
+ set_input_device,
8
+ set_output_device,
9
+ )
10
+ from .paths import LIB_DIR
11
+ from .plot import plot, plot_freq, plot_spec
12
+ from .score import (
13
+ BasicMetronome,
14
+ Event,
15
+ Metronome,
16
+ Score,
17
+ )
18
+
19
+ __all__ = [
20
+ "__version__",
21
+ "Audio",
22
+ "BasicMetronome",
23
+ "Metronome",
24
+ "Score",
25
+ "Event",
26
+ "play",
27
+ "plot",
28
+ "plot_freq",
29
+ "plot_spec",
30
+ "record",
31
+ "set_input_device",
32
+ "set_output_device",
33
+ ]
34
+
35
+
36
+ # NOTE: This changes the test discovery pattern from "test*.py" (default) to "*test.py".
37
+ def load_tests(loader, standard_tests, pattern):
38
+ package_tests = loader.discover(start_dir=LIB_DIR, pattern="*test.py")
39
+ standard_tests.addTests(package_tests)
40
+ return standard_tests
pyquist/audio.py ADDED
@@ -0,0 +1,505 @@
1
+ import pathlib
2
+ from io import BytesIO
3
+ from typing import IO, Optional, Union
4
+ from urllib.request import urlopen
5
+
6
+ import numpy as np
7
+ import resampy
8
+ import soundfile as sf
9
+
10
+ from .helper import db_to_amplitude
11
+
12
+
13
+ class Audio:
14
+ """A wrapper around a 2D float32 numpy array of audio samples.
15
+
16
+ The two primary attributes are :attr:`samples` (a ``float32`` array
17
+ shaped ``(num_samples, num_channels)``) and :attr:`sample_rate` (Hz, or
18
+ ``None`` for buffers without a defined rate). By convention, sample
19
+ values in ``[-1.0, 1.0]`` correspond to digital full-scale amplitude;
20
+ values outside this range are valid in memory but will clip when sent
21
+ to playback or written to most file formats.
22
+
23
+ Example:
24
+ >>> import numpy as np
25
+ >>> import pyquist as pq
26
+ >>> sr = 44100
27
+ >>> t = np.arange(sr) / sr
28
+ >>> audio = pq.Audio(np.sin(2 * np.pi * 440 * t), sample_rate=sr)
29
+ >>> pq.play(audio)
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ samples: np.ndarray,
35
+ sample_rate: Optional[int] = None,
36
+ ):
37
+ """Wraps an existing numpy array as ``Audio``.
38
+
39
+ Args:
40
+ samples: A numpy array of samples. Accepted as 0-D, 1-D, or 2-D
41
+ (see the ``samples`` setter for shape normalization). Must be
42
+ ``float32`` or ``float64`` (the latter is auto-converted).
43
+ sample_rate: Optional sample rate in Hz; ``None`` for unspecified
44
+ (e.g. when used as a real-time block buffer).
45
+ """
46
+ self.samples = samples
47
+ self.sample_rate = sample_rate
48
+
49
+ @classmethod
50
+ def zeros(
51
+ cls,
52
+ num_samples: int,
53
+ num_channels: int,
54
+ sample_rate: Optional[int] = None,
55
+ ) -> "Audio":
56
+ """Creates a silent (zero-filled) ``Audio`` of the given shape.
57
+
58
+ Useful as a destination buffer that you fill in via ``audio.samples``
59
+ or via in-place arithmetic.
60
+
61
+ Args:
62
+ num_samples: Number of samples per channel. Must be ``>= 0``.
63
+ num_channels: Number of channels (1 for mono, 2 for stereo).
64
+ Must be ``>= 0``.
65
+ sample_rate: Optional sample rate in Hz.
66
+ """
67
+ if num_samples < 0:
68
+ raise ValueError("num_samples must be non-negative.")
69
+ if num_channels < 0:
70
+ raise ValueError("num_channels must be non-negative.")
71
+ return cls(
72
+ np.zeros((num_samples, num_channels), dtype=np.float32),
73
+ sample_rate=sample_rate,
74
+ )
75
+
76
+ @classmethod
77
+ def from_file(cls, file: Union[str, pathlib.Path, IO]) -> "Audio":
78
+ """Loads an ``Audio`` from a file on disk or a file-like object.
79
+
80
+ Decoding is delegated to ``soundfile`` (libsndfile), which supports
81
+ WAV, FLAC, OGG, MP3, and most common formats. The file's native sample
82
+ rate is preserved; channels remain in their original order. Use
83
+ :meth:`resample` to change the rate after loading.
84
+
85
+ Raises :class:`FileNotFoundError` (with the offending path) when
86
+ ``file`` is a path that doesn't exist — clearer than libsndfile's
87
+ generic ``"System error"`` message.
88
+ """
89
+ # Pre-check path-like inputs so a missing file produces a useful error
90
+ # instead of LibsndfileError: "Error opening ...: System error.".
91
+ if isinstance(file, (str, pathlib.Path)):
92
+ path = pathlib.Path(file)
93
+ if not path.exists():
94
+ raise FileNotFoundError(f"Audio file not found: {path}.")
95
+ samples, sample_rate = sf.read(file)
96
+ return cls(samples, sample_rate=sample_rate)
97
+
98
+ @classmethod
99
+ def from_url(cls, url: str) -> "Audio":
100
+ """Downloads an audio file from a URL and loads it as ``Audio``.
101
+
102
+ The full response is buffered in memory before decoding.
103
+ """
104
+ return cls.from_file(BytesIO(urlopen(url).read()))
105
+
106
+ # --- Core attributes ----------------------------------------------------
107
+
108
+ @property
109
+ def samples(self) -> np.ndarray:
110
+ """The underlying ``(num_samples, num_channels)`` ``float32`` array.
111
+
112
+ Returned by reference: in-place mutations (``audio.samples[0] = 0``,
113
+ ``audio.samples *= 0.5``) modify the audio directly. Reassigning the
114
+ attribute (``audio.samples = new_array``) re-runs validation.
115
+ """
116
+ return self._samples
117
+
118
+ @samples.setter
119
+ def samples(self, value: np.ndarray) -> None:
120
+ """Validates and stores ``value`` as the underlying sample array.
121
+
122
+ Three conveniences are applied before validation:
123
+
124
+ * a 0-D array becomes shape ``(1, 1)``;
125
+ * a 1-D array of length ``n`` becomes shape ``(n, 1)`` (mono);
126
+ * a ``float64`` array is cast to ``float32``.
127
+
128
+ Anything else with the wrong dtype raises ``TypeError``; arrays with
129
+ more than 2 dimensions raise ``ValueError``. When ``value`` is already
130
+ a 2-D ``float32`` array, it is stored by reference (no copy) — this
131
+ is what allows ``Audio`` to act as a thin view over an externally
132
+ owned buffer (e.g. the ``outdata`` array in a real-time callback).
133
+ """
134
+ if not isinstance(value, np.ndarray):
135
+ raise TypeError(
136
+ f"samples must be a numpy.ndarray, got {type(value).__name__}."
137
+ )
138
+ if value.ndim == 0:
139
+ value = value[np.newaxis, np.newaxis]
140
+ elif value.ndim == 1:
141
+ value = value[:, np.newaxis]
142
+ elif value.ndim > 2:
143
+ raise ValueError(
144
+ f"samples must have shape (num_samples, num_channels); "
145
+ f"got array with {value.ndim} dimensions."
146
+ )
147
+ if value.dtype == np.float64:
148
+ value = value.astype(np.float32)
149
+ if value.dtype != np.float32:
150
+ raise TypeError(f"samples must have dtype np.float32, got {value.dtype}.")
151
+ self._samples = value
152
+
153
+ @property
154
+ def sample_rate(self) -> Optional[int]:
155
+ """The sample rate in Hz, or ``None`` if unspecified."""
156
+ return self._sample_rate
157
+
158
+ @sample_rate.setter
159
+ def sample_rate(self, value: Optional[int]) -> None:
160
+ """Sets the sample rate.
161
+
162
+ Accepts a positive ``int`` or ``None``. Non-int values raise
163
+ ``TypeError``; zero or negative values raise ``ValueError``.
164
+ """
165
+ if value is None:
166
+ self._sample_rate = None
167
+ return
168
+ if not isinstance(value, (int, np.integer)):
169
+ raise TypeError(
170
+ f"sample_rate must be int or None, got {type(value).__name__}."
171
+ )
172
+ if value <= 0:
173
+ raise ValueError(f"sample_rate must be positive, got {value}.")
174
+ self._sample_rate = int(value)
175
+
176
+ # --- Shape-derived properties ------------------------------------------
177
+
178
+ @property
179
+ def num_samples(self) -> int:
180
+ """Number of samples per channel (``samples.shape[0]``)."""
181
+ return self._samples.shape[0]
182
+
183
+ @property
184
+ def num_channels(self) -> int:
185
+ """Number of channels (``samples.shape[1]``); 1 for mono, 2 for stereo."""
186
+ return self._samples.shape[1]
187
+
188
+ @property
189
+ def shape(self) -> tuple:
190
+ """Shape of the underlying array: ``(num_samples, num_channels)``."""
191
+ return self._samples.shape
192
+
193
+ @property
194
+ def duration(self) -> float:
195
+ """Duration of the audio in seconds. Requires sample_rate to be set."""
196
+ if self._sample_rate is None:
197
+ raise ValueError("Cannot compute duration without a sample_rate.")
198
+ return self.num_samples / self._sample_rate
199
+
200
+ @property
201
+ def peak_amplitude(self) -> float:
202
+ """Peak absolute sample value across all samples and channels.
203
+
204
+ This is a linear amplitude (not decibels): ``1.0`` corresponds to
205
+ digital full scale. Empty audio returns ``0.0``. Use
206
+ :func:`pyquist.helper.amplitude_to_db` to convert to dBFS.
207
+ """
208
+ if self._samples.size == 0:
209
+ return 0.0
210
+ return float(np.abs(self._samples).max())
211
+
212
+ # --- Mutation methods ---------------------------------------------------
213
+
214
+ def clear(self) -> None:
215
+ """Fills the audio with silence (zeros) in place.
216
+
217
+ Shape, dtype, and ``sample_rate`` are unchanged.
218
+ """
219
+ self._samples.fill(0.0)
220
+
221
+ def segment(
222
+ self,
223
+ *,
224
+ offset: Optional[float] = None,
225
+ duration: Optional[float] = None,
226
+ ) -> "Audio":
227
+ """Returns a new ``Audio`` containing a time-slice of this one.
228
+
229
+ Both ``offset`` and ``duration`` are in seconds and require
230
+ ``sample_rate`` to be set. Out-of-range values are clamped: a negative
231
+ ``offset`` is treated as zero, and a ``duration`` that runs past the
232
+ end is truncated. With both arguments ``None`` this is a no-op that
233
+ returns ``self``.
234
+
235
+ Args:
236
+ offset: Start time in seconds. Defaults to the beginning.
237
+ duration: Length in seconds. Defaults to the rest of the audio.
238
+
239
+ Returns:
240
+ A new ``Audio`` carrying the same ``sample_rate`` as ``self``.
241
+ """
242
+ if offset is None and duration is None:
243
+ return self
244
+ if self._sample_rate is None:
245
+ raise ValueError("segment() requires a sample_rate.")
246
+ start = max(0, int((offset or 0.0) * self._sample_rate))
247
+ end = (
248
+ self.num_samples
249
+ if duration is None
250
+ else start + int(duration * self._sample_rate)
251
+ )
252
+ start = min(start, self.num_samples)
253
+ end = max(start, min(end, self.num_samples))
254
+ return Audio(self._samples[start:end, :], sample_rate=self._sample_rate)
255
+
256
+ def normalize(self, *, peak_dbfs: float = 0.0, in_place: bool = True) -> "Audio":
257
+ """Scales the audio so its peak amplitude matches ``peak_dbfs``.
258
+
259
+ ``peak_dbfs`` is measured in decibels relative to digital full scale
260
+ (dBFS). ``0.0`` means full-scale (peak = 1.0); ``-6.0`` means roughly
261
+ half full-scale (peak ≈ 0.501); positive values exceed full scale and
262
+ will clip on playback. Silent audio (all zeros) is returned unchanged.
263
+
264
+ Args:
265
+ peak_dbfs: Target peak level in dBFS. Defaults to ``0.0``.
266
+ in_place: If ``True`` (default), modifies and returns ``self``.
267
+ If ``False``, returns a new ``Audio`` and leaves the original
268
+ untouched.
269
+ """
270
+ peak = self.peak_amplitude
271
+ if peak == 0.0:
272
+ gain = 1.0
273
+ else:
274
+ gain = float(db_to_amplitude(peak_dbfs)) / peak
275
+ if in_place:
276
+ self._samples *= gain
277
+ return self
278
+ return Audio(self._samples * gain, sample_rate=self._sample_rate)
279
+
280
+ def clip(self, *, peak_amplitude: float = 1.0, in_place: bool = True) -> "Audio":
281
+ """Symmetrically clamps every sample to ``[-peak_amplitude, +peak_amplitude]``.
282
+
283
+ This is a hard clip — samples beyond the threshold are truncated, not
284
+ scaled. To rescale instead, use :meth:`normalize`.
285
+
286
+ Args:
287
+ peak_amplitude: Symmetric clip threshold in linear amplitude.
288
+ Defaults to ``1.0`` (digital full scale).
289
+ in_place: If ``True`` (default), modifies and returns ``self``.
290
+ If ``False``, returns a new ``Audio`` and leaves the original
291
+ untouched.
292
+ """
293
+ clipped = np.clip(self._samples, -peak_amplitude, peak_amplitude)
294
+ if in_place:
295
+ self._samples[:] = clipped
296
+ return self
297
+ return Audio(clipped, sample_rate=self._sample_rate)
298
+
299
+ def as_mono(self) -> "Audio":
300
+ """Returns a mono (1-channel) version of the audio.
301
+
302
+ Multi-channel audio is mixed down by averaging across channels
303
+ (mean, not sum), which preserves perceived loudness without risking
304
+ clipping. If the audio is already mono, returns ``self`` (no copy).
305
+ """
306
+ if self.num_channels == 1:
307
+ return self
308
+ mono = self._samples.mean(axis=1, keepdims=True).astype(np.float32)
309
+ return Audio(mono, sample_rate=self._sample_rate)
310
+
311
+ def as_stereo(self) -> "Audio":
312
+ """Returns a stereo (2-channel) version of the audio.
313
+
314
+ Mono audio is duplicated across both channels (the same signal in
315
+ L and R). Stereo audio is returned as ``self`` (no copy). Audio with
316
+ 3 or more channels raises ``ValueError`` — this method does not try
317
+ to guess a downmix.
318
+ """
319
+ if self.num_channels == 2:
320
+ return self
321
+ if self.num_channels == 1:
322
+ stereo = np.repeat(self._samples, 2, axis=1)
323
+ return Audio(stereo, sample_rate=self._sample_rate)
324
+ raise ValueError(
325
+ f"Cannot convert audio with {self.num_channels} channels to stereo."
326
+ )
327
+
328
+ def resample(self, new_sample_rate: int, **kwargs) -> "Audio":
329
+ """Returns a new ``Audio`` resampled to ``new_sample_rate``.
330
+
331
+ Resampling is performed by ``resampy`` using a polyphase bandlimited
332
+ filter; extra keyword arguments (e.g. ``filter='kaiser_fast'``) are
333
+ forwarded to :func:`resampy.resample`. The number of channels is
334
+ preserved; the number of samples scales by
335
+ ``new_sample_rate / self.sample_rate``.
336
+
337
+ Raises ``ValueError`` if ``self.sample_rate`` is ``None`` or
338
+ ``new_sample_rate`` is non-positive.
339
+ """
340
+ if self._sample_rate is None:
341
+ raise ValueError("Cannot resample without a sample_rate.")
342
+ if not isinstance(new_sample_rate, (int, np.integer)):
343
+ raise TypeError("new_sample_rate must be an int.")
344
+ if new_sample_rate <= 0:
345
+ raise ValueError("new_sample_rate must be positive.")
346
+ resampled = resampy.resample(
347
+ self._samples, self._sample_rate, new_sample_rate, axis=0, **kwargs
348
+ )
349
+ return Audio(resampled, sample_rate=new_sample_rate)
350
+
351
+ def write(self, file: Union[str, IO], **kwargs) -> None:
352
+ """Writes the audio to a file via ``soundfile``.
353
+
354
+ The output format is inferred from the file extension (``.wav``,
355
+ ``.flac``, ``.ogg``, ...). Extra keyword arguments are forwarded to
356
+ :func:`soundfile.write` (e.g. ``subtype='PCM_24'``). Samples outside
357
+ ``[-1.0, 1.0]`` will clip in fixed-point formats; consider calling
358
+ :meth:`clip` or :meth:`normalize` first.
359
+
360
+ Raises ``ValueError`` if ``self.sample_rate`` is ``None``.
361
+ """
362
+ if self._sample_rate is None:
363
+ raise ValueError("Cannot write audio without a sample_rate.")
364
+ sf.write(file, self._samples, self._sample_rate, **kwargs)
365
+
366
+ # --- numpy interop ------------------------------------------------------
367
+
368
+ def __array__(self, dtype=None, copy=None) -> np.ndarray:
369
+ """NumPy's "convert to ndarray" hook.
370
+
371
+ Lets ``Audio`` be passed transparently to any function that calls
372
+ ``np.asarray(...)`` internally (``np.mean``, ``np.fft.rfft``,
373
+ ``matplotlib.plot``, ...). Returns the underlying samples by
374
+ reference on the fast path; copies only when the caller requests
375
+ a dtype change or ``copy=True``.
376
+ """
377
+ if dtype is None and not copy:
378
+ return self._samples
379
+ return self._samples.astype(dtype if dtype is not None else self._samples.dtype)
380
+
381
+ # --- Indexing / length --------------------------------------------------
382
+
383
+ def __len__(self) -> int:
384
+ return self.num_samples
385
+
386
+ def __getitem__(self, key) -> "Audio":
387
+ """Returns a new ``Audio`` wrapping the indexed samples.
388
+
389
+ Only patterns that preserve the ``(num_samples, num_channels)``
390
+ layout are accepted — i.e., the sample axis (axis 0) must be
391
+ sliced, not collapsed to a single int. Examples (``audio`` has
392
+ shape ``(10000, 2)``)::
393
+
394
+ audio[1000:2000] # → Audio with shape (1000, 2)
395
+ audio[:, 0] # → Audio with shape (10000, 1)
396
+ audio[1000:2000, 1:3] # → Audio with shape (1000, 2)
397
+
398
+ Indexing axis 0 with a single ``int`` (``audio[1000]``,
399
+ ``audio[0, 0]``) is rejected with ``TypeError`` — it's ambiguous
400
+ as Audio, and almost always either a scalar read (use
401
+ ``audio.samples[i, j]``) or a length-1 slice (use
402
+ ``audio[i:i+1]``).
403
+
404
+ The returned ``Audio`` is a view of the underlying samples when
405
+ the key supports it, and carries the same ``sample_rate``.
406
+ """
407
+ first = key[0] if isinstance(key, tuple) and key else key
408
+ if isinstance(first, (int, np.integer)):
409
+ raise TypeError(
410
+ f"Audio[...] does not support indexing the sample axis with "
411
+ f"a single int (got {key!r}). Use audio.samples[...] for raw "
412
+ f"numpy access, or audio[i:i+1] for a length-1 Audio."
413
+ )
414
+ return Audio(self._samples[key], sample_rate=self._sample_rate)
415
+
416
+ def __setitem__(self, key, value) -> None:
417
+ self._samples[key] = value
418
+
419
+ # --- Arithmetic ---------------------------------------------------------
420
+
421
+ def _check_compatible(self, other: "Audio") -> Optional[int]:
422
+ """Validates that ``other`` can be combined with ``self`` and returns
423
+ the sample rate the result should carry."""
424
+ if self.shape != other.shape:
425
+ raise ValueError(f"Shape mismatch: {self.shape} vs {other.shape}.")
426
+ if (
427
+ self._sample_rate is not None
428
+ and other._sample_rate is not None
429
+ and self._sample_rate != other._sample_rate
430
+ ):
431
+ raise ValueError(
432
+ f"Sample rate mismatch: {self._sample_rate} != {other._sample_rate}."
433
+ )
434
+ return (
435
+ self._sample_rate if self._sample_rate is not None else other._sample_rate
436
+ )
437
+
438
+ def _binary_op(self, other, op) -> "Audio":
439
+ if isinstance(other, Audio):
440
+ sr = self._check_compatible(other)
441
+ return Audio(op(self._samples, other._samples), sample_rate=sr)
442
+ return Audio(op(self._samples, other), sample_rate=self._sample_rate)
443
+
444
+ def _ibinary_op(self, other, op) -> "Audio":
445
+ if isinstance(other, Audio):
446
+ self._check_compatible(other)
447
+ op(self._samples, other._samples)
448
+ else:
449
+ op(self._samples, other)
450
+ return self
451
+
452
+ def __add__(self, other) -> "Audio":
453
+ return self._binary_op(other, lambda a, b: a + b)
454
+
455
+ def __radd__(self, other) -> "Audio":
456
+ return Audio(other + self._samples, sample_rate=self._sample_rate)
457
+
458
+ def __iadd__(self, other) -> "Audio":
459
+ def _iadd(a, b):
460
+ a += b
461
+
462
+ return self._ibinary_op(other, _iadd)
463
+
464
+ def __sub__(self, other) -> "Audio":
465
+ return self._binary_op(other, lambda a, b: a - b)
466
+
467
+ def __rsub__(self, other) -> "Audio":
468
+ return Audio(other - self._samples, sample_rate=self._sample_rate)
469
+
470
+ def __isub__(self, other) -> "Audio":
471
+ def _isub(a, b):
472
+ a -= b
473
+
474
+ return self._ibinary_op(other, _isub)
475
+
476
+ def __mul__(self, other) -> "Audio":
477
+ return self._binary_op(other, lambda a, b: a * b)
478
+
479
+ def __rmul__(self, other) -> "Audio":
480
+ return Audio(other * self._samples, sample_rate=self._sample_rate)
481
+
482
+ def __imul__(self, other) -> "Audio":
483
+ def _imul(a, b):
484
+ a *= b
485
+
486
+ return self._ibinary_op(other, _imul)
487
+
488
+ def __truediv__(self, other) -> "Audio":
489
+ return self._binary_op(other, lambda a, b: a / b)
490
+
491
+ def __itruediv__(self, other) -> "Audio":
492
+ def _idiv(a, b):
493
+ a /= b
494
+
495
+ return self._ibinary_op(other, _idiv)
496
+
497
+ def __neg__(self) -> "Audio":
498
+ return Audio(-self._samples, sample_rate=self._sample_rate)
499
+
500
+ def __repr__(self) -> str:
501
+ return (
502
+ f"Audio(num_samples={self.num_samples}, "
503
+ f"num_channels={self.num_channels}, "
504
+ f"sample_rate={self._sample_rate})"
505
+ )