diff --git a/CLAUDE.md b/CLAUDE.md index e1f7ea5..85be826 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -114,6 +114,23 @@ Two independent apps that talk over HTTP: `backend/bench_grid_detect.py` scores it against any library's single-marker grids and reports that constant separately from detection error (29 Rekordbox references: old 1/29 BPMs, new 27/29). + Either half can be HELD — the Analyze dialog's BPM / Grid ticks: + `bpm=` keeps that tempo (no search, no round snap, no re-octave) and + finds only the phase; `anchor=` detects the tempo and returns the anchor + untouched, `drift_ms` then measuring how well the kept anchor fits. + `bench_grid_detect.py --hold bpm|anchor` scores each alone (2026-10-04, + 15 local refs: phase given the right BPM 15/15; tempo given the right + anchor 14/15, the same miss as full analysis). + - `grid_plan.py` — **what an analysis does to one track's grid**, as one + pure function (`plan_grid` → `GridStep`) so the batch, the dialog's + counts and the tests agree. BPM+Grid = full, an existing grid replaced + only with Replace ticked; BPM alone keeps the first marker's anchor; Grid + alone keeps its BPM (else the track's TEMPO). With ONE tick, Replace does + not apply (adjusting is the point) and a track with nothing to keep is + analysed in full; a flexible grid is skipped, never flattened; locked is + always skipped. `main._analyse_grid` writes each through the hand-edit + command for the same thing — `set_grid_marker_bpm(0)` / `move_grid_marker(0)` + — so companions, marker names and time bases behave as for a hand edit. - `key_detect.py` + `key_model.npz` — **musical key detection**: a small CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer over the WHOLE pitch axis, since a key is not pitch-invariant, logits @@ -1067,7 +1084,11 @@ serialization path.** It enforces: tempo and first beat are known rather than borrowed from another analyser: exact integer and non-integer BPMs, the 125 BPM the old detector could not return, octave choice, and the loud off-beat hat and syncopated bassline that - each fooled one band on real music. Accuracy on REAL music is + each fooled one band on real music. Holding either half: a held BPM comes + back untouched (never snapped or re-octaved, a wrong one reports drift) with + the phase still found through the hat/bass traps; a held anchor comes back + untouched with the tempo detected, an off-beat one reported as drift. And + `plan_grid`'s every rule. Accuracy on REAL music is `bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio). - `test_key_detect.py` — key detection on SYNTHETIC cadences in all 24 keys (I-IV-V-I / i-iv-V-i — a pop I-V-vi-IV is fairly called minor by an EDM @@ -1093,6 +1114,10 @@ serialization path.** It enforces: returns its result; opening another library cancels the run. Each shares its helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track button. + Also BPM alone / Grid alone through `_analyse_grid` on a real Traktor copy: + the detector is asked to hold the right half, BPM alone retempos the marker + in place with its beat-1 cue untouched, Grid alone moves it (cue dragged + along) at the same tempo, and a TEMPO-only track gets one marker at it. - `test_bulk_remove.py` — the context menu's **Remove ▸** routes (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): locked grids are kept, clearing hotcues empties the whole bank (loops and the diff --git a/backend/bench_grid_detect.py b/backend/bench_grid_detect.py index aa8f4a6..73a71e7 100644 --- a/backend/bench_grid_detect.py +++ b/backend/bench_grid_detect.py @@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved. python bench_grid_detect.py # the local Rekordbox library python bench_grid_detect.py path/to/collection.nml path/to/master.db python bench_grid_detect.py --legacy # score the old librosa beat_track + python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM + python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor The reference is each track's own grid, and only single-marker grids are used: a multi-marker grid is either a real tempo change (which a constant-tempo @@ -102,6 +104,9 @@ def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("libraries", nargs="*", type=Path) ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector") + ap.add_argument("--hold", choices=("bpm", "anchor"), + help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's " + "'Grid' tick — phase is all that is scored) or its anchor ('BPM')") args = ap.parse_args() libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"] @@ -119,7 +124,8 @@ def main() -> int: for name, audio, r0, rb in refs: t0 = time.perf_counter() try: - res = detect(str(audio)) + hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {}) + res = detect(str(audio), **hold) except Exception as ex: # a failure is a data point, not a crash print(f" FAIL {name[:48]:48} {ex}") rows.append(None) diff --git a/backend/konduktor/core/grid_detect.py b/backend/konduktor/core/grid_detect.py index 040e973..7c852f7 100644 --- a/backend/konduktor/core/grid_detect.py +++ b/backend/konduktor/core/grid_detect.py @@ -213,12 +213,27 @@ def detect_grid( *, y: np.ndarray | None = None, sr: int = _SR, + bpm: float | None = None, + anchor: float | None = None, ) -> GridResult: """Detect a track's constant tempo and first beat. ``y``/``sr`` let a caller (or a test) pass decoded mono audio directly. Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot). + + Either half can be held fixed — the Analyze dialog's BPM and Grid ticks: + - ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no + round-BPM snap — and only where its beats fall is found. For a BPM the + user trusts (typed, or a store's) and a grid that sits off the beat. + - ``anchor`` given ("BPM" alone): the tempo is detected and the anchor + returned as given, so the grid's downbeat stays where the user put it. + ``drift_ms`` is then measured against THAT anchor: large means the kept + anchor does not sit on the detected beat. """ + if bpm is not None and anchor is not None: + raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect") + if bpm is not None and not (20.0 <= bpm <= 400.0): + raise ValueError(f"Not a usable BPM: {bpm}") if y is None: import librosa y, sr = librosa.load(audio_path, sr=sr, mono=True) @@ -227,10 +242,42 @@ def detect_grid( if duration < 1.5: raise ValueError("Track is too short to detect a tempo") - lo, hi = bpm_range low = _onset(_band_env(y, sr, 30.0, 150.0)) - mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3)) attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3)) + + if bpm is not None: + period = 60.0 / bpm + if not np.isfinite(attack).all() or attack.max() <= 0: + raise ValueError("No onsets found") + phase = _phase(low, attack, period) + return GridResult( + bpm=float(bpm), + anchor=round(_first_beat(low + attack, phase, period), 4), + duration=duration, + drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1), + ) + + found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration) + period = 60.0 / found_bpm + if anchor is not None: + return GridResult( + bpm=round(found_bpm, 4), + anchor=float(anchor), + duration=duration, + drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1), + ) + return GridResult( + bpm=round(found_bpm, 4), + anchor=round(_first_beat(low + attack, phase, period), 4), + duration=duration, + drift_ms=round(drift * 1000.0, 1), + ) + + +def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]: + """(bpm, phase, drift) — the tempo search, octave rule and round snap.""" + lo, hi = bpm_range + mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3)) full = _onset(_band_env(y, sr, None, None, smooth_ms=3)) o_tempo = low + mid + 0.5 * full if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0: @@ -260,15 +307,7 @@ def detect_grid( bpm, _ = _refine(o_t, bpm, 0.02, 0.001) phase = _phase(low, attack, 60.0 / bpm) drift = _drift(attack, bpm, phase) - bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration) - - period = 60.0 / bpm - return GridResult( - bpm=round(bpm, 4), - anchor=round(_first_beat(low + attack, phase, period), 4), - duration=duration, - drift_ms=round(drift * 1000.0, 1), - ) + return _snap_round(low, attack, bpm, phase, drift, duration) def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]: diff --git a/backend/konduktor/core/grid_plan.py b/backend/konduktor/core/grid_plan.py new file mode 100644 index 0000000..16951af --- /dev/null +++ b/backend/konduktor/core/grid_plan.py @@ -0,0 +1,63 @@ +"""What an analysis does to one track's grid, given the BPM / Grid ticks. + +One pure function, so the batch, the dialog's counts and the tests cannot come +to mean different things. Decided with the user (2026-10-04, see +`.claude/discussions/discuss-key-analysis-2026-10-04.md`): + + - BPM + Grid: a full analysis. A track that already has a grid is replaced + only when the user ticked "Replace" — a grid may hold hand edits. + - BPM alone: re-detect the tempo, KEEP the anchor (the first marker). + - Grid alone: KEEP the BPM, find only where the beats fall. + - With one tick, adjusting the existing grid is the point, so "Replace" does + not apply; a track with nothing to keep (no grid / no BPM) is analysed in + full rather than skipped — one tick never leaves a track worse off. + - A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its + tempo changes are exactly what one constant tempo would flatten. + - A locked grid is skipped whatever is ticked. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal, Sequence + +Action = Literal["none", "full", "bpm", "phase", "skip"] +SkipReason = Literal["locked", "existing", "flexible"] + + +@dataclass(frozen=True) +class GridStep: + action: Action + reason: SkipReason | None = None + hold_bpm: float | None = None # "phase": the tempo kept + hold_anchor: float | None = None # "bpm": the anchor kept (seconds) + + +def plan_grid( + *, + bpm: bool, + grid: bool, + markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order + track_bpm: float | None, + locked: bool, + replace_existing: bool, +) -> GridStep: + if not (bpm or grid): + return GridStep("none") + if locked: + return GridStep("skip", "locked") + ordered = sorted(markers, key=lambda m: m.start) + if bpm and grid: + if ordered and not replace_existing: + return GridStep("skip", "existing") + return GridStep("full") + if len(ordered) > 1: + return GridStep("skip", "flexible") + if bpm: # BPM alone + if not ordered: + return GridStep("full") + return GridStep("bpm", hold_anchor=float(ordered[0].start)) + # Grid alone + held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None) + if not held or held <= 0: + return GridStep("full") + return GridStep("phase", hold_bpm=held) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index c2ff9a1..b0b9662 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -18,6 +18,7 @@ from . import __version__, exporter, exports, history, prefs from .app_state import STATE from .core import auto_hotcues as ah from .core import grid_detect, structure +from .core.grid_plan import GridStep from . import importer from .core import export as core_export from .core import places, registry @@ -1285,16 +1286,44 @@ def _submit_batch(kind: str, run) -> "Job": raise HTTPException(409, "A batch analysis is already running") -def _analyse_grid(a, track_id: str) -> TrackCues: +def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *, + y=None, sr: int | None = None) -> TrackCues: """Detect and write one track's grid — shared by the deck's Analyze and the - batch job, so the two cannot come to mean different things.""" - path = a.audio_path(track_id) - if path is None or not path.exists(): - raise _AnalysisError("Audio file not found (is the drive mounted?)") + batch job, so the two cannot come to mean different things. + + `step` is `core/grid_plan`'s decision. Each kind is written through the + command a hand edit of the same thing uses, so it inherits that command's + handling (Traktor's beat-1 companion cue, the time base, the BPM column): + - "full": `set_analysed_grid` — one marker, written as the platform's + own analyser would (on Traktor also hotcue 1 on the first beat); + - "bpm": `set_grid_marker_bpm` on the first marker — the anchor, the + marker's name and its companion stay exactly where they are; + - "phase": `move_grid_marker` on the first marker (dragging its + companion), or a fresh marker at the kept BPM when there was + only a TEMPO and no grid. + `y`/`sr` let a caller that already decoded the file share it.""" + if step.action in ("none", "skip"): + raise ValueError(f"nothing to write for a {step.action!r} step") + if y is None: + path = a.audio_path(track_id) + if path is None or not path.exists(): + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: - found = grid_detect.detect_grid(str(path)) + kw = {"y": y, "sr": sr} if y is not None else {} + found = grid_detect.detect_grid( + "" if y is not None else str(path), + bpm=step.hold_bpm if step.action == "phase" else None, + anchor=step.hold_anchor if step.action == "bpm" else None, + **kw, + ) except Exception as ex: # analysis is best-effort; never 500 the UI raise _AnalysisError(f"Analysis failed: {ex}") from ex + if step.action == "bpm": + return a.set_grid_marker_bpm(track_id, 0, found.bpm) + if step.action == "phase": + cues = a.track_cues(track_id) + if cues is not None and cues.grid_markers: + return a.move_grid_marker(track_id, 0, found.anchor) # "Analysed", not "replace": each platform writes an analysis result in its # own shape (Traktor pairs the first marker with a beat-1 cue). return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py index f7ccee5..8e6744a 100644 --- a/backend/test_grid_batch.py +++ b/backend/test_grid_batch.py @@ -239,6 +239,63 @@ with tempfile.TemporaryDirectory() as d: jid = main.JOBS.submit("unit-probe", lambda h: h.progress(done=1, total=2, unit="bytes")).id check("a job's unit reaches the client", wait(c, jid).get("unit") == "bytes") +print("== BPM alone / Grid alone write through the hand-edit commands ==") +with tempfile.TemporaryDirectory() as d: + from konduktor.adapters.traktor.adapter import TraktorAdapter + from konduktor.core.grid_plan import GridStep + + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + a = TraktorAdapter(work) + a.audio_path = lambda tid: Path(__file__) + asked: list[dict] = [] + + def fake_detect(path, *args, **k): + asked.append({key: k.get(key) for key in ("bpm", "anchor")}) + return SimpleNamespace(anchor=k.get("anchor") or 0.777, bpm=k.get("bpm") or 131.0) + + main.grid_detect.detect_grid = fake_detect + + def single_with_companion(): + for t in a.tracks: + cues = a.track_cues(t.id) + if t.grid_locked or not cues or len(cues.grid_markers) != 1: + continue + m = cues.grid_markers[0] + comp = [c for c in cues.cues if c.slot is not None and abs(c.start - m.start) < 0.002] + if comp: + yield t.id, m, comp[0] + + picks = single_with_companion() + tid, m, comp = next(picks) + out = main._analyse_grid(a, tid, GridStep("bpm", hold_anchor=m.start)) + g = out.grid_markers + check("BPM alone asks the detector to hold the anchor", asked[-1] == {"bpm": None, "anchor": m.start}, str(asked[-1])) + check("…and retempos the marker in place", + len(g) == 1 and abs(g[0].bpm - 131.0) < 1e-6 and abs(g[0].start - m.start) < 1e-6, str(g)) + check("…leaving its beat-1 cue where it was", + any(c.slot == comp.slot and abs(c.start - comp.start) < 1e-6 for c in out.cues)) + check("the track's BPM follows", abs(a.track(tid).bpm - 131.0) < 0.01, str(a.track(tid).bpm)) + + tid, m, comp = next(picks) + out = main._analyse_grid(a, tid, GridStep("phase", hold_bpm=m.bpm)) + g = out.grid_markers + check("Grid alone asks the detector to hold the BPM", asked[-1] == {"bpm": m.bpm, "anchor": None}, str(asked[-1])) + check("…and moves the marker, keeping its tempo", + len(g) == 1 and abs(g[0].start - 0.777) < 0.002 and abs(g[0].bpm - m.bpm) < 1e-6, str(g)) + check("…dragging its beat-1 cue along", + any(c.slot == comp.slot and abs(c.start - 0.777) < 0.002 for c in out.cues)) + + bare = next(t for t in a.tracks if t.grid_marker_count == 0 and not t.grid_locked) + out = main._analyse_grid(a, bare.id, GridStep("phase", hold_bpm=128.0)) + check("Grid alone with a BPM but no grid creates one marker at that BPM", + [(round(x.start, 3), x.bpm) for x in out.grid_markers] == [(0.777, 128.0)], str(out.grid_markers)) + try: + main._analyse_grid(a, bare.id, GridStep("skip", "locked")) + check("a skip step is never written", False) + except ValueError: + check("a skip step is never written", True) + print() print("FAILED" if failed else "RESULT: ALL PASSED") raise SystemExit(1 if failed else 0) diff --git a/backend/test_grid_detect.py b/backend/test_grid_detect.py index 36c6db4..d50f355 100644 --- a/backend/test_grid_detect.py +++ b/backend/test_grid_detect.py @@ -136,6 +136,38 @@ print("== a wandering tempo is reported, not hidden ==") r = detect(track(124, tempo_b=124.15)) check("drift is reported when one grid cannot fit", r.drift_ms is not None and r.drift_ms >= 12, f"{r.drift_ms}") +print("== Grid alone: the BPM is held, only the phase is found ==") +r = detect(track(124, first=0.3), bpm=124.0) +check("the given BPM comes back untouched", r.bpm == 124.0, f"got {r.bpm}") +check("the anchor is found on the first kick (±3 ms)", abs(r.anchor - 0.3) <= 0.003, f"got {r.anchor}") +r = detect(track(123.37, first=0.2), bpm=123.37) +check("a non-round held BPM is not snapped to 123", r.bpm == 123.37, f"got {r.bpm}") +check("…and its grid is on the beat at the end (±5 ms)", abs(beat_error_ms(r, 123.37, 0.2, 175)) <= 5) +r = detect(track(124, first=0.4, hat=1.5, bass=1.2), bpm=124.0) +check("the phase traps still hold with a held BPM", + abs(beat_error_ms(r, 124, 0.4, 60)) <= 3, f"{beat_error_ms(r, 124, 0.4, 60):+.1f} ms") +r = detect(track(87, first=0.3), bpm=174.0) +check("a held double-time BPM is kept (the octave is the user's call)", + r.bpm == 174.0 and abs(beat_error_ms(r, 87, 0.3, 60)) <= 3, f"{r.bpm} {beat_error_ms(r, 87, 0.3, 60):+.1f}") +r = detect(track(124, first=0.3), bpm=124.2) +check("a WRONG held BPM is kept, and its drift reported", r.bpm == 124.2 and r.drift_ms >= 20, f"{r.drift_ms}") + +print("== BPM alone: the tempo is found, the anchor is held ==") +r = detect(track(125, first=0.3), anchor=0.3 + 2 * 60 / 125) # a downbeat two beats in +check("the tempo is detected", r.bpm == 125.0, f"got {r.bpm}") +check("the given anchor comes back untouched", r.anchor == 0.3 + 2 * 60 / 125, f"got {r.anchor}") +check("an anchor on the beat reports little drift", r.drift_ms <= 5, f"{r.drift_ms}") +r = detect(track(125, first=0.3), anchor=0.33) +check("an anchor 30 ms off the beat is kept, and the drift says so", + r.anchor == 0.33 and 25 <= r.drift_ms <= 35, f"{r.anchor} {r.drift_ms}") + +print("== holding both is refused ==") +try: + detect(track(124), bpm=124.0, anchor=0.3) + check("bpm + anchor raises ValueError", False) +except ValueError: + check("bpm + anchor raises ValueError", True) + print("== nothing to fit ==") for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", np.zeros(SR, dtype=np.float32))): try: @@ -144,6 +176,39 @@ for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", except ValueError: check(f"{label} raises ValueError", True) +print("== the BPM / Grid plan (core/grid_plan) ==") +from types import SimpleNamespace as M # noqa: E402 + +from konduktor.core.grid_plan import plan_grid # noqa: E402 + +one = [M(start=0.5, bpm=124.0)] +two = [M(start=60.0, bpm=126.0), M(start=0.5, bpm=124.0)] # unsorted on purpose + + +def plan(bpm, grid, markers=(), track_bpm=None, locked=False, replace=False): + return plan_grid(bpm=bpm, grid=grid, markers=list(markers), track_bpm=track_bpm, + locked=locked, replace_existing=replace) + + +check("nothing ticked does nothing", plan(False, False, one).action == "none") +check("locked is skipped whatever is ticked", + all(plan(b, g, one, locked=True).reason == "locked" for b, g in ((1, 1), (1, 0), (0, 1)))) +check("BPM+Grid on an ungridded track: full", plan(True, True).action == "full") +check("BPM+Grid on a gridded track, no Replace: skipped as existing", + plan(True, True, one).reason == "existing") +check("BPM+Grid with Replace replaces even a flexible grid", plan(True, True, two, replace=True).action == "full") +s_ = plan(True, False, one) +check("BPM alone keeps the anchor", s_.action == "bpm" and s_.hold_anchor == 0.5) +check("BPM alone ignores Replace (adjusting IS the point)", plan(True, False, one, replace=False).action == "bpm") +check("BPM alone, no grid: analysed in full", plan(True, False, track_bpm=124).action == "full") +s_ = plan(False, True, one, track_bpm=999) +check("Grid alone keeps the MARKER's BPM", s_.action == "phase" and s_.hold_bpm == 124.0) +s_ = plan(False, True, track_bpm=128.0) +check("Grid alone, no grid but a BPM: keeps that BPM", s_.action == "phase" and s_.hold_bpm == 128.0) +check("Grid alone, no BPM at all: analysed in full", plan(False, True).action == "full") +check("one tick on a flexible grid: skipped, never flattened", + plan(True, False, two).reason == "flexible" and plan(False, True, two).reason == "flexible") + print() print("FAILED" if failed else "OK") raise SystemExit(1 if failed else 0)