pyquist 0.3.0__tar.gz → 0.3.1__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 (37) hide show
  1. {pyquist-0.3.0/pyquist.egg-info → pyquist-0.3.1}/PKG-INFO +1 -1
  2. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/__init__.py +1 -1
  3. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/device.py +22 -0
  4. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/device_test.py +39 -0
  5. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/web/freesound.py +63 -31
  6. {pyquist-0.3.0 → pyquist-0.3.1/pyquist.egg-info}/PKG-INFO +1 -1
  7. {pyquist-0.3.0 → pyquist-0.3.1}/LICENSE +0 -0
  8. {pyquist-0.3.0 → pyquist-0.3.1}/README.md +0 -0
  9. {pyquist-0.3.0 → pyquist-0.3.1}/pyproject.toml +0 -0
  10. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/audio.py +0 -0
  11. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/audio_test.py +0 -0
  12. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/cli.py +0 -0
  13. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/env.py +0 -0
  14. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/env_test.py +0 -0
  15. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/helper.py +0 -0
  16. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/helper_test.py +0 -0
  17. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/paths.py +0 -0
  18. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/plot.py +0 -0
  19. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/plot_test.py +0 -0
  20. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/py.typed +0 -0
  21. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/score.py +0 -0
  22. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/score_test.py +0 -0
  23. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/stream.py +0 -0
  24. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/stream_test.py +0 -0
  25. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/test_data/232009__danmitch3ll__xylophone-sweep.wav +0 -0
  26. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/test_data/388954__fullmetaljedi__blues-riff-in-g-nylon.wav +0 -0
  27. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/test_data/434013__mrpearch__drum-patern.mp3 +0 -0
  28. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/test_data/ATTRIBUTION.md +0 -0
  29. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/test_data/ravel_bolero.mid +0 -0
  30. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/web/__init__.py +0 -0
  31. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist/web/theorytab.py +0 -0
  32. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist.egg-info/SOURCES.txt +0 -0
  33. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist.egg-info/dependency_links.txt +0 -0
  34. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist.egg-info/entry_points.txt +0 -0
  35. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist.egg-info/requires.txt +0 -0
  36. {pyquist-0.3.0 → pyquist-0.3.1}/pyquist.egg-info/top_level.txt +0 -0
  37. {pyquist-0.3.0 → pyquist-0.3.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.3.0
3
+ Version: 0.3.1
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.3.0"
1
+ __version__ = "0.3.1"
2
2
 
3
3
  from .audio import Audio
4
4
  from .device import (
@@ -98,6 +98,28 @@ def list_devices(kind: Optional[str] = None) -> None:
98
98
  _print_devices(k)
99
99
 
100
100
 
101
+ def has_audio_device(kind: str = "output") -> bool:
102
+ """Returns True if an audio device of this ``kind`` is available.
103
+
104
+ Use it to guard anything that needs a real sound card, like
105
+ :class:`~pyquist.Stream` or :func:`record`. It's False in a browser
106
+ (Pyodide / JupyterLite), on Google Colab, and on headless machines such
107
+ as CI runners, where querying the device raises instead.
108
+
109
+ Args:
110
+ kind: ``"input"`` or ``"output"`` (default).
111
+ """
112
+ if kind not in ("input", "output"):
113
+ raise ValueError(f"kind must be 'input' or 'output', got {kind!r}.")
114
+ if in_browser():
115
+ return False
116
+ try:
117
+ device = sd.query_devices(kind=kind)
118
+ except Exception:
119
+ return False
120
+ return device[f"max_{kind}_channels"] > 0
121
+
122
+
101
123
  def play(
102
124
  audio: Audio,
103
125
  *,
@@ -538,5 +538,44 @@ class TestRecordDispatch(unittest.TestCase):
538
538
  mock_browser.assert_not_called()
539
539
 
540
540
 
541
+ class TestHasAudioDevice(unittest.TestCase):
542
+ def _query(self, **kwargs):
543
+ return mock.patch.object(device.sd, "query_devices", **kwargs)
544
+
545
+ def setUp(self):
546
+ p = mock.patch.object(device, "in_browser", return_value=False)
547
+ p.start()
548
+ self.addCleanup(p.stop)
549
+
550
+ def test_true_when_default_device_has_channels(self):
551
+ speakers = {
552
+ "name": "Speakers",
553
+ "max_input_channels": 0,
554
+ "max_output_channels": 2,
555
+ }
556
+ with self._query(return_value=speakers):
557
+ self.assertTrue(device.has_audio_device())
558
+ self.assertFalse(device.has_audio_device("input"))
559
+
560
+ def test_false_when_query_raises(self):
561
+ # Headless CI: PortAudio has no default device ("Error querying
562
+ # device -1").
563
+ error = device.sd.PortAudioError("Error querying device -1")
564
+ with self._query(side_effect=error):
565
+ self.assertFalse(device.has_audio_device())
566
+
567
+ def test_false_in_browser_without_querying(self):
568
+ with (
569
+ mock.patch.object(device, "in_browser", return_value=True),
570
+ self._query() as mock_query,
571
+ ):
572
+ self.assertFalse(device.has_audio_device())
573
+ mock_query.assert_not_called()
574
+
575
+ def test_rejects_bad_kind(self):
576
+ with self.assertRaises(ValueError):
577
+ device.has_audio_device("both")
578
+
579
+
541
580
  if __name__ == "__main__":
542
581
  unittest.main()
@@ -11,6 +11,7 @@ Credentials and downloaded files are cached under ``CACHE_DIR / "freesound"``.
11
11
  import json
12
12
  import pathlib
13
13
  import re
14
+ import time
14
15
  from io import BytesIO
15
16
  from typing import Optional, Tuple, Union
16
17
  from urllib.parse import urlparse
@@ -27,6 +28,8 @@ _OAUTH_TOKEN_PATH = _CACHE_DIR / "oauthv2_token.json"
27
28
  _API_BASE = "https://freesound.org/apiv2"
28
29
  _OAUTH_AUTHORIZE_URL = f"{_API_BASE}/oauth2/authorize/"
29
30
  _OAUTH_TOKEN_URL = f"{_API_BASE}/oauth2/access_token/"
31
+ # Treat tokens as expired slightly early to avoid racing the server clock.
32
+ _TOKEN_EXPIRY_MARGIN_S = 60
30
33
 
31
34
  # Matches paths like "/sounds/123456" or "/people/<user>/sounds/123456" with
32
35
  # an optional trailing slash. Captures the numeric ID.
@@ -114,48 +117,70 @@ def _credentials(*, reauthenticate: bool = False) -> Tuple[str, str]:
114
117
  return client_id, client_secret
115
118
 
116
119
 
120
+ def _request_token(client_id: str, client_secret: str, **grant: str) -> dict:
121
+ """POSTs to the OAuth2 token endpoint and caches the resulting token."""
122
+ response = requests.post(
123
+ _OAUTH_TOKEN_URL,
124
+ data={"client_id": client_id, "client_secret": client_secret, **grant},
125
+ )
126
+ if response.status_code != 200:
127
+ raise RuntimeError(
128
+ f"OAuth token request failed: {response.status_code} - {response.text}"
129
+ )
130
+ token_data = response.json()
131
+ if "access_token" not in token_data:
132
+ raise RuntimeError(f"OAuth response missing access_token: {token_data}")
133
+ # Stash credentials and issue time alongside the token for refresh logic.
134
+ token_data["client_id"] = client_id
135
+ token_data["client_secret"] = client_secret
136
+ token_data["obtained_at"] = time.time()
137
+ _save_json(_OAUTH_TOKEN_PATH, token_data)
138
+ return token_data
139
+
140
+
141
+ def _token_expired(token_data: dict) -> bool:
142
+ # Tokens cached before ``obtained_at`` was recorded are treated as expired.
143
+ obtained_at = token_data.get("obtained_at")
144
+ if obtained_at is None:
145
+ return True
146
+ expires_in = float(token_data.get("expires_in", 0))
147
+ return time.time() >= obtained_at + expires_in - _TOKEN_EXPIRY_MARGIN_S
148
+
149
+
117
150
  def _oauth_token(*, reauthenticate: bool = False) -> str:
118
- """Returns a FreeSound OAuth2 access token — cached or freshly obtained.
151
+ """Returns a FreeSound OAuth2 access token — cached, refreshed, or new.
119
152
 
120
153
  Only needed for downloading the original (uncompressed) sound files;
121
154
  fetching previews uses the API key alone.
122
155
 
123
- .. note::
124
- Refresh-token handling is not implemented. If the cached token
125
- expires, the user can pass ``reauthenticate=True`` to re-run the
126
- flow.
156
+ A cached token is reused while valid. Once expired, the refresh token is
157
+ tried; if that fails (or ``reauthenticate`` is set), the interactive
158
+ authorization flow runs again.
127
159
  """
128
160
  if not reauthenticate:
129
161
  cached = _load_json(_OAUTH_TOKEN_PATH)
130
162
  if cached and "access_token" in cached:
131
- return cached["access_token"]
163
+ if not _token_expired(cached):
164
+ return cached["access_token"]
165
+ if cached.get("refresh_token"):
166
+ try:
167
+ return _request_token(
168
+ cached["client_id"],
169
+ cached["client_secret"],
170
+ grant_type="refresh_token",
171
+ refresh_token=cached["refresh_token"],
172
+ )["access_token"]
173
+ except (RuntimeError, KeyError, requests.RequestException):
174
+ pass
175
+ print("FreeSound authorization has expired.")
132
176
 
133
177
  client_id, client_secret = _credentials(reauthenticate=reauthenticate)
134
178
  print("To authorize this app, visit:")
135
179
  print(f" {_OAUTH_AUTHORIZE_URL}?client_id={client_id}&response_type=code")
136
180
  code = input("Authorization code: ").strip()
137
-
138
- response = requests.post(
139
- _OAUTH_TOKEN_URL,
140
- data={
141
- "client_id": client_id,
142
- "client_secret": client_secret,
143
- "grant_type": "authorization_code",
144
- "code": code,
145
- },
146
- )
147
- if response.status_code != 200:
148
- raise RuntimeError(
149
- f"OAuth token request failed: {response.status_code} - {response.text}"
150
- )
151
- token_data = response.json()
152
- if "access_token" not in token_data:
153
- raise RuntimeError(f"OAuth response missing access_token: {token_data}")
154
- # Stash credentials alongside the token for future refresh logic.
155
- token_data["client_id"] = client_id
156
- token_data["client_secret"] = client_secret
157
- _save_json(_OAUTH_TOKEN_PATH, token_data)
158
- return token_data["access_token"]
181
+ return _request_token(
182
+ client_id, client_secret, grant_type="authorization_code", code=code
183
+ )["access_token"]
159
184
 
160
185
 
161
186
  # ---------------------------------------------------------------------------
@@ -218,17 +243,24 @@ def fetch_audio_bytes(
218
243
  cache_path = (
219
244
  _CACHE_DIR / str(sound_id) / f"{preview_tag[:-4]}.{preview_tag[-3:]}"
220
245
  )
221
- headers = None
222
246
  else:
223
247
  url = f"{_API_BASE}/sounds/{sound_id}/download/"
224
248
  cache_path = _CACHE_DIR / str(sound_id) / f"original.{metadata['type']}"
225
- token = _oauth_token(reauthenticate=reauthenticate)
226
- headers = {"Authorization": f"Bearer {token}"}
227
249
 
228
250
  if cache_path.exists():
229
251
  return cache_path.read_bytes(), metadata
230
252
 
253
+ headers = None
254
+ if preview_tag is None:
255
+ token = _oauth_token(reauthenticate=reauthenticate)
256
+ headers = {"Authorization": f"Bearer {token}"}
257
+
231
258
  response = requests.get(url, headers=headers)
259
+ if response.status_code == 401 and preview_tag is None:
260
+ raise RuntimeError(
261
+ "FreeSound rejected the OAuth token. Pass reauthenticate=True "
262
+ f"or delete {_OAUTH_TOKEN_PATH} to authorize again."
263
+ )
232
264
  if response.status_code != 200:
233
265
  raise RuntimeError(
234
266
  f"FreeSound download failed for sound {sound_id}: "
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyquist
3
- Version: 0.3.0
3
+ Version: 0.3.1
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
File without changes
File without changes
File without changes
File without changes
File without changes