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.
@@ -0,0 +1,288 @@
1
+ """FreeSound API client.
2
+
3
+ Most users only need :func:`fetch_freesound`, which downloads a sound by URL
4
+ or numeric ID and returns it as an :class:`pyquist.Audio`. Previews download
5
+ without authentication; fetching the original uncompressed file requires the
6
+ FreeSound OAuth2 flow (walked through interactively on first use).
7
+
8
+ Credentials and downloaded files are cached under ``CACHE_DIR / "freesound"``.
9
+ """
10
+
11
+ import json
12
+ import pathlib
13
+ import re
14
+ from io import BytesIO
15
+ from typing import Optional, Tuple, Union
16
+ from urllib.parse import urlparse
17
+
18
+ import requests
19
+
20
+ from ..audio import Audio
21
+ from ..paths import CACHE_DIR
22
+
23
+ _CACHE_DIR = CACHE_DIR / "freesound"
24
+ _API_KEY_PATH = _CACHE_DIR / "api_key.json"
25
+ _OAUTH_TOKEN_PATH = _CACHE_DIR / "oauthv2_token.json"
26
+
27
+ _API_BASE = "https://freesound.org/apiv2"
28
+ _OAUTH_AUTHORIZE_URL = f"{_API_BASE}/oauth2/authorize/"
29
+ _OAUTH_TOKEN_URL = f"{_API_BASE}/oauth2/access_token/"
30
+
31
+ # Matches paths like "/sounds/123456" or "/people/<user>/sounds/123456" with
32
+ # an optional trailing slash. Captures the numeric ID.
33
+ _URL_PATH_PATTERN = re.compile(r"^/(?:people/[^/]+/)?sounds/(\d+)/?$")
34
+
35
+ _VALID_PREVIEW_TAGS = (
36
+ "preview-hq-mp3",
37
+ "preview-hq-ogg",
38
+ "preview-lq-mp3",
39
+ "preview-lq-ogg",
40
+ )
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # URL / ID parsing
45
+ # ---------------------------------------------------------------------------
46
+
47
+
48
+ def url_to_id(id_or_url: Union[int, str]) -> int:
49
+ """Parses a FreeSound URL or numeric ID into an integer sound ID.
50
+
51
+ Accepted forms:
52
+
53
+ * ``123456`` — raw int
54
+ * ``"123456"`` — numeric string
55
+ * ``"https://freesound.org/sounds/123456/"``
56
+ * ``"https://freesound.org/people/<user>/sounds/123456/"``
57
+ * ``http://`` and ``www.`` variants of the above
58
+
59
+ Raises ``ValueError`` if the input isn't a recognized FreeSound URL or
60
+ a numeric ID.
61
+ """
62
+ if isinstance(id_or_url, int):
63
+ return id_or_url
64
+ s = id_or_url.strip()
65
+ if s.isdigit():
66
+ return int(s)
67
+ parsed = urlparse(s)
68
+ host = parsed.netloc.lower().removeprefix("www.")
69
+ if host != "freesound.org":
70
+ raise ValueError(f"Not a FreeSound URL or numeric ID: {id_or_url!r}.")
71
+ match = _URL_PATH_PATTERN.match(parsed.path)
72
+ if not match:
73
+ raise ValueError(f"Could not extract sound ID from URL: {id_or_url!r}.")
74
+ return int(match.group(1))
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Credential storage
79
+ # ---------------------------------------------------------------------------
80
+
81
+
82
+ def _load_json(path: pathlib.Path) -> Optional[dict]:
83
+ if not path.exists():
84
+ return None
85
+ try:
86
+ with open(path, "r") as f:
87
+ return json.load(f)
88
+ except (json.JSONDecodeError, OSError):
89
+ return None
90
+
91
+
92
+ def _save_json(path: pathlib.Path, data: dict) -> None:
93
+ path.parent.mkdir(parents=True, exist_ok=True)
94
+ with open(path, "w") as f:
95
+ json.dump(data, f)
96
+
97
+
98
+ def _credentials(*, reauthenticate: bool = False) -> Tuple[str, str]:
99
+ """Returns ``(client_id, client_secret)`` — cached or prompted.
100
+
101
+ On first use (or when ``reauthenticate=True``) walks the user through
102
+ creating a FreeSound API key.
103
+ """
104
+ if not reauthenticate:
105
+ cached = _load_json(_API_KEY_PATH)
106
+ if cached:
107
+ return cached["client_id"].strip(), cached["client_secret"].strip()
108
+
109
+ print("FreeSound API credentials required.")
110
+ print("Create an API key at https://freesound.org/apiv2/apply")
111
+ client_id = input("Client ID: ").strip()
112
+ client_secret = input("Client secret: ").strip()
113
+ _save_json(_API_KEY_PATH, {"client_id": client_id, "client_secret": client_secret})
114
+ return client_id, client_secret
115
+
116
+
117
+ def _oauth_token(*, reauthenticate: bool = False) -> str:
118
+ """Returns a FreeSound OAuth2 access token — cached or freshly obtained.
119
+
120
+ Only needed for downloading the original (uncompressed) sound files;
121
+ fetching previews uses the API key alone.
122
+
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.
127
+ """
128
+ if not reauthenticate:
129
+ cached = _load_json(_OAUTH_TOKEN_PATH)
130
+ if cached and "access_token" in cached:
131
+ return cached["access_token"]
132
+
133
+ client_id, client_secret = _credentials(reauthenticate=reauthenticate)
134
+ print("To authorize this app, visit:")
135
+ print(f" {_OAUTH_AUTHORIZE_URL}?client_id={client_id}&response_type=code")
136
+ 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"]
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # API calls
163
+ # ---------------------------------------------------------------------------
164
+
165
+
166
+ def fetch_metadata(sound_id: int, *, reauthenticate: bool = False) -> dict:
167
+ """Fetches the FreeSound JSON metadata for a sound (cached on disk)."""
168
+ cache_path = _CACHE_DIR / str(sound_id) / "metadata.json"
169
+ cached = _load_json(cache_path)
170
+ if cached is not None:
171
+ return cached
172
+
173
+ # The FreeSound API accepts the API key as a query-string ``token``.
174
+ _, api_key = _credentials(reauthenticate=reauthenticate)
175
+ response = requests.get(f"{_API_BASE}/sounds/{sound_id}", params={"token": api_key})
176
+ if response.status_code == 404:
177
+ raise ValueError(f"FreeSound sound {sound_id} not found.")
178
+ if response.status_code != 200:
179
+ raise RuntimeError(
180
+ f"FreeSound metadata request failed for sound {sound_id}: "
181
+ f"{response.status_code} - {response.text}"
182
+ )
183
+ metadata = response.json()
184
+ _save_json(cache_path, metadata)
185
+ return metadata
186
+
187
+
188
+ def fetch_audio_bytes(
189
+ sound_id: int,
190
+ *,
191
+ preview_tag: Optional[str] = "preview-hq-ogg",
192
+ reauthenticate: bool = False,
193
+ ) -> Tuple[bytes, dict]:
194
+ """Downloads the raw audio bytes for a sound, plus its metadata.
195
+
196
+ Args:
197
+ sound_id: FreeSound numeric ID.
198
+ preview_tag: Which preview to download. One of ``"preview-hq-ogg"``
199
+ (default), ``"preview-hq-mp3"``, ``"preview-lq-ogg"``, or
200
+ ``"preview-lq-mp3"``. Pass ``None`` to download the original
201
+ uncompressed file instead — this requires OAuth2 and triggers an
202
+ interactive auth flow on first use.
203
+ reauthenticate: Force a re-prompt of API credentials.
204
+
205
+ Returns ``(audio_bytes, metadata)``. Both are cached on disk so repeated
206
+ calls for the same sound are free.
207
+ """
208
+ metadata = fetch_metadata(sound_id, reauthenticate=reauthenticate)
209
+
210
+ if preview_tag is not None:
211
+ if preview_tag not in _VALID_PREVIEW_TAGS:
212
+ raise ValueError(
213
+ f"Invalid preview_tag {preview_tag!r}; "
214
+ f"must be one of {list(_VALID_PREVIEW_TAGS)} or None."
215
+ )
216
+ url = metadata["previews"][preview_tag]
217
+ # preview_tag has the form "preview-hq-ogg"; the last 3 chars are the extension.
218
+ cache_path = (
219
+ _CACHE_DIR / str(sound_id) / f"{preview_tag[:-4]}.{preview_tag[-3:]}"
220
+ )
221
+ headers = None
222
+ else:
223
+ url = f"{_API_BASE}/sounds/{sound_id}/download/"
224
+ cache_path = _CACHE_DIR / str(sound_id) / f"original.{metadata['type']}"
225
+ token = _oauth_token(reauthenticate=reauthenticate)
226
+ headers = {"Authorization": f"Bearer {token}"}
227
+
228
+ if cache_path.exists():
229
+ return cache_path.read_bytes(), metadata
230
+
231
+ response = requests.get(url, headers=headers)
232
+ if response.status_code != 200:
233
+ raise RuntimeError(
234
+ f"FreeSound download failed for sound {sound_id}: "
235
+ f"{response.status_code} - {response.text}"
236
+ )
237
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
238
+ cache_path.write_bytes(response.content)
239
+ return response.content, metadata
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # Public entry point
244
+ # ---------------------------------------------------------------------------
245
+
246
+
247
+ def fetch_freesound(
248
+ id_or_url: Union[int, str],
249
+ *,
250
+ preview_tag: Optional[str] = "preview-hq-ogg",
251
+ reauthenticate: bool = False,
252
+ ) -> Tuple[Audio, dict]:
253
+ """Fetches an ``Audio`` (and metadata) from FreeSound by URL or numeric ID.
254
+
255
+ Example::
256
+
257
+ from pyquist.web import fetch_freesound
258
+ audio, meta = fetch_freesound(
259
+ "https://freesound.org/people/cdonahueucsd/sounds/337131/"
260
+ )
261
+
262
+ Args:
263
+ id_or_url: A FreeSound URL or numeric sound ID. See :func:`url_to_id`
264
+ for the recognized URL forms.
265
+ preview_tag: Which preview to fetch (default high-quality OGG). Pass
266
+ ``None`` to fetch the original uncompressed file (OAuth2 required).
267
+ reauthenticate: Force a re-prompt of API credentials.
268
+
269
+ Returns:
270
+ ``(audio, metadata)`` — ``audio`` is decoded via
271
+ :meth:`pyquist.Audio.from_file` and ``metadata`` is the raw JSON dict
272
+ returned by the FreeSound API.
273
+ """
274
+ sound_id = url_to_id(id_or_url)
275
+ audio_bytes, metadata = fetch_audio_bytes(
276
+ sound_id, preview_tag=preview_tag, reauthenticate=reauthenticate
277
+ )
278
+ return Audio.from_file(BytesIO(audio_bytes)), metadata
279
+
280
+
281
+ if __name__ == "__main__":
282
+ import sys
283
+
284
+ from ..device import play
285
+
286
+ audio, metadata = fetch_freesound(sys.argv[1])
287
+ print(json.dumps(metadata, indent=2))
288
+ play(audio)
@@ -0,0 +1,408 @@
1
+ """TheoryTab API client.
2
+
3
+ `TheoryTab <https://www.hooktheory.com/theorytab>`_ is a community database of
4
+ pop-song melody and chord progressions hosted by Hooktheory. This module
5
+ fetches a song by URL or 11-character ID and turns it into pyquist
6
+ :class:`pyquist.Score` objects ready for rendering.
7
+
8
+ Most users only need :func:`fetch`, which combines :func:`fetch_theorytab_json`
9
+ (network + caching) with :func:`theorytab_json_to_score` (parsing).
10
+
11
+ Downloaded JSON is cached under ``CACHE_DIR / "theorytab"`` so repeat lookups
12
+ are free.
13
+ """
14
+
15
+ import json
16
+ from typing import Any, Dict, List, Tuple
17
+ from urllib.parse import parse_qs, urlparse
18
+
19
+ import numpy as np
20
+ import requests
21
+
22
+ from ..helper import pitch_name_to_pitch
23
+ from ..paths import CACHE_DIR as _ROOT_CACHE_DIR
24
+ from ..score import BasicMetronome, Event, Metronome, Score
25
+
26
+ _CACHE_DIR = _ROOT_CACHE_DIR / "theorytab"
27
+
28
+ # TheoryTab song identifiers (``idOfSong`` in Hookpad URLs) are 11 characters.
29
+ _THEORYTAB_ID_LENGTH = 11
30
+
31
+ _HOOKTHEORY_API_URL = "https://api.hooktheory.com/v1/songs/public"
32
+
33
+ # Diatonic scales as ordered (whole-/half-) step intervals between successive
34
+ # notes. Each tuple has 6 entries (7 notes → 6 gaps).
35
+ _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS = {
36
+ "major": (2, 2, 1, 2, 2, 2),
37
+ "dorian": (2, 1, 2, 2, 2, 1),
38
+ "phrygian": (1, 2, 2, 2, 1, 2),
39
+ "lydian": (2, 2, 2, 1, 2, 2),
40
+ "mixolydian": (2, 2, 1, 2, 2, 1),
41
+ "minor": (2, 1, 2, 2, 1, 2),
42
+ "locrian": (1, 2, 2, 1, 2, 2),
43
+ "harmonicMinor": (2, 1, 2, 2, 1, 3),
44
+ "phrygianDominant": (1, 3, 1, 2, 1, 2),
45
+ }
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Music-theory helpers
50
+ # ---------------------------------------------------------------------------
51
+
52
+
53
+ def _cumulative_intervals(intervals: Tuple[int, int, int, int, int, int]) -> List[int]:
54
+ """Converts inter-note steps to cumulative semitones from the tonic.
55
+
56
+ e.g. major ``(2, 2, 1, 2, 2, 2)`` → ``[0, 2, 4, 5, 7, 9, 11]``.
57
+ """
58
+ assert len(intervals) == 6
59
+ return [0] + np.cumsum(intervals).tolist()
60
+
61
+
62
+ def _theorytab_note_to_pitch(note: Dict[str, Any], key: Dict[str, Any]) -> int:
63
+ """Converts a TheoryTab JSON melody note into an absolute MIDI pitch.
64
+
65
+ TheoryTab notates pitches as ``<accidentals><scale-degree>`` (e.g. ``"#5"``,
66
+ ``"b3"``, ``"5"``) plus an ``octave`` integer. The scale degree is
67
+ interpreted in the song's current scale; accidentals shift by ±1 semitone.
68
+ """
69
+ sd_str = note["sd"]
70
+ *accidentals, degree_char = sd_str
71
+ degree = int(degree_char)
72
+
73
+ key_pitches = _cumulative_intervals(
74
+ _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS[key["scale"]]
75
+ )
76
+ pitch = key_pitches[degree - 1]
77
+ for c in accidentals:
78
+ if c == "#":
79
+ pitch += 1
80
+ elif c == "b":
81
+ pitch -= 1
82
+ else:
83
+ raise ValueError(f"Invalid scale degree {sd_str!r}: unexpected {c!r}.")
84
+
85
+ pitch += int(pitch_name_to_pitch(key["tonic"] + "0"))
86
+ pitch += note["octave"] * 12
87
+ return pitch
88
+
89
+
90
+ def _theorytab_chord_to_pitches(
91
+ chord: Dict[str, Any], key: Dict[str, Any]
92
+ ) -> List[int]:
93
+ """Converts a TheoryTab JSON chord into a list of absolute MIDI pitches.
94
+
95
+ Handles type (triad / 7 / 9 / ...), suspensions, additions, omissions,
96
+ alterations, borrowed scales, and secondary dominants. Returns the chord
97
+ in root position (no inversions).
98
+ """
99
+ # Build chord scale degrees
100
+ chord_degrees = set(range(1, chord["type"] + 1, 2))
101
+
102
+ # Apply suspensions
103
+ for i, d in enumerate(chord["suspensions"]):
104
+ if i == 0:
105
+ assert 3 in chord_degrees
106
+ chord_degrees.remove(3)
107
+ assert d not in chord_degrees
108
+ chord_degrees.add(d)
109
+
110
+ # Apply adds
111
+ for d in chord["adds"]:
112
+ if d in [4, 6]:
113
+ d += 7
114
+ chord_degrees.add(d)
115
+
116
+ # Apply omits
117
+ for d in chord["omits"]:
118
+ assert d in [3, 5]
119
+ assert d in chord_degrees
120
+ chord_degrees.remove(d)
121
+
122
+ # Apply alterations
123
+ for d in chord["alterations"]:
124
+ d = int(d[1:])
125
+ chord_degrees.add(d)
126
+
127
+ chord_degrees_list = sorted(chord_degrees)
128
+
129
+ # Find scale intervals
130
+ key_tonic_pc = pitch_name_to_pitch(key["tonic"] + "0")
131
+ key_scale_intervals_rel = _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS[key["scale"]]
132
+
133
+ # Apply borrow (changes intervals)
134
+ if isinstance(chord["borrowed"], list):
135
+ key_scale_intervals = chord["borrowed"]
136
+ else:
137
+ if chord["borrowed"] in _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS:
138
+ key_scale_intervals_rel = _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS[
139
+ chord["borrowed"]
140
+ ]
141
+ key_scale_intervals = _cumulative_intervals(key_scale_intervals_rel)
142
+ assert len(key_scale_intervals) == 7
143
+
144
+ # Apply secondary (changes tonic and intervals)
145
+ major_scale_intervals = _cumulative_intervals(
146
+ _THEORYTAB_SCALE_NAME_TO_PITCH_INTERVALS["major"]
147
+ )
148
+ if chord["applied"] > 0:
149
+ key_tonic_pc = (key_tonic_pc + key_scale_intervals[chord["root"] - 1]) % 12
150
+ chord["root"] = chord["applied"]
151
+ key_scale_intervals = major_scale_intervals
152
+
153
+ # Convert scale degrees to pitch offsets
154
+ chord_degree_to_interval = {}
155
+ for d in chord_degrees_list:
156
+ d_abs = (chord["root"] - 1) + (d - 1)
157
+ interval = key_scale_intervals[d_abs % 7]
158
+ interval += 12 * (d_abs // 7)
159
+ chord_degree_to_interval[d] = interval
160
+ # NOTE: Not sure if this is a bug in Hookpad or what?
161
+ if d == 7 and chord["applied"] == 7:
162
+ chord_degree_to_interval[d] -= 1
163
+
164
+ # Apply alterations
165
+ for alt in chord["alterations"]:
166
+ d = int(alt[1:])
167
+ assert d in chord_degree_to_interval
168
+ chord_degree_to_interval[d] += -1 if alt[0] == "b" else 1
169
+
170
+ return [key_tonic_pc + v for _, v in chord_degree_to_interval.items()]
171
+
172
+
173
+ # ---------------------------------------------------------------------------
174
+ # URL / ID parsing
175
+ # ---------------------------------------------------------------------------
176
+
177
+
178
+ def _extract_theorytab_id(id_or_url: str) -> str:
179
+ """Returns the 11-character TheoryTab song ID for ``id_or_url``.
180
+
181
+ Accepts either a bare ID or a Hookpad/Hooktheory URL containing an
182
+ ``idOfSong=...`` query parameter (e.g.
183
+ ``https://hookpad.hooktheory.com/?idOfSong=RPxeJeJaob_``).
184
+ Raises ``ValueError`` if neither form is recognized.
185
+ """
186
+ s = id_or_url.strip()
187
+ if len(s) == _THEORYTAB_ID_LENGTH:
188
+ return s
189
+ url = urlparse(s)
190
+ if "hooktheory.com" not in url.netloc:
191
+ raise ValueError(f"Not a TheoryTab URL or ID: {id_or_url!r}.")
192
+ ids = parse_qs(url.query).get("idOfSong")
193
+ if not ids:
194
+ raise ValueError(
195
+ f"TheoryTab URL is missing 'idOfSong' query parameter: {id_or_url!r}."
196
+ )
197
+ return ids[0]
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # Public API
202
+ # ---------------------------------------------------------------------------
203
+
204
+
205
+ def fetch_theorytab_json(id_or_url: str, *, ignore_cache: bool = False) -> dict:
206
+ """Fetches the raw TheoryTab JSON for a song, caching it on disk.
207
+
208
+ Args:
209
+ id_or_url: A bare 11-character TheoryTab song ID or any URL that
210
+ contains it as the ``idOfSong`` query parameter.
211
+ ignore_cache: If ``True``, re-fetch even if a cached copy exists.
212
+
213
+ Raises:
214
+ ValueError: if ``id_or_url`` can't be parsed.
215
+ RuntimeError: on a non-200 response from the Hooktheory API or
216
+ unexpected response shape.
217
+ NotImplementedError: if the song's data is in a legacy format
218
+ without parsed ``jsonData``.
219
+ """
220
+ theorytab_id = _extract_theorytab_id(id_or_url)
221
+ assert len(theorytab_id) == _THEORYTAB_ID_LENGTH
222
+
223
+ cache_file = _CACHE_DIR / f"{theorytab_id}.json"
224
+ if cache_file.exists() and not ignore_cache:
225
+ with open(cache_file, "r") as f:
226
+ return json.load(f)
227
+
228
+ response = requests.get(
229
+ f"{_HOOKTHEORY_API_URL}/{theorytab_id}",
230
+ params={"fields": "ID,song,jsonData"},
231
+ )
232
+ if response.status_code != 200:
233
+ raise RuntimeError(
234
+ f"TheoryTab API request failed for {theorytab_id}: "
235
+ f"{response.status_code} - {response.text}"
236
+ )
237
+ data = response.json()
238
+ if "jsonData" not in data:
239
+ raise RuntimeError(f"Unexpected response from TheoryTab API: {data}")
240
+ if data["jsonData"] is None:
241
+ # TODO(chrisdonahue): parse legacy XML data?
242
+ raise NotImplementedError(
243
+ "This song has an unsupported format. Try a different one."
244
+ )
245
+ result = json.loads(data["jsonData"])
246
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
247
+ with open(cache_file, "w") as f:
248
+ json.dump(result, f)
249
+ return result
250
+
251
+
252
+ def theorytab_json_to_score(
253
+ song_data: dict,
254
+ *,
255
+ durations_in_beats: bool = False,
256
+ melody_octave: int = 5,
257
+ harmony_octave: int = 4,
258
+ ) -> Tuple[Metronome, Score, Score]:
259
+ """Parses a TheoryTab JSON object into a metronome and two scores.
260
+
261
+ The ``time`` of each event is in **beats** (starting from 0). Pair it
262
+ with the returned :class:`BasicMetronome` when rendering so beats are
263
+ converted to seconds.
264
+
265
+ Chord events are emitted as one :class:`Event` per chord tone in
266
+ root position, each with a ``"pitch"`` kwarg — so a triad at beat 4
267
+ becomes three events sharing ``time == 4.0``.
268
+
269
+ Args:
270
+ song_data: TheoryTab JSON (as returned by :func:`fetch_theorytab_json`).
271
+ durations_in_beats: If ``False`` (default), each event's
272
+ ``kwargs["duration"]`` is converted to **seconds** via the
273
+ song's tempo. If ``True``, durations stay in beats and the
274
+ instrument is responsible for any further conversion.
275
+ melody_octave: Octave offset added to melody pitches.
276
+ harmony_octave: Octave offset added to harmony pitches.
277
+
278
+ Returns:
279
+ ``(metronome, melody, harmony)`` where ``metronome`` is a
280
+ :class:`BasicMetronome` carrying the song's tempo, and ``melody`` /
281
+ ``harmony`` are :class:`Score` objects.
282
+
283
+ Raises:
284
+ NotImplementedError: if the song's time signature / tempo / key
285
+ structure is more complex than this parser supports.
286
+ """
287
+ # We only support single-section songs in 3/4 or 4/4, single-tempo, single-key.
288
+ meters = song_data["meters"]
289
+ if (
290
+ len(meters) != 1
291
+ or meters[0]["beat"] != 1
292
+ or meters[0]["numBeats"] not in [3, 4]
293
+ or meters[0]["beatUnit"] != 1
294
+ ):
295
+ raise NotImplementedError(
296
+ "This song has an unsupported time signature. Try a different one."
297
+ )
298
+ tempos = song_data["tempos"]
299
+ if len(tempos) != 1 or tempos[0]["beat"] != 1:
300
+ raise NotImplementedError(
301
+ "This song has an unsupported tempo. Try a different one."
302
+ )
303
+ keys = song_data["keys"]
304
+ if len(keys) != 1 or keys[0]["beat"] != 1:
305
+ raise NotImplementedError(
306
+ "This song has an unsupported key signature. Try a different one."
307
+ )
308
+
309
+ metronome = BasicMetronome(tempos[0]["bpm"])
310
+ key = keys[0]
311
+
312
+ # Parse melody
313
+ melody: List[Event] = []
314
+ for note in song_data["notes"]:
315
+ if note["isRest"]:
316
+ continue
317
+ beat = note["beat"] - 1.0
318
+ duration = note["duration"]
319
+ if not durations_in_beats:
320
+ duration = metronome.tick_to_seconds(duration)
321
+ pitch = _theorytab_note_to_pitch(note, key) + melody_octave * 12
322
+ melody.append(Event(beat, {"duration": duration, "pitch": pitch}))
323
+ melody.sort(key=lambda e: e.time)
324
+
325
+ # Parse harmony (chords)
326
+ harmony: List[Event] = []
327
+ for chord in song_data["chords"]:
328
+ if chord["isRest"]:
329
+ continue
330
+ beat = chord["beat"] - 1.0
331
+ duration = chord["duration"]
332
+ if not durations_in_beats:
333
+ duration = metronome.tick_to_seconds(duration)
334
+ pitches = _theorytab_chord_to_pitches(chord, key)
335
+ for pitch in pitches:
336
+ harmony.append(
337
+ Event(
338
+ beat,
339
+ {"duration": duration, "pitch": pitch + harmony_octave * 12},
340
+ )
341
+ )
342
+ harmony.sort(key=lambda e: e.time)
343
+
344
+ return metronome, Score(melody), Score(harmony)
345
+
346
+
347
+ def fetch_theorytab(id_or_url: str, **kwargs) -> Tuple[Metronome, Score, Score]:
348
+ """Fetches and parses a TheoryTab song in one call.
349
+
350
+ Equivalent to ``theorytab_json_to_score(fetch_theorytab_json(id_or_url),
351
+ **kwargs)``.
352
+
353
+ Example::
354
+
355
+ from pyquist.web import fetch_theorytab
356
+ metronome, melody, harmony = fetch_theorytab(
357
+ "https://hookpad.hooktheory.com/?idOfSong=RPxeJeJaob_"
358
+ )
359
+
360
+ To get a URL: find a song on `TheoryTab
361
+ <https://www.hooktheory.com/theorytab>`_, right-click "Open in Hookpad",
362
+ and "Copy Link Address."
363
+
364
+ Args:
365
+ id_or_url: A bare 11-character TheoryTab ID or a Hookpad/Hooktheory URL.
366
+ **kwargs: Forwarded to :func:`theorytab_json_to_score`.
367
+ """
368
+ return theorytab_json_to_score(fetch_theorytab_json(id_or_url), **kwargs)
369
+
370
+
371
+ if __name__ == "__main__":
372
+ import sys
373
+
374
+ from ..audio import Audio
375
+ from ..device import play
376
+ from ..helper import db_to_amplitude, pitch_to_frequency
377
+
378
+ if len(sys.argv) != 2:
379
+ raise SystemExit("Usage: python -m pyquist.web.theorytab <id-or-url>")
380
+
381
+ def _osc(
382
+ duration: float, pitch: int, dbfs: float, sample_rate: int = 44100
383
+ ) -> Audio:
384
+ """A tiny sine-wave instrument. TODO: add an envelope."""
385
+ t = np.arange(int(duration * sample_rate)) / sample_rate
386
+ samples = np.sin(2 * np.pi * t * pitch_to_frequency(pitch)) * db_to_amplitude(
387
+ dbfs
388
+ )
389
+ return Audio(samples, sample_rate=sample_rate)
390
+
391
+ def _melody(**kwargs):
392
+ return _osc(**kwargs, dbfs=-12)
393
+
394
+ def _harmony(**kwargs):
395
+ return _osc(**kwargs, dbfs=-18)
396
+
397
+ # Grab the score and render each part with its own instrument, then mix.
398
+ metronome, melody, harmony = fetch_theorytab(sys.argv[1])
399
+ melody_audio = melody.render(_melody, metronome=metronome)
400
+ harmony_audio = harmony.render(_harmony, metronome=metronome)
401
+ mixed = Audio.zeros(
402
+ max(melody_audio.num_samples, harmony_audio.num_samples),
403
+ 1,
404
+ sample_rate=melody_audio.sample_rate,
405
+ )
406
+ mixed[: melody_audio.num_samples, :] += melody_audio
407
+ mixed[: harmony_audio.num_samples, :] += harmony_audio
408
+ play(mixed, normalize=True)