uppercut-beat-grid 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- uppercut_beat_grid-0.1.0/.gitignore +8 -0
- uppercut_beat_grid-0.1.0/PKG-INFO +90 -0
- uppercut_beat_grid-0.1.0/README.md +69 -0
- uppercut_beat_grid-0.1.0/pyproject.toml +37 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/__init__.py +34 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/align.py +93 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/audio.py +71 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/bed.py +295 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/cli.py +96 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/detect.py +298 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/grid.py +100 -0
- uppercut_beat_grid-0.1.0/src/uppercut_beat_grid/py.typed +0 -0
- uppercut_beat_grid-0.1.0/tests/test_beat_grid.py +404 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-beat-grid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Detect beats, downbeats and tempo into a JSON beat grid, align cut times to it, and render a beat-synced music bed.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-beat-grid
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Keywords: beat,beat-grid,downbeat,music,tempo,video-editing
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: numpy>=1.24
|
|
16
|
+
Provides-Extra: audio
|
|
17
|
+
Requires-Dist: soundfile>=0.12; extra == 'audio'
|
|
18
|
+
Provides-Extra: librosa
|
|
19
|
+
Requires-Dist: librosa>=0.10; extra == 'librosa'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# uppercut-beat-grid
|
|
23
|
+
|
|
24
|
+
Detects tempo, beats and downbeats in audio and writes them as a JSON beat grid with a frame index for every beat. It also checks or snaps cut times to a grid, and renders a synthesized music bed at an exact tempo together with the grid it was built on, so cuts can land on beats with no detection error. The grid data model, alignment and bed synthesis use only NumPy. WAV files load with the standard library; other formats need the `audio` extra, and the optional `librosa` extra adds librosa's beat tracker as a second detection backend.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install uppercut-beat-grid
|
|
30
|
+
pip install "uppercut-beat-grid[audio]" # FLAC, OGG and float WAV input
|
|
31
|
+
pip install "uppercut-beat-grid[librosa]" # librosa backend
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Example
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from uppercut_beat_grid import detect, align, make_grid, generate_bed, write_bed
|
|
38
|
+
|
|
39
|
+
result = detect("track.wav") # tempo, beats, downbeats, energy, onsets
|
|
40
|
+
print(result["tempo"], result["downbeats"][:4])
|
|
41
|
+
|
|
42
|
+
grid = make_grid(bpm=128, duration=15, fps=60) # planned grid with frame indices
|
|
43
|
+
report = align([0.47, 0.94, 1.6], grid, tolerance_ms=17)
|
|
44
|
+
print(report.misses, [r.delta_ms for r in report.results])
|
|
45
|
+
|
|
46
|
+
bed = generate_bed(124, "intro:2,build:4,drop:4,outro:2", style="pulse", seed=3)
|
|
47
|
+
write_bed(bed, "sound/bed") # bed.wav, bed.stems/*.wav, bed.grid.json
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Command line:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
uppercut-beat-grid detect track.wav --json track.grid.json
|
|
54
|
+
uppercut-beat-grid grid --bpm 128 --duration 15 --fps 60 --json plan.json
|
|
55
|
+
uppercut-beat-grid align --cuts cuts.json --beats plan.json --tolerance-ms 17
|
|
56
|
+
uppercut-beat-grid bed --bpm 124 --sections intro:2,build:4,drop:4,outro:2 --out sound/bed
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`align` exits with 1 when any cut misses. A cuts file is a JSON list of times in seconds or `{"cuts": [...]}`.
|
|
60
|
+
|
|
61
|
+
## Functions
|
|
62
|
+
|
|
63
|
+
| Function | What it does |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `detect(audio, sr=None, backend="fit", bpm_hint=None, beats_per_bar=4)` | Tempo, beat times, downbeat phase and times, per-beat energy and onset times. `audio` is a path or a mono array (with `sr`). Backend `"fit"` uses NumPy; `"librosa"` needs the extra. Detected tempo can be off by a factor of two; `bpm_hint` pins it. |
|
|
66
|
+
| `fit_tempo(envelope, hop_seconds, bpm_hint=None)` | Constant-tempo and phase fit on an onset envelope: grid search over the half, same and double of the estimate, an octave prior around 120 BPM, and a least-squares refinement. |
|
|
67
|
+
| `onset_envelope(y, sr)` | Spectral-flux onset strength and its seconds per frame. |
|
|
68
|
+
| `pick_downbeat_phase(envelope, hop_seconds, beats, beats_per_bar)` | Which beat starts a bar, by onset strength. |
|
|
69
|
+
| `grid_from_detection(result, fps=60)` | A grid dict from a `detect` result. |
|
|
70
|
+
| `make_grid(bpm, duration, offset=0, fps=60, beats_per_bar=4)` | A planned grid: beats with `i`, `t`, `bar`, `beat`, `frame`, plus half-beats. |
|
|
71
|
+
| `save_grid(grid, path)`, `load_grid(path)`, `beat_times(grid)`, `frame_index(t, fps)` | JSON round trip and helpers. |
|
|
72
|
+
| `snap_to_grid(t, beats, reach=None)` | Nearest beat time, or `None` beyond `reach` seconds. |
|
|
73
|
+
| `align(cuts, beats, tolerance_ms=17, half=False, auto_offset=False)` | An `AlignReport` with each cut's distance to the nearest beat. `half` adds half-beats as targets. `auto_offset` removes the median delta first, for judging a delivered file whose detected beats lag by a constant. 17 ms is one frame at 60 fps. |
|
|
74
|
+
| `snap_cuts(cuts, beats, half=False, reach=None)` | Cut times moved to their nearest beats. |
|
|
75
|
+
| `generate_bed(bpm, sections, style="pulse", key="A", scale="minor", seed=3, fps=60, end_hit=False, gaps=(), rate=48000)` | A `Bed(stems, mix, grid, rate)`. Sections: `intro`, `build`, `groove`, `drop`, `break`, `outro`, `hold`. Styles: `pulse`, `lofi`, `drive`. Scales: `minor`, `major`, `dorian`. Each beat in `gaps` is preceded by half a beat of silence. |
|
|
76
|
+
| `write_bed(bed, out)` | Writes `out.wav` (24-bit stereo, peak -6 dBFS), `out.stems/*.wav` and `out.grid.json`. |
|
|
77
|
+
| `read_audio(path)`, `write_wav24(path, samples, rate)` | Audio file helpers. |
|
|
78
|
+
|
|
79
|
+
The same bed arguments always produce the same samples.
|
|
80
|
+
|
|
81
|
+
## Errors
|
|
82
|
+
|
|
83
|
+
| Error | Raised when |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `ValueError` | A tempo, fps or tolerance is out of range, a section string is malformed, a gap is outside the bed, a style, key or scale is unknown, there are no beats to align to, or the audio is too short to analyse. |
|
|
86
|
+
| `ImportError` | The `librosa` backend or a non-WAV format is used without its extra installed. |
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# uppercut-beat-grid
|
|
2
|
+
|
|
3
|
+
Detects tempo, beats and downbeats in audio and writes them as a JSON beat grid with a frame index for every beat. It also checks or snaps cut times to a grid, and renders a synthesized music bed at an exact tempo together with the grid it was built on, so cuts can land on beats with no detection error. The grid data model, alignment and bed synthesis use only NumPy. WAV files load with the standard library; other formats need the `audio` extra, and the optional `librosa` extra adds librosa's beat tracker as a second detection backend.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install uppercut-beat-grid
|
|
9
|
+
pip install "uppercut-beat-grid[audio]" # FLAC, OGG and float WAV input
|
|
10
|
+
pip install "uppercut-beat-grid[librosa]" # librosa backend
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Example
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from uppercut_beat_grid import detect, align, make_grid, generate_bed, write_bed
|
|
17
|
+
|
|
18
|
+
result = detect("track.wav") # tempo, beats, downbeats, energy, onsets
|
|
19
|
+
print(result["tempo"], result["downbeats"][:4])
|
|
20
|
+
|
|
21
|
+
grid = make_grid(bpm=128, duration=15, fps=60) # planned grid with frame indices
|
|
22
|
+
report = align([0.47, 0.94, 1.6], grid, tolerance_ms=17)
|
|
23
|
+
print(report.misses, [r.delta_ms for r in report.results])
|
|
24
|
+
|
|
25
|
+
bed = generate_bed(124, "intro:2,build:4,drop:4,outro:2", style="pulse", seed=3)
|
|
26
|
+
write_bed(bed, "sound/bed") # bed.wav, bed.stems/*.wav, bed.grid.json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Command line:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
uppercut-beat-grid detect track.wav --json track.grid.json
|
|
33
|
+
uppercut-beat-grid grid --bpm 128 --duration 15 --fps 60 --json plan.json
|
|
34
|
+
uppercut-beat-grid align --cuts cuts.json --beats plan.json --tolerance-ms 17
|
|
35
|
+
uppercut-beat-grid bed --bpm 124 --sections intro:2,build:4,drop:4,outro:2 --out sound/bed
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`align` exits with 1 when any cut misses. A cuts file is a JSON list of times in seconds or `{"cuts": [...]}`.
|
|
39
|
+
|
|
40
|
+
## Functions
|
|
41
|
+
|
|
42
|
+
| Function | What it does |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `detect(audio, sr=None, backend="fit", bpm_hint=None, beats_per_bar=4)` | Tempo, beat times, downbeat phase and times, per-beat energy and onset times. `audio` is a path or a mono array (with `sr`). Backend `"fit"` uses NumPy; `"librosa"` needs the extra. Detected tempo can be off by a factor of two; `bpm_hint` pins it. |
|
|
45
|
+
| `fit_tempo(envelope, hop_seconds, bpm_hint=None)` | Constant-tempo and phase fit on an onset envelope: grid search over the half, same and double of the estimate, an octave prior around 120 BPM, and a least-squares refinement. |
|
|
46
|
+
| `onset_envelope(y, sr)` | Spectral-flux onset strength and its seconds per frame. |
|
|
47
|
+
| `pick_downbeat_phase(envelope, hop_seconds, beats, beats_per_bar)` | Which beat starts a bar, by onset strength. |
|
|
48
|
+
| `grid_from_detection(result, fps=60)` | A grid dict from a `detect` result. |
|
|
49
|
+
| `make_grid(bpm, duration, offset=0, fps=60, beats_per_bar=4)` | A planned grid: beats with `i`, `t`, `bar`, `beat`, `frame`, plus half-beats. |
|
|
50
|
+
| `save_grid(grid, path)`, `load_grid(path)`, `beat_times(grid)`, `frame_index(t, fps)` | JSON round trip and helpers. |
|
|
51
|
+
| `snap_to_grid(t, beats, reach=None)` | Nearest beat time, or `None` beyond `reach` seconds. |
|
|
52
|
+
| `align(cuts, beats, tolerance_ms=17, half=False, auto_offset=False)` | An `AlignReport` with each cut's distance to the nearest beat. `half` adds half-beats as targets. `auto_offset` removes the median delta first, for judging a delivered file whose detected beats lag by a constant. 17 ms is one frame at 60 fps. |
|
|
53
|
+
| `snap_cuts(cuts, beats, half=False, reach=None)` | Cut times moved to their nearest beats. |
|
|
54
|
+
| `generate_bed(bpm, sections, style="pulse", key="A", scale="minor", seed=3, fps=60, end_hit=False, gaps=(), rate=48000)` | A `Bed(stems, mix, grid, rate)`. Sections: `intro`, `build`, `groove`, `drop`, `break`, `outro`, `hold`. Styles: `pulse`, `lofi`, `drive`. Scales: `minor`, `major`, `dorian`. Each beat in `gaps` is preceded by half a beat of silence. |
|
|
55
|
+
| `write_bed(bed, out)` | Writes `out.wav` (24-bit stereo, peak -6 dBFS), `out.stems/*.wav` and `out.grid.json`. |
|
|
56
|
+
| `read_audio(path)`, `write_wav24(path, samples, rate)` | Audio file helpers. |
|
|
57
|
+
|
|
58
|
+
The same bed arguments always produce the same samples.
|
|
59
|
+
|
|
60
|
+
## Errors
|
|
61
|
+
|
|
62
|
+
| Error | Raised when |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `ValueError` | A tempo, fps or tolerance is out of range, a section string is malformed, a gap is outside the bed, a style, key or scale is unknown, there are no beats to align to, or the audio is too short to analyse. |
|
|
65
|
+
| `ImportError` | The `librosa` backend or a non-WAV format is used without its extra installed. |
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-beat-grid"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Detect beats, downbeats and tempo into a JSON beat grid, align cut times to it, and render a beat-synced music bed."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
dependencies = ["numpy>=1.24"]
|
|
14
|
+
keywords = ["beat", "tempo", "downbeat", "beat-grid", "video-editing", "music"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Multimedia :: Sound/Audio :: Analysis",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
audio = ["soundfile>=0.12"]
|
|
25
|
+
librosa = ["librosa>=0.10"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-beat-grid"
|
|
29
|
+
|
|
30
|
+
[project.scripts]
|
|
31
|
+
uppercut-beat-grid = "uppercut_beat_grid.cli:main"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.wheel]
|
|
34
|
+
packages = ["src/uppercut_beat_grid"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.sdist]
|
|
37
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Beat grids: detect them, build them, align cuts to them, and render a bed on one."""
|
|
2
|
+
|
|
3
|
+
from .align import AlignReport, CutResult, align, cut_times, snap_cuts
|
|
4
|
+
from .audio import read_audio, write_wav24
|
|
5
|
+
from .bed import Bed, generate_bed, parse_sections, write_bed
|
|
6
|
+
from .detect import detect, fit_tempo, grid_from_detection, onset_envelope, pick_downbeat_phase
|
|
7
|
+
from .grid import beat_times, frame_index, load_grid, make_grid, save_grid, snap_to_grid, with_half_beats
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AlignReport",
|
|
11
|
+
"Bed",
|
|
12
|
+
"CutResult",
|
|
13
|
+
"align",
|
|
14
|
+
"beat_times",
|
|
15
|
+
"cut_times",
|
|
16
|
+
"detect",
|
|
17
|
+
"fit_tempo",
|
|
18
|
+
"frame_index",
|
|
19
|
+
"generate_bed",
|
|
20
|
+
"grid_from_detection",
|
|
21
|
+
"load_grid",
|
|
22
|
+
"make_grid",
|
|
23
|
+
"onset_envelope",
|
|
24
|
+
"parse_sections",
|
|
25
|
+
"pick_downbeat_phase",
|
|
26
|
+
"read_audio",
|
|
27
|
+
"save_grid",
|
|
28
|
+
"snap_cuts",
|
|
29
|
+
"snap_to_grid",
|
|
30
|
+
"with_half_beats",
|
|
31
|
+
"write_bed",
|
|
32
|
+
"write_wav24",
|
|
33
|
+
]
|
|
34
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Check and fix cut times against a beat grid."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Mapping, Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .grid import beat_times, with_half_beats
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class CutResult:
|
|
15
|
+
cut: float
|
|
16
|
+
nearest: float
|
|
17
|
+
delta_ms: float # cut minus nearest beat
|
|
18
|
+
residual_ms: float # delta after the global offset is removed
|
|
19
|
+
ok: bool
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class AlignReport:
|
|
24
|
+
results: list[CutResult]
|
|
25
|
+
offset_ms: float
|
|
26
|
+
tolerance_ms: float
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def misses(self) -> int:
|
|
30
|
+
return sum(not r.ok for r in self.results)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def all_ok(self) -> bool:
|
|
34
|
+
return self.misses == 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cut_times(cuts: Sequence[Any] | Mapping[str, Any]) -> list[float]:
|
|
38
|
+
"""Cut times from a list of numbers or `{"t": ...}` dicts, or a dict with a `cuts` list."""
|
|
39
|
+
items = cuts["cuts"] if isinstance(cuts, Mapping) else cuts
|
|
40
|
+
return [float(c["t"]) if isinstance(c, Mapping) else float(c) for c in items]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def align(
|
|
44
|
+
cuts: Sequence[Any] | Mapping[str, Any],
|
|
45
|
+
beats: Sequence[Any] | Mapping[str, Any],
|
|
46
|
+
tolerance_ms: float = 17.0,
|
|
47
|
+
half: bool = False,
|
|
48
|
+
auto_offset: bool = False,
|
|
49
|
+
) -> AlignReport:
|
|
50
|
+
"""Measure how far each cut is from the nearest beat.
|
|
51
|
+
|
|
52
|
+
`tolerance_ms` is how far a cut may sit from a beat and still pass: 17 ms is one frame at
|
|
53
|
+
60 fps, 34 ms one frame at 30 fps. With `half`, half-beats count as targets too. With
|
|
54
|
+
`auto_offset`, the median cut-to-beat delta is removed first, for checking a delivered
|
|
55
|
+
file whose detected beats lag the true transients by a constant.
|
|
56
|
+
"""
|
|
57
|
+
if tolerance_ms < 0:
|
|
58
|
+
raise ValueError("tolerance_ms must not be negative")
|
|
59
|
+
cs = cut_times(cuts)
|
|
60
|
+
bs = beat_times(beats)
|
|
61
|
+
if not bs:
|
|
62
|
+
raise ValueError("there are no beats to align to")
|
|
63
|
+
if half:
|
|
64
|
+
bs = with_half_beats(bs)
|
|
65
|
+
arr = np.asarray(bs)
|
|
66
|
+
nearest = [float(arr[int(np.argmin(np.abs(arr - c)))]) for c in cs]
|
|
67
|
+
deltas = [(c - n) * 1000.0 for c, n in zip(cs, nearest)]
|
|
68
|
+
offset = float(np.median(deltas)) if auto_offset and deltas else 0.0
|
|
69
|
+
results = [
|
|
70
|
+
CutResult(c, n, d, d - offset, abs(d - offset) <= tolerance_ms) for c, n, d in zip(cs, nearest, deltas)
|
|
71
|
+
]
|
|
72
|
+
return AlignReport(results, offset, tolerance_ms)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def snap_cuts(
|
|
76
|
+
cuts: Sequence[Any] | Mapping[str, Any],
|
|
77
|
+
beats: Sequence[Any] | Mapping[str, Any],
|
|
78
|
+
half: bool = False,
|
|
79
|
+
reach: float | None = None,
|
|
80
|
+
) -> list[float]:
|
|
81
|
+
"""Move each cut to its nearest beat. Cuts farther than `reach` seconds from any beat are kept."""
|
|
82
|
+
cs = cut_times(cuts)
|
|
83
|
+
bs = beat_times(beats)
|
|
84
|
+
if not bs:
|
|
85
|
+
raise ValueError("there are no beats to snap to")
|
|
86
|
+
if half:
|
|
87
|
+
bs = with_half_beats(bs)
|
|
88
|
+
arr = np.asarray(bs)
|
|
89
|
+
out = []
|
|
90
|
+
for c in cs:
|
|
91
|
+
nearest = float(arr[int(np.argmin(np.abs(arr - c)))])
|
|
92
|
+
out.append(nearest if reach is None or abs(nearest - c) <= reach else c)
|
|
93
|
+
return out
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Reading and writing audio. WAV works with the standard library; other formats need `soundfile`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import wave
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def read_audio(path: str | Path) -> tuple[np.ndarray, int]:
|
|
12
|
+
"""Load a file as mono float64 in [-1, 1]; returns `(samples, sample_rate)`.
|
|
13
|
+
|
|
14
|
+
16, 24 and 32-bit PCM WAV files load without extra packages. Everything else (FLAC, OGG,
|
|
15
|
+
float WAV) needs `pip install uppercut-beat-grid[audio]`.
|
|
16
|
+
"""
|
|
17
|
+
p = Path(path)
|
|
18
|
+
if p.suffix.lower() in {".wav", ".wave"}:
|
|
19
|
+
try:
|
|
20
|
+
return _read_wav(p)
|
|
21
|
+
except wave.Error:
|
|
22
|
+
pass # float or extensible WAV: let soundfile try
|
|
23
|
+
try:
|
|
24
|
+
import soundfile
|
|
25
|
+
except ImportError as error:
|
|
26
|
+
raise ImportError(
|
|
27
|
+
f"reading {p.name} needs the soundfile package: pip install uppercut-beat-grid[audio]"
|
|
28
|
+
) from error
|
|
29
|
+
data, rate = soundfile.read(str(p), dtype="float64", always_2d=True)
|
|
30
|
+
return data.mean(axis=1), int(rate)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _read_wav(path: Path) -> tuple[np.ndarray, int]:
|
|
34
|
+
with wave.open(str(path), "rb") as w:
|
|
35
|
+
channels, width, rate, frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
|
|
36
|
+
raw = w.readframes(frames)
|
|
37
|
+
if width == 1:
|
|
38
|
+
data = (np.frombuffer(raw, dtype=np.uint8).astype(np.float64) - 128.0) / 128.0
|
|
39
|
+
elif width == 2:
|
|
40
|
+
data = np.frombuffer(raw, dtype="<i2").astype(np.float64) / 32768.0
|
|
41
|
+
elif width == 3:
|
|
42
|
+
b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
|
|
43
|
+
ints = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
|
|
44
|
+
ints = np.where(ints >= 1 << 23, ints - (1 << 24), ints)
|
|
45
|
+
data = ints.astype(np.float64) / float(1 << 23)
|
|
46
|
+
elif width == 4:
|
|
47
|
+
data = np.frombuffer(raw, dtype="<i4").astype(np.float64) / float(1 << 31)
|
|
48
|
+
else:
|
|
49
|
+
raise wave.Error(f"unsupported sample width {width}")
|
|
50
|
+
return data.reshape(-1, channels).mean(axis=1), rate
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def pcm24_bytes(x: np.ndarray) -> bytes:
|
|
54
|
+
"""Little-endian 24-bit PCM for samples shaped (n,) or (n, channels); clips at full scale."""
|
|
55
|
+
ints = np.round(np.clip(np.asarray(x, dtype=np.float64), -1.0, 1.0) * float(2**23 - 1)).astype("<i4")
|
|
56
|
+
raw = ints.tobytes()
|
|
57
|
+
return b"".join(raw[i : i + 3] for i in range(0, len(raw), 4))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def write_wav24(path: str | Path, x: np.ndarray, rate: int) -> None:
|
|
61
|
+
"""Write a 24-bit PCM WAV for mono (n,) or stereo (n, 2) samples. Same samples, same bytes."""
|
|
62
|
+
a = np.asarray(x)
|
|
63
|
+
channels = 1 if a.ndim == 1 else a.shape[1]
|
|
64
|
+
if a.ndim not in (1, 2) or not 1 <= channels <= 2:
|
|
65
|
+
raise ValueError("samples must be shaped (n,) or (n, 2)")
|
|
66
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
with wave.open(str(path), "wb") as w:
|
|
68
|
+
w.setnchannels(channels)
|
|
69
|
+
w.setsampwidth(3)
|
|
70
|
+
w.setframerate(rate)
|
|
71
|
+
w.writeframes(pcm24_bytes(a))
|