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/device.py ADDED
@@ -0,0 +1,323 @@
1
+ """Sounddevice integration: device selection, ``play``, and ``record``.
2
+
3
+ The user's chosen input/output devices are persisted as JSON under
4
+ ``CACHE_DIR / "device_defaults.json"`` and applied to ``sounddevice.default``
5
+ once at module import time.
6
+ """
7
+
8
+ import json
9
+ import sys
10
+ import time
11
+ from typing import Any, Optional, Tuple, Union
12
+
13
+ import sounddevice as sd
14
+ import tqdm
15
+
16
+ from .audio import Audio
17
+ from .paths import CACHE_DIR
18
+
19
+ _DEFAULTS_PATH = CACHE_DIR / "device_defaults.json"
20
+
21
+ DeviceRef = Union[int, str]
22
+
23
+
24
+ def set_input_device(
25
+ device_id_or_name: Optional[DeviceRef] = None,
26
+ *,
27
+ update_default: bool = False,
28
+ ) -> None:
29
+ """Selects the input device for the current Python session.
30
+
31
+ Args:
32
+ device_id_or_name: Device index, or a substring of the device name.
33
+ If ``None``, prompts the user interactively.
34
+ update_default: If ``False`` (default), the change applies only to
35
+ this Python session. If ``True``, the choice is also persisted
36
+ to the cache and reapplied next time pyquist is imported. The
37
+ ``pyquist devices`` CLI command is the usual way to update the
38
+ persistent default.
39
+ """
40
+ if device_id_or_name is None:
41
+ device_id, device_name = _prompt_device("input", update_default=update_default)
42
+ else:
43
+ device_id, device_name = _resolve_device(device_id_or_name, "input")
44
+ _set_device_slot(0, device_id)
45
+ if update_default:
46
+ defaults = _load_defaults()
47
+ defaults["input"] = device_name
48
+ _save_defaults(defaults)
49
+
50
+
51
+ def set_output_device(
52
+ device_id_or_name: Optional[DeviceRef] = None,
53
+ *,
54
+ update_default: bool = False,
55
+ ) -> None:
56
+ """Selects the output device for the current Python session.
57
+
58
+ Args:
59
+ device_id_or_name: Device index, or a substring of the device name.
60
+ If ``None``, prompts the user interactively.
61
+ update_default: If ``False`` (default), the change applies only to
62
+ this Python session. If ``True``, the choice is also persisted
63
+ to the cache and reapplied next time pyquist is imported. The
64
+ ``pyquist devices`` CLI command is the usual way to update the
65
+ persistent default.
66
+ """
67
+ if device_id_or_name is None:
68
+ device_id, device_name = _prompt_device("output", update_default=update_default)
69
+ else:
70
+ device_id, device_name = _resolve_device(device_id_or_name, "output")
71
+ _set_device_slot(1, device_id)
72
+ if update_default:
73
+ defaults = _load_defaults()
74
+ defaults["output"] = device_name
75
+ _save_defaults(defaults)
76
+
77
+
78
+ def _in_ipython_notebook() -> bool:
79
+ """Returns True if running inside a notebook-style IPython kernel.
80
+
81
+ Anything that isn't plain Python or the IPython terminal REPL counts —
82
+ this covers Jupyter (``ZMQInteractiveShell``), Google Colab
83
+ (``google.colab._shell.Shell``), VSCode notebooks, and other kernel
84
+ hosts where inline display is the right playback path.
85
+ """
86
+ try:
87
+ from IPython import get_ipython # type: ignore[import-not-found]
88
+ except ImportError:
89
+ return False
90
+ ipy = get_ipython()
91
+ if ipy is None:
92
+ return False
93
+ # The only IPython context where inline display ISN'T the right answer
94
+ # is the terminal REPL, which has its own audio output.
95
+ return ipy.__class__.__name__ != "TerminalInteractiveShell"
96
+
97
+
98
+ def play(
99
+ audio: Audio,
100
+ *,
101
+ safe: bool = True,
102
+ normalize: bool = False,
103
+ force_sounddevice: bool = False,
104
+ ) -> None:
105
+ """Plays an Audio.
106
+
107
+ In a Jupyter / IPython notebook this renders an inline player widget via
108
+ :class:`IPython.display.Audio`. Outside a notebook (or when
109
+ ``force_sounddevice=True``) it plays through the default output device
110
+ via :mod:`sounddevice`.
111
+
112
+ Args:
113
+ audio: The audio to play. Must have a ``sample_rate``.
114
+ safe: If True (default), attenuates the audio to -18 dBFS before
115
+ playback to protect ears against accidentally hot signals.
116
+ normalize: If True, normalizes the audio to 0 dBFS before playback.
117
+ force_sounddevice: If True, always use sounddevice playback, even
118
+ when called from a notebook. Useful when you want the audio
119
+ played through the OS audio output rather than as an inline
120
+ player widget.
121
+ """
122
+ if normalize:
123
+ audio = audio.normalize(in_place=False)
124
+ audio = audio.clip(in_place=False)
125
+ if safe:
126
+ audio = audio.normalize(peak_dbfs=-18.0, in_place=False)
127
+
128
+ if not force_sounddevice and _in_ipython_notebook():
129
+ # Imported lazily so headless / non-notebook usage doesn't need IPython.
130
+ from IPython.display import Audio as IPythonAudio, display # type: ignore[import-not-found] # noqa: I001
131
+
132
+ display(
133
+ IPythonAudio(
134
+ audio.samples.swapaxes(0, 1),
135
+ rate=audio.sample_rate,
136
+ normalize=False,
137
+ )
138
+ )
139
+ else:
140
+ sd.play(audio, audio.sample_rate)
141
+ sd.wait()
142
+
143
+
144
+ def record(duration: float, *, progress_bar: bool = True, **kwargs: Any) -> Audio:
145
+ """Records audio from the default input device.
146
+
147
+ Args:
148
+ duration: Recording length in seconds.
149
+ progress_bar: Whether to display a tqdm progress bar.
150
+
151
+ Returns:
152
+ The recorded Audio at the input device's native sample rate.
153
+ """
154
+ device_info = sd.query_devices(sd.default.device[0])
155
+ sample_rate = round(device_info["default_samplerate"])
156
+ num_channels = device_info["max_input_channels"]
157
+ samples = sd.rec(
158
+ frames=int(duration * sample_rate),
159
+ channels=num_channels,
160
+ samplerate=sample_rate,
161
+ dtype="float32",
162
+ **kwargs,
163
+ )
164
+ if progress_bar:
165
+ with tqdm.tqdm(total=100, desc="Recording") as pbar:
166
+ for _ in range(100):
167
+ pbar.update(1)
168
+ time.sleep(duration / 100)
169
+ sd.wait()
170
+ return Audio(samples, sample_rate=sample_rate)
171
+
172
+
173
+ def _resolve_device(device_id_or_name: DeviceRef, kind: str) -> Tuple[int, str]:
174
+ """Resolves an int ID or name substring to a ``(device_id, device_name)`` pair.
175
+
176
+ Args:
177
+ device_id_or_name: Device index, or a substring of the device name.
178
+ kind: ``"input"`` or ``"output"``.
179
+
180
+ Raises:
181
+ TypeError: if ``device_id_or_name`` is not int or str.
182
+ ValueError: if the ID is out of range, has no channels of the given
183
+ kind, or if the name matches zero or multiple devices.
184
+ """
185
+ devices = sd.query_devices()
186
+ chan_key = f"max_{kind}_channels"
187
+
188
+ if isinstance(device_id_or_name, bool) or not isinstance(
189
+ device_id_or_name, (int, str)
190
+ ):
191
+ raise TypeError(
192
+ f"device must be an int ID or str name, "
193
+ f"got {type(device_id_or_name).__name__}."
194
+ )
195
+
196
+ if isinstance(device_id_or_name, int):
197
+ if not 0 <= device_id_or_name < len(devices):
198
+ raise ValueError(f"Device ID {device_id_or_name} out of range.")
199
+ dev = devices[device_id_or_name]
200
+ if dev[chan_key] == 0:
201
+ raise ValueError(
202
+ f"Device {device_id_or_name} ('{dev['name']}') has no {kind} channels."
203
+ )
204
+ return device_id_or_name, dev["name"]
205
+
206
+ matches = [
207
+ (i, dev["name"])
208
+ for i, dev in enumerate(devices)
209
+ if device_id_or_name in dev["name"] and dev[chan_key] > 0
210
+ ]
211
+ if not matches:
212
+ raise ValueError(f"No {kind} device matches '{device_id_or_name}'.")
213
+ if len(matches) > 1:
214
+ names = ", ".join(name for _, name in matches)
215
+ raise ValueError(
216
+ f"Multiple {kind} devices match '{device_id_or_name}': {names}."
217
+ )
218
+ return matches[0]
219
+
220
+
221
+ def _prompt_device(kind: str, *, update_default: bool = False) -> Tuple[int, str]:
222
+ """Interactively prompt the user to pick a device of the given kind.
223
+
224
+ Each device in the listing is annotated with ``[current]`` if it is the
225
+ one currently active in ``sd.default``, and ``[default]`` if it is the
226
+ persisted default for this kind. The prompt phrasing reflects whether
227
+ the choice will be persisted (``update_default=True``) or applied for
228
+ this session only.
229
+ """
230
+ devices = sd.query_devices()
231
+ slot = 0 if kind == "input" else 1
232
+
233
+ # Find devices that match the requested kind. Bail out cleanly if none —
234
+ # otherwise we'd print an empty listing and ask the user to pick anyway.
235
+ eligible = [
236
+ (i, dev) for i, dev in enumerate(devices) if dev[f"max_{kind}_channels"] > 0
237
+ ]
238
+ if not eligible:
239
+ raise RuntimeError(f"No {kind} devices are available on this machine.")
240
+
241
+ current_id = sd.default.device[slot]
242
+
243
+ # Resolve the persisted default name (if any) to its current device ID.
244
+ default_id: Optional[int] = None
245
+ default_name = _load_defaults().get(kind)
246
+ if default_name is not None:
247
+ try:
248
+ default_id, _ = _resolve_device(default_name, kind)
249
+ except (ValueError, TypeError):
250
+ pass # Cached default no longer resolvable; just don't tag it.
251
+
252
+ print(f"Available {kind} devices:")
253
+ for i, dev in eligible:
254
+ tags = []
255
+ if i == current_id:
256
+ tags.append("current")
257
+ if i == default_id:
258
+ tags.append("default")
259
+ suffix = f" [{', '.join(tags)}]" if tags else ""
260
+ print(f" {i}: {dev['name']}{suffix}")
261
+
262
+ label = f"default {kind}" if update_default else kind
263
+ choice = input(f"Select {label} device (ID or name): ").strip()
264
+ if choice.isdigit() or (choice.startswith("-") and choice[1:].isdigit()):
265
+ return _resolve_device(int(choice), kind)
266
+ return _resolve_device(choice, kind)
267
+
268
+
269
+ def _set_device_slot(slot: int, device_id: int) -> None:
270
+ """Updates one half of ``sd.default.device`` without disturbing the other."""
271
+ current = list(sd.default.device)
272
+ current[slot] = device_id
273
+ sd.default.device = tuple(current)
274
+
275
+
276
+ def _load_defaults() -> dict:
277
+ if not _DEFAULTS_PATH.exists():
278
+ return {}
279
+ try:
280
+ with open(_DEFAULTS_PATH, "r") as f:
281
+ return json.load(f)
282
+ except (json.JSONDecodeError, OSError) as e:
283
+ print(f"warning: could not read device defaults cache: {e}", file=sys.stderr)
284
+ return {}
285
+
286
+
287
+ def _save_defaults(defaults: dict) -> None:
288
+ _DEFAULTS_PATH.parent.mkdir(parents=True, exist_ok=True)
289
+ with open(_DEFAULTS_PATH, "w") as f:
290
+ json.dump(defaults, f)
291
+
292
+
293
+ def _apply_persisted_defaults() -> None:
294
+ """Applies cached input/output device choices to ``sd.default``.
295
+
296
+ Called once at module import. Any failure (cached device no longer
297
+ exists, audio backend uninitialized, no devices at all, ...) logs a
298
+ warning to stderr and is skipped — module import must never fail just
299
+ because audio is unavailable, since the rest of pyquist is still useful
300
+ on a headless machine.
301
+ """
302
+ defaults = _load_defaults()
303
+ for kind, slot in [("input", 0), ("output", 1)]:
304
+ name = defaults.get(kind)
305
+ if name is None:
306
+ continue
307
+ try:
308
+ device_id, _ = _resolve_device(name, kind)
309
+ _set_device_slot(slot, device_id)
310
+ except Exception as e:
311
+ print(
312
+ f"warning: could not restore {kind} device {name!r}: {e} "
313
+ f"To pick a different default, run `pyquist devices`. "
314
+ f"To suppress this warning, delete {_DEFAULTS_PATH}.",
315
+ file=sys.stderr,
316
+ )
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # Module init
321
+ # ---------------------------------------------------------------------------
322
+
323
+ _apply_persisted_defaults()