loopcutter 0.3.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.
- loopcutter/__init__.py +13 -0
- loopcutter/analyse.py +153 -0
- loopcutter/audio_io.py +46 -0
- loopcutter/cli.py +768 -0
- loopcutter/cut.py +197 -0
- loopcutter/grid.py +205 -0
- loopcutter/keydetect.py +77 -0
- loopcutter/keyreport.py +236 -0
- loopcutter/keys.py +346 -0
- loopcutter/manifest.py +245 -0
- loopcutter/markers.py +175 -0
- loopcutter/model.py +114 -0
- loopcutter/naming.py +95 -0
- loopcutter/onsets.py +117 -0
- loopcutter/prep.py +188 -0
- loopcutter/provenance.py +64 -0
- loopcutter/snap.py +215 -0
- loopcutter/stems.py +197 -0
- loopcutter/tags.py +135 -0
- loopcutter/timing.py +144 -0
- loopcutter/trackdb.py +77 -0
- loopcutter/verify.py +200 -0
- loopcutter/workspace.py +119 -0
- loopcutter-0.3.0.dist-info/METADATA +664 -0
- loopcutter-0.3.0.dist-info/RECORD +29 -0
- loopcutter-0.3.0.dist-info/WHEEL +5 -0
- loopcutter-0.3.0.dist-info/entry_points.txt +2 -0
- loopcutter-0.3.0.dist-info/licenses/LICENSE +21 -0
- loopcutter-0.3.0.dist-info/top_level.txt +1 -0
loopcutter/verify.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Verification.
|
|
2
|
+
|
|
3
|
+
An agent cannot hear the output. These checks are the substitute, and every
|
|
4
|
+
one has a test proving it can fail:
|
|
5
|
+
|
|
6
|
+
- sample_count, sample_rate: the file is exactly the declared length.
|
|
7
|
+
- peak_headroom: the loop is no louder than its source, after any trim.
|
|
8
|
+
- not_silent, dc_offset.
|
|
9
|
+
- beat_alignment: the strongest attack near each of the loop's beats, found in
|
|
10
|
+
the source around the loop. Placement catches a start in the wrong place,
|
|
11
|
+
drift a wrong tempo. Gross errors fail, and fine ones warn.
|
|
12
|
+
- bpm_match (automatic when the track has been analysed, or with --check-bpm):
|
|
13
|
+
how far the loop's end lands from where the next bar begins.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import soundfile as sf
|
|
23
|
+
|
|
24
|
+
from .cut import CutResult
|
|
25
|
+
from .onsets import HOP, attacks_near, detect_onsets, onset_envelope
|
|
26
|
+
from .timing import loop_length_samples
|
|
27
|
+
|
|
28
|
+
MAX_DC_OFFSET = 0.01
|
|
29
|
+
PEAK_EPS = 1e-4
|
|
30
|
+
CONTEXT_S = 0.1
|
|
31
|
+
ALIGN_WINDOW_S = 0.060
|
|
32
|
+
MIN_AGREEMENT = 0.5 # below this there is no steady attack to judge (breakdowns, pads)
|
|
33
|
+
PASS_PLACEMENT_MS = (-3.0, 8.0) # an attack before the start means the start cuts into it
|
|
34
|
+
FAIL_PLACEMENT_MS = (-10.0, 15.0)
|
|
35
|
+
DRIFT_WARN_MS = 4.0
|
|
36
|
+
DRIFT_FAIL_MS = 10.0
|
|
37
|
+
REFERENCE_END_ERROR_MS = 2.0
|
|
38
|
+
MEASURED_END_ERROR_MS = 5.0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Check:
|
|
43
|
+
name: str
|
|
44
|
+
passed: bool
|
|
45
|
+
detail: str = ""
|
|
46
|
+
warn: bool = False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Report:
|
|
51
|
+
output: Path
|
|
52
|
+
checks: list[Check] = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def ok(self) -> bool:
|
|
56
|
+
return all(check.passed for check in self.checks)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def failures(self) -> list[Check]:
|
|
60
|
+
return [c for c in self.checks if not c.passed]
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def warnings(self) -> list[Check]:
|
|
64
|
+
return [c for c in self.checks if c.passed and c.warn]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _librosa_available() -> bool:
|
|
68
|
+
try:
|
|
69
|
+
import librosa # noqa: F401
|
|
70
|
+
except ImportError:
|
|
71
|
+
return False
|
|
72
|
+
return True
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def verify_cut(result: CutResult, check_bpm: bool = False,
|
|
76
|
+
reference_bpm: float | None = None) -> Report:
|
|
77
|
+
report = Report(output=result.output)
|
|
78
|
+
audio, sample_rate = sf.read(str(result.output), dtype="float32", always_2d=True)
|
|
79
|
+
|
|
80
|
+
loop = result.spec.kind == "loop"
|
|
81
|
+
expected = (loop_length_samples(result.spec.bars, result.spec.bpm, sample_rate,
|
|
82
|
+
result.spec.beats_per_bar) if loop
|
|
83
|
+
else int(round(result.spec.end_seconds * sample_rate)) - result.start_sample)
|
|
84
|
+
report.checks.append(Check("sample_count", len(audio) == expected,
|
|
85
|
+
f"got {len(audio)}, expected {expected}"))
|
|
86
|
+
report.checks.append(Check("sample_rate", sample_rate == result.sample_rate,
|
|
87
|
+
f"{sample_rate} vs source {result.sample_rate}"))
|
|
88
|
+
|
|
89
|
+
peak = float(np.max(np.abs(audio))) if audio.size else 0.0
|
|
90
|
+
ceiling = result.source_peak * 10.0 ** (result.trim_db / 20.0)
|
|
91
|
+
trim = f" with {result.trim_db:+.1f} dB trim" if result.trim_db else ""
|
|
92
|
+
report.checks.append(Check("peak_headroom",
|
|
93
|
+
ceiling <= 1.0 + PEAK_EPS and peak <= ceiling + PEAK_EPS,
|
|
94
|
+
f"peak {peak:.4f}; source {result.source_peak:.4f}{trim}"))
|
|
95
|
+
report.checks.append(Check("not_silent", peak > 1e-5, f"peak {peak:.6f}"))
|
|
96
|
+
dc = float(np.max(np.abs(audio.mean(axis=0)))) if audio.size else 0.0
|
|
97
|
+
report.checks.append(Check("dc_offset", dc <= MAX_DC_OFFSET, f"dc {dc:.5f}"))
|
|
98
|
+
if not loop:
|
|
99
|
+
return report # one-shots have no beats to align and no tempo to match
|
|
100
|
+
|
|
101
|
+
if not _librosa_available():
|
|
102
|
+
report.checks.append(Check("beat_alignment", True, "not judged - librosa not installed"))
|
|
103
|
+
if check_bpm and reference_bpm:
|
|
104
|
+
report.checks.append(_bpm_from_reference(result, reference_bpm))
|
|
105
|
+
return report
|
|
106
|
+
|
|
107
|
+
mono, lead = _timing_window(result)
|
|
108
|
+
report.checks.append(_beat_alignment_check(result, mono, lead, sample_rate))
|
|
109
|
+
if check_bpm:
|
|
110
|
+
report.checks.append(_bpm_from_reference(result, reference_bpm) if reference_bpm
|
|
111
|
+
else _bpm_from_audio(result, mono, sample_rate))
|
|
112
|
+
return report
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _timing_window(result: CutResult) -> tuple[np.ndarray, float]:
|
|
116
|
+
"""The source around the loop (the full mix for a stem) as mono, with context either
|
|
117
|
+
side so the onset detector sees the first attack. Returns it and where the loop starts."""
|
|
118
|
+
path = result.timing_source or result.spec.source
|
|
119
|
+
info = sf.info(str(path))
|
|
120
|
+
pad = int(round(CONTEXT_S * info.samplerate))
|
|
121
|
+
lo = max(0, result.start_sample - pad)
|
|
122
|
+
hi = min(info.frames, result.start_sample + result.length_samples + pad)
|
|
123
|
+
audio, _ = sf.read(str(path), start=lo, stop=hi, dtype="float32", always_2d=True)
|
|
124
|
+
return audio.mean(axis=1), (result.start_sample - lo) / info.samplerate
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _beat_alignment_check(result: CutResult, mono: np.ndarray, lead: float, sr: int) -> Check:
|
|
128
|
+
"""The strongest attack within 60 ms of each of the loop's beats. Placement is their
|
|
129
|
+
strength-weighted median; drift is how the kick train moves from first beat to last."""
|
|
130
|
+
period = 60.0 / result.spec.bpm
|
|
131
|
+
n = int(round(result.spec.bars * result.spec.beats_per_bar))
|
|
132
|
+
if n < 2:
|
|
133
|
+
return Check("beat_alignment", True, "not judged - shorter than two beats")
|
|
134
|
+
times, strengths = detect_onsets(mono, sr)
|
|
135
|
+
times = times - lead
|
|
136
|
+
inside = (times > -ALIGN_WINDOW_S) & (times < n * period)
|
|
137
|
+
found = attacks_near(times[inside], strengths[inside], np.arange(n) * period, ALIGN_WINDOW_S)
|
|
138
|
+
if len(found) < max(2, n // 2):
|
|
139
|
+
if inside.sum() >= n:
|
|
140
|
+
return Check("beat_alignment", False,
|
|
141
|
+
f"attacks don't sit on the loop's beats: only {len(found)} of {n} beats "
|
|
142
|
+
f"have one within {ALIGN_WINDOW_S * 1000:.0f} ms - check the start and the tempo")
|
|
143
|
+
return Check("beat_alignment", True, f"not judged - only {int(inside.sum())} onsets")
|
|
144
|
+
agreement = found.agreement(n)
|
|
145
|
+
if agreement < MIN_AGREEMENT:
|
|
146
|
+
return Check("beat_alignment", True,
|
|
147
|
+
f"not judged - no steady attack on the beats ({agreement:.0%} agree)")
|
|
148
|
+
placement = found.placement * 1000
|
|
149
|
+
drift = (found.drift(n) or 0.0) * 1000
|
|
150
|
+
detail = f"attacks sit {placement:+.1f} ms from the beats, drifting {drift:+.1f} ms over the loop"
|
|
151
|
+
lo, hi = FAIL_PLACEMENT_MS
|
|
152
|
+
if not lo <= placement <= hi or abs(drift) > DRIFT_FAIL_MS:
|
|
153
|
+
return Check("beat_alignment", False, detail)
|
|
154
|
+
lo, hi = PASS_PLACEMENT_MS
|
|
155
|
+
if not lo <= placement <= hi or abs(drift) > DRIFT_WARN_MS:
|
|
156
|
+
return Check("beat_alignment", True, detail + " - worth a listen", warn=True)
|
|
157
|
+
return Check("beat_alignment", True, detail)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _bpm_from_reference(result: CutResult, reference_bpm: float) -> Check:
|
|
161
|
+
beats = result.spec.bars * result.spec.beats_per_bar
|
|
162
|
+
end_ms = beats * abs(60 / result.spec.bpm - 60 / reference_bpm) * 1000
|
|
163
|
+
return Check("bpm_match", end_ms <= REFERENCE_END_ERROR_MS,
|
|
164
|
+
f"declared {result.spec.bpm:g}, analysed {reference_bpm:.3f}: "
|
|
165
|
+
f"the loop's end is {end_ms:.1f} ms from the next bar")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _bpm_from_audio(result: CutResult, mono: np.ndarray, sr: int) -> Check:
|
|
169
|
+
declared = result.spec.bpm
|
|
170
|
+
n = int(round(result.spec.bars * result.spec.beats_per_bar))
|
|
171
|
+
measured = _measured_bpm(onset_envelope(mono, sr), sr, declared, n)
|
|
172
|
+
if measured is None:
|
|
173
|
+
return Check("bpm_match", True, "not judged - no clear pulse near the declared tempo")
|
|
174
|
+
end_ms = n * abs(60 / declared - 60 / measured) * 1000
|
|
175
|
+
return Check("bpm_match", end_ms <= MEASURED_END_ERROR_MS,
|
|
176
|
+
f"declared {declared:g}, measured {measured:.2f}: "
|
|
177
|
+
f"the loop's end is {end_ms:.1f} ms from the next bar")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _measured_bpm(envelope: np.ndarray, sr: int, declared: float, n_beats: int) -> float | None:
|
|
181
|
+
"""Tempo from the audio: the autocorrelation peak of the onset envelope near K beats
|
|
182
|
+
of the declared tempo, refined between frames. K beats rather than one beat divides
|
|
183
|
+
the frame quantisation by K."""
|
|
184
|
+
x = envelope - envelope.mean()
|
|
185
|
+
size = x.size
|
|
186
|
+
spectrum = np.fft.rfft(x, 2 * size)
|
|
187
|
+
ac = np.fft.irfft(spectrum * np.conj(spectrum))[:size] / np.arange(size, 0, -1)
|
|
188
|
+
k = max(1, min(4, n_beats // 2))
|
|
189
|
+
width = min(0.15, 0.45 / k) # keeps the half-beat peaks outside the search
|
|
190
|
+
centre = k * 60.0 / declared * sr / HOP
|
|
191
|
+
lo, hi = int(centre * (1 - width)), int(np.ceil(centre * (1 + width)))
|
|
192
|
+
if lo < 1 or hi + 1 >= size or ac[0] <= 0:
|
|
193
|
+
return None
|
|
194
|
+
peak = lo + int(np.argmax(ac[lo : hi + 1]))
|
|
195
|
+
if peak in (lo, hi) or ac[peak] < 0.2 * ac[0]:
|
|
196
|
+
return None
|
|
197
|
+
a, b, c = ac[peak - 1], ac[peak], ac[peak + 1]
|
|
198
|
+
denom = a - 2 * b + c
|
|
199
|
+
frac = 0.5 * (a - c) / denom if denom else 0.0
|
|
200
|
+
return 60.0 * sr * k / (HOP * (peak + frac))
|
loopcutter/workspace.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Workspaces: private working data kept outside the tool's repository.
|
|
2
|
+
|
|
3
|
+
A workspace is any folder containing loopcutter.toml. Commands find it the way
|
|
4
|
+
git finds a repository, by walking up from the current directory. A workspace
|
|
5
|
+
may never sit inside a repository that has a remote: it holds private data.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import subprocess
|
|
11
|
+
import tomllib
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
MARKER = "loopcutter.toml"
|
|
16
|
+
DIRS = ("masters", "analysis", "manifests", "reports", "loops/aiff", "loops/wav", "stems")
|
|
17
|
+
|
|
18
|
+
DEFAULT_CONFIG = """\
|
|
19
|
+
# loopcutter workspace. Everything in this folder is private working data.
|
|
20
|
+
|
|
21
|
+
[audio]
|
|
22
|
+
sample_rate = 48000 # rate of the working masters; a cut never resamples
|
|
23
|
+
subtype = "PCM_24"
|
|
24
|
+
headroom_db = 3.0 # taken off every master, so overs from decoding and resampling don't clip
|
|
25
|
+
|
|
26
|
+
[sources]
|
|
27
|
+
paths = [] # folders or files that `loopcutter prep` reads by default
|
|
28
|
+
|
|
29
|
+
[prep]
|
|
30
|
+
replaced_dir = "masters/.replaced" # a copy of a lossy-built master is kept here when a lossless copy replaces it
|
|
31
|
+
|
|
32
|
+
[snap]
|
|
33
|
+
max_shift_ms = 60 # refuse to move a start further than this
|
|
34
|
+
|
|
35
|
+
[marking]
|
|
36
|
+
app = "rekordbox" # rekordbox | rekordbox-xml | serato
|
|
37
|
+
playlist = "" # the playlist that holds your masters
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
GITIGNORE = ("masters/\nloops/\nstems/\nanalysis/beats/\n"
|
|
41
|
+
"*.wav\n*.aif\n*.aiff\n*.flac\n*.mp3\n*.m4a\n.DS_Store\n")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class WorkspaceError(RuntimeError):
|
|
45
|
+
"""Raised when a workspace can't be created or found safely."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Workspace:
|
|
50
|
+
root: Path
|
|
51
|
+
config: dict = field(default_factory=dict)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def masters(self) -> Path:
|
|
55
|
+
return self.root / "masters"
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def tracks_csv(self) -> Path:
|
|
59
|
+
return self.root / "analysis" / "tracks.csv"
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def beats_dir(self) -> Path:
|
|
63
|
+
return self.root / "analysis" / "beats"
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def manifests(self) -> Path:
|
|
67
|
+
return self.root / "manifests"
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def reports(self) -> Path:
|
|
71
|
+
return self.root / "reports"
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def loops(self) -> Path:
|
|
75
|
+
return self.root / "loops"
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def stems(self) -> Path:
|
|
79
|
+
return self.root / "stems"
|
|
80
|
+
|
|
81
|
+
def setting(self, section: str, key: str, default=None):
|
|
82
|
+
return self.config.get(section, {}).get(key, default)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def load_workspace(root: str | Path) -> Workspace:
|
|
86
|
+
root = Path(root).expanduser().resolve()
|
|
87
|
+
with (root / MARKER).open("rb") as handle:
|
|
88
|
+
return Workspace(root=root, config=tomllib.load(handle))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def find_workspace(start: str | Path | None = None) -> Workspace | None:
|
|
92
|
+
here = Path(start or Path.cwd()).expanduser().resolve()
|
|
93
|
+
for candidate in (here, *here.parents):
|
|
94
|
+
if (candidate / MARKER).is_file():
|
|
95
|
+
return load_workspace(candidate)
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _repo_with_remote(path: Path) -> Path | None:
|
|
100
|
+
for candidate in (path, *path.parents):
|
|
101
|
+
if (candidate / ".git").exists():
|
|
102
|
+
remotes = subprocess.run(["git", "-C", str(candidate), "remote"],
|
|
103
|
+
capture_output=True, text=True).stdout.strip()
|
|
104
|
+
return candidate if remotes else None
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def init_workspace(root: str | Path) -> Workspace:
|
|
109
|
+
root = Path(root).expanduser().resolve()
|
|
110
|
+
repo = _repo_with_remote(root)
|
|
111
|
+
if repo is not None:
|
|
112
|
+
raise WorkspaceError(f"{root} is inside {repo}, a git repository with a remote; "
|
|
113
|
+
"a workspace holds private data, so put it somewhere else")
|
|
114
|
+
for sub in DIRS:
|
|
115
|
+
(root / sub).mkdir(parents=True, exist_ok=True)
|
|
116
|
+
for name, text in ((MARKER, DEFAULT_CONFIG), (".gitignore", GITIGNORE)):
|
|
117
|
+
if not (root / name).exists():
|
|
118
|
+
(root / name).write_text(text, encoding="utf-8")
|
|
119
|
+
return load_workspace(root)
|