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 +40 -0
- pyquist/audio.py +505 -0
- pyquist/audio_test.py +447 -0
- pyquist/cli.py +102 -0
- pyquist/device.py +323 -0
- pyquist/device_test.py +508 -0
- pyquist/helper.py +133 -0
- pyquist/helper_test.py +107 -0
- pyquist/paths.py +13 -0
- pyquist/plot.py +285 -0
- pyquist/plot_test.py +190 -0
- pyquist/py.typed +0 -0
- pyquist/score.py +512 -0
- pyquist/score_test.py +476 -0
- pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
- pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
- pyquist/test_data/ravel_bolero.mid +0 -0
- pyquist/web/__init__.py +7 -0
- pyquist/web/freesound.py +288 -0
- pyquist/web/theorytab.py +408 -0
- pyquist-0.1.0.dist-info/METADATA +180 -0
- pyquist-0.1.0.dist-info/RECORD +26 -0
- pyquist-0.1.0.dist-info/WHEEL +5 -0
- pyquist-0.1.0.dist-info/entry_points.txt +2 -0
- pyquist-0.1.0.dist-info/licenses/LICENSE +7 -0
- pyquist-0.1.0.dist-info/top_level.txt +1 -0
pyquist/device_test.py
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
import tempfile
|
|
5
|
+
import unittest
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from unittest import mock
|
|
8
|
+
|
|
9
|
+
from . import device
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _FakeSdDefault:
|
|
13
|
+
"""Stand-in for ``sounddevice.default``."""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.device = (0, 0)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_FAKE_DEVICES = [
|
|
20
|
+
{"name": "MacBook Microphone", "max_input_channels": 1, "max_output_channels": 0},
|
|
21
|
+
{"name": "MacBook Speakers", "max_input_channels": 0, "max_output_channels": 2},
|
|
22
|
+
{
|
|
23
|
+
"name": "External Audio Interface",
|
|
24
|
+
"max_input_channels": 2,
|
|
25
|
+
"max_output_channels": 2,
|
|
26
|
+
},
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _patch_sd(test, *, devices=None, default=None):
|
|
31
|
+
"""Helper: patches ``device.sd.query_devices`` and ``device.sd.default``."""
|
|
32
|
+
devices = _FAKE_DEVICES if devices is None else devices
|
|
33
|
+
default = _FakeSdDefault() if default is None else default
|
|
34
|
+
patches = [
|
|
35
|
+
mock.patch.object(device.sd, "query_devices", return_value=devices),
|
|
36
|
+
mock.patch.object(device.sd, "default", default),
|
|
37
|
+
]
|
|
38
|
+
for p in patches:
|
|
39
|
+
p.start()
|
|
40
|
+
test.addCleanup(p.stop)
|
|
41
|
+
return default
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TestResolveDevice(unittest.TestCase):
|
|
45
|
+
def setUp(self):
|
|
46
|
+
_patch_sd(self)
|
|
47
|
+
|
|
48
|
+
def test_int_id(self):
|
|
49
|
+
self.assertEqual(device._resolve_device(0, "input"), (0, "MacBook Microphone"))
|
|
50
|
+
self.assertEqual(device._resolve_device(1, "output"), (1, "MacBook Speakers"))
|
|
51
|
+
|
|
52
|
+
def test_int_id_out_of_range(self):
|
|
53
|
+
with self.assertRaises(ValueError):
|
|
54
|
+
device._resolve_device(99, "input")
|
|
55
|
+
with self.assertRaises(ValueError):
|
|
56
|
+
device._resolve_device(-1, "input")
|
|
57
|
+
|
|
58
|
+
def test_int_id_wrong_kind(self):
|
|
59
|
+
# Device 0 is input-only.
|
|
60
|
+
with self.assertRaises(ValueError):
|
|
61
|
+
device._resolve_device(0, "output")
|
|
62
|
+
# Device 1 is output-only.
|
|
63
|
+
with self.assertRaises(ValueError):
|
|
64
|
+
device._resolve_device(1, "input")
|
|
65
|
+
|
|
66
|
+
def test_name_substring_match(self):
|
|
67
|
+
self.assertEqual(
|
|
68
|
+
device._resolve_device("Microphone", "input"), (0, "MacBook Microphone")
|
|
69
|
+
)
|
|
70
|
+
self.assertEqual(
|
|
71
|
+
device._resolve_device("External", "output"),
|
|
72
|
+
(2, "External Audio Interface"),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def test_name_no_match(self):
|
|
76
|
+
with self.assertRaises(ValueError):
|
|
77
|
+
device._resolve_device("Nonexistent", "input")
|
|
78
|
+
|
|
79
|
+
def test_name_kind_filtered_out(self):
|
|
80
|
+
# "Speakers" exists but only as output.
|
|
81
|
+
with self.assertRaises(ValueError):
|
|
82
|
+
device._resolve_device("Speakers", "input")
|
|
83
|
+
|
|
84
|
+
def test_name_multiple_matches(self):
|
|
85
|
+
ambiguous = _FAKE_DEVICES + [
|
|
86
|
+
{
|
|
87
|
+
"name": "USB Microphone Array",
|
|
88
|
+
"max_input_channels": 4,
|
|
89
|
+
"max_output_channels": 0,
|
|
90
|
+
}
|
|
91
|
+
]
|
|
92
|
+
with mock.patch.object(device.sd, "query_devices", return_value=ambiguous):
|
|
93
|
+
with self.assertRaises(ValueError):
|
|
94
|
+
device._resolve_device("Microphone", "input")
|
|
95
|
+
|
|
96
|
+
def test_invalid_argument_type(self):
|
|
97
|
+
with self.assertRaises(TypeError):
|
|
98
|
+
device._resolve_device(1.5, "input") # type: ignore[arg-type]
|
|
99
|
+
with self.assertRaises(TypeError):
|
|
100
|
+
device._resolve_device(True, "input") # bool subclass of int — reject
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TestPromptDevice(unittest.TestCase):
|
|
104
|
+
def setUp(self):
|
|
105
|
+
_patch_sd(self)
|
|
106
|
+
# Silence the device-list print that _prompt_device emits.
|
|
107
|
+
p = mock.patch("sys.stdout")
|
|
108
|
+
p.start()
|
|
109
|
+
self.addCleanup(p.stop)
|
|
110
|
+
|
|
111
|
+
def test_prompt_with_int_input(self):
|
|
112
|
+
with mock.patch("builtins.input", return_value="0"):
|
|
113
|
+
self.assertEqual(device._prompt_device("input"), (0, "MacBook Microphone"))
|
|
114
|
+
|
|
115
|
+
def test_prompt_with_name_input(self):
|
|
116
|
+
with mock.patch("builtins.input", return_value="External"):
|
|
117
|
+
self.assertEqual(
|
|
118
|
+
device._prompt_device("output"), (2, "External Audio Interface")
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
def test_prompt_phrasing_session_only(self):
|
|
122
|
+
with mock.patch("builtins.input", return_value="0") as mock_input:
|
|
123
|
+
device._prompt_device("input", update_default=False)
|
|
124
|
+
self.assertIn("Select input device", mock_input.call_args.args[0])
|
|
125
|
+
self.assertNotIn("default", mock_input.call_args.args[0])
|
|
126
|
+
|
|
127
|
+
def test_prompt_phrasing_persistent(self):
|
|
128
|
+
with mock.patch("builtins.input", return_value="0") as mock_input:
|
|
129
|
+
device._prompt_device("input", update_default=True)
|
|
130
|
+
self.assertIn("Select default input device", mock_input.call_args.args[0])
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class TestPromptDeviceAnnotations(unittest.TestCase):
|
|
134
|
+
"""Verify [current] and [default] markers in the prompt listing."""
|
|
135
|
+
|
|
136
|
+
def setUp(self):
|
|
137
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
138
|
+
self.tmp_path = Path(self.tmp.name) / "device_defaults.json"
|
|
139
|
+
p = mock.patch.object(device, "_DEFAULTS_PATH", self.tmp_path)
|
|
140
|
+
p.start()
|
|
141
|
+
self.addCleanup(p.stop)
|
|
142
|
+
self.addCleanup(self.tmp.cleanup)
|
|
143
|
+
|
|
144
|
+
def _run_prompt(self, kind, fake_default, *, default_name=None):
|
|
145
|
+
if default_name is not None:
|
|
146
|
+
self.tmp_path.write_text(json.dumps({kind: default_name}))
|
|
147
|
+
with (
|
|
148
|
+
mock.patch.object(device.sd, "default", fake_default),
|
|
149
|
+
mock.patch.object(device.sd, "query_devices", return_value=_FAKE_DEVICES),
|
|
150
|
+
mock.patch("builtins.input", return_value="0"),
|
|
151
|
+
):
|
|
152
|
+
buf = io.StringIO()
|
|
153
|
+
with contextlib.redirect_stdout(buf):
|
|
154
|
+
device._prompt_device(kind)
|
|
155
|
+
return buf.getvalue()
|
|
156
|
+
|
|
157
|
+
def test_no_tags_when_neither_current_nor_default(self):
|
|
158
|
+
# Set sd.default.device[0] to an out-of-range index → no "current" tag.
|
|
159
|
+
fake = _FakeSdDefault()
|
|
160
|
+
fake.device = (-1, -1)
|
|
161
|
+
out = self._run_prompt("input", fake)
|
|
162
|
+
self.assertIn("0: MacBook Microphone", out)
|
|
163
|
+
self.assertNotIn("[current]", out)
|
|
164
|
+
self.assertNotIn("[default]", out)
|
|
165
|
+
|
|
166
|
+
def test_current_only(self):
|
|
167
|
+
fake = _FakeSdDefault()
|
|
168
|
+
fake.device = (2, 0) # External Audio Interface as input
|
|
169
|
+
out = self._run_prompt("input", fake)
|
|
170
|
+
self.assertIn("2: External Audio Interface [current]", out)
|
|
171
|
+
self.assertNotIn("[default]", out)
|
|
172
|
+
|
|
173
|
+
def test_default_only(self):
|
|
174
|
+
# Default is set but current is something else.
|
|
175
|
+
fake = _FakeSdDefault()
|
|
176
|
+
fake.device = (0, 0)
|
|
177
|
+
out = self._run_prompt("input", fake, default_name="External Audio Interface")
|
|
178
|
+
self.assertIn("0: MacBook Microphone [current]", out)
|
|
179
|
+
self.assertIn("2: External Audio Interface [default]", out)
|
|
180
|
+
|
|
181
|
+
def test_current_and_default_same_device(self):
|
|
182
|
+
fake = _FakeSdDefault()
|
|
183
|
+
fake.device = (0, 0)
|
|
184
|
+
out = self._run_prompt("input", fake, default_name="MacBook Microphone")
|
|
185
|
+
self.assertIn("0: MacBook Microphone [current, default]", out)
|
|
186
|
+
|
|
187
|
+
def test_unresolvable_default_silently_skipped(self):
|
|
188
|
+
# Persisted default refers to a device that no longer exists.
|
|
189
|
+
fake = _FakeSdDefault()
|
|
190
|
+
out = self._run_prompt("input", fake, default_name="Phantom Device")
|
|
191
|
+
self.assertIn("0: MacBook Microphone", out)
|
|
192
|
+
self.assertNotIn("[default]", out)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class TestNoDevicesAvailable(unittest.TestCase):
|
|
196
|
+
"""Behavior when the machine has zero (or zero of one kind of) devices."""
|
|
197
|
+
|
|
198
|
+
def test_prompt_device_raises_when_no_devices(self):
|
|
199
|
+
with (
|
|
200
|
+
mock.patch.object(device.sd, "query_devices", return_value=[]),
|
|
201
|
+
mock.patch.object(device.sd, "default", _FakeSdDefault()),
|
|
202
|
+
mock.patch("sys.stdout"),
|
|
203
|
+
):
|
|
204
|
+
with self.assertRaises(RuntimeError) as ctx:
|
|
205
|
+
device._prompt_device("input")
|
|
206
|
+
self.assertIn("No input devices", str(ctx.exception))
|
|
207
|
+
|
|
208
|
+
def test_prompt_device_raises_when_no_devices_of_kind(self):
|
|
209
|
+
# Output-only world → asking for input prompt should fail clearly.
|
|
210
|
+
output_only = [
|
|
211
|
+
{"name": "Speakers", "max_input_channels": 0, "max_output_channels": 2}
|
|
212
|
+
]
|
|
213
|
+
with (
|
|
214
|
+
mock.patch.object(device.sd, "query_devices", return_value=output_only),
|
|
215
|
+
mock.patch.object(device.sd, "default", _FakeSdDefault()),
|
|
216
|
+
mock.patch("sys.stdout"),
|
|
217
|
+
):
|
|
218
|
+
with self.assertRaises(RuntimeError):
|
|
219
|
+
device._prompt_device("input")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class TestApplyPersistedDefaultsRobust(unittest.TestCase):
|
|
223
|
+
"""``_apply_persisted_defaults`` must never let module import fail."""
|
|
224
|
+
|
|
225
|
+
def setUp(self):
|
|
226
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
227
|
+
self.tmp_path = Path(self.tmp.name) / "device_defaults.json"
|
|
228
|
+
p = mock.patch.object(device, "_DEFAULTS_PATH", self.tmp_path)
|
|
229
|
+
p.start()
|
|
230
|
+
self.addCleanup(p.stop)
|
|
231
|
+
self.addCleanup(self.tmp.cleanup)
|
|
232
|
+
|
|
233
|
+
def test_no_audio_backend_does_not_raise(self):
|
|
234
|
+
# Cached default exists, but sd.query_devices itself errors out
|
|
235
|
+
# (e.g. headless server with no audio backend).
|
|
236
|
+
self.tmp_path.write_text(json.dumps({"input": "MacBook"}))
|
|
237
|
+
with (
|
|
238
|
+
mock.patch.object(
|
|
239
|
+
device.sd, "query_devices", side_effect=OSError("no audio backend")
|
|
240
|
+
),
|
|
241
|
+
mock.patch("sys.stderr"),
|
|
242
|
+
):
|
|
243
|
+
device._apply_persisted_defaults() # must not raise
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class TestPersistence(unittest.TestCase):
|
|
247
|
+
def setUp(self):
|
|
248
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
249
|
+
self.tmp_path = Path(self.tmp.name) / "device_defaults.json"
|
|
250
|
+
p = mock.patch.object(device, "_DEFAULTS_PATH", self.tmp_path)
|
|
251
|
+
p.start()
|
|
252
|
+
self.addCleanup(p.stop)
|
|
253
|
+
self.addCleanup(self.tmp.cleanup)
|
|
254
|
+
|
|
255
|
+
def test_load_missing_file(self):
|
|
256
|
+
self.assertEqual(device._load_defaults(), {})
|
|
257
|
+
|
|
258
|
+
def test_load_corrupt_file(self):
|
|
259
|
+
self.tmp_path.write_text("{not json")
|
|
260
|
+
with mock.patch("sys.stderr"):
|
|
261
|
+
self.assertEqual(device._load_defaults(), {})
|
|
262
|
+
|
|
263
|
+
def test_save_load_roundtrip(self):
|
|
264
|
+
d = {"input": "Mic", "output": "Speakers"}
|
|
265
|
+
device._save_defaults(d)
|
|
266
|
+
self.assertEqual(device._load_defaults(), d)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class TestSetInputOutputDevice(unittest.TestCase):
|
|
270
|
+
def setUp(self):
|
|
271
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
272
|
+
self.tmp_path = Path(self.tmp.name) / "device_defaults.json"
|
|
273
|
+
p = mock.patch.object(device, "_DEFAULTS_PATH", self.tmp_path)
|
|
274
|
+
p.start()
|
|
275
|
+
self.addCleanup(p.stop)
|
|
276
|
+
self.addCleanup(self.tmp.cleanup)
|
|
277
|
+
self.fake = _patch_sd(self)
|
|
278
|
+
|
|
279
|
+
def test_set_input_by_id_session_only(self):
|
|
280
|
+
# Default is session-only — must not persist.
|
|
281
|
+
device.set_input_device(2) # External Audio Interface
|
|
282
|
+
self.assertEqual(self.fake.device, (2, 0))
|
|
283
|
+
self.assertFalse(self.tmp_path.exists())
|
|
284
|
+
|
|
285
|
+
def test_set_input_by_name_session_only(self):
|
|
286
|
+
device.set_input_device("Microphone")
|
|
287
|
+
self.assertEqual(self.fake.device, (0, 0))
|
|
288
|
+
self.assertFalse(self.tmp_path.exists())
|
|
289
|
+
|
|
290
|
+
def test_set_output_session_only(self):
|
|
291
|
+
device.set_output_device(1)
|
|
292
|
+
self.assertEqual(self.fake.device, (0, 1))
|
|
293
|
+
self.assertFalse(self.tmp_path.exists())
|
|
294
|
+
|
|
295
|
+
def test_set_input_persists_with_update_default(self):
|
|
296
|
+
device.set_input_device(2, update_default=True)
|
|
297
|
+
self.assertEqual(self.fake.device, (2, 0))
|
|
298
|
+
with open(self.tmp_path) as f:
|
|
299
|
+
self.assertEqual(json.load(f), {"input": "External Audio Interface"})
|
|
300
|
+
|
|
301
|
+
def test_set_output_persists_with_update_default(self):
|
|
302
|
+
device.set_output_device(1, update_default=True)
|
|
303
|
+
self.assertEqual(self.fake.device, (0, 1))
|
|
304
|
+
with open(self.tmp_path) as f:
|
|
305
|
+
self.assertEqual(json.load(f), {"output": "MacBook Speakers"})
|
|
306
|
+
|
|
307
|
+
def test_set_input_then_output_merges_cache(self):
|
|
308
|
+
device.set_input_device("Microphone", update_default=True)
|
|
309
|
+
device.set_output_device("Speakers", update_default=True)
|
|
310
|
+
self.assertEqual(self.fake.device, (0, 1))
|
|
311
|
+
with open(self.tmp_path) as f:
|
|
312
|
+
self.assertEqual(
|
|
313
|
+
json.load(f),
|
|
314
|
+
{"input": "MacBook Microphone", "output": "MacBook Speakers"},
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
def test_invalid_choice_does_not_persist(self):
|
|
318
|
+
with self.assertRaises(ValueError):
|
|
319
|
+
device.set_input_device("Nonexistent", update_default=True)
|
|
320
|
+
self.assertFalse(self.tmp_path.exists())
|
|
321
|
+
self.assertEqual(self.fake.device, (0, 0)) # untouched
|
|
322
|
+
|
|
323
|
+
def test_interactive_prompt_session_only_by_default(self):
|
|
324
|
+
with (
|
|
325
|
+
mock.patch("builtins.input", return_value="External"),
|
|
326
|
+
mock.patch("sys.stdout"),
|
|
327
|
+
):
|
|
328
|
+
device.set_input_device()
|
|
329
|
+
self.assertEqual(self.fake.device, (2, 0))
|
|
330
|
+
self.assertFalse(self.tmp_path.exists())
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class TestApplyPersistedDefaults(unittest.TestCase):
|
|
334
|
+
def setUp(self):
|
|
335
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
336
|
+
self.tmp_path = Path(self.tmp.name) / "device_defaults.json"
|
|
337
|
+
p = mock.patch.object(device, "_DEFAULTS_PATH", self.tmp_path)
|
|
338
|
+
p.start()
|
|
339
|
+
self.addCleanup(p.stop)
|
|
340
|
+
self.addCleanup(self.tmp.cleanup)
|
|
341
|
+
self.fake = _patch_sd(self)
|
|
342
|
+
|
|
343
|
+
def test_no_cache_no_op(self):
|
|
344
|
+
device._apply_persisted_defaults()
|
|
345
|
+
self.assertEqual(self.fake.device, (0, 0)) # initial unchanged
|
|
346
|
+
|
|
347
|
+
def test_applies_cached_input(self):
|
|
348
|
+
self.tmp_path.write_text(json.dumps({"input": "External"}))
|
|
349
|
+
device._apply_persisted_defaults()
|
|
350
|
+
self.assertEqual(self.fake.device, (2, 0))
|
|
351
|
+
|
|
352
|
+
def test_applies_cached_input_and_output(self):
|
|
353
|
+
self.tmp_path.write_text(
|
|
354
|
+
json.dumps({"input": "Microphone", "output": "Speakers"})
|
|
355
|
+
)
|
|
356
|
+
device._apply_persisted_defaults()
|
|
357
|
+
self.assertEqual(self.fake.device, (0, 1))
|
|
358
|
+
|
|
359
|
+
def test_skips_missing_device_with_warning(self):
|
|
360
|
+
self.tmp_path.write_text(
|
|
361
|
+
json.dumps({"input": "Nonexistent", "output": "Speakers"})
|
|
362
|
+
)
|
|
363
|
+
with mock.patch("sys.stderr"):
|
|
364
|
+
device._apply_persisted_defaults()
|
|
365
|
+
# Output still applied even though input failed
|
|
366
|
+
self.assertEqual(self.fake.device, (0, 1))
|
|
367
|
+
|
|
368
|
+
def test_stale_default_preserves_cache_across_sessions(self):
|
|
369
|
+
# Simulates: user persisted "External", later unplugged it.
|
|
370
|
+
self.tmp_path.write_text(
|
|
371
|
+
json.dumps({"input": "External", "output": "External"})
|
|
372
|
+
)
|
|
373
|
+
original = self.tmp_path.read_text()
|
|
374
|
+
|
|
375
|
+
# Only built-in devices remain.
|
|
376
|
+
remaining = [
|
|
377
|
+
{
|
|
378
|
+
"name": "MacBook Microphone",
|
|
379
|
+
"max_input_channels": 1,
|
|
380
|
+
"max_output_channels": 0,
|
|
381
|
+
},
|
|
382
|
+
{
|
|
383
|
+
"name": "MacBook Speakers",
|
|
384
|
+
"max_input_channels": 0,
|
|
385
|
+
"max_output_channels": 2,
|
|
386
|
+
},
|
|
387
|
+
]
|
|
388
|
+
with (
|
|
389
|
+
mock.patch.object(device.sd, "query_devices", return_value=remaining),
|
|
390
|
+
mock.patch("sys.stderr"),
|
|
391
|
+
):
|
|
392
|
+
device._apply_persisted_defaults()
|
|
393
|
+
# sd.default.device untouched (sounddevice's own default stands).
|
|
394
|
+
self.assertEqual(self.fake.device, (0, 0))
|
|
395
|
+
# Cache file is preserved verbatim — re-plugging the device next
|
|
396
|
+
# session should restore it.
|
|
397
|
+
self.assertEqual(self.tmp_path.read_text(), original)
|
|
398
|
+
|
|
399
|
+
def test_stale_default_warning_includes_remediation(self):
|
|
400
|
+
self.tmp_path.write_text(json.dumps({"input": "Phantom"}))
|
|
401
|
+
captured = io.StringIO()
|
|
402
|
+
with contextlib.redirect_stderr(captured):
|
|
403
|
+
device._apply_persisted_defaults()
|
|
404
|
+
msg = captured.getvalue()
|
|
405
|
+
self.assertIn("Phantom", msg)
|
|
406
|
+
self.assertIn("pyquist devices", msg)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class TestPlayDispatch(unittest.TestCase):
|
|
410
|
+
"""``play`` picks the right backend based on context."""
|
|
411
|
+
|
|
412
|
+
def _make_audio(self):
|
|
413
|
+
import numpy as np
|
|
414
|
+
|
|
415
|
+
from .audio import Audio
|
|
416
|
+
|
|
417
|
+
return Audio(np.zeros(100, dtype=np.float32), sample_rate=44100)
|
|
418
|
+
|
|
419
|
+
def test_uses_sounddevice_outside_notebook(self):
|
|
420
|
+
audio = self._make_audio()
|
|
421
|
+
with (
|
|
422
|
+
mock.patch.object(device, "_in_ipython_notebook", return_value=False),
|
|
423
|
+
mock.patch.object(device.sd, "play") as mock_play,
|
|
424
|
+
mock.patch.object(device.sd, "wait") as mock_wait,
|
|
425
|
+
):
|
|
426
|
+
device.play(audio)
|
|
427
|
+
mock_play.assert_called_once()
|
|
428
|
+
mock_wait.assert_called_once()
|
|
429
|
+
|
|
430
|
+
def test_uses_ipython_in_notebook(self):
|
|
431
|
+
audio = self._make_audio()
|
|
432
|
+
# Build a fake IPython.display module with Audio + display
|
|
433
|
+
fake_display = mock.MagicMock()
|
|
434
|
+
fake_audio_widget = mock.MagicMock()
|
|
435
|
+
fake_module = mock.MagicMock()
|
|
436
|
+
fake_module.Audio = fake_audio_widget
|
|
437
|
+
fake_module.display = fake_display
|
|
438
|
+
with (
|
|
439
|
+
mock.patch.object(device, "_in_ipython_notebook", return_value=True),
|
|
440
|
+
mock.patch.dict("sys.modules", {"IPython.display": fake_module}),
|
|
441
|
+
mock.patch.object(device.sd, "play") as mock_play,
|
|
442
|
+
):
|
|
443
|
+
device.play(audio)
|
|
444
|
+
mock_play.assert_not_called()
|
|
445
|
+
fake_audio_widget.assert_called_once()
|
|
446
|
+
fake_display.assert_called_once()
|
|
447
|
+
|
|
448
|
+
def test_force_sounddevice_overrides_notebook(self):
|
|
449
|
+
audio = self._make_audio()
|
|
450
|
+
with (
|
|
451
|
+
mock.patch.object(device, "_in_ipython_notebook", return_value=True),
|
|
452
|
+
mock.patch.object(device.sd, "play") as mock_play,
|
|
453
|
+
mock.patch.object(device.sd, "wait"),
|
|
454
|
+
):
|
|
455
|
+
device.play(audio, force_sounddevice=True)
|
|
456
|
+
mock_play.assert_called_once()
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class TestInIPythonNotebook(unittest.TestCase):
|
|
460
|
+
"""``_in_ipython_notebook`` must recognise every flavour of notebook
|
|
461
|
+
kernel — Jupyter, Colab, etc. — so that ``play`` doesn't fall through
|
|
462
|
+
to a sounddevice call that would crash in browser-hosted environments
|
|
463
|
+
with no audio device."""
|
|
464
|
+
|
|
465
|
+
def _fake_ipython_module(self, shell_class_name: str):
|
|
466
|
+
"""Returns a fake ``IPython`` module whose ``get_ipython()`` yields a
|
|
467
|
+
shell of the given class name."""
|
|
468
|
+
# A real class (not MagicMock) is needed so .__class__.__name__ works.
|
|
469
|
+
shell_cls = type(shell_class_name, (), {})
|
|
470
|
+
fake_ipython = mock.MagicMock()
|
|
471
|
+
fake_ipython.get_ipython.return_value = shell_cls()
|
|
472
|
+
return fake_ipython
|
|
473
|
+
|
|
474
|
+
def test_jupyter_kernel_detected(self):
|
|
475
|
+
with mock.patch.dict(
|
|
476
|
+
"sys.modules", {"IPython": self._fake_ipython_module("ZMQInteractiveShell")}
|
|
477
|
+
):
|
|
478
|
+
self.assertTrue(device._in_ipython_notebook())
|
|
479
|
+
|
|
480
|
+
def test_colab_kernel_detected(self):
|
|
481
|
+
# Google Colab's shell is `google.colab._shell.Shell`. The class name
|
|
482
|
+
# alone is enough to distinguish from the terminal REPL.
|
|
483
|
+
with mock.patch.dict(
|
|
484
|
+
"sys.modules", {"IPython": self._fake_ipython_module("Shell")}
|
|
485
|
+
):
|
|
486
|
+
self.assertTrue(device._in_ipython_notebook())
|
|
487
|
+
|
|
488
|
+
def test_terminal_repl_not_detected(self):
|
|
489
|
+
with mock.patch.dict(
|
|
490
|
+
"sys.modules",
|
|
491
|
+
{"IPython": self._fake_ipython_module("TerminalInteractiveShell")},
|
|
492
|
+
):
|
|
493
|
+
self.assertFalse(device._in_ipython_notebook())
|
|
494
|
+
|
|
495
|
+
def test_no_active_kernel_not_detected(self):
|
|
496
|
+
fake_ipython = mock.MagicMock()
|
|
497
|
+
fake_ipython.get_ipython.return_value = None
|
|
498
|
+
with mock.patch.dict("sys.modules", {"IPython": fake_ipython}):
|
|
499
|
+
self.assertFalse(device._in_ipython_notebook())
|
|
500
|
+
|
|
501
|
+
def test_no_ipython_installed_not_detected(self):
|
|
502
|
+
# Simulate IPython being missing entirely.
|
|
503
|
+
with mock.patch.dict("sys.modules", {"IPython": None}):
|
|
504
|
+
self.assertFalse(device._in_ipython_notebook())
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
if __name__ == "__main__":
|
|
508
|
+
unittest.main()
|
pyquist/helper.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def db_to_amplitude(
|
|
5
|
+
db: float | np.ndarray, *, reference: float = 1.0
|
|
6
|
+
) -> float | np.ndarray:
|
|
7
|
+
"""Converts a decibel level to a linear amplitude.
|
|
8
|
+
|
|
9
|
+
Decibels are a logarithmic ratio: ``amplitude = reference * 10**(db / 20)``.
|
|
10
|
+
With the default ``reference=1.0`` and float audio (where ``±1.0`` is
|
|
11
|
+
digital full scale), this is dBFS:
|
|
12
|
+
|
|
13
|
+
* ``0 dB`` → ``1.0`` (unity / full scale)
|
|
14
|
+
* ``-6 dB`` → ``≈ 0.501`` (roughly half amplitude)
|
|
15
|
+
* ``-20 dB`` → ``0.1`` (exactly 1/10th amplitude)
|
|
16
|
+
* ``+6 dB`` → ``≈ 1.995`` (roughly double amplitude)
|
|
17
|
+
|
|
18
|
+
Pass a different ``reference`` to compare against another baseline (e.g.
|
|
19
|
+
a measured RMS level, or a non-unity peak).
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
db: Decibel value. Scalar or numpy array.
|
|
23
|
+
reference: The linear amplitude that corresponds to 0 dB. Defaults
|
|
24
|
+
to ``1.0`` (full scale).
|
|
25
|
+
"""
|
|
26
|
+
return reference * 10.0 ** (db / 20.0)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def amplitude_to_db(
|
|
30
|
+
amplitude: float | np.ndarray, *, reference: float = 1.0
|
|
31
|
+
) -> float | np.ndarray:
|
|
32
|
+
"""Converts a linear amplitude to a decibel level.
|
|
33
|
+
|
|
34
|
+
Inverse of :func:`db_to_amplitude`:
|
|
35
|
+
``db = 20 * log10(amplitude / reference)``.
|
|
36
|
+
With the default ``reference=1.0``, this is dBFS:
|
|
37
|
+
|
|
38
|
+
* ``1.0`` → ``0 dB`` (full scale)
|
|
39
|
+
* ``0.5`` → ``≈ -6.02 dB``
|
|
40
|
+
* ``0.1`` → ``-20 dB``
|
|
41
|
+
* ``2.0`` → ``≈ +6.02 dB``
|
|
42
|
+
|
|
43
|
+
An amplitude of ``0.0`` produces ``-inf`` and emits a numpy log warning;
|
|
44
|
+
callers that may pass exactly zero should clamp first.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
amplitude: Linear amplitude. Scalar or numpy array.
|
|
48
|
+
reference: The linear amplitude that corresponds to 0 dB. Defaults
|
|
49
|
+
to ``1.0`` (full scale).
|
|
50
|
+
"""
|
|
51
|
+
return 20.0 * np.log10(amplitude / reference)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def frequency_to_pitch(frequency: float | np.ndarray) -> float | np.ndarray:
|
|
55
|
+
"""Converts a frequency in Hz to a MIDI pitch number.
|
|
56
|
+
|
|
57
|
+
Uses the standard 12-tone equal-temperament tuning anchored to A4 = 440 Hz
|
|
58
|
+
(MIDI pitch 69): ``pitch = 69 + 12 * log2(frequency / 440)``.
|
|
59
|
+
|
|
60
|
+
The result is a real number, not just an integer — fractional values
|
|
61
|
+
represent intermediate frequencies (one semitone = 1.0, one cent = 0.01).
|
|
62
|
+
For example, ``frequency_to_pitch(466.16) ≈ 70.0`` (A#4).
|
|
63
|
+
"""
|
|
64
|
+
return 69 + 12 * np.log2(frequency / 440.0)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pitch_to_frequency(pitch: float | np.ndarray) -> float | np.ndarray:
|
|
68
|
+
"""Converts a MIDI pitch number to a frequency in Hz.
|
|
69
|
+
|
|
70
|
+
Inverse of :func:`frequency_to_pitch`: ``frequency = 440 * 2**((pitch - 69) / 12)``,
|
|
71
|
+
using A4 = 440 Hz (MIDI 69) and 12-tone equal temperament.
|
|
72
|
+
|
|
73
|
+
Fractional pitches are valid: ``pitch_to_frequency(60.5)`` is a quarter-tone
|
|
74
|
+
above C4.
|
|
75
|
+
"""
|
|
76
|
+
return 440.0 * 2 ** ((pitch - 69) / 12)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
PITCHES = {"a": 9, "b": 11, "c": 0, "d": 2, "e": 4, "f": 5, "g": 7}
|
|
80
|
+
ACCIDENTALS = ["#", "b"]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _scientific_pitch_name_to_pitch(pitch_name: str) -> int:
|
|
84
|
+
# Reference: https://en.wikipedia.org/wiki/Scientific_pitch_notation
|
|
85
|
+
if len(pitch_name) < 2:
|
|
86
|
+
raise ValueError(f"Invalid pitch name: {pitch_name}")
|
|
87
|
+
|
|
88
|
+
# Parse pitch
|
|
89
|
+
pitch_class = pitch_name[0].lower()
|
|
90
|
+
if pitch_class not in PITCHES:
|
|
91
|
+
raise ValueError(f"Invalid pitch: {pitch_name}")
|
|
92
|
+
pitch = PITCHES[pitch_class]
|
|
93
|
+
|
|
94
|
+
# Parse accidentals
|
|
95
|
+
accidentals = pitch_name[1:-1]
|
|
96
|
+
while accidentals:
|
|
97
|
+
if accidentals.startswith("#"):
|
|
98
|
+
pitch += 1
|
|
99
|
+
elif accidentals.startswith("b"):
|
|
100
|
+
pitch -= 1
|
|
101
|
+
else:
|
|
102
|
+
raise ValueError(f"Invalid accidental: {pitch_name}")
|
|
103
|
+
accidentals = accidentals[1:]
|
|
104
|
+
|
|
105
|
+
# Parse octave
|
|
106
|
+
try:
|
|
107
|
+
octave = int(pitch_name[-1])
|
|
108
|
+
except ValueError:
|
|
109
|
+
raise ValueError(f"Invalid octave: {pitch_name}")
|
|
110
|
+
pitch += 12 * (octave + 1)
|
|
111
|
+
|
|
112
|
+
return pitch
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def pitch_name_to_pitch(pitch: str | np.ndarray) -> int | np.ndarray:
|
|
116
|
+
"""Converts scientific pitch notation (e.g. ``"C4"``) to a MIDI pitch number.
|
|
117
|
+
|
|
118
|
+
Recognized forms:
|
|
119
|
+
|
|
120
|
+
* Pitch class: one letter ``A``-``G`` (case insensitive).
|
|
121
|
+
* Accidentals (optional, may repeat): ``#`` for sharp, ``b`` for flat.
|
|
122
|
+
``"C##4"`` (double-sharp) and ``"Bbb3"`` (double-flat) both work.
|
|
123
|
+
* Octave (required): one digit, using scientific octave numbering where
|
|
124
|
+
C4 = middle C = MIDI 60 and A4 = MIDI 69.
|
|
125
|
+
|
|
126
|
+
Examples: ``"C4"`` → 60, ``"A4"`` → 69, ``"Bb3"`` → 58, ``"C#4"`` → 61.
|
|
127
|
+
|
|
128
|
+
Accepts a single string or a numpy array of strings (vectorized via
|
|
129
|
+
:func:`numpy.vectorize`). Raises ``ValueError`` on malformed input.
|
|
130
|
+
"""
|
|
131
|
+
if isinstance(pitch, str):
|
|
132
|
+
return _scientific_pitch_name_to_pitch(pitch)
|
|
133
|
+
return np.vectorize(_scientific_pitch_name_to_pitch)(pitch)
|