chordotomy 0.2.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.
chordotomy/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """chordotomy: dissect a song's harmony."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("chordotomy")
chordotomy/beats.py ADDED
@@ -0,0 +1,298 @@
1
+ """The Beat This! beat grid for the model engine, and the weights it runs on.
2
+
3
+ Beat This! (Foscarin, Schlüter & Widmer, ISMIR 2024; code and weights MIT) finds beats and
4
+ downbeats with a transformer. Its checkpoint is not in the package: it is downloaded on first use
5
+ into the cache, pinned to a SHA-256 and checked on every load, and `chordotomy fetch-weights`
6
+ fetches it ahead of time.
7
+
8
+ beat_this and torch are imported only inside the functions that use them, so importing this
9
+ module loads neither and the DSP path never pays for them.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import hashlib
16
+ import inspect
17
+ import os
18
+ import pickle
19
+ import tempfile
20
+ from collections.abc import Callable
21
+ from http.client import HTTPException
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING
24
+ from urllib.request import urlopen
25
+
26
+ import librosa
27
+ import numpy as np
28
+ from scipy.special import expit
29
+
30
+ from .features import HOP, SR, NoBeatsError
31
+ from .model import EngineError
32
+
33
+ if TYPE_CHECKING:
34
+ from beat_this.model.beat_tracker import BeatThis
35
+
36
+ CHECKPOINT = "final0"
37
+ # beat_this.inference.CHECKPOINT_URL, copied because that module imports torchaudio and so cannot
38
+ # be read without the extra.
39
+ CHECKPOINT_URL = "https://cloud.cp.jku.at/public.php/dav/files/7ik4RrBKTS273gp"
40
+ # name -> (SHA-256, bytes). The pin is ours, not the server's: the URL has changed once before.
41
+ CHECKPOINTS = {
42
+ "final0": ("8c328b45f59d8dd3dff219253ff6a8d6482be57d0133a29140e2febbf8eb8331", 81_058_141),
43
+ }
44
+ CACHE_DIR: Path | None = None
45
+ _TIMEOUT = 30 # seconds per socket operation, not for the whole download
46
+ _CHUNK = 1 << 20
47
+ _REFETCH = "run `chordotomy fetch-weights` once online, or pass --engine dsp"
48
+ _REINSTALL = (
49
+ "reinstall beat-this with `uv sync --extra model --reinstall-package beat-this`, "
50
+ "or pass --engine dsp"
51
+ )
52
+
53
+ # beat_this.preprocessing.LogMelSpect's spectrogram, of a signal at SR as LogMelSpect expects:
54
+ # FPS frames a second, MEL_HOP = SR / FPS samples apart.
55
+ FPS = 50
56
+ N_FFT = 1024
57
+ MEL_HOP = 441
58
+ N_MELS = 128
59
+ FMIN = 30
60
+ FMAX = 11000
61
+ LOG_MULTIPLIER = 1000
62
+ # beat_this.inference.Spect2Frames: the net runs over chunks of the 30 s it was trained on and drops
63
+ # BORDER_FRAMES of each chunk's output at both ends, edges it was not trained on (split_piece).
64
+ CHUNK_FRAMES = 1500
65
+ BORDER_FRAMES = 6
66
+
67
+
68
+ def cache_dir() -> Path:
69
+ """CACHE_DIR if set, else $XDG_CACHE_HOME/chordotomy, else ~/.cache/chordotomy."""
70
+ if CACHE_DIR is not None:
71
+ return CACHE_DIR
72
+ # An empty XDG_CACHE_HOME counts as unset, per the XDG spec.
73
+ base = os.environ.get("XDG_CACHE_HOME")
74
+ return (Path(base) if base else Path.home() / ".cache") / "chordotomy"
75
+
76
+
77
+ def checkpoint_path(name: str = CHECKPOINT) -> Path:
78
+ return cache_dir() / f"beat_this-{name}.ckpt"
79
+
80
+
81
+ def verified(name: str = CHECKPOINT) -> bool:
82
+ """Whether the cached checkpoint exists, can be read, and matches the pinned size and SHA-256.
83
+
84
+ Checked on every load, about 0.03 s here for 81 MB, rather than recorded once, so a copied or
85
+ damaged file never runs. A file that cannot be read, as a root-owned one left by a sudo
86
+ fetch-weights, is not verified either, so fetch replaces it instead of the CLI raising.
87
+ """
88
+ digest, size = CHECKPOINTS[name]
89
+ path = checkpoint_path(name)
90
+ try:
91
+ if path.stat().st_size != size:
92
+ return False
93
+ sha = hashlib.sha256()
94
+ with path.open("rb") as f:
95
+ while chunk := f.read(_CHUNK):
96
+ sha.update(chunk)
97
+ except OSError:
98
+ return False
99
+ return sha.hexdigest() == digest
100
+
101
+
102
+ def fetch(name: str = CHECKPOINT) -> Path:
103
+ """The verified checkpoint's path, downloading it first if the cache does not hold it.
104
+
105
+ A plain GET of a fixed URL that carries nothing about the audio. torch.hub would fetch the
106
+ same file but never checks a hash, so this streams to a temp file, checks the pin, and only
107
+ then moves it into place; a download that fails the pin is not kept.
108
+ """
109
+ path = checkpoint_path(name)
110
+ if verified(name):
111
+ return path
112
+ digest, size = CHECKPOINTS[name]
113
+ url = f"{CHECKPOINT_URL}/{name}.ckpt"
114
+ tmp = None
115
+ try:
116
+ # A present file that fails the pin stays until the verified download replaces it: another
117
+ # process may be writing a good one, and a failed download must not remove it.
118
+ path.parent.mkdir(parents=True, exist_ok=True)
119
+ sha = hashlib.sha256()
120
+ count = 0
121
+ with (
122
+ urlopen(url, timeout=_TIMEOUT) as response,
123
+ tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out,
124
+ ):
125
+ tmp = Path(out.name)
126
+ while chunk := response.read(_CHUNK):
127
+ out.write(chunk)
128
+ sha.update(chunk)
129
+ count += len(chunk)
130
+ if count != size:
131
+ raise EngineError(
132
+ f"the download from {url} has {count} bytes, not the pinned {size}, and was not "
133
+ f"kept; {_REFETCH}"
134
+ )
135
+ if sha.hexdigest() != digest:
136
+ raise EngineError(
137
+ f"the download from {url} does not match the pinned SHA-256 and was not kept; "
138
+ f"{_REFETCH}"
139
+ )
140
+ os.replace(tmp, path)
141
+ tmp = None
142
+ except (OSError, HTTPException) as exc:
143
+ raise EngineError(
144
+ f"cannot fetch the Beat This! weights from {url} into {path} ({exc}); {_REFETCH}"
145
+ ) from exc
146
+ finally:
147
+ # Anything but a completed replace, KeyboardInterrupt included, leaves no temp file.
148
+ if tmp is not None:
149
+ tmp.unlink(missing_ok=True)
150
+ return path
151
+
152
+
153
+ @functools.cache
154
+ def _tracker(name: str) -> BeatThis:
155
+ """The named checkpoint's BeatThis net, fetched (again) if the cache lacks it or it fails the
156
+ pin, and loaded on the CPU."""
157
+ try:
158
+ import torch
159
+ from beat_this.model.beat_tracker import BeatThis
160
+ from beat_this.utils import replace_state_dict_key
161
+ except ImportError as exc:
162
+ raise EngineError(
163
+ f"beat_this cannot be imported ({exc}); install the model extra with "
164
+ "`uv sync --extra model`, or pass --engine dsp"
165
+ ) from exc
166
+
167
+ path = fetch(name)
168
+ # beat_this.inference.load_model's steps; that module imports torchaudio. map_location keeps
169
+ # every tensor on the CPU and nothing moves the net, so it runs there whatever torch sees.
170
+ try:
171
+ checkpoint = torch.load(path, map_location="cpu", weights_only=True)
172
+ # The hyperparameters include the training run's; final0's lack sum_head and
173
+ # partial_transformers, which then take BeatThis's defaults.
174
+ accepted = inspect.signature(BeatThis).parameters
175
+ net = BeatThis(**{k: v for k, v in checkpoint["hyper_parameters"].items() if k in accepted})
176
+ # The Lightning module held the net as its "model" attribute.
177
+ net.load_state_dict(replace_state_dict_key(checkpoint["state_dict"], "model.", ""))
178
+ except (
179
+ OSError,
180
+ EOFError,
181
+ RuntimeError,
182
+ pickle.UnpicklingError,
183
+ KeyError,
184
+ TypeError,
185
+ ValueError,
186
+ ) as exc:
187
+ # fetch has just checked the file against its pin, so fetching it again cannot help.
188
+ raise EngineError(
189
+ f"the Beat This! checkpoint {path} matches its pin but the installed beat_this or "
190
+ f"torch cannot load it ({exc!r}); {_REINSTALL}"
191
+ ) from exc
192
+ return net.eval()
193
+
194
+
195
+ def _log_mel(y: np.ndarray) -> np.ndarray:
196
+ """The net's input: the (1 + len(y) // MEL_HOP, N_MELS) log-mel spectrogram of a signal at SR.
197
+
198
+ A replica of beat_this.preprocessing.LogMelSpect, which is torchaudio's MelSpectrogram with
199
+ mel_scale="slaney", normalized="frame_length" and power=1, built from torch.stft and librosa's
200
+ Slaney filterbank so torchaudio is never imported. It matches LogMelSpect to 2e-5.
201
+ """
202
+ import torch
203
+
204
+ magnitude = torch.stft(
205
+ torch.as_tensor(y, dtype=torch.float32),
206
+ n_fft=N_FFT,
207
+ hop_length=MEL_HOP,
208
+ window=torch.hann_window(N_FFT),
209
+ center=True,
210
+ pad_mode="reflect",
211
+ normalized=True,
212
+ return_complex=True,
213
+ ).abs()
214
+ bank = librosa.filters.mel(
215
+ sr=SR, n_fft=N_FFT, n_mels=N_MELS, fmin=FMIN, fmax=FMAX, htk=False, norm=None
216
+ )
217
+ return torch.log1p(LOG_MULTIPLIER * (torch.from_numpy(bank) @ magnitude)).T.numpy()
218
+
219
+
220
+ def _chunked(spect: np.ndarray, run: Callable[[np.ndarray], np.ndarray]) -> np.ndarray:
221
+ """Per-frame outputs of run over a (n_frames, bins) spectrogram, run on chunks of CHUNK_FRAMES.
222
+
223
+ beat_this.inference's split_piece(avoid_short_end=True) and
224
+ aggregate_prediction(overlap_mode="keep_first"): the chunks start BORDER_FRAMES before the
225
+ piece and overlap by 2 * BORDER_FRAMES, the last one ends at the piece's end, and each is
226
+ zero-padded by at most BORDER_FRAMES where it runs past either end, so a piece of at most
227
+ CHUNK_FRAMES - 2 * BORDER_FRAMES frames runs as one shorter chunk. Of each chunk's output the
228
+ BORDER_FRAMES at both ends are dropped, and where the kept spans overlap the earlier chunk's
229
+ is kept.
230
+ """
231
+ n = len(spect)
232
+ step = CHUNK_FRAMES - 2 * BORDER_FRAMES
233
+ starts = list(range(-BORDER_FRAMES, n - BORDER_FRAMES, step))
234
+ if n > step:
235
+ starts[-1] = n - (CHUNK_FRAMES - BORDER_FRAMES)
236
+ out = np.empty(n, dtype=np.float32)
237
+ # Last chunk first, so each earlier chunk overwrites the overlap.
238
+ for start in reversed(starts):
239
+ left = max(-start, 0)
240
+ right = max(0, min(BORDER_FRAMES, start + CHUNK_FRAMES - n))
241
+ chunk = np.pad(spect[max(start, 0) : start + CHUNK_FRAMES], ((left, right), (0, 0)))
242
+ kept = run(chunk)[BORDER_FRAMES:-BORDER_FRAMES]
243
+ out[start + BORDER_FRAMES : start + BORDER_FRAMES + len(kept)] = kept
244
+ return out
245
+
246
+
247
+ def logits(y: np.ndarray) -> np.ndarray:
248
+ """The net's beat logit per FPS frame of a mono signal at SR, 1 + len(y) // MEL_HOP of them.
249
+
250
+ Raises EngineError when the net cannot be loaded.
251
+ """
252
+ # First, so a missing torch is _tracker's EngineError rather than an ImportError.
253
+ net = _tracker(CHECKPOINT)
254
+ import torch
255
+
256
+ def run(chunk: np.ndarray) -> np.ndarray:
257
+ return net(torch.as_tensor(chunk, dtype=torch.float32)[None])["beat"][0].numpy()
258
+
259
+ with torch.inference_mode():
260
+ return _chunked(_log_mel(y), run)
261
+
262
+
263
+ def has_peaks(values: np.ndarray) -> bool:
264
+ """Whether Beat This!'s own peak picking finds a beat in these logits.
265
+
266
+ Postprocessor.postp_minimal keeps a frame as a beat when it is the maximum of the 7-frame
267
+ window centred on it (max_pool1d(7, 1, 3)) and its logit is above 0, a probability over 0.5.
268
+ For finite logits the global maximum is such a frame whenever any logit is above 0, and no
269
+ frame is when none is, so the gate is this one test, needs no torch, and the deduplication of
270
+ adjacent peaks cannot change it.
271
+ """
272
+ return bool(np.any(values > 0))
273
+
274
+
275
+ def resample(values: np.ndarray, n_frames: int) -> np.ndarray:
276
+ """A series at FPS linearly interpolated onto n_frames frames HOP samples apart at SR."""
277
+ times = librosa.frames_to_time(np.arange(n_frames), sr=SR, hop_length=HOP)
278
+ return np.interp(times, np.arange(len(values)) / FPS, values)
279
+
280
+
281
+ def activation(y: np.ndarray) -> np.ndarray:
282
+ """The model engine's onset envelope for beat_features: the net's beat probability per HOP
283
+ frame of a mono signal at SR, 1 + len(y) // HOP float64 values.
284
+
285
+ Raises NoBeatsError when Beat This! finds no beat, and EngineError when the net cannot be
286
+ loaded.
287
+ """
288
+ # torch.stft's reflect padding needs more samples than the N_FFT // 2 it pads, so it raises
289
+ # RuntimeError on a shorter signal, and 23 ms holds no beat. The DSP's beat_features raises
290
+ # NoBeatsError on every signal up to 1,024 samples (measured), so the engines agree here.
291
+ if len(y) <= N_FFT // 2:
292
+ raise NoBeatsError("no beats detected")
293
+ beat_logits = logits(y)
294
+ # The one-tempo DP puts beats into digital silence, 10 in 4 s of zeros, so the gate is
295
+ # Beat This!'s own peak picking.
296
+ if not has_peaks(beat_logits):
297
+ raise NoBeatsError("no beats detected")
298
+ return resample(expit(beat_logits), 1 + len(y) // HOP)