realtime-bpm-analyzer 6.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.
@@ -0,0 +1,34 @@
1
+ """Offline BPM detection with the same readings as the realtime-bpm-analyzer JS library.
2
+
3
+ The shared conformance vectors (conformance/ in the repository) prove the readings equal. Decoding audio is the
4
+ caller's job: pass one channel of samples and its sample rate to `analyze_channel_data`.
5
+ """
6
+
7
+ from ._analysis import Samples, analyze_channel_data
8
+ from ._types import (
9
+ RELATION_TOLERANCE,
10
+ AudioSpan,
11
+ Candidate,
12
+ CandidateRelation,
13
+ EngineName,
14
+ InvalidSamplesError,
15
+ Lowpass,
16
+ OutOfRangeError,
17
+ Reading,
18
+ TempoRange,
19
+ )
20
+
21
+ __all__ = [
22
+ "RELATION_TOLERANCE",
23
+ "AudioSpan",
24
+ "Candidate",
25
+ "CandidateRelation",
26
+ "EngineName",
27
+ "InvalidSamplesError",
28
+ "Lowpass",
29
+ "OutOfRangeError",
30
+ "Reading",
31
+ "Samples",
32
+ "TempoRange",
33
+ "analyze_channel_data",
34
+ ]
@@ -0,0 +1,225 @@
1
+ """Whole-input analysis: the checks, in the JS library's order, then the engine, then the reading.
2
+
3
+ A port of `analyzeChannelData` (packages/realtime-bpm-analyzer/src/node.ts) and of what it calls in
4
+ src/core/{offline,engine,tempo,lowpass}.ts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from collections.abc import Sequence
11
+ from numbers import Real
12
+ from typing import Any, TypeAlias
13
+
14
+ import numpy as np
15
+ from numpy.typing import NDArray
16
+
17
+ from ._calibration import calibrate
18
+ from ._peaks import MINIMUM_SAMPLE_RATE as PEAKS_MINIMUM_SAMPLE_RATE
19
+ from ._peaks import Tempo, detect_peaks
20
+ from ._tempogram import MINIMUM_SAMPLE_RATE, detect_tempogram
21
+ from ._types import (
22
+ RELATION_TOLERANCE,
23
+ AudioSpan,
24
+ Candidate,
25
+ CandidateRelation,
26
+ EngineName,
27
+ InvalidSamplesError,
28
+ Lowpass,
29
+ OutOfRangeError,
30
+ Reading,
31
+ TempoRange,
32
+ )
33
+
34
+ Samples: TypeAlias = Sequence[float] | NDArray[np.floating[Any]]
35
+ """One channel of floats from -1 to 1: a sequence (a list, a float `array.array`) or a 1-D float NumPy array."""
36
+
37
+ DEFAULT_TEMPO_RANGE = TempoRange(min=90, max=180)
38
+ # The largest tempo_range max, JS's maxTempoRangeBpm: 2^31 - 1, so a whole BPM fits a signed 32-bit integer
39
+ MAXIMUM_TEMPO_RANGE_BPM = 2**31 - 1
40
+ ENGINES: tuple[EngineName, ...] = ("tempogram", "peaks")
41
+ # Where 10^(q/20), Web Audio's 32-bit resonance term, is a normal, finite float (the JS library's qMin and qMax)
42
+ Q_MIN = -758
43
+ Q_MAX = 770
44
+ MAX_CANDIDATES = 5
45
+
46
+
47
+ def _is_number(value: object) -> bool:
48
+ return isinstance(value, Real) and not isinstance(value, bool)
49
+
50
+
51
+ def _as_channel(samples: Samples) -> NDArray[np.float32]:
52
+ """The samples as 32-bit floats, as the JS library holds them: a float64 input is rounded the same way."""
53
+ try:
54
+ channel = np.asarray(samples)
55
+ except (TypeError, ValueError) as error:
56
+ raise TypeError("samples must be a sequence of floats or a NumPy array") from error
57
+ # Integer PCM (int16, say) would read as samples far outside -1 to 1, which the peaks engine misreads. The JS
58
+ # library takes only a Float32Array, so any integer input is refused, whatever holds it, rather than read unscaled
59
+ if channel.dtype.kind != "f":
60
+ raise TypeError(f"samples must be floats from -1 to 1, not {channel.dtype}: scale integer PCM first (int16 / 32768)")
61
+ if channel.ndim != 1:
62
+ raise InvalidSamplesError(f"samples must be one channel, a 1-D sequence, not {channel.ndim}-D")
63
+ if channel.size == 0:
64
+ raise InvalidSamplesError("samples must not be empty")
65
+ # A float64 past float32's range becomes infinite, as a Float32Array stores it, and is refused below as JS refuses it
66
+ with np.errstate(over="ignore"):
67
+ channel = channel.astype(np.float32)
68
+ # A NaN or infinite sample is no PCM: through the peaks lowpass it turns every later sample into NaN. The caller
69
+ # can fix its decoding, so it is refused, as the JS library refuses it (RBA-260)
70
+ not_finite = np.flatnonzero(~np.isfinite(channel))
71
+ if not_finite.size > 0:
72
+ index = int(not_finite[0])
73
+ raise InvalidSamplesError(f"Invalid channel data: sample {index} is {channel[index]}, and every sample must be a finite number.")
74
+ return channel
75
+
76
+
77
+ def _sample_rate(value: float) -> float:
78
+ if not _is_number(value):
79
+ raise TypeError(f"sample_rate must be a number, not {type(value).__name__}")
80
+ # A double, as in JS: a NumPy float32 rate would otherwise turn the arithmetic below into float32
81
+ return float(value)
82
+
83
+
84
+ def _tempo_range(tempo_range: TempoRange | None) -> TempoRange:
85
+ """The range, or the default 90 to 180 BPM. Folding moves a tempo by octaves, so it must span one."""
86
+ if tempo_range is None:
87
+ return DEFAULT_TEMPO_RANGE
88
+ if not isinstance(tempo_range, TempoRange):
89
+ raise TypeError(f"tempo_range must be a TempoRange, not {type(tempo_range).__name__}")
90
+ low, high = tempo_range.min, tempo_range.max
91
+ if not (_is_number(low) and _is_number(high)):
92
+ raise TypeError("tempo_range.min and tempo_range.max must be numbers")
93
+ low, high = float(low), float(high)
94
+ if not (math.isfinite(low) and low > 0 and math.isfinite(high) and high > 0):
95
+ raise OutOfRangeError(f"tempo_range min and max must be positive finite numbers (got min={low}, max={high})")
96
+ if high < low * 2:
97
+ raise OutOfRangeError(f"tempo_range max ({high}) must be at least twice min ({low})")
98
+ # The JS library's two bounds (RBA-260): a whole BPM fits a signed 32-bit integer, and the tempogram's grid has a
99
+ # finite size, at most 71,333 tempos for any finite max / min
100
+ if high > MAXIMUM_TEMPO_RANGE_BPM:
101
+ raise OutOfRangeError(f"tempo_range max ({high}) must be at most {MAXIMUM_TEMPO_RANGE_BPM} BPM")
102
+ if not math.isfinite(high / low):
103
+ raise OutOfRangeError(f"tempo_range max / min ({high} / {low}) is too large, past the largest finite number")
104
+ return TempoRange(min=low, max=high)
105
+
106
+
107
+ def _finite_setting(name: str, value: float) -> float:
108
+ if not _is_number(value):
109
+ raise TypeError(f"lowpass.{name} must be a number, not {type(value).__name__}")
110
+ if not math.isfinite(value):
111
+ raise OutOfRangeError(f"lowpass.{name} {value} is not a finite number")
112
+ return float(value)
113
+
114
+
115
+ def _lowpass(lowpass: Lowpass | None, sample_rate: float) -> tuple[float, float]:
116
+ """The cutoff and Q, checked as the JS library checks every lowpass path."""
117
+ settings = Lowpass() if lowpass is None else lowpass
118
+ if not isinstance(settings, Lowpass):
119
+ raise TypeError(f"lowpass must be a Lowpass, not {type(settings).__name__}")
120
+ frequency = _finite_setting("frequency", settings.frequency)
121
+ q = _finite_setting("q", settings.q)
122
+ if not (math.isfinite(sample_rate) and sample_rate > 0):
123
+ raise OutOfRangeError(f"Invalid sample rate: {sample_rate}. Sample rate must be positive.")
124
+ nyquist = sample_rate / 2
125
+ # Read as the 32-bit float a Web Audio AudioParam stores, so a cutoff that rounds onto 0 or Nyquist is refused
126
+ with np.errstate(over="ignore"):
127
+ stored = float(np.float32(frequency))
128
+ if not (0 < stored < nyquist):
129
+ raise OutOfRangeError(
130
+ f"lowpass.frequency {frequency} is out of range: at {sample_rate} Hz it must be above 0 and below {nyquist} Hz"
131
+ )
132
+ if q < Q_MIN or q > Q_MAX:
133
+ raise OutOfRangeError(f"lowpass.q {q} is out of range: it must be from {Q_MIN} to {Q_MAX} dB")
134
+ return frequency, q
135
+
136
+
137
+ def _relation_to(top: int, bpm: int) -> CandidateRelation:
138
+ def near(target: float) -> bool:
139
+ return abs(bpm - target) <= target * RELATION_TOLERANCE
140
+
141
+ if near(top / 2):
142
+ return "half"
143
+ return "double" if near(top * 2) else "other"
144
+
145
+
146
+ def _to_reading(tempos: list[Tempo], audio: AudioSpan, engine: EngineName, tempo_range: TempoRange) -> Reading | None:
147
+ if not tempos:
148
+ return None
149
+ top = tempos[0]
150
+ candidates = tuple(
151
+ Candidate(bpm=tempo.tempo, relation="top" if index == 0 else _relation_to(top.tempo, tempo.tempo))
152
+ for index, tempo in enumerate(tempos[:MAX_CANDIDATES])
153
+ )
154
+ return Reading(
155
+ bpm=top.tempo,
156
+ bpm_exact=top.exact,
157
+ confidence=calibrate(engine, top.confidence, top.tempo, tempo_range),
158
+ candidates=candidates,
159
+ audio=audio,
160
+ engine=engine,
161
+ )
162
+
163
+
164
+ def analyze_channel_data(
165
+ samples: Samples,
166
+ sample_rate: float,
167
+ *,
168
+ engine: EngineName = "tempogram",
169
+ tempo_range: TempoRange | None = None,
170
+ lowpass: Lowpass | None = None,
171
+ ) -> Reading | None:
172
+ """Detects the tempo of one channel of decoded audio, as the JS library's `analyzeChannelData` does.
173
+
174
+ Args:
175
+ samples: The samples of one channel, from -1 to 1: a list, an `array.array` or a 1-D NumPy array. They are
176
+ analysed as 32-bit floats, as the JS library holds them. Decoding a file is the caller's job.
177
+ sample_rate: Their rate in Hz. The tempogram needs at least 100 Hz.
178
+ engine: `"tempogram"` (the default) reads the full band; `"peaks"` counts intervals between bass peaks.
179
+ tempo_range: The tempos a reading is reported in, 90 to 180 BPM by default. Any other range, even one
180
+ holding 90 to 180, leaves `confidence` None: it was calibrated on the default range only.
181
+ lowpass: The `peaks` engine's lowpass, 200 Hz and 1 dB by default. Only `peaks` takes one.
182
+
183
+ Returns:
184
+ The reading, or None when no tempo was found: silence, noise, or under 1.5 s for the tempogram.
185
+
186
+ Raises:
187
+ InvalidSamplesError: The samples are empty, not one channel, or hold a NaN or infinite sample.
188
+ OutOfRangeError: The sample rate is not finite and positive (at least 100 Hz for the tempogram, 2 Hz for
189
+ peaks), the engine is unknown, a lowpass is given to the tempogram, the tempo range's bounds are not
190
+ positive and finite, span less than an octave, put max above 2^31 - 1 or overflow max / min, or a
191
+ lowpass setting is not finite, its cutoff not between 0 and half the sample rate, or its Q not from -758
192
+ to 770 dB.
193
+ TypeError: An argument has the wrong type, or the samples are integers.
194
+ """
195
+ channel = _as_channel(samples)
196
+ rate = _sample_rate(sample_rate)
197
+ # The engine, its lowpass and the peaks floor first, then the range, then the tempogram's sample rate: the JS
198
+ # library's order, so a call with two faults fails on the same one
199
+ if engine not in ENGINES:
200
+ raise OutOfRangeError(f"Invalid engine: {engine!r}. Use 'tempogram' or 'peaks'.")
201
+ if lowpass is not None:
202
+ if engine != "peaks":
203
+ raise OutOfRangeError("Only the peaks engine takes a lowpass")
204
+ _lowpass(lowpass, rate)
205
+ # Below 2 Hz the peak search's skip rounds to 0, and the JS library refuses the rate too (RBA-260)
206
+ if engine == "peaks" and not rate >= PEAKS_MINIMUM_SAMPLE_RATE:
207
+ raise OutOfRangeError(f"Invalid sample rate: {rate}. The peaks engine needs at least {PEAKS_MINIMUM_SAMPLE_RATE} Hz.")
208
+ resolved_range = _tempo_range(tempo_range)
209
+
210
+ if engine == "tempogram":
211
+ if not (math.isfinite(rate) and rate >= MINIMUM_SAMPLE_RATE):
212
+ raise OutOfRangeError(f"Invalid sample rate: {rate}. The tempogram needs at least {MINIMUM_SAMPLE_RATE} Hz.")
213
+ frequency = q = math.nan
214
+ else:
215
+ frequency, q = _lowpass(lowpass, rate)
216
+ # The samples are finite by now. NumPy's invalid and overflow warnings stay off, as before RBA-260: JS's arithmetic
217
+ # has no such warnings, and the engines follow it
218
+ with np.errstate(invalid="ignore", over="ignore"):
219
+ if engine == "tempogram":
220
+ tempos = detect_tempogram(channel, rate, resolved_range)
221
+ else:
222
+ tempos = detect_peaks(channel, rate, resolved_range, frequency, q)
223
+ # One double division, as in JS: the rate is checked by now
224
+ audio = AudioSpan(start=0.0, end=len(channel) / rate)
225
+ return _to_reading(tempos, audio, engine, resolved_range)
@@ -0,0 +1,104 @@
1
+ """Maps each engine's raw score to the chance its reading is right, as the JS library does.
2
+
3
+ The tables are data from the JS library's benchmark, copied from
4
+ packages/realtime-bpm-analyzer/src/core/calibration.ts, which explains how they were fitted. Regenerate them there,
5
+ never edit them here: tests/test_calibration.py holds this copy equal to that file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+
12
+ from ._types import EngineName, TempoRange
13
+
14
+ Point = tuple[float, float]
15
+ """[raw, calibrated], raw increasing, calibrated non-decreasing"""
16
+
17
+ MEASURED_TEMPO_RANGE = TempoRange(min=90, max=180)
18
+ """The range the tables were fitted on. A reading outside it, or from any other range, gets no confidence."""
19
+
20
+ CALIBRATION: dict[EngineName, dict[str, tuple[Point, ...]]] = {
21
+ "tempogram": {
22
+ "all": (
23
+ (0.028638, 0.20051), (0.055144, 0.372585), (0.097521, 0.575647), (0.149595, 0.635569),
24
+ (0.20161, 0.690485), (0.249703, 0.72767), (0.295928, 0.762304), (0.341343, 0.765585),
25
+ (0.385679, 0.799125), (0.429153, 0.835641), (0.470513, 0.845789), (0.511768, 0.869486),
26
+ (0.553363, 0.884798), (0.595264, 0.895735), (0.638504, 0.910317), (0.681735, 0.915421),
27
+ (0.725551, 0.919825), (0.772671, 0.936566), (0.825921, 0.944951), (0.89822, 0.951513),
28
+ ),
29
+ "from140": (
30
+ (0.033034, 0.33474), (0.070347, 0.6), (0.119277, 0.732771), (0.172728, 0.746835),
31
+ (0.221609, 0.808451), (0.267829, 0.831224), (0.314113, 0.845288), (0.356172, 0.871921),
32
+ (0.396377, 0.871921), (0.434812, 0.907042), (0.471061, 0.931083), (0.505789, 0.939479),
33
+ (0.542801, 0.939479), (0.584486, 0.947257), (0.624045, 0.947257), (0.663255, 0.960563),
34
+ (0.705149, 0.964838), (0.749939, 0.964838), (0.800818, 0.971147), (0.875589, 0.971147),
35
+ ),
36
+ "from165": (
37
+ (0.025208, 0.107843), (0.03957, 0.230392), (0.060399, 0.323529), (0.092567, 0.338235),
38
+ (0.135659, 0.367647), (0.181557, 0.5), (0.223155, 0.5), (0.257036, 0.5),
39
+ (0.290288, 0.5), (0.323952, 0.5), (0.358273, 0.519608), (0.396653, 0.607843),
40
+ (0.434505, 0.644608), (0.473727, 0.644608), (0.518908, 0.671569), (0.562945, 0.720588),
41
+ (0.60891, 0.735294), (0.668028, 0.77451), (0.745682, 0.872549), (0.853984, 0.872549),
42
+ ),
43
+ },
44
+ "peaks": {
45
+ "all": (
46
+ (0.049989, 0.185357), (0.063145, 0.222892), (0.072474, 0.267501), (0.08232, 0.352641),
47
+ (0.093329, 0.44393), (0.105524, 0.544738), (0.116928, 0.613531), (0.130731, 0.671918),
48
+ (0.145092, 0.692771), (0.161133, 0.753012), (0.177844, 0.798795), (0.19531, 0.81696),
49
+ (0.214063, 0.830862), (0.233928, 0.855355), (0.257586, 0.890176), (0.283525, 0.914041),
50
+ (0.315376, 0.914041), (0.349677, 0.923077), (0.402366, 0.952028), (0.460666, 0.952028),
51
+ ),
52
+ "from90": (
53
+ (0.050458, 0.131043), (0.06287, 0.155952), (0.071476, 0.21056), (0.080422, 0.259707),
54
+ (0.090315, 0.323791), (0.102045, 0.446849), (0.114534, 0.545165), (0.127676, 0.612985),
55
+ (0.142688, 0.650763), (0.159642, 0.708015), (0.17782, 0.786123), (0.195999, 0.81743),
56
+ (0.215531, 0.839593), (0.236985, 0.87341), (0.261563, 0.900064), (0.288806, 0.928731),
57
+ (0.322089, 0.928731), (0.357312, 0.942748), (0.410527, 0.95226), (0.463758, 0.95229),
58
+ ),
59
+ "from140": (
60
+ (0.049556, 0.37037), (0.06546, 0.537118), (0.07873, 0.636166), (0.092901, 0.775599),
61
+ (0.104952, 0.801743), (0.115942, 0.846783), (0.129333, 0.846783), (0.141899, 0.846783),
62
+ (0.15554, 0.846783), (0.168455, 0.893636), (0.183293, 0.893636), (0.199214, 0.893636),
63
+ (0.215719, 0.893636), (0.233491, 0.893636), (0.253891, 0.924796), (0.276331, 0.924796),
64
+ (0.304078, 0.924796), (0.333819, 0.924796), (0.380988, 0.954148), (0.449856, 0.980392),
65
+ ),
66
+ "from165": (
67
+ (0.046601, 0.21875), (0.059947, 0.275591), (0.070681, 0.275591), (0.080616, 0.421875),
68
+ (0.09109, 0.4375), (0.102163, 0.468504), (0.111915, 0.468504), (0.122919, 0.476562),
69
+ (0.134567, 0.561659), (0.146673, 0.561659), (0.160881, 0.561659), (0.17397, 0.561659),
70
+ (0.189685, 0.561659), (0.207642, 0.561659), (0.225608, 0.561659), (0.247324, 0.609375),
71
+ (0.277984, 0.670588), (0.313866, 0.670588), (0.36136, 0.779528), (0.439176, 0.804688),
72
+ ),
73
+ },
74
+ }
75
+
76
+
77
+ def _band_of(bpm: float) -> str:
78
+ """The reading's own tempo picks the band: up to 140, 140 to 165, 165 and over."""
79
+ if bpm < 140:
80
+ return "from90"
81
+ return "from140" if bpm < 165 else "from165"
82
+
83
+
84
+ def _read(table: tuple[Point, ...], raw: float) -> float:
85
+ """The table at `raw`, by linear interpolation, flat past either end."""
86
+ if raw <= table[0][0]:
87
+ return table[0][1]
88
+ for (x0, y0), (x1, y1) in zip(table, table[1:]):
89
+ if raw <= x1:
90
+ return y0 + ((y1 - y0) * (raw - x0) / (x1 - x0))
91
+ return table[-1][1]
92
+
93
+
94
+ def calibrate(engine: EngineName, raw: float, bpm: float, tempo_range: TempoRange) -> float | None:
95
+ """The chance a reading is right, 0 to 1, or None when its tempo or the analysis's range was never measured."""
96
+ if tempo_range.min != MEASURED_TEMPO_RANGE.min or tempo_range.max != MEASURED_TEMPO_RANGE.max:
97
+ return None
98
+ # Written so that a bpm that is not a number fails the test and reads as unmeasured
99
+ if not (MEASURED_TEMPO_RANGE.min <= bpm <= MEASURED_TEMPO_RANGE.max):
100
+ return None
101
+ mapping = CALIBRATION[engine]
102
+ # A score that is not a number reads as no evidence, not as the top of the table
103
+ score = min(1.0, max(0.0, raw)) if math.isfinite(raw) else 0.0
104
+ return _read(mapping.get(_band_of(bpm), mapping["all"]), score)
@@ -0,0 +1,17 @@
1
+ """The JS arithmetic the readings depend on, where Python's defaults differ."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+
8
+ def js_round(value: float) -> int:
9
+ """JS `Math.round`: halves go towards +infinity, so 2.5 gives 3 and -2.5 gives -2.
10
+
11
+ Python's `round` sends halves to the even neighbour (2.5 gives 2), which moves tempos that land exactly on a
12
+ half, such as the peaks engine's 122.5 BPM (conformance/readme.md, Rounding). `floor(x + 0.5)` is not used
13
+ either: the addition itself rounds below 0.5 and above 2^52. `x - floor(x)` is exact for x >= 0 and x <= -1
14
+ (Sterbenz), and between -1 and 0 its rounding can't cross 0.5. The value must be finite.
15
+ """
16
+ floor = math.floor(value)
17
+ return floor + 1 if value - floor >= 0.5 else floor
@@ -0,0 +1,186 @@
1
+ """The `peaks` engine: a biquad lowpass, bass peaks over a falling threshold, and votes for the intervals between them.
2
+
3
+ A port of packages/realtime-bpm-analyzer/src/core/{lowpass,peak-detection,tempo,detect-tempo}.ts, offline path.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+ from numpy.typing import NDArray
13
+
14
+ from ._jsmath import js_round
15
+ from ._types import TempoRange
16
+
17
+ START_THRESHOLD = 0.95
18
+ MIN_VALID_THRESHOLD = 0.2
19
+ THRESHOLD_STEP = 0.05
20
+ MIN_PEAKS = 15
21
+ PEAK_SKIP_SECONDS = 0.25
22
+ # The lowest rate whose skip rounds to at least one sample, js_round(0.25 * 2) == 1
23
+ MINIMUM_SAMPLE_RATE = 2
24
+ MAX_INTERVAL_COMPARISONS = 10
25
+ MAX_CANDIDATES = 5
26
+ _THRESHOLD_DECIMALS = 1e9
27
+ # The recursion runs in Python, a block at a time, so the floats it holds stay bounded on long inputs
28
+ _FILTER_BLOCK = 1 << 16
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class Tempo:
33
+ """One whole-BPM candidate: its unrounded tempo, its vote count and its raw score from 0 to 1."""
34
+
35
+ tempo: int
36
+ exact: float
37
+ count: int
38
+ confidence: float
39
+
40
+
41
+ def lowpass_coefficients(frequency: float, q: float, sample_rate: float) -> tuple[float, float, float, float, float]:
42
+ """b0, b1, b2, a1, a2 as the Web Audio spec defines a `lowpass` BiquadFilterNode, with Q in dB."""
43
+ w0 = math.pi * (frequency / (sample_rate / 2))
44
+ cos_w0 = math.cos(w0)
45
+ alpha = math.sin(w0) / (2 * (10 ** (q / 20)))
46
+ a0 = 1 + alpha
47
+ return (
48
+ ((1 - cos_w0) / 2) / a0,
49
+ (1 - cos_w0) / a0,
50
+ ((1 - cos_w0) / 2) / a0,
51
+ (-2 * cos_w0) / a0,
52
+ (1 - alpha) / a0,
53
+ )
54
+
55
+
56
+ def apply_lowpass(samples: NDArray[np.float64], sample_rate: float, frequency: float, q: float) -> NDArray[np.float32]:
57
+ """The filtered samples, stored as 32-bit floats as the reference stores them, from double-precision state.
58
+
59
+ The reference computes `b0*x0 + b1*x1 + b2*x2 - a1*y1 - a2*y2` left to right. The feed-forward part is a prefix
60
+ of that sum, so NumPy computes it for the whole input in the same order; only the feedback runs in a loop.
61
+ """
62
+ b0, b1, b2, a1, a2 = lowpass_coefficients(frequency, q, sample_rate)
63
+ x1 = np.concatenate(([0.0], samples[:-1]))
64
+ x2 = np.concatenate(([0.0, 0.0], samples[:-2]))[: len(samples)]
65
+ forward = (b0 * samples + b1 * x1) + b2 * x2
66
+ output = np.empty(len(samples), dtype=np.float32)
67
+ y1 = 0.0
68
+ y2 = 0.0
69
+ for start in range(0, len(samples), _FILTER_BLOCK):
70
+ block = forward[start : start + _FILTER_BLOCK].tolist()
71
+ for index, value in enumerate(block):
72
+ y0 = value - (a1 * y1) - (a2 * y2)
73
+ block[index] = y0
74
+ y2 = y1
75
+ y1 = y0
76
+ output[start : start + len(block)] = block
77
+ return output
78
+
79
+
80
+ def threshold_ladder() -> list[float]:
81
+ """0.9, 0.85, ... 0.2: each rung rounded to 9 decimals as the reference rounds it, so they compare the same."""
82
+ rungs: list[float] = []
83
+ for n in range(1, max(1, math.ceil(START_THRESHOLD / THRESHOLD_STEP)) + 1):
84
+ threshold = js_round((START_THRESHOLD - (n * THRESHOLD_STEP)) * _THRESHOLD_DECIMALS) / _THRESHOLD_DECIMALS
85
+ rungs.append(threshold)
86
+ if threshold <= MIN_VALID_THRESHOLD:
87
+ break
88
+ return rungs
89
+
90
+
91
+ def find_peaks_at_threshold(data: NDArray[np.float64], threshold: float, skip: int) -> list[int]:
92
+ """Each index above the threshold, then the next one at least `skip` samples on, past the peak's decay."""
93
+ assert skip >= 1, "a skip of 0 would find the same peak forever"
94
+ above = np.flatnonzero(data > threshold)
95
+ peaks: list[int] = []
96
+ position = 0
97
+ while position < len(above):
98
+ peak = int(above[position])
99
+ peaks.append(peak)
100
+ position = int(np.searchsorted(above, peak + skip, side="left"))
101
+ return peaks
102
+
103
+
104
+ def find_peaks(data: NDArray[np.float64], sample_rate: float) -> list[int]:
105
+ """The peaks at the highest threshold that finds enough of them, or none."""
106
+ skip = js_round(PEAK_SKIP_SECONDS * sample_rate)
107
+ for threshold in threshold_ladder():
108
+ peaks = find_peaks_at_threshold(data, threshold, skip)
109
+ if len(peaks) >= MIN_PEAKS:
110
+ return peaks
111
+ return []
112
+
113
+
114
+ def identify_intervals(peaks: list[int]) -> dict[int, int]:
115
+ """How often each interval occurs between a peak and its next 9, in the order first met: ties keep that order."""
116
+ counts: dict[int, int] = {}
117
+ for n, peak in enumerate(peaks):
118
+ for other in peaks[n + 1 : n + MAX_INTERVAL_COMPARISONS]:
119
+ interval = other - peak
120
+ counts[interval] = counts.get(interval, 0) + 1
121
+ return counts
122
+
123
+
124
+ # A whole BPM's votes: their count, and the sum of their unrounded tempos weighted by count
125
+ Votes = tuple[int, float]
126
+
127
+
128
+ def _add_vote(groups: dict[int, Votes], tempo: float, count: int) -> None:
129
+ key = js_round(tempo)
130
+ votes_count, weighted_sum = groups.get(key, (0, 0.0))
131
+ groups[key] = (votes_count + count, weighted_sum + (count * tempo))
132
+
133
+
134
+ def group_by_tempo(intervals: dict[int, int], sample_rate: float, tempo_range: TempoRange) -> list[Tempo]:
135
+ """Folds each interval's tempo into the range by octaves and groups the votes by the whole BPM they round to."""
136
+ groups: dict[int, Votes] = {}
137
+ # The same votes seen from across the range's edge, for the exact tempo only
138
+ across_edge: dict[int, Votes] = {}
139
+ low, high = tempo_range.min, tempo_range.max
140
+ for interval, count in intervals.items():
141
+ if interval == 0:
142
+ continue
143
+ folded = 60 / (abs(interval) / sample_rate)
144
+ # Bounded: high >= 2 * low, so each loop ends within one pass of octaves
145
+ while folded < low:
146
+ folded *= 2
147
+ while folded > high:
148
+ folded /= 2
149
+ _add_vote(groups, folded, count)
150
+ if folded * 2 > high:
151
+ _add_vote(across_edge, folded * 2, count)
152
+ if folded / 2 < low:
153
+ _add_vote(across_edge, folded / 2, count)
154
+ return _with_confidence(groups, across_edge)
155
+
156
+
157
+ def _with_confidence(groups: dict[int, Votes], across_edge: dict[int, Votes]) -> list[Tempo]:
158
+ """Each group's score and exact tempo from its ±1 BPM window; the exact tempo also takes the votes across an edge."""
159
+ total = sum(count for count, _ in groups.values())
160
+ tempos: list[Tempo] = []
161
+ for tempo, (count, _) in groups.items():
162
+ keys = (tempo - 1, tempo, tempo + 1)
163
+ window = [groups.get(key) for key in keys]
164
+ folded = window + [across_edge.get(key) for key in keys]
165
+ support = sum(votes[0] for votes in window if votes is not None)
166
+ folded_support = sum(votes[0] for votes in folded if votes is not None)
167
+ weighted_sum = 0.0
168
+ for votes in folded:
169
+ weighted_sum += votes[1] if votes is not None else 0
170
+ tempos.append(Tempo(
171
+ tempo=tempo,
172
+ # A group of zero-count votes has no mean: its whole BPM is all there is
173
+ exact=weighted_sum / folded_support if folded_support > 0 else float(tempo),
174
+ count=count,
175
+ confidence=support / total if total > 0 else 0,
176
+ ))
177
+ return tempos
178
+
179
+
180
+ def detect_peaks(samples: NDArray[np.float32], sample_rate: float, tempo_range: TempoRange, frequency: float, q: float) -> list[Tempo]:
181
+ """Up to 5 candidates, most votes first, ties in the order they were first met."""
182
+ filtered = apply_lowpass(samples.astype(np.float64), sample_rate, frequency, q)
183
+ # Compared as doubles, as JS compares: NumPy would compare a float32 array with a float threshold in float32
184
+ peaks = find_peaks(filtered.astype(np.float64), sample_rate)
185
+ tempos = group_by_tempo(identify_intervals(peaks), sample_rate, tempo_range)
186
+ return sorted(tempos, key=lambda tempo: tempo.count, reverse=True)[:MAX_CANDIDATES]
@@ -0,0 +1,255 @@
1
+ """The `tempogram` engine, whole-input path: band-wise onset strength, its autocorrelation read through a comb on a
2
+ tempo grid, a log-Gaussian tempo prior, and every frame's salience accumulated with the same weight.
3
+
4
+ A port of packages/realtime-bpm-analyzer/src/core/tempogram.ts (`detectTempogram`). The realtime detector's
5
+ stability rule decides only when a live reading is shown, so it has no part here. NumPy runs the per-frame FFTs and
6
+ logarithms; the recurrences (loudness, local means) and the small tempo grid run in Python, in the reference's order.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+ from numpy.lib.stride_tricks import sliding_window_view
16
+ from numpy.typing import NDArray
17
+
18
+ from ._jsmath import js_round
19
+ from ._peaks import Tempo
20
+ from ._types import OutOfRangeError, TempoRange
21
+
22
+ # The tuning the JS library ships (defaultTempogramTuning), with the half-life whole-input analysis sets
23
+ FRAME_RATE = 100
24
+ BANDS = (30, 200, 500, 1500, 4000, 10_000)
25
+ COMPRESSION = 1000
26
+ LOCAL_MEAN_SECONDS = 0.5
27
+ WINDOW_SECONDS = 8
28
+ WARMUP_SECONDS = 4
29
+ UPDATE_SECONDS = 0.5
30
+ COMB_BEATS = 4
31
+ HALF_LIFE_SECONDS = math.inf
32
+ HALF_BEAT_PENALTY = 0
33
+ THIRD_BEAT_PENALTY = 0.3
34
+ PRIOR_BPM = 80
35
+ PRIOR_OCTAVES = 1.7
36
+ READING_SALIENCE = 0.02
37
+
38
+ GRID_RATIO = 1.01
39
+ LOUDNESS_DECAY = 0.9995
40
+ MINIMUM_LOUDNESS = 0.05
41
+ SMOOTHING_WEIGHTS = (1 / 9, 2 / 9, 3 / 9, 2 / 9, 1 / 9)
42
+ MAX_CANDIDATES = 5
43
+ SHORTEST_RECORDING_SECONDS = 1.5
44
+ MINIMUM_SAMPLE_RATE = FRAME_RATE
45
+ # Frames transformed at once: bounds the memory a long input takes, about 8 MB at 44.1 kHz
46
+ _FRAME_BLOCK = 1024
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class _Grid:
51
+ tempos: list[float]
52
+ prior: list[float]
53
+ # For each tempo, each beat multiple: the lag in frames
54
+ lags: list[list[float]]
55
+ max_lag: int
56
+
57
+
58
+ def _tempo_grid(tempo_range: TempoRange, frame_rate: float, window_frames: int) -> _Grid:
59
+ ratio = tempo_range.max / tempo_range.min
60
+ # _tempo_range refuses an overflowing ratio first, as JS's resolveTempoRange does since RBA-260: this keeps the
61
+ # grid's size finite for any caller
62
+ if not math.isfinite(ratio):
63
+ raise OutOfRangeError(f"tempo_range spans too much: max / min ({tempo_range.max} / {tempo_range.min}) overflows")
64
+ size = math.floor(math.log(ratio) / math.log(GRID_RATIO)) + 1
65
+ tempos: list[float] = []
66
+ prior: list[float] = []
67
+ lags: list[list[float]] = []
68
+ max_lag = 0.0
69
+ for i in range(size):
70
+ tempo = tempo_range.min * (GRID_RATIO**i)
71
+ tempos.append(tempo)
72
+ prior.append(math.exp(-0.5 * ((math.log2(tempo / PRIOR_BPM) / PRIOR_OCTAVES) ** 2)))
73
+ row = [((k + 1) * 60 * frame_rate) / tempo for k in range(COMB_BEATS)]
74
+ lags.append(row)
75
+ for lag in row:
76
+ max_lag = lag if lag < window_frames - 1 and lag > max_lag else max_lag
77
+ return _Grid(tempos, prior, lags, math.ceil(max_lag) + 1)
78
+
79
+
80
+ def _onset_strengths(samples: NDArray[np.float64], sample_rate: float, hop: int, frame_rate: float) -> NDArray[np.float64]:
81
+ """One onset strength per hop: the positive band-wise rise of log-compressed spectra, less each band's local mean."""
82
+ fft_size = 2 ** js_round(math.log2(0.023 * sample_rate))
83
+ bins = fft_size // 2
84
+ nyquist = sample_rate / 2
85
+ edges = [min(bins, max(1, js_round((hz / nyquist) * bins))) for hz in BANDS]
86
+ low, high = edges[0], edges[-1]
87
+ mean_step = 1 / (LOCAL_MEAN_SECONDS * frame_rate)
88
+ # Periodic Hann (divided by N, not N - 1): the reference's, and a symmetric one fails the vectors
89
+ hann = 0.5 - (0.5 * np.cos((2 * math.pi * np.arange(fft_size)) / fft_size))
90
+ frames = len(samples) // hop
91
+ # Frame j sees the fft_size samples before sample j * hop, zeros before the input starts, as the ring does
92
+ windows = sliding_window_view(np.concatenate((np.zeros(fft_size), samples)), fft_size)[hop : frames * hop + 1 : hop]
93
+
94
+ onset = np.zeros(frames)
95
+ loudness = MINIMUM_LOUDNESS
96
+ previous_log = np.zeros(high - low)
97
+ local_means = [0.0] * (len(edges) - 1)
98
+ has_previous = False
99
+ for block_start in range(0, frames, _FRAME_BLOCK):
100
+ spectrum = np.fft.rfft(windows[block_start : block_start + _FRAME_BLOCK] * hann, axis=1)[:, :bins]
101
+ power = (spectrum.real * spectrum.real) + (spectrum.imag * spectrum.imag)
102
+ totals = power[:, 1:].sum(axis=1)
103
+ peaks = power[:, 1:].max(axis=1, initial=0.0)
104
+ rows: list[int] = []
105
+ scales: list[float] = []
106
+ for row, total in enumerate(totals.tolist()):
107
+ # A NaN or infinite sample is no audio: no onset, and the state is kept, as the reference keeps it.
108
+ # analyze_channel_data refuses such samples first (RBA-260); this mirrors the reference's realtime rule
109
+ if not math.isfinite(total):
110
+ continue
111
+ loudness = max(math.sqrt(float(peaks[row])), loudness * LOUDNESS_DECAY, MINIMUM_LOUDNESS)
112
+ rows.append(row)
113
+ scales.append(COMPRESSION / loudness)
114
+ if not rows:
115
+ continue
116
+ logs = np.log(1 + (np.asarray(scales)[:, None] * np.sqrt(power[rows, low:high])))
117
+ rises = np.diff(np.vstack((previous_log, logs)), axis=0)
118
+ previous_log = logs[-1]
119
+ positive = np.where(rises > 0, rises, 0.0)
120
+ fluxes = [
121
+ positive[:, first - low : end - low].sum(axis=1) / max(1, end - first)
122
+ for first, end in zip(edges, edges[1:])
123
+ ]
124
+ for index, row in enumerate(rows):
125
+ strength = 0.0
126
+ for band, flux_by_row in enumerate(fluxes):
127
+ flux = float(flux_by_row[index])
128
+ local_means[band] += mean_step * (flux - local_means[band])
129
+ novelty = flux - local_means[band]
130
+ strength += novelty if novelty > 0 else 0
131
+ # The first frame rises from nothing, which is no onset
132
+ onset[block_start + row] = strength if has_previous else 0.0
133
+ has_previous = True
134
+ return onset
135
+
136
+
137
+ def _smoothed(onset: NDArray[np.float64]) -> NDArray[np.float64]:
138
+ """The 50 ms smoothing, summed in the reference's order, then stored as 32-bit floats as its ring stores them."""
139
+ smoothed = onset * SMOOTHING_WEIGHTS[0]
140
+ for delay, weight in enumerate(SMOOTHING_WEIGHTS[1:], start=1):
141
+ smoothed = smoothed + (np.concatenate((np.zeros(delay), onset))[: len(onset)] * weight)
142
+ return smoothed.astype(np.float32).astype(np.float64)
143
+
144
+
145
+ class _Accumulator:
146
+ """The tempo state across tempogram frames: the autocorrelation buffer, the accumulated salience, the ranking."""
147
+
148
+ def __init__(self, grid: _Grid) -> None:
149
+ self.grid = grid
150
+ # Kept across frames: a lag past this frame's end reads what an earlier frame left, as in the reference
151
+ self.autocorrelation = [0.0] * (grid.max_lag + 1)
152
+ self.accumulated = [0.0] * len(grid.tempos)
153
+ self.ranking = [0.0] * len(grid.tempos)
154
+ self.weight = 0.0
155
+ self.memory = 0.5 ** (UPDATE_SECONDS / HALF_LIFE_SECONDS)
156
+
157
+ def _correlation_at(self, lag: float) -> float:
158
+ # Past the buffer the reference reads undefined, which is NaN: a NaN penalty then counts as none. Checked
159
+ # before the floor, since a tempo near 0 BPM gives an infinite lag, which JS floors and Python can't (RBA-260)
160
+ if not lag < len(self.autocorrelation) - 1:
161
+ return math.nan
162
+ low = math.floor(lag)
163
+ values = self.autocorrelation
164
+ return values[low] + ((lag - low) * (values[low + 1] - values[low]))
165
+
166
+ def _salience(self, window: NDArray[np.float64]) -> list[float] | None:
167
+ """Each tempo's comb over the window's autocorrelation, or None when nothing pulses in it."""
168
+ length = len(window)
169
+ # cumsum adds left to right, as the reference's loops do, so these sums are the reference's own
170
+ mean = float(np.cumsum(window)[-1]) / length
171
+ centred = window - mean
172
+ lag_end = min(self.grid.max_lag, length - 1)
173
+ for shift in range(lag_end + 1):
174
+ total = float(np.cumsum(centred[shift:] * centred[: length - shift])[-1])
175
+ # Unbiased: a long lag overlaps less, which must not read as less periodic
176
+ self.autocorrelation[shift] = (total * length) / (length - shift)
177
+ energy = self.autocorrelation[0]
178
+ if energy < 1e-12:
179
+ return None
180
+ salience: list[float] = []
181
+ for row in self.grid.lags:
182
+ comb_sum = 0.0
183
+ teeth = 0
184
+ for lag in row:
185
+ if lag >= lag_end:
186
+ break
187
+ comb_sum += self._correlation_at(lag)
188
+ teeth += 1
189
+ comb = comb_sum / (teeth * energy) if teeth > 0 else 0
190
+ beat = row[0]
191
+ between = (HALF_BEAT_PENALTY * self._correlation_at(beat / 2)) + (
192
+ THIRD_BEAT_PENALTY * self._correlation_at(beat / 3)
193
+ )
194
+ salience.append(comb - ((between if between > 0 else 0) / energy))
195
+ return salience
196
+
197
+ def add_frame(self, window: NDArray[np.float64]) -> None:
198
+ salience = self._salience(window)
199
+ if salience is None:
200
+ return
201
+ self.weight = (self.weight * self.memory) + 1
202
+ for i, value in enumerate(salience):
203
+ self.accumulated[i] = (self.accumulated[i] * self.memory) + (value if value > 0 else 0)
204
+ self.ranking[i] = (self.accumulated[i] / self.weight) * self.grid.prior[i]
205
+
206
+ def _refined_tempo(self, i: int) -> float:
207
+ """The grid tempo moved to the vertex of the parabola through its ranking and its neighbours'."""
208
+ ranking = self.ranking
209
+ if i == 0 or i == len(ranking) - 1:
210
+ return self.grid.tempos[i]
211
+ denominator = ranking[i - 1] - (2 * ranking[i]) + ranking[i + 1]
212
+ offset: float = 0 if denominator == 0 else (0.5 * (ranking[i - 1] - ranking[i + 1])) / denominator
213
+ return self.grid.tempos[i] * float(GRID_RATIO**offset)
214
+
215
+ def candidates(self) -> list[Tempo]:
216
+ ranking = self.ranking
217
+ last = len(ranking) - 1
218
+ peaks = [
219
+ i
220
+ for i, value in enumerate(ranking)
221
+ if value > 0
222
+ and (i == 0 or value >= ranking[i - 1])
223
+ and (i == last or value >= ranking[i + 1])
224
+ ]
225
+ # Stable: equal rankings keep grid order, as the reference's sort keeps it
226
+ ranked = sorted(peaks, key=lambda i: ranking[i], reverse=True)[:MAX_CANDIDATES]
227
+ tempos: list[Tempo] = []
228
+ for i in ranked:
229
+ exact = self._refined_tempo(i)
230
+ confidence = min(1, self.accumulated[i] / self.weight)
231
+ if confidence >= READING_SALIENCE:
232
+ tempos.append(Tempo(js_round(exact), exact, js_round(ranking[i] * 1000), confidence))
233
+ return tempos
234
+
235
+
236
+ def detect_tempogram(samples: NDArray[np.float32], sample_rate: float, tempo_range: TempoRange) -> list[Tempo]:
237
+ """Up to 5 candidates, best first, empty when no pulse stands out. The sample rate is at least 100 Hz."""
238
+ seconds = len(samples) / sample_rate
239
+ # Shorter audio has no two beats to compare at the slowest tempo searched
240
+ if seconds < SHORTEST_RECORDING_SECONDS:
241
+ return []
242
+ hop = js_round(sample_rate / FRAME_RATE)
243
+ frame_rate = sample_rate / hop
244
+ window_frames = js_round(WINDOW_SECONDS * frame_rate)
245
+ update_frames = max(1, js_round(UPDATE_SECONDS * frame_rate))
246
+ # A frame short of the end: rounding must not ask for more frames than the input holds
247
+ warmup_frames = js_round(min(WARMUP_SECONDS, seconds - (1 / FRAME_RATE)) * frame_rate)
248
+
249
+ oss = _smoothed(_onset_strengths(samples.astype(np.float64), sample_rate, hop, frame_rate))
250
+ state = _Accumulator(_tempo_grid(tempo_range, frame_rate, window_frames))
251
+ # The reference reads a tempogram frame once `frames`, counted from 1, reaches the warm-up, then every update
252
+ first = warmup_frames if warmup_frames >= 1 else update_frames
253
+ for frames in range(first, len(oss) + 1, update_frames):
254
+ state.add_frame(oss[max(0, frames - window_frames) : frames])
255
+ return state.candidates()
@@ -0,0 +1,78 @@
1
+ """The public value types and exceptions: the JS library's `Reading`, its options and its two error categories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ EngineName = Literal["tempogram", "peaks"]
9
+ """`tempogram` (the default) reads the full band; `peaks` counts the intervals between bass peaks."""
10
+
11
+ CandidateRelation = Literal["top", "half", "double", "other"]
12
+ """How a candidate relates to the reading's tempo. May grow in a minor release, as in JS."""
13
+
14
+ RELATION_TOLERANCE = 0.02
15
+ """Relative tolerance for `half` and `double`: within 2% of the exact ratio."""
16
+
17
+
18
+ class InvalidSamplesError(ValueError):
19
+ """The samples can't be analysed: none at all, or not one channel. JS throws an `Error` for these."""
20
+
21
+
22
+ class OutOfRangeError(ValueError):
23
+ """A value is outside its valid range: the sample rate, the tempo range, the engine or a lowpass setting.
24
+
25
+ JS throws a `RangeError` for these.
26
+ """
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class TempoRange:
31
+ """The tempos a reading is reported in, in BPM, both included. `max` must be at least twice `min`."""
32
+
33
+ min: float
34
+ max: float
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Lowpass:
39
+ """The `peaks` engine's lowpass: the cutoff in Hz, below half the sample rate, and the resonance in dB."""
40
+
41
+ frequency: float = 200
42
+ q: float = 1
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class Candidate:
47
+ """A tempo the engine considered, in its rank order."""
48
+
49
+ bpm: int
50
+ relation: CandidateRelation
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class AudioSpan:
55
+ """The span analysed, in seconds: always the whole input. JS calls these `from` and `to`.
56
+
57
+ JS's `contextTime` has no equivalent here: it is a Web Audio clock, and whole-input analysis sets it to null.
58
+ """
59
+
60
+ start: float
61
+ end: float
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class Reading:
66
+ """A tempo reading, with the same fields and the same meaning as the JS library's `Reading`."""
67
+
68
+ bpm: int
69
+ """The tempo, a whole BPM inside the tempo range. Equal to `candidates[0].bpm`."""
70
+ bpm_exact: float
71
+ """The same tempo, unrounded."""
72
+ confidence: float | None
73
+ """The chance, 0 to 1, that `bpm` is right. None when unmeasured: the reading's `bpm` is outside 90 to 180 BPM,
74
+ or the analysis ran on any tempo range other than 90 to 180."""
75
+ candidates: tuple[Candidate, ...]
76
+ """1 to 5 tempos in the engine's rank order, the first with relation `top`."""
77
+ audio: AudioSpan
78
+ engine: EngineName
File without changes
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: realtime-bpm-analyzer
3
+ Version: 6.2.0
4
+ Summary: Offline BPM detection with the same readings as the realtime-bpm-analyzer JS library, held to it by shared conformance vectors.
5
+ Project-URL: Homepage, https://www.realtime-bpm-analyzer.com
6
+ Project-URL: Documentation, https://www.realtime-bpm-analyzer.com/guide/python
7
+ Project-URL: Repository, https://github.com/dlepaux/realtime-bpm-analyzer
8
+ Project-URL: Issues, https://github.com/dlepaux/realtime-bpm-analyzer/issues
9
+ Project-URL: Changelog, https://github.com/dlepaux/realtime-bpm-analyzer/blob/main/packages/python/changelog.md
10
+ Author: David Lepaux
11
+ License-Expression: Apache-2.0
12
+ License-File: license.md
13
+ Keywords: audio,beat,bpm,dj,music,tempo,tempo detection
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.11
27
+ Requires-Dist: numpy>=1.26
28
+ Description-Content-Type: text/markdown
29
+
30
+ # realtime-bpm-analyzer for Python
31
+
32
+ The offline BPM analysis of [realtime-bpm-analyzer](https://www.realtime-bpm-analyzer.com), ported to Python. You
33
+ pass the decoded samples of one channel and get a reading back: the tempo, its confidence, and the other candidate
34
+ tempos.
35
+
36
+ It gives the same readings as the JS library's `analyzeChannelData`. The repository's
37
+ [conformance vectors](https://github.com/dlepaux/realtime-bpm-analyzer/tree/main/conformance) hold the JS library's
38
+ readings of 140 cases, plus 8 that must fail, and the port's tests compare every one of them.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install realtime-bpm-analyzer
44
+ ```
45
+
46
+ > **Not on PyPI before 6.2.0.** The first release, 6.2.0, reaches PyPI with the JS library's 6.2.0. If `pip` can't
47
+ > find it yet, build it from a clone of the repository with `pip install ./packages/python`.
48
+
49
+ It needs Python 3.11 or later and NumPy 1.26 or later, and has no native code of its own.
50
+
51
+ ## Versions
52
+
53
+ The version is the JS library's major and minor whose conformance vectors the port passes, plus its own patch:
54
+ 6.2.x reads the same as `realtime-bpm-analyzer` 6.2 on npm. A patch of the port can ship without a JS release.
55
+
56
+ ## Example
57
+
58
+ Decoding a file is your job. This example uses [soundfile](https://pypi.org/project/soundfile/), but any decoder
59
+ that gives you samples from -1 to 1 works.
60
+
61
+ ```python
62
+ import soundfile
63
+ from realtime_bpm_analyzer import analyze_channel_data
64
+
65
+ samples, sample_rate = soundfile.read("song.wav", dtype="float32", always_2d=True)
66
+ reading = analyze_channel_data(samples[:, 0], sample_rate)
67
+
68
+ if reading is None:
69
+ print("No tempo found")
70
+ else:
71
+ print(f"{reading.bpm} BPM, confidence {reading.confidence}")
72
+ print("Candidates:", [candidate.bpm for candidate in reading.candidates])
73
+ ```
74
+
75
+ ## API
76
+
77
+ ```python
78
+ def analyze_channel_data(
79
+ samples: Samples,
80
+ sample_rate: float,
81
+ *,
82
+ engine: Literal["tempogram", "peaks"] = "tempogram",
83
+ tempo_range: TempoRange | None = None,
84
+ lowpass: Lowpass | None = None,
85
+ ) -> Reading | None
86
+ ```
87
+
88
+ - `samples`: one channel of numbers from -1 to 1, as a list, a float `array.array` or a 1-D float NumPy array.
89
+ They are analysed as 32-bit floats, as the JS library holds them, so a float64 array reads like its float32 copy.
90
+ Integers are refused, whatever holds them: scale integer PCM first, for 16-bit samples `pcm / 32768`.
91
+ - `sample_rate`: their rate in Hz. The tempogram needs at least 100 Hz, and `peaks` at least 2 Hz.
92
+ - `engine`: `"tempogram"`, the default, reads the full band. `"peaks"` counts the intervals between bass peaks.
93
+ - `tempo_range`: `TempoRange(min=90, max=180)` by default. A reading is folded into this range by octaves, so `max`
94
+ must be at least twice `min`.
95
+ - `lowpass`: the peaks engine's filter, `Lowpass(frequency=200, q=1)` by default, with Q in dB. Only `peaks` takes
96
+ one.
97
+
98
+ It returns `None` when it finds no tempo: silence, noise, or under 1.5 seconds of audio for the tempogram. Otherwise
99
+ it returns a frozen `Reading`:
100
+
101
+ | Field | Type | |
102
+ |-------|------|-|
103
+ | `bpm` | `int` | The tempo, rounded |
104
+ | `bpm_exact` | `float` | The tempo before rounding |
105
+ | `confidence` | `float \| None` | From 0 to 1, calibrated on the default 90 to 180 BPM range. `None` with any other range |
106
+ | `candidates` | `tuple[Candidate, ...]` | Up to 5 tempos, best first. Each has a `bpm` and a `relation` to the top one: `"top"`, `"half"`, `"double"` or `"other"` |
107
+ | `audio` | `AudioSpan` | The span read, in seconds: `start` and `end` |
108
+ | `engine` | `str` | The engine that read it |
109
+
110
+ The options and defaults are the JS library's, in snake case. Two names differ from the JS reading: the JS
111
+ `audio.from` and `audio.to` are `audio.start` and `audio.end` here, since `from` is a Python keyword, and the JS
112
+ `audio.contextTime` is left out, since it is always `null` in an offline reading.
113
+
114
+ ### Errors
115
+
116
+ | Exception | When |
117
+ |-----------|------|
118
+ | `InvalidSamplesError` (a `ValueError`) | The samples are empty, not one channel, or hold a NaN or infinite sample (a float64 past float32's range included, which becomes infinite) |
119
+ | `OutOfRangeError` (a `ValueError`) | A value is out of range: the sample rate, the engine, the tempo range (its `max` must be at least twice its `min` and at most 2^31 - 1, and `max / min` must be finite), or the lowpass settings |
120
+ | `TypeError` | An argument has the wrong type, or the samples are integers |
121
+
122
+ ## Limits
123
+
124
+ - Offline only: it reads samples you already have. There is no live or microphone input, which the JS library does
125
+ in the browser.
126
+ - It reads one channel. To read a stereo file, pass one channel, or your own mix of both.
127
+ - It doesn't decode audio files.
128
+
129
+ ## License
130
+
131
+ Apache-2.0, like the JS library.
@@ -0,0 +1,12 @@
1
+ realtime_bpm_analyzer/__init__.py,sha256=XoEjogilL1H_ibVRPURSuHtjceVc15RIyvzlYpb1yHs,813
2
+ realtime_bpm_analyzer/_analysis.py,sha256=LZu4Q3jJfLaDSRzhYjHzPJmQJzgJtBpQxMa3e4ZBX9U,10970
3
+ realtime_bpm_analyzer/_calibration.py,sha256=tt6EPuJ8IuuP3WjdoCYw0ZIHzshUFL3Q1Bj08N-98r4,5821
4
+ realtime_bpm_analyzer/_jsmath.py,sha256=4QB5wYiBabsz8n80Lo9VHPJWRRo3DDQvJ2TMfBq-pRc,777
5
+ realtime_bpm_analyzer/_peaks.py,sha256=7IP83YQY2ThL5pXHV_L3DbMupqZkrO-v1hR3pSax61Q,7769
6
+ realtime_bpm_analyzer/_tempogram.py,sha256=NxHabk8tAFVUWu4zODQQJrvcAFlRSxdGbNhvVMz062g,12085
7
+ realtime_bpm_analyzer/_types.py,sha256=0mgOeKo8pMacCxLaLIIzY03AGMbrnBGva40nV4ceUG8,2523
8
+ realtime_bpm_analyzer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ realtime_bpm_analyzer-6.2.0.dist-info/METADATA,sha256=kuk7AIeurEQiXk-VSWCjV7x99vSTz0xMmThgG7nxxec,6103
10
+ realtime_bpm_analyzer-6.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ realtime_bpm_analyzer-6.2.0.dist-info/licenses/license.md,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ realtime_bpm_analyzer-6.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.