mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Improved auto hot cue system
This commit is contained in:
1 parent
6cc73267a6
commit
46ce3db916
12 files changed
+1199
-312
No files matched your search
@@ -46,7 +46,36 @@ Two independent apps that talk over HTTP:
|
|||||||
when a path remap changes track ids. Recording `before` keeps undo cheap later.
|
when a path remap changes track ids. Recording `before` keeps undo cheap later.
|
||||||
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
|
- `registry.py` — adapter selection by **`can_open()` probe**, not extension
|
||||||
(Rekordbox is a `.db`, Serato is a directory).
|
(Rekordbox is a `.db`, Serato is a directory).
|
||||||
- `audio_tags.py`, `pathmap.py`, `auto_hotcues.py` — format-agnostic helpers.
|
- `audio_tags.py`, `pathmap.py` — format-agnostic helpers.
|
||||||
|
- `structure.py` + `auto_hotcues.py` — **Auto Hotcues** (the deck's ✨ Auto
|
||||||
|
button → `AutoCueDialog` → `POST /api/tracks/cue/auto`). The user binds each
|
||||||
|
slot to an EVENT (`first_beat`, `intro_end`, `build_n`, `drop_n`,
|
||||||
|
`breakdown_n` for n ≤ 3, `outro`, `last_beat`) plus an offset in BEATS;
|
||||||
|
`structure.analyse` finds the events, `auto_hotcues.plan` resolves the
|
||||||
|
template and reports an outcome per slot (`placed` / `not_found` /
|
||||||
|
`out_of_range` / `occupied` / `protected`) — "this track has no third drop"
|
||||||
|
is an answer, not a silent gap. How it finds them:
|
||||||
|
- **Everything is per bar ON THE TRACK'S GRID**, bar 1 = the first marker
|
||||||
|
(Traktor's convention). Bar-1 detection from audio was tried: it never
|
||||||
|
beat that rule, because DJ tracks start on a downbeat.
|
||||||
|
- Per-bar kick / bass / loudness / brightness + MFCC, then an **exact DP
|
||||||
|
segmentation whose boundary price depends on bar position** (cheap on
|
||||||
|
×8, dearer on ×4, very dear elsewhere) — the phrase bias lives in the
|
||||||
|
objective, not in a snap afterwards.
|
||||||
|
- **A drop is a high section entered from a low one**, not a loud one: a
|
||||||
|
house intro is often as loud as its drop. A breakdown is where a drop
|
||||||
|
ends when another drop follows; the end of the last one is the outro's.
|
||||||
|
- Kick is the grid detector's sharp low-band onset, NOT on- vs off-beat
|
||||||
|
energy (a house bassline lives on the off-beat), and "high" does not
|
||||||
|
require a kick (drum & bass has none on every beat).
|
||||||
|
Measured against the phrase analysis Rekordbox stores for 12 local
|
||||||
|
"High"-mood tracks (PSSI; the previous detector's cues scored below a cue
|
||||||
|
every 16 bars): drops 81% on the exact bar (22/27), breakdowns 80%
|
||||||
|
(12/15), outro 42% within 4 bars — `backend/bench_structure.py` reruns
|
||||||
|
it. Rekordbox's own "Up" spans the whole pre-drop groove where a DJ's
|
||||||
|
build is the last 8–16 bars, so build scores against it are not
|
||||||
|
meaningful. Halftime tracks inherit the grid's octave: at 174 a "bar" is
|
||||||
|
half a musical bar.
|
||||||
- `grid_detect.py` — **beatgrid detection** (the deck's Analyze button,
|
- `grid_detect.py` — **beatgrid detection** (the deck's Analyze button,
|
||||||
`POST /api/tracks/grid/auto`). Fits ONE constant tempo + anchor to the whole
|
`POST /api/tracks/grid/auto`). Fits ONE constant tempo + anchor to the whole
|
||||||
track rather than tracking beats: `librosa.beat.beat_track`, which it
|
track rather than tracking beats: `librosa.beat.beat_track`, which it
|
||||||
@@ -313,6 +342,10 @@ Two independent apps that talk over HTTP:
|
|||||||
array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each
|
array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each
|
||||||
render with no `onSortingChange` makes TanStack Table re-sync its internal
|
render with no `onSortingChange` makes TanStack Table re-sync its internal
|
||||||
state every commit → infinite re-render loop. Keep that reference stable.
|
state every commit → infinite re-render loop. Keep that reference stable.
|
||||||
|
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
|
||||||
|
slot, a per-slot Replace tick for occupied slots — never remembered, since
|
||||||
|
overwriting is a decision about THIS track — and the template itself
|
||||||
|
persisted as `autoCueTemplate` in userprefs),
|
||||||
`SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog`
|
`SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog`
|
||||||
(right-click → multi-field metadata + album-art edit), `StatusBar`,
|
(right-click → multi-field metadata + album-art edit), `StatusBar`,
|
||||||
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
|
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
|
||||||
@@ -436,6 +469,12 @@ serialization path.** It enforces:
|
|||||||
return, octave choice, and the loud off-beat hat and syncopated bassline that
|
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. Accuracy on REAL music is
|
||||||
`bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio).
|
`bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio).
|
||||||
|
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
||||||
|
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
||||||
|
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
||||||
|
(across a tempo change), and the ROUTE end to end on a temp copy of the real
|
||||||
|
collection — the previous implementation's route returned 500 on every call
|
||||||
|
for a week while its helper's tests passed.
|
||||||
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
|
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
|
||||||
replaced was invisible: `/api/library/options` flattened every driver's
|
replaced was invisible: `/api/library/options` flattened every driver's
|
||||||
detections and returned `[0]`, so a plugged-in USB stick could be offered as
|
detections and returned `[0]`, so a plugged-in USB stick could be offered as
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Benchmark Auto Hotcues' structure events against Rekordbox's phrase analysis.
|
||||||
|
|
||||||
|
NOT part of `run_tests.sh`: it needs real audio and a Rekordbox library whose
|
||||||
|
tracks were analysed with phrase analysis on (the `PSSI` tag in each `.EXT`).
|
||||||
|
Read-only — nothing is saved.
|
||||||
|
|
||||||
|
python bench_structure.py # the local Rekordbox library
|
||||||
|
python bench_structure.py -v # per-track events, detected vs reference
|
||||||
|
|
||||||
|
The reference is Rekordbox's own analysis, not ground truth, and it is only
|
||||||
|
comparable on "High"-mood tracks, whose labels map onto what a DJ cues:
|
||||||
|
Intro / Up (build) / Down (breakdown) / Chorus (drop) / Outro. "Mid" tracks are
|
||||||
|
labelled Verse / Chorus / Bridge and are reported separately for that reason.
|
||||||
|
Tracks whose detected BPM is a different octave from Rekordbox's are skipped:
|
||||||
|
their bars are not the same bars.
|
||||||
|
|
||||||
|
Events are compared in bars from each side's own first downbeat:
|
||||||
|
- drop_n = start of the n-th Chorus run;
|
||||||
|
- breakdown_n = end of the n-th drop, when another drop follows;
|
||||||
|
- build_n = the Up run right before drop_n (Rekordbox's Up usually spans the
|
||||||
|
whole pre-drop groove, so this one is indicative at best);
|
||||||
|
- outro = start of the Outro.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
os.environ.setdefault("KONDUKTOR_DATA_DIR", tempfile.mkdtemp(prefix="konduktor-bench-"))
|
||||||
|
|
||||||
|
import konduktor.adapters # noqa: E402,F401 — registers the drivers
|
||||||
|
from konduktor.core import grid_detect, registry, structure # noqa: E402
|
||||||
|
|
||||||
|
DROP = {1: 5, 2: 9} # PSSI kind of a Chorus, by mood (1 = High, 2 = Mid)
|
||||||
|
OUTRO = {1: 6, 2: 10}
|
||||||
|
UP = {1: 2}
|
||||||
|
|
||||||
|
|
||||||
|
def references(db: Path) -> list[dict]:
|
||||||
|
from pyrekordbox.anlz import AnlzFile
|
||||||
|
|
||||||
|
a = registry.open_library(db)
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
st = a._store
|
||||||
|
for t in a.tracks:
|
||||||
|
path = a.audio_path(t.id)
|
||||||
|
rel = getattr(st.content(t.id), "AnalysisDataPath", None)
|
||||||
|
if not path or not path.exists() or not rel:
|
||||||
|
continue
|
||||||
|
base = st.path.parent / "share" / str(rel).lstrip("/\\")
|
||||||
|
ext = base.with_suffix(".EXT")
|
||||||
|
if not (base.is_file() and ext.is_file()):
|
||||||
|
continue
|
||||||
|
rec = {"path": str(path), "title": t.title or path.stem}
|
||||||
|
for tag in AnlzFile.parse_file(str(base)).tags:
|
||||||
|
if tag.type == "PQTZ" and len(tag.content.entries): # one-shots have none
|
||||||
|
e = tag.content.entries
|
||||||
|
rec["bpm"] = e[0].tempo / 100
|
||||||
|
rec["first_down"] = next(i for i, x in enumerate(e) if x.beat == 1)
|
||||||
|
for tag in AnlzFile.parse_file(str(ext)).tags:
|
||||||
|
if tag.type == "PSSI":
|
||||||
|
rec["mood"] = tag.content.mood
|
||||||
|
rec["phrases"] = [(x.beat, x.kind) for x in tag.content.entries]
|
||||||
|
if "phrases" in rec and "bpm" in rec:
|
||||||
|
out.append(rec)
|
||||||
|
finally:
|
||||||
|
a.close()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def truth(rec: dict) -> dict[str, int]:
|
||||||
|
runs: list[tuple[int, int]] = []
|
||||||
|
for beat, kind in rec["phrases"]:
|
||||||
|
bar = round((beat - 1 - rec["first_down"]) / 4)
|
||||||
|
if not runs or runs[-1][1] != kind:
|
||||||
|
runs.append((bar, kind))
|
||||||
|
m, ev = rec["mood"], {}
|
||||||
|
drops = [i for i, (_, k) in enumerate(runs) if k == DROP.get(m)]
|
||||||
|
for n, i in enumerate(drops, start=1):
|
||||||
|
ev[f"drop_{n}"] = runs[i][0]
|
||||||
|
if n < len(drops) and i + 1 < len(runs):
|
||||||
|
ev[f"breakdown_{n}"] = runs[i + 1][0]
|
||||||
|
if m in UP and i > 0 and runs[i - 1][1] == UP[m]:
|
||||||
|
ev[f"build_{n}"] = runs[i - 1][0]
|
||||||
|
outro = [b for b, k in runs if k == OUTRO.get(m)]
|
||||||
|
if outro:
|
||||||
|
ev["outro"] = outro[0]
|
||||||
|
return ev
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
verbose = "-v" in sys.argv
|
||||||
|
args = [a for a in sys.argv[1:] if not a.startswith("-")]
|
||||||
|
db = Path(args[0]) if args else Path.home() / "Library/Pioneer/rekordbox/master.db"
|
||||||
|
refs = references(db)
|
||||||
|
if not refs:
|
||||||
|
print("No tracks with Rekordbox phrase analysis and reachable audio.")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
for mood, label in ((1, "High"), (2, "Mid")):
|
||||||
|
stats: dict[str, list[int]] = {}
|
||||||
|
for rec in (r for r in refs if r["mood"] == mood):
|
||||||
|
g = grid_detect.detect_grid(rec["path"])
|
||||||
|
if abs(g.bpm - rec["bpm"]) >= 1:
|
||||||
|
continue # a different octave: not the same bars
|
||||||
|
st = structure.analyse(rec["path"], [(g.anchor, g.bpm)])
|
||||||
|
det = {k: (v - st.bar0) // 4 for k, v in st.events.items()}
|
||||||
|
tru = truth(rec)
|
||||||
|
if verbose:
|
||||||
|
print(f" {rec['title'][:28]:28} ref {tru}\n {'':28} got { {k: det[k] for k in tru if k in det} }")
|
||||||
|
for e, bar in tru.items():
|
||||||
|
key = e if e in ("drop_1", "drop_2", "breakdown_1", "build_1", "build_2", "outro") else e.split("_")[0] + "_n"
|
||||||
|
s = stats.setdefault(key, [0, 0, 0])
|
||||||
|
s[0] += 1
|
||||||
|
if e in det:
|
||||||
|
s[1] += det[e] == bar
|
||||||
|
s[2] += abs(det[e] - bar) <= 4
|
||||||
|
if not stats:
|
||||||
|
continue
|
||||||
|
print(f"== {label}-mood tracks")
|
||||||
|
for k in sorted(stats):
|
||||||
|
n, exact, near = stats[k]
|
||||||
|
print(f" {k:12} n={n:2} exact bar {exact:2} ({exact / n:4.0%}) within 4 bars {near:2} ({near / n:4.0%})")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -1,218 +1,98 @@
|
|||||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
"""Auto Hotcues: resolve a slot template against a track's structure.
|
||||||
|
|
||||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
The user binds each hotcue slot to an EVENT ("first drop", "start of the second
|
||||||
implemented on top of librosa: beat-synchronous CQT features → a
|
breakdown", …) plus an offset in beats ("16 beats before the first drop"). The
|
||||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
events come from `core/structure.py`; this module is the pure part — which
|
||||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
slots get a cue, where, called what, and why a slot got nothing — so it is
|
||||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
testable without audio.
|
||||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
|
||||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
|
||||||
|
|
||||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
Offsets are counted along the grid's own beats, not in seconds, so a -16 on a
|
||||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
flexible grid lands 16 BEATS earlier even across a tempo change.
|
||||||
beatgrid) — the latter is unit-testable without audio.
|
|
||||||
|
Each slot reports an outcome rather than silently dropping, because a template
|
||||||
|
names specific events and "no second drop in this track" is an answer the user
|
||||||
|
needs, not a cue that quietly failed to appear.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import numpy as np
|
from dataclasses import dataclass
|
||||||
|
|
||||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
from .structure import EVENTS, Structure
|
||||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
|
||||||
MAX_HOTCUES = 8
|
|
||||||
|
|
||||||
_SR = 22050
|
LABELS: dict[str, str] = {
|
||||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
"first_beat": "First Beat",
|
||||||
|
"intro_end": "Intro End",
|
||||||
|
"build_1": "Build 1",
|
||||||
|
"drop_1": "Drop 1",
|
||||||
|
"breakdown_1": "Breakdown 1",
|
||||||
|
"build_2": "Build 2",
|
||||||
|
"drop_2": "Drop 2",
|
||||||
|
"breakdown_2": "Breakdown 2",
|
||||||
|
"build_3": "Build 3",
|
||||||
|
"drop_3": "Drop 3",
|
||||||
|
"breakdown_3": "Breakdown 3",
|
||||||
|
"outro": "Outro",
|
||||||
|
"last_beat": "Last Beat",
|
||||||
|
}
|
||||||
|
assert set(LABELS) == set(EVENTS)
|
||||||
|
|
||||||
|
# Outcomes a slot can report.
|
||||||
|
PLACED = "placed"
|
||||||
|
NOT_FOUND = "not_found" # the track has no such event (e.g. no third drop)
|
||||||
|
OUT_OF_RANGE = "out_of_range" # the offset moves it before the start / past the end
|
||||||
|
OCCUPIED = "occupied" # the slot holds a cue and overwrite was not asked for
|
||||||
|
PROTECTED = "protected" # the slot holds a cue the adapter will not replace
|
||||||
|
|
||||||
|
|
||||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
@dataclass(frozen=True)
|
||||||
"""Detect structural boundaries in a track.
|
class SlotRequest:
|
||||||
|
slot: int
|
||||||
|
event: str
|
||||||
|
offset_beats: int = 0
|
||||||
|
overwrite: bool = False
|
||||||
|
|
||||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
|
||||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
@dataclass(frozen=True)
|
||||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
class SlotOutcome:
|
||||||
(used downstream for positional naming). Sorted by time.
|
slot: int
|
||||||
|
event: str
|
||||||
|
status: str
|
||||||
|
start: float | None = None
|
||||||
|
name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def cue_name(event: str, offset_beats: int) -> str:
|
||||||
|
"""The label a placed cue carries, e.g. ``Drop 1`` or ``Drop 1 -16``."""
|
||||||
|
label = LABELS[event]
|
||||||
|
return f"{label} {offset_beats:+d}" if offset_beats else label
|
||||||
|
|
||||||
|
|
||||||
|
def plan(
|
||||||
|
structure: Structure,
|
||||||
|
requests: list[SlotRequest],
|
||||||
|
existing: dict[int, bool],
|
||||||
|
) -> list[SlotOutcome]:
|
||||||
|
"""Decide every requested slot.
|
||||||
|
|
||||||
|
``existing`` maps each occupied slot to whether its cue is EDITABLE — a
|
||||||
|
non-editable one (a Traktor grid marker's companion) is never replaced, even
|
||||||
|
when overwrite is ticked, because the adapter would refuse it anyway.
|
||||||
"""
|
"""
|
||||||
import librosa
|
out: list[SlotOutcome] = []
|
||||||
from scipy.ndimage import median_filter
|
for r in requests:
|
||||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
if r.slot in existing and not existing[r.slot]:
|
||||||
from scipy.linalg import eigh
|
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
|
||||||
import sklearn.cluster
|
continue
|
||||||
|
if r.slot in existing and not r.overwrite:
|
||||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
out.append(SlotOutcome(r.slot, r.event, OCCUPIED))
|
||||||
duration = len(y) / sr
|
continue
|
||||||
if duration < 1.0:
|
beat = structure.events.get(r.event)
|
||||||
return [], duration
|
if beat is None:
|
||||||
|
out.append(SlotOutcome(r.slot, r.event, NOT_FOUND))
|
||||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
continue
|
||||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
t = structure.beat_time(beat + r.offset_beats)
|
||||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
if t < 0 or t >= structure.duration:
|
||||||
if len(beats) < 4:
|
out.append(SlotOutcome(r.slot, r.event, OUT_OF_RANGE))
|
||||||
return [], duration
|
continue
|
||||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
out.append(SlotOutcome(r.slot, r.event, PLACED, round(t, 4), cue_name(r.event, r.offset_beats)))
|
||||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
|
||||||
|
|
||||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
|
||||||
# a repetition graph (which beats sound alike) blended with a local path
|
|
||||||
# graph (consecutive-beat timbral continuity).
|
|
||||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
|
||||||
rec = median_filter(rec, size=(1, 7))
|
|
||||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
|
||||||
msync = librosa.util.sync(mfcc, beats)
|
|
||||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
|
||||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
|
||||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
|
||||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
|
||||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
|
||||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
|
||||||
graph = mu * rec + (1 - mu) * path
|
|
||||||
|
|
||||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
|
||||||
lap = csgraph_laplacian(graph, normed=True)
|
|
||||||
_, evecs = eigh(lap)
|
|
||||||
evecs = median_filter(evecs, size=(9, 1))
|
|
||||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
|
||||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
|
||||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
|
||||||
|
|
||||||
# Boundaries = beats where the section-type label changes (plus the start).
|
|
||||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
|
||||||
|
|
||||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
|
||||||
rms = librosa.feature.rms(y=y)[0]
|
|
||||||
rms_t = librosa.times_like(rms, sr=sr)
|
|
||||||
rms_max = float(rms.max()) or 1.0
|
|
||||||
out: list[tuple[float, float]] = []
|
|
||||||
for j, bi in enumerate(bound_beats):
|
|
||||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
|
||||||
t_next = (
|
|
||||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
|
||||||
if j + 1 < len(bound_beats)
|
|
||||||
else duration
|
|
||||||
)
|
|
||||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
|
||||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
|
||||||
out.append((t, energy))
|
|
||||||
return out, duration
|
|
||||||
|
|
||||||
|
|
||||||
def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]:
|
|
||||||
"""The ``(start, bpm)`` of the beatgrid segment containing ``t``.
|
|
||||||
|
|
||||||
Times before the first marker use the first segment, extrapolated backwards
|
|
||||||
— the same convention the deck draws with.
|
|
||||||
"""
|
|
||||||
seg = markers[0]
|
|
||||||
for m in markers:
|
|
||||||
if m[0] <= t:
|
|
||||||
seg = m
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
return seg
|
|
||||||
|
|
||||||
|
|
||||||
def snap_to_phrase(
|
|
||||||
t: float, markers: list[tuple[float, float]], phrase_bars: int = 16
|
|
||||||
) -> float:
|
|
||||||
"""Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT.
|
|
||||||
|
|
||||||
Snapping is deliberately segment-local rather than a running phrase count
|
|
||||||
across the whole track: a flexible grid exists precisely because the tempo
|
|
||||||
drifted, so carrying a phrase count across a marker seam would propagate the
|
|
||||||
very error the marker was placed to correct. With a single marker this is
|
|
||||||
exactly the old ``anchor + round((t - anchor) / phrase) * phrase``.
|
|
||||||
"""
|
|
||||||
anchor, bpm = _segment_for(t, markers)
|
|
||||||
phrase = phrase_bars * 4 * (60.0 / bpm)
|
|
||||||
return anchor + round((t - anchor) / phrase) * phrase
|
|
||||||
|
|
||||||
|
|
||||||
def select_hotcues(
|
|
||||||
boundaries: list[tuple[float, float]],
|
|
||||||
*,
|
|
||||||
markers: list[tuple[float, float]],
|
|
||||||
duration: float,
|
|
||||||
free_slots: list[int],
|
|
||||||
existing_times: list[float],
|
|
||||||
max_cues: int = MAX_HOTCUES,
|
|
||||||
phrase_bars: int = 16,
|
|
||||||
) -> list[dict]:
|
|
||||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
|
||||||
|
|
||||||
``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start —
|
|
||||||
a constant-tempo track is simply a one-element list.
|
|
||||||
|
|
||||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own
|
|
||||||
tempo segment (which also merges near-duplicates), drops any coinciding with
|
|
||||||
an existing hotcue, caps to the free slots (down-sampling evenly if there
|
|
||||||
are too many), and assigns positional names. Returns dicts with
|
|
||||||
slot/start/name/type/length.
|
|
||||||
"""
|
|
||||||
if not boundaries or not free_slots or not markers or markers[0][1] <= 0:
|
|
||||||
return []
|
|
||||||
|
|
||||||
# Tolerance for "same place as an existing cue" and the end clamp. Marker
|
|
||||||
# BPMs differ by well under 1% in practice, so the first is representative.
|
|
||||||
beat = 60.0 / markers[0][1]
|
|
||||||
|
|
||||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
|
||||||
snapped: dict[float, float] = {}
|
|
||||||
for t, energy in boundaries:
|
|
||||||
p = snap_to_phrase(t, markers, phrase_bars)
|
|
||||||
p = max(0.0, min(p, duration - beat))
|
|
||||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
|
||||||
|
|
||||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
|
||||||
def near_existing(t: float) -> bool:
|
|
||||||
return any(abs(t - e) < beat for e in existing_times)
|
|
||||||
|
|
||||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
|
||||||
if not points:
|
|
||||||
return []
|
|
||||||
|
|
||||||
# If more candidates than free slots, down-sample evenly across the track
|
|
||||||
# (keeps intro..outro coverage rather than just the first N).
|
|
||||||
n = min(len(free_slots), max_cues)
|
|
||||||
if len(points) > n:
|
|
||||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
|
||||||
points = [points[i] for i in sorted(set(idx))]
|
|
||||||
|
|
||||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
|
||||||
slots = sorted(free_slots)[: len(points)]
|
|
||||||
return [
|
|
||||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
|
||||||
for slot, (t, _), name in zip(slots, points, names)
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
|
||||||
"""Positional-hint names from track position + energy trend (not true
|
|
||||||
structural classification — the names are hints; value is the position)."""
|
|
||||||
if not times:
|
|
||||||
return []
|
|
||||||
med = float(np.median(energies))
|
|
||||||
raw: list[str] = []
|
|
||||||
n = len(times)
|
|
||||||
for i, (t, e) in enumerate(zip(times, energies)):
|
|
||||||
frac = t / duration if duration else 0.0
|
|
||||||
prev = energies[i - 1] if i > 0 else e
|
|
||||||
if i == 0 or frac < 0.08:
|
|
||||||
name = "Intro"
|
|
||||||
elif i == n - 1 or frac > 0.85:
|
|
||||||
name = "Outro"
|
|
||||||
elif e - prev > 0.12 and e >= med:
|
|
||||||
name = "Drop"
|
|
||||||
elif prev - e > 0.12:
|
|
||||||
name = "Break"
|
|
||||||
elif e > prev:
|
|
||||||
name = "Build"
|
|
||||||
else:
|
|
||||||
name = "Mid"
|
|
||||||
raw.append(name)
|
|
||||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
|
||||||
counts: dict[str, int] = {}
|
|
||||||
out: list[str] = []
|
|
||||||
for name in raw:
|
|
||||||
counts[name] = counts.get(name, 0) + 1
|
|
||||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
|
||||||
return out
|
return out
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
"""Track structure on a KNOWN beatgrid: sections, and the events a DJ cues.
|
||||||
|
|
||||||
|
This is what Auto Hotcues resolves its slots against ("first drop", "start of
|
||||||
|
the second breakdown", …). It replaced a librosa Laplacian segmentation that
|
||||||
|
ran its own beat tracker and ignored the track's grid; against Rekordbox's
|
||||||
|
phrase analysis its cues scored WORSE than placing one every 16 bars.
|
||||||
|
|
||||||
|
Why it is built the way it is — each choice was measured against the phrase
|
||||||
|
analysis Rekordbox stores for 20 local tracks (PSSI; see the Auto Hotcues
|
||||||
|
section of CLAUDE.md for the numbers):
|
||||||
|
|
||||||
|
- **Everything is per BAR, on the track's own grid.** Bar 1 is the grid's first
|
||||||
|
marker (Traktor's convention: a marker is beat 1). Detecting the bar start
|
||||||
|
from audio was tried and never beat that rule — DJ tracks start on a
|
||||||
|
downbeat — so a wrong bar 1 is fixed by moving the marker, not second-guessed.
|
||||||
|
- **The features are the ones a DJ hears**: is the kick in, is the bass in,
|
||||||
|
how loud and bright is it — plus timbre (MFCC), for changes that keep the
|
||||||
|
level (a lead swapping out). Timbre-only novelty scored below this: the
|
||||||
|
sections that get cued are defined by energy, not by chord changes.
|
||||||
|
- **Sections are an optimal segmentation, and the boundary price depends on
|
||||||
|
where it falls**: cheap on a multiple of 8 bars, dearer on 4, very dear
|
||||||
|
anywhere else. That is the phrase bias, built into the objective rather than
|
||||||
|
applied as a snap afterwards — a snap can only move a boundary, never decide
|
||||||
|
that an off-phrase change was not worth a boundary at all.
|
||||||
|
- **A drop is a high section that follows a low one** — not merely a loud one.
|
||||||
|
A house intro is often as loud as its drop (the full groove, for mixing), and
|
||||||
|
what makes the drop is the breakdown before it.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
_SR = 22050
|
||||||
|
_FR = 100 # envelope frame rate for per-bar levels (Hz)
|
||||||
|
|
||||||
|
# Boundary cost multipliers by bar position (x the variance of ~4 bars).
|
||||||
|
_LAMBDA_8 = 0.2
|
||||||
|
_LAMBDA_4 = 1.0
|
||||||
|
_LAMBDA_OTHER = 12.0
|
||||||
|
_MIN_SECTION = 4 # bars
|
||||||
|
_HIGH_DB = 4.0 # a section within this of the track's loud parts is "high"
|
||||||
|
_TIMBRE_WEIGHT = 1.0
|
||||||
|
_OUTRO_BARS = 16 # the outro is looked for this far before the music ends
|
||||||
|
_BUILD_MAX = 16 # a longer low stretch is not all build: take its last 8 bars
|
||||||
|
|
||||||
|
# The events a slot can be bound to, in the order the dialog lists them.
|
||||||
|
EVENTS: tuple[str, ...] = (
|
||||||
|
"first_beat", "intro_end",
|
||||||
|
"build_1", "drop_1", "breakdown_1",
|
||||||
|
"build_2", "drop_2", "breakdown_2",
|
||||||
|
"build_3", "drop_3", "breakdown_3",
|
||||||
|
"outro", "last_beat",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Section:
|
||||||
|
start: int # bar index (0 = the grid's first marker)
|
||||||
|
end: int # exclusive
|
||||||
|
high: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Structure:
|
||||||
|
beats: np.ndarray # every grid beat time (s), including before the first marker
|
||||||
|
bar0: int # index into `beats` of bar 1's downbeat
|
||||||
|
n_bars: int
|
||||||
|
duration: float
|
||||||
|
sections: list[Section] = field(default_factory=list)
|
||||||
|
events: dict[str, int] = field(default_factory=dict) # event -> BEAT index
|
||||||
|
|
||||||
|
def beat_of_bar(self, bar: int) -> int:
|
||||||
|
return self.bar0 + 4 * bar
|
||||||
|
|
||||||
|
def beat_time(self, index: int) -> float:
|
||||||
|
"""Time of beat ``index``, extrapolated past either end at the local tempo."""
|
||||||
|
b = self.beats
|
||||||
|
if 0 <= index < len(b):
|
||||||
|
return float(b[index])
|
||||||
|
if index < 0:
|
||||||
|
step = b[1] - b[0] if len(b) > 1 else 0.5
|
||||||
|
return float(b[0] + index * step)
|
||||||
|
step = b[-1] - b[-2] if len(b) > 1 else 0.5
|
||||||
|
return float(b[-1] + (index - len(b) + 1) * step)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the grid -----------------------------------------------------------------
|
||||||
|
def grid_beats(markers: list[tuple[float, float]], duration: float) -> tuple[np.ndarray, int]:
|
||||||
|
"""Every beat of a (possibly flexible) grid, and the index of the first marker.
|
||||||
|
|
||||||
|
Each marker's tempo governs until the next marker, as the deck draws it;
|
||||||
|
beats before the first marker are extrapolated back to the track start.
|
||||||
|
"""
|
||||||
|
markers = sorted(markers)
|
||||||
|
start0, bpm0 = markers[0]
|
||||||
|
step0 = 60.0 / bpm0
|
||||||
|
before = np.arange(start0 - step0, -1e-9, -step0)[::-1]
|
||||||
|
beats = list(before)
|
||||||
|
bar0 = len(beats)
|
||||||
|
for i, (start, bpm) in enumerate(markers):
|
||||||
|
end = markers[i + 1][0] if i + 1 < len(markers) else duration
|
||||||
|
beats.extend(np.arange(start, end - 1e-6, 60.0 / bpm))
|
||||||
|
return np.asarray(beats, dtype=np.float64), bar0
|
||||||
|
|
||||||
|
|
||||||
|
# ---- per-bar features ----------------------------------------------------------
|
||||||
|
def _power_env(y: np.ndarray, lo: float | None, hi: float | None) -> np.ndarray:
|
||||||
|
from scipy.signal import butter, sosfiltfilt
|
||||||
|
|
||||||
|
if lo and hi:
|
||||||
|
sos = butter(4, [lo, hi], btype="bandpass", fs=_SR, output="sos")
|
||||||
|
elif hi:
|
||||||
|
sos = butter(4, hi, btype="lowpass", fs=_SR, output="sos")
|
||||||
|
else:
|
||||||
|
sos = butter(4, lo, btype="highpass", fs=_SR, output="sos")
|
||||||
|
x = sosfiltfilt(sos, y) ** 2
|
||||||
|
h = _SR // _FR
|
||||||
|
n = len(x) // h
|
||||||
|
return x[: n * h].reshape(n, h).mean(axis=1)
|
||||||
|
|
||||||
|
|
||||||
|
def _db(x):
|
||||||
|
return 10.0 * np.log10(np.asarray(x) + 1e-10)
|
||||||
|
|
||||||
|
|
||||||
|
def _bar_features(y: np.ndarray, beats: np.ndarray, bar0: int, n_bars: int):
|
||||||
|
"""``(D, T)``: per-bar [kick, bass, mid, high, loud] and mean MFCC.
|
||||||
|
|
||||||
|
Levels are dB BELOW the track's own 90th percentile, so every track is on
|
||||||
|
the same scale whatever its mastering; kick is 0..~1 of the track's usual.
|
||||||
|
"""
|
||||||
|
import librosa
|
||||||
|
|
||||||
|
from . import grid_detect
|
||||||
|
|
||||||
|
bass = _power_env(y, 30.0, 120.0)
|
||||||
|
mid = _power_env(y, 200.0, 2000.0)
|
||||||
|
high = _power_env(y, 5000.0, None)
|
||||||
|
full = _power_env(y, 20.0, 10000.0)
|
||||||
|
# The kick is read as the grid detector reads it: the sharp low-band onset,
|
||||||
|
# peaked within ±15 ms of each beat. Comparing on-beat to off-beat ENERGY
|
||||||
|
# does not work: a house bassline lives on the off-beat.
|
||||||
|
kick_on = grid_detect._onset(grid_detect._band_env(y, _SR, 30.0, 150.0))
|
||||||
|
S = np.abs(librosa.stft(y, n_fft=2048, hop_length=512))
|
||||||
|
mel = librosa.power_to_db(librosa.feature.melspectrogram(S=S**2, sr=_SR, n_mels=40))
|
||||||
|
mfcc = librosa.feature.mfcc(S=mel, n_mfcc=13)
|
||||||
|
mfcc_t = librosa.frames_to_time(np.arange(mfcc.shape[1]), sr=_SR, hop_length=512)
|
||||||
|
|
||||||
|
rows, timbre = [], []
|
||||||
|
for b in range(n_bars):
|
||||||
|
i = bar0 + 4 * b
|
||||||
|
t0, t1 = beats[i], beats[i + 4]
|
||||||
|
ks = []
|
||||||
|
for k in range(4):
|
||||||
|
c = int(round(beats[i + k] * 1000))
|
||||||
|
seg = kick_on[max(0, c - 15) : c + 16]
|
||||||
|
ks.append(float(seg.max()) if len(seg) else 0.0)
|
||||||
|
a, z = int(t0 * _FR), max(int(t1 * _FR), int(t0 * _FR) + 1)
|
||||||
|
rows.append([
|
||||||
|
float(np.median(ks)),
|
||||||
|
_db(bass[a:z].mean()), _db(mid[a:z].mean()), _db(high[a:z].mean()), _db(full[a:z].mean()),
|
||||||
|
])
|
||||||
|
ia, iz = np.searchsorted(mfcc_t, t0), np.searchsorted(mfcc_t, t1)
|
||||||
|
timbre.append(mfcc[:, ia : max(iz, ia + 1)].mean(axis=1))
|
||||||
|
D = np.asarray(rows)
|
||||||
|
D[:, 0] /= np.percentile(D[:, 0], 90) + 1e-9
|
||||||
|
D[:, 1:] -= np.percentile(D[:, 1:], 90, axis=0)
|
||||||
|
D[:, 1:] = np.maximum(D[:, 1:], -30.0) # silence is only "very quiet"
|
||||||
|
return D, np.asarray(timbre), _db(full)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- segmentation ---------------------------------------------------------------
|
||||||
|
def _segment(F: np.ndarray, penalty: np.ndarray) -> list[int]:
|
||||||
|
"""Section start bars minimising squared deviation from each section's mean
|
||||||
|
plus a price per boundary (exact dynamic programme; n is ~100–250 bars)."""
|
||||||
|
n = len(F)
|
||||||
|
cs = np.vstack([np.zeros(F.shape[1]), np.cumsum(F, axis=0)])
|
||||||
|
cs2 = np.r_[0.0, np.cumsum((F**2).sum(axis=1))]
|
||||||
|
|
||||||
|
def cost(i: int, j: int) -> float:
|
||||||
|
s = cs[j] - cs[i]
|
||||||
|
return float(cs2[j] - cs2[i] - (s @ s) / (j - i))
|
||||||
|
|
||||||
|
best = np.full(n + 1, np.inf)
|
||||||
|
best[0] = 0.0
|
||||||
|
arg = np.zeros(n + 1, dtype=np.int64)
|
||||||
|
for j in range(1, n + 1):
|
||||||
|
for i in range(0, j):
|
||||||
|
# every section is at least _MIN_SECTION long, except a short tail
|
||||||
|
if j - i < _MIN_SECTION and j != n:
|
||||||
|
continue
|
||||||
|
if 0 < i < _MIN_SECTION:
|
||||||
|
continue
|
||||||
|
v = best[i] + cost(i, j) + (penalty[i] if i else 0.0)
|
||||||
|
if v < best[j]:
|
||||||
|
best[j], arg[j] = v, i
|
||||||
|
starts, j = [], n
|
||||||
|
while j > 0:
|
||||||
|
starts.append(int(arg[j]))
|
||||||
|
j = int(arg[j])
|
||||||
|
return sorted(set(starts))
|
||||||
|
|
||||||
|
|
||||||
|
def _sections(D: np.ndarray, T: np.ndarray) -> list[Section]:
|
||||||
|
Z = np.column_stack([D[:, 0] * 10, D[:, 1] / 3, D[:, 4] / 3, D[:, 3] / 6, D[:, 2] / 6])
|
||||||
|
Tz = (T - T.mean(axis=0)) / (T.std(axis=0) + 1e-9) * _TIMBRE_WEIGHT
|
||||||
|
F = np.column_stack([Z, Tz])
|
||||||
|
n = len(F)
|
||||||
|
idx = np.arange(n)
|
||||||
|
scale = float(F.var(axis=0).sum()) * 4.0
|
||||||
|
penalty = scale * np.where(idx % 8 == 0, _LAMBDA_8, np.where(idx % 4 == 0, _LAMBDA_4, _LAMBDA_OTHER))
|
||||||
|
starts = _segment(F, penalty)
|
||||||
|
out = []
|
||||||
|
for k, s in enumerate(starts):
|
||||||
|
e = starts[k + 1] if k + 1 < len(starts) else n
|
||||||
|
d = D[s:e].mean(axis=0)
|
||||||
|
# High = near the track's loud parts on BOTH bass and loudness. The kick
|
||||||
|
# is deliberately not required: drum & bass has no kick on every beat.
|
||||||
|
out.append(Section(s, e, bool(d[1] > -_HIGH_DB and d[4] > -_HIGH_DB)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---- events ----------------------------------------------------------------------
|
||||||
|
def _events(secs: list[Section], music_end_bar: int) -> dict[str, int]:
|
||||||
|
"""Event -> BAR. Drops are high sections entered from a low one."""
|
||||||
|
ev: dict[str, int] = {}
|
||||||
|
drops: list[int] = []
|
||||||
|
seen_low = False
|
||||||
|
for i, s in enumerate(secs):
|
||||||
|
if s.high:
|
||||||
|
if seen_low and (i == 0 or not secs[i - 1].high):
|
||||||
|
drops.append(i)
|
||||||
|
else:
|
||||||
|
seen_low = True
|
||||||
|
|
||||||
|
def run_end(i: int) -> int:
|
||||||
|
while i + 1 < len(secs) and secs[i + 1].high:
|
||||||
|
i += 1
|
||||||
|
return i
|
||||||
|
|
||||||
|
for n, di in enumerate(drops, start=1):
|
||||||
|
ev[f"drop_{n}"] = secs[di].start
|
||||||
|
prev = secs[di - 1]
|
||||||
|
ev[f"build_{n}"] = prev.start if prev.end - prev.start <= _BUILD_MAX else secs[di].start - 8
|
||||||
|
# A breakdown is the end of a drop that ANOTHER drop follows; the end of
|
||||||
|
# the last one is the outro's business.
|
||||||
|
if n < len(drops):
|
||||||
|
ev[f"breakdown_{n}"] = secs[run_end(di) + 1].start
|
||||||
|
|
||||||
|
if len(secs) > 1:
|
||||||
|
ev["intro_end"] = secs[1].start
|
||||||
|
after = drops[-1] if drops else 0
|
||||||
|
cands = [s.start for s in secs[after + 1 :]] or [s.start for s in secs[1:]]
|
||||||
|
if cands:
|
||||||
|
ev["outro"] = min(cands, key=lambda b: abs(b - (music_end_bar - _OUTRO_BARS)))
|
||||||
|
return ev
|
||||||
|
|
||||||
|
|
||||||
|
# ---- entry point ---------------------------------------------------------------
|
||||||
|
def analyse(
|
||||||
|
audio_path: str,
|
||||||
|
markers: list[tuple[float, float]],
|
||||||
|
*,
|
||||||
|
y: np.ndarray | None = None,
|
||||||
|
) -> Structure:
|
||||||
|
"""Sections and cue events for a track, on its own beatgrid.
|
||||||
|
|
||||||
|
``markers`` is the grid as ``[(start_sec, bpm), …]``. Raises ``ValueError``
|
||||||
|
when there is no grid or too little music to have a structure.
|
||||||
|
"""
|
||||||
|
if not markers:
|
||||||
|
raise ValueError("Set a beatgrid first")
|
||||||
|
if y is None:
|
||||||
|
import librosa
|
||||||
|
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
|
||||||
|
y = np.asarray(y, dtype=np.float32)
|
||||||
|
duration = len(y) / _SR
|
||||||
|
beats, bar0 = grid_beats(markers, duration)
|
||||||
|
n_bars = max(0, (len(beats) - bar0 - 1) // 4)
|
||||||
|
if n_bars < 2 * _MIN_SECTION:
|
||||||
|
raise ValueError("Track is too short to find a structure")
|
||||||
|
|
||||||
|
D, T, full_db = _bar_features(y, beats, bar0, n_bars)
|
||||||
|
st = Structure(beats=beats, bar0=bar0, n_bars=n_bars, duration=duration)
|
||||||
|
st.sections = _sections(D, T)
|
||||||
|
|
||||||
|
# Where the music starts and ends: the first/last beat within 30 dB of the
|
||||||
|
# track's loud parts, so a silent lead-in or tail is not cued.
|
||||||
|
loud = full_db >= np.percentile(full_db, 90) - 30.0
|
||||||
|
frames = np.flatnonzero(loud)
|
||||||
|
t_first = frames[0] / _FR if len(frames) else 0.0
|
||||||
|
t_last = frames[-1] / _FR if len(frames) else duration
|
||||||
|
first_beat = int(np.searchsorted(beats, t_first - 0.05))
|
||||||
|
last_beat = max(first_beat, int(np.searchsorted(beats, t_last, side="right")) - 1)
|
||||||
|
music_end_bar = min(n_bars, max(0, (last_beat - bar0) // 4))
|
||||||
|
|
||||||
|
st.events = {k: st.beat_of_bar(b) for k, b in _events(st.sections, music_end_bar).items()}
|
||||||
|
st.events["first_beat"] = first_beat
|
||||||
|
st.events["last_beat"] = last_beat
|
||||||
|
return st
|
||||||
+39
-22
@@ -16,7 +16,7 @@ from fastapi.responses import FileResponse, JSONResponse
|
|||||||
from . import __version__, exporter, exports, history, prefs
|
from . import __version__, exporter, exports, history, prefs
|
||||||
from .app_state import STATE
|
from .app_state import STATE
|
||||||
from .core import auto_hotcues as ah
|
from .core import auto_hotcues as ah
|
||||||
from .core import grid_detect
|
from .core import grid_detect, structure
|
||||||
from . import importer
|
from . import importer
|
||||||
from .core import export as core_export
|
from .core import export as core_export
|
||||||
from .core import places, registry
|
from .core import places, registry
|
||||||
@@ -33,8 +33,10 @@ from .jobs import JOBS
|
|||||||
from .core.pathmap import PathMapping
|
from .core.pathmap import PathMapping
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
AutoGridRequest,
|
AutoGridRequest,
|
||||||
|
AutoCueOutcome,
|
||||||
AutoHotcue,
|
AutoHotcue,
|
||||||
AutoHotcuesRequest,
|
AutoHotcuesRequest,
|
||||||
|
AutoHotcuesResult,
|
||||||
CollectionCandidate,
|
CollectionCandidate,
|
||||||
CollectionOptions,
|
CollectionOptions,
|
||||||
CollectionStatus,
|
CollectionStatus,
|
||||||
@@ -815,43 +817,58 @@ def create_cue(body: SetCue) -> TrackCues:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/tracks/cue/auto", response_model=TrackCues)
|
@app.post("/api/tracks/cue/auto", response_model=AutoHotcuesResult)
|
||||||
def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
|
def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
|
||||||
"""Analyze the track's audio and place structural hotcues into empty slots.
|
"""Analyse the track's structure on its beatgrid and place the template.
|
||||||
|
|
||||||
Detects section boundaries (librosa Laplacian segmentation), snaps them to
|
Each requested slot is bound to an event (``drop_1``, ``outro``, …) plus an
|
||||||
the track's beatgrid phrases, names them positionally, and places up to
|
offset in beats. Every slot reports an outcome — placed, not found, out of
|
||||||
MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid."""
|
range, occupied (a cue is there and overwrite was not asked for) or
|
||||||
|
protected (a cue the adapter will not replace) — so the UI can say which
|
||||||
|
events this track does not have. Requires a beatgrid.
|
||||||
|
"""
|
||||||
a = require_adapter()
|
a = require_adapter()
|
||||||
cues = a.track_cues(body.track_id)
|
cues = a.track_cues(body.track_id)
|
||||||
if cues is None:
|
if cues is None:
|
||||||
raise HTTPException(404, "Track not found")
|
raise HTTPException(404, "Track not found")
|
||||||
if not cues.grid_markers:
|
if not cues.grid_markers:
|
||||||
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
|
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
|
||||||
|
slots = a.capabilities().cues.hotcue_slots
|
||||||
|
seen: set[int] = set()
|
||||||
|
for r in body.slots:
|
||||||
|
if not 0 <= r.slot < slots:
|
||||||
|
raise HTTPException(400, f"Slot {r.slot} is outside this library's {slots} hotcues")
|
||||||
|
if r.slot in seen:
|
||||||
|
raise HTTPException(400, f"Slot {r.slot} is requested twice")
|
||||||
|
seen.add(r.slot)
|
||||||
path = a.audio_path(body.track_id)
|
path = a.audio_path(body.track_id)
|
||||||
if path is None or not path.exists():
|
if path is None or not path.exists():
|
||||||
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
|
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
boundaries, duration = ah.detect_boundaries(str(path))
|
found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers])
|
||||||
except Exception as ex: # analysis is best-effort; never 500 the UI
|
except Exception as ex: # analysis is best-effort; never 500 the UI
|
||||||
raise HTTPException(400, f"Analysis failed: {ex}")
|
raise HTTPException(400, f"Analysis failed: {ex}")
|
||||||
|
|
||||||
slots = a.capabilities().cues.hotcue_slots
|
existing = {c.slot: c.editable for c in cues.cues if c.role == "hotcue" and c.slot is not None}
|
||||||
occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0}
|
outcomes = ah.plan(
|
||||||
free = [s for s in range(slots) if s not in occupied]
|
found,
|
||||||
existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0]
|
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots],
|
||||||
specs = ah.select_hotcues(
|
existing,
|
||||||
boundaries,
|
)
|
||||||
markers=[(m.start, m.bpm) for m in cues.grid_markers],
|
placed = [o for o in outcomes if o.status == ah.PLACED]
|
||||||
duration=duration,
|
if placed:
|
||||||
free_slots=free,
|
# overwrite=True is safe: `plan` only passes an occupied slot when the
|
||||||
existing_times=existing_times,
|
# user ticked it, and the adapter still refuses a protected one.
|
||||||
max_cues=body.max_cues or slots,
|
cues = a.place_cues(
|
||||||
|
body.track_id,
|
||||||
|
[AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed],
|
||||||
|
overwrite=True,
|
||||||
|
)
|
||||||
|
return AutoHotcuesResult(
|
||||||
|
cues=cues,
|
||||||
|
outcomes=[AutoCueOutcome(**vars(o)) for o in outcomes],
|
||||||
)
|
)
|
||||||
if not specs:
|
|
||||||
return cues # no confident structure / no free slots — leave untouched
|
|
||||||
return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs])
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/tracks/grid/auto", response_model=TrackCues)
|
@app.post("/api/tracks/grid/auto", response_model=TrackCues)
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
"""API response models (Pydantic)."""
|
"""API response models (Pydantic)."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
from .core.capabilities import CueRole, CueType
|
from .core.capabilities import CueRole, CueType
|
||||||
@@ -79,9 +81,37 @@ class SetCue(BaseModel):
|
|||||||
color: str | None = None
|
color: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
AutoCueEvent = Literal[
|
||||||
|
"first_beat", "intro_end",
|
||||||
|
"build_1", "drop_1", "breakdown_1",
|
||||||
|
"build_2", "drop_2", "breakdown_2",
|
||||||
|
"build_3", "drop_3", "breakdown_3",
|
||||||
|
"outro", "last_beat",
|
||||||
|
]
|
||||||
|
AutoCueStatus = Literal["placed", "not_found", "out_of_range", "occupied", "protected"]
|
||||||
|
|
||||||
|
|
||||||
|
class AutoCueSlot(BaseModel):
|
||||||
|
"""One row of the Auto Hotcues template: bind a slot to a structural event."""
|
||||||
|
|
||||||
|
slot: int
|
||||||
|
event: AutoCueEvent
|
||||||
|
offset_beats: int = 0
|
||||||
|
overwrite: bool = False # replace a cue already in this slot
|
||||||
|
|
||||||
|
|
||||||
class AutoHotcuesRequest(BaseModel):
|
class AutoHotcuesRequest(BaseModel):
|
||||||
track_id: str
|
track_id: str
|
||||||
max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side
|
slots: list[AutoCueSlot]
|
||||||
|
|
||||||
|
|
||||||
|
class AutoCueOutcome(BaseModel):
|
||||||
|
slot: int
|
||||||
|
event: AutoCueEvent
|
||||||
|
status: AutoCueStatus
|
||||||
|
start: float | None = None # seconds, when placed
|
||||||
|
name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class AutoGridRequest(BaseModel):
|
class AutoGridRequest(BaseModel):
|
||||||
@@ -274,6 +304,13 @@ from .core.model import ( # noqa: E402,F401
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AutoHotcuesResult(BaseModel):
|
||||||
|
"""The refreshed cues, plus what happened to every requested slot."""
|
||||||
|
|
||||||
|
cues: TrackCues
|
||||||
|
outcomes: list[AutoCueOutcome]
|
||||||
|
|
||||||
|
|
||||||
# ---- import sources ---------------------------------------------------
|
# ---- import sources ---------------------------------------------------
|
||||||
#
|
#
|
||||||
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
|
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
fail=0
|
fail=0
|
||||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
|
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
echo "▶ $t"
|
echo "▶ $t"
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""Tests for Auto Hotcues: structure analysis, slot resolution and the route.
|
||||||
|
|
||||||
|
Three layers, because each failed silently before:
|
||||||
|
- `structure.analyse` on SYNTHETIC audio whose sections are known by
|
||||||
|
construction (intro / breakdown / drop / …), so a wrong bar is a wrong answer
|
||||||
|
rather than a disagreement with another analyser;
|
||||||
|
- `auto_hotcues.plan`, the pure part: offsets in beats (across a tempo change),
|
||||||
|
and every outcome a slot can report;
|
||||||
|
- the ROUTE, end to end against a temp copy of the real collection. The previous
|
||||||
|
implementation's route raised a 500 on every call for a week after a model
|
||||||
|
change, and nothing noticed, because only its placement helper was tested.
|
||||||
|
|
||||||
|
Accuracy on real music is measured against Rekordbox's phrase analysis, which
|
||||||
|
needs local audio; see the Auto Hotcues section of CLAUDE.md.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-autocue-appdata-")
|
||||||
|
|
||||||
|
from konduktor.core import auto_hotcues as ah # noqa: E402
|
||||||
|
from konduktor.core import structure # noqa: E402
|
||||||
|
|
||||||
|
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||||
|
SR = 22050
|
||||||
|
failed = False
|
||||||
|
|
||||||
|
|
||||||
|
def check(label, cond, detail=""):
|
||||||
|
global failed
|
||||||
|
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||||
|
if not cond:
|
||||||
|
failed = True
|
||||||
|
|
||||||
|
|
||||||
|
# ---- synthetic track ----------------------------------------------------------
|
||||||
|
rng = np.random.default_rng(0)
|
||||||
|
BPM, FIRST = 128.0, 0.25
|
||||||
|
BEAT = 60.0 / BPM
|
||||||
|
BAR = 4 * BEAT
|
||||||
|
|
||||||
|
|
||||||
|
def _fade(x):
|
||||||
|
n = min(len(x), int(0.02 * SR))
|
||||||
|
x = x.copy()
|
||||||
|
x[-n:] *= np.linspace(1, 0, n)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
def _kick():
|
||||||
|
t = np.arange(int(0.25 * SR)) / SR
|
||||||
|
return _fade(np.sin(2 * np.pi * 52 * t) * np.exp(-t / 0.1) + np.r_[rng.standard_normal(40) * 0.4, np.zeros(len(t) - 40)])
|
||||||
|
|
||||||
|
|
||||||
|
def _hat():
|
||||||
|
n = int(0.04 * SR)
|
||||||
|
return _fade(np.diff(rng.standard_normal(n + 1)) * np.exp(-np.arange(n) / SR / 0.01) * 0.3)
|
||||||
|
|
||||||
|
|
||||||
|
# (name, bars, kick, bass, pad, hats)
|
||||||
|
LAYOUT = [
|
||||||
|
("intro", 16, True, False, False, True),
|
||||||
|
("breakdown", 16, False, False, True, False),
|
||||||
|
("drop", 32, True, True, True, True),
|
||||||
|
("breakdown", 16, False, False, True, False),
|
||||||
|
("drop", 32, True, True, True, True),
|
||||||
|
("outro", 16, True, False, False, True),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def synth():
|
||||||
|
total = sum(b for _, b, *_ in LAYOUT) * BAR + FIRST + 1.0
|
||||||
|
y = np.zeros(int(total * SR))
|
||||||
|
t_all = np.arange(len(y)) / SR
|
||||||
|
k, h = _kick(), _hat()
|
||||||
|
bar = 0
|
||||||
|
for _, bars, kick, bass, pad, hats in LAYOUT:
|
||||||
|
t0 = FIRST + bar * BAR
|
||||||
|
t1 = t0 + bars * BAR
|
||||||
|
m = (t_all >= t0) & (t_all < t1)
|
||||||
|
if bass: # a loud sustained 55 Hz bass with some harmonics
|
||||||
|
y[m] += 0.5 * np.sign(np.sin(2 * np.pi * 55 * t_all[m])) * 0.6
|
||||||
|
if pad: # a mid-range chord
|
||||||
|
y[m] += 0.08 * sum(np.sin(2 * np.pi * f * t_all[m]) for f in (330, 415, 494))
|
||||||
|
for b in range(bars * 4):
|
||||||
|
tb = t0 + b * BEAT
|
||||||
|
i = int(tb * SR)
|
||||||
|
if kick:
|
||||||
|
y[i : i + len(k)] += k[: len(y) - i]
|
||||||
|
if hats:
|
||||||
|
j = int((tb + BEAT / 2) * SR)
|
||||||
|
y[j : j + len(h)] += h[: max(0, len(y) - j)]
|
||||||
|
bar += bars
|
||||||
|
return (0.3 * y).astype(np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
print("== structure on a track whose sections are known ==")
|
||||||
|
y = synth()
|
||||||
|
st = structure.analyse("", [(FIRST, BPM)], y=y)
|
||||||
|
bar_of = {e: (b - st.bar0) // 4 for e, b in st.events.items()}
|
||||||
|
check("first drop at bar 32", bar_of.get("drop_1") == 32, str(bar_of))
|
||||||
|
check("first breakdown at bar 64 (where the first drop ends)", bar_of.get("breakdown_1") == 64, str(bar_of))
|
||||||
|
check("second drop at bar 80", bar_of.get("drop_2") == 80, str(bar_of))
|
||||||
|
check("the intro is NOT a drop, though it has a kick", bar_of.get("drop_1") != 0, str(bar_of))
|
||||||
|
check("intro ends at bar 16", bar_of.get("intro_end") == 16, str(bar_of))
|
||||||
|
check("no third drop is invented", "drop_3" not in bar_of, str(bar_of))
|
||||||
|
check("no breakdown after the LAST drop (that is the outro)", "breakdown_2" not in bar_of, str(bar_of))
|
||||||
|
check("outro starts at bar 112", bar_of.get("outro") == 112, str(bar_of))
|
||||||
|
check("first beat is the first kick", abs(st.beat_time(st.events["first_beat"]) - FIRST) < 0.01,
|
||||||
|
f"{st.beat_time(st.events['first_beat'])}")
|
||||||
|
check("every section boundary is on a 4-bar line", all(s.start % 4 == 0 for s in st.sections),
|
||||||
|
str([s.start for s in st.sections]))
|
||||||
|
|
||||||
|
print("== a flexible grid: beats follow each marker's tempo ==")
|
||||||
|
beats, bar0 = structure.grid_beats([(1.0, 120.0), (9.0, 60.0)], duration=20.0)
|
||||||
|
check("beats before the first marker are extrapolated back", bar0 == 2 and abs(beats[0] - 0.0) < 1e-9, f"{bar0} {beats[:3]}")
|
||||||
|
check("0.5 s apart under the first marker", abs(beats[bar0 + 1] - beats[bar0] - 0.5) < 1e-9)
|
||||||
|
check("1.0 s apart after the second", abs(beats[-1] - beats[-2] - 1.0) < 1e-9)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- plan: the pure part ----------------------------------------------------------
|
||||||
|
def fake_structure(events, n_beats=400, bpm=120.0):
|
||||||
|
s = structure.Structure(beats=np.arange(n_beats) * 60.0 / bpm, bar0=0, n_bars=n_beats // 4,
|
||||||
|
duration=n_beats * 60.0 / bpm)
|
||||||
|
s.events = dict(events)
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
print("== plan: offsets and outcomes ==")
|
||||||
|
fs = fake_structure({"drop_1": 128, "outro": 384, "first_beat": 0})
|
||||||
|
R = ah.SlotRequest
|
||||||
|
out = {o.slot: o for o in ah.plan(fs, [
|
||||||
|
R(0, "first_beat"),
|
||||||
|
R(1, "drop_1", -16),
|
||||||
|
R(2, "drop_3"),
|
||||||
|
R(3, "first_beat", -4),
|
||||||
|
R(4, "drop_1"),
|
||||||
|
R(5, "drop_1", 0, overwrite=True),
|
||||||
|
R(6, "drop_1", 0, overwrite=True),
|
||||||
|
], existing={4: True, 5: True, 6: False})}
|
||||||
|
check("placed on the event's beat", out[0].status == ah.PLACED and out[0].start == 0.0)
|
||||||
|
check("an offset counts BEATS: drop -16 is 8 s earlier at 120 BPM",
|
||||||
|
out[1].status == ah.PLACED and abs(out[1].start - (128 - 16) * 0.5) < 1e-9, str(out[1]))
|
||||||
|
check("the offset is in the cue's name", out[1].name == "Drop 1 -16", str(out[1].name))
|
||||||
|
check("a missing event is reported, not placed", out[2].status == ah.NOT_FOUND)
|
||||||
|
check("an offset before the track start is out of range", out[3].status == ah.OUT_OF_RANGE)
|
||||||
|
check("an occupied slot is left alone by default", out[4].status == ah.OCCUPIED)
|
||||||
|
check("…and replaced when overwrite is asked for", out[5].status == ah.PLACED)
|
||||||
|
check("a protected cue is never replaced, even with overwrite", out[6].status == ah.PROTECTED)
|
||||||
|
|
||||||
|
flex = structure.Structure(beats=np.r_[np.arange(0, 10, 0.5), np.arange(10, 30, 1.0)], bar0=0, n_bars=10, duration=30)
|
||||||
|
flex.events = {"drop_1": 24} # beat 24 is at 14 s (20 beats at 0.5 s, then 4 at 1.0 s)
|
||||||
|
o = ah.plan(flex, [R(0, "drop_1", -8)], {})[0]
|
||||||
|
# 8 beats back is beat 16, at 8.0 s; 8 beats at the LOCAL tempo would be 6.0 s.
|
||||||
|
check("an offset across a tempo change counts beats, not seconds", abs(o.start - 8.0) < 1e-9, str(o.start))
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the route --------------------------------------------------------------------
|
||||||
|
print("== the route, end to end ==")
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
work = Path(d) / "collection.nml"
|
||||||
|
shutil.copy2(REAL, work)
|
||||||
|
os.environ["KONDUKTOR_NML"] = str(work)
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
import konduktor.main as main
|
||||||
|
|
||||||
|
# The real collection's audio is not on every machine, so the route gets a
|
||||||
|
# stand-in structure and an existing file: this pins the WIRING — request
|
||||||
|
# validation, the plan, the adapter write and the response model.
|
||||||
|
main.structure.analyse = lambda path, markers: fake_structure({"drop_1": 64, "first_beat": 0}, bpm=markers[0][1])
|
||||||
|
with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||||
|
a = main.require_adapter()
|
||||||
|
a.audio_path = lambda track_id: Path(__file__)
|
||||||
|
def free_slots(cu):
|
||||||
|
return [s for s in range(8) if not any(q.slot == s for q in cu.cues)]
|
||||||
|
tid = next(t.id for t in a.tracks
|
||||||
|
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) == 1 and len(free_slots(cu)) >= 3)
|
||||||
|
f0, f1, f2 = free_slots(a.track_cues(tid))[:3]
|
||||||
|
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [
|
||||||
|
{"slot": f0, "event": "first_beat"},
|
||||||
|
{"slot": f1, "event": "drop_1", "offset_beats": -16},
|
||||||
|
{"slot": f2, "event": "drop_3"},
|
||||||
|
]})
|
||||||
|
check("the route answers 200", r.status_code == 200, r.text[:200])
|
||||||
|
if r.status_code == 200:
|
||||||
|
j = r.json()
|
||||||
|
st_ = {o["slot"]: o["status"] for o in j["outcomes"]}
|
||||||
|
check("outcomes per slot", st_ == {f0: "placed", f1: "placed", f2: "not_found"}, str(st_))
|
||||||
|
names = {q["slot"]: q["name"] for q in j["cues"]["cues"] if q["slot"] is not None}
|
||||||
|
check("the cues are in the returned projection", names.get(f1) == "Drop 1 -16", str(names))
|
||||||
|
r2 = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f1, "event": "drop_1"}]})
|
||||||
|
check("running again leaves the now-occupied slot alone",
|
||||||
|
r2.status_code == 200 and r2.json()["outcomes"][0]["status"] == "occupied", r2.text[:200])
|
||||||
|
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "drop_1"}, {"slot": f0, "event": "outro"}]})
|
||||||
|
check("a slot requested twice is refused", r.status_code == 400)
|
||||||
|
r = c.post("/api/tracks/cue/auto", json={"track_id": tid, "slots": [{"slot": f0, "event": "the_best_bit"}]})
|
||||||
|
check("an unknown event is refused", r.status_code == 422)
|
||||||
|
check("nothing was written to disk (edits stay in memory until Save)",
|
||||||
|
work.read_bytes() == REAL.read_bytes())
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("FAILED" if failed else "RESULT: ALL PASSED")
|
||||||
|
raise SystemExit(1 if failed else 0)
|
||||||
@@ -385,50 +385,9 @@ with tempfile.TemporaryDirectory() as d:
|
|||||||
c is not None and abs(c.start - (30000.0 + i * 10000)) < 1,
|
c is not None and abs(c.start - (30000.0 + i * 10000)) < 1,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---- Invariant G: select_hotcues placement logic (pure, no audio) ------
|
# ---- Invariant G: moved -------------------------------------------------
|
||||||
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
|
# Auto Hotcues' placement logic is tested in test_auto_hotcues.py, which also
|
||||||
from konduktor.core import auto_hotcues as ah # noqa: E402
|
# covers its structure analysis and its route.
|
||||||
|
|
||||||
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; marker at 0.0.
|
|
||||||
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
|
|
||||||
GRID = [(ANCHOR, BPM)] # a constant grid is a one-marker list
|
|
||||||
# Raw boundaries near (but not exactly on) phrase multiples + a fragmented pair.
|
|
||||||
raw = [(0.3, 0.2), (29.4, 0.5), (30.6, 0.55), (61.0, 0.9), (150.0, 0.3), (270.2, 0.25)]
|
|
||||||
specs = ah.select_hotcues(
|
|
||||||
raw, markers=GRID, duration=DUR,
|
|
||||||
free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8,
|
|
||||||
)
|
|
||||||
starts = [s["start"] for s in specs]
|
|
||||||
check("snaps to 30s phrase grid", all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in starts), str(starts))
|
|
||||||
check("fragmented 29.4/30.6 merge to one boundary (30.0)", starts.count(30.0) == 1, str(starts))
|
|
||||||
check("only free slots used, in ascending order", [s["slot"] for s in specs] == sorted(s["slot"] for s in specs) and set(s["slot"] for s in specs) <= {2, 3, 4, 5, 6, 7})
|
|
||||||
check("first cue named Intro", specs and specs[0]["name"] == "Intro")
|
|
||||||
check("last cue named Outro", specs and specs[-1]["name"] == "Outro")
|
|
||||||
check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == len(specs), str([s["name"] for s in specs]))
|
|
||||||
|
|
||||||
# A hotcue already sitting on the 60s phrase must not get a duplicate.
|
|
||||||
specs2 = ah.select_hotcues(
|
|
||||||
raw, markers=GRID, duration=DUR,
|
|
||||||
free_slots=[0, 1, 2, 3, 4, 5, 6, 7], existing_times=[60.0], max_cues=8,
|
|
||||||
)
|
|
||||||
check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["start"] for s in specs2], str([s["start"] for s in specs2]))
|
|
||||||
|
|
||||||
# No free slots => nothing placed.
|
|
||||||
check("no free slots => empty result", ah.select_hotcues(raw, markers=GRID, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
|
|
||||||
|
|
||||||
# Flexible grid: each segment snaps to ITS OWN phrase length. Segment 2 starts
|
|
||||||
# at 120s at 120 BPM => 16-bar phrase = 32.0s, so points there land on 120+k*32.
|
|
||||||
FLEX = [(0.0, 128.0), (120.0, 120.0)]
|
|
||||||
flex_specs = ah.select_hotcues(
|
|
||||||
[(29.4, 0.5), (61.0, 0.9), (152.5, 0.4), (215.0, 0.3)],
|
|
||||||
markers=FLEX, duration=DUR, free_slots=[0, 1, 2, 3, 4, 5, 6, 7],
|
|
||||||
existing_times=[], max_cues=8,
|
|
||||||
)
|
|
||||||
flex_starts = [s_["start"] for s_ in flex_specs]
|
|
||||||
check("flexible grid: pre-seam points snap to the 30s phrase",
|
|
||||||
all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in flex_starts if t < 120.0), str(flex_starts))
|
|
||||||
check("flexible grid: post-seam points snap to that segment's 32s phrase",
|
|
||||||
all(abs(120.0 + round((t - 120.0) / 32.0) * 32.0 - t) < 0.01 for t in flex_starts if t >= 120.0), str(flex_starts))
|
|
||||||
|
|
||||||
# ---- Invariant H: path write-back is localized + round-trips -----------
|
# ---- Invariant H: path write-back is localized + round-trips -----------
|
||||||
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
|
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
|
||||||
|
|||||||
+41
-4
@@ -146,6 +146,42 @@ export interface TrackCues {
|
|||||||
cues: CuePoint[]
|
cues: CuePoint[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A structural event an Auto Hotcues slot can be bound to (`core/structure.py`
|
||||||
|
* EVENTS; keep in lockstep with `schemas.AutoCueEvent`). */
|
||||||
|
export type AutoCueEvent =
|
||||||
|
| 'first_beat' | 'intro_end'
|
||||||
|
| 'build_1' | 'drop_1' | 'breakdown_1'
|
||||||
|
| 'build_2' | 'drop_2' | 'breakdown_2'
|
||||||
|
| 'build_3' | 'drop_3' | 'breakdown_3'
|
||||||
|
| 'outro' | 'last_beat'
|
||||||
|
|
||||||
|
export interface AutoCueSlot {
|
||||||
|
slot: number
|
||||||
|
event: AutoCueEvent
|
||||||
|
offset_beats: number
|
||||||
|
/** Replace a cue already in this slot. */
|
||||||
|
overwrite: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What happened to one requested slot. `not_found`: the track has no such
|
||||||
|
* event (e.g. no third drop); `out_of_range`: the offset moves it outside the
|
||||||
|
* track; `occupied`: a cue is there and overwrite was off; `protected`: a cue
|
||||||
|
* the adapter will not replace (a grid marker's). */
|
||||||
|
export type AutoCueStatus = 'placed' | 'not_found' | 'out_of_range' | 'occupied' | 'protected'
|
||||||
|
|
||||||
|
export interface AutoCueOutcome {
|
||||||
|
slot: number
|
||||||
|
event: AutoCueEvent
|
||||||
|
status: AutoCueStatus
|
||||||
|
start: number | null
|
||||||
|
name: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AutoHotcuesResult {
|
||||||
|
cues: TrackCues
|
||||||
|
outcomes: AutoCueOutcome[]
|
||||||
|
}
|
||||||
|
|
||||||
export interface CueCapabilities {
|
export interface CueCapabilities {
|
||||||
/** Whether cues can be created or changed. Symmetric with grid.editable: a
|
/** Whether cues can be created or changed. Symmetric with grid.editable: a
|
||||||
* platform can be writable overall while its cue store is not implemented. */
|
* platform can be writable overall while its cue store is not implemented. */
|
||||||
@@ -615,11 +651,12 @@ export const api = {
|
|||||||
length,
|
length,
|
||||||
name,
|
name,
|
||||||
}),
|
}),
|
||||||
// Backend analyses the audio and places structural hotcues into empty slots.
|
// Analyses the track's structure on its beatgrid and places the template:
|
||||||
autoCues: (trackId: string, maxCues?: number) =>
|
// one event (+ offset in beats) per slot. Every slot reports an outcome.
|
||||||
send<TrackCues>('POST', '/api/tracks/cue/auto', {
|
autoCues: (trackId: string, slots: AutoCueSlot[]) =>
|
||||||
|
send<AutoHotcuesResult>('POST', '/api/tracks/cue/auto', {
|
||||||
track_id: trackId,
|
track_id: trackId,
|
||||||
max_cues: maxCues,
|
slots,
|
||||||
}),
|
}),
|
||||||
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
|
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
|
||||||
autoGrid: (trackId: string) =>
|
autoGrid: (trackId: string) =>
|
||||||
|
|||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import {
|
||||||
|
api,
|
||||||
|
type AutoCueEvent,
|
||||||
|
type AutoHotcuesResult,
|
||||||
|
type CuePoint,
|
||||||
|
type Track,
|
||||||
|
} from '../api'
|
||||||
|
import { formatDuration } from '../lib/format'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto Hotcues: bind each hotcue slot to a structural event plus an offset in
|
||||||
|
* beats, then analyse the track and place them all in one go.
|
||||||
|
*
|
||||||
|
* The template (event + offset per slot) is remembered in userprefs — a DJ cues
|
||||||
|
* every track the same way — but the per-slot "replace" ticks are NOT: whether
|
||||||
|
* to overwrite a hand-placed cue is a decision about THIS track, and a
|
||||||
|
* remembered tick would silently clobber the next track's cues.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [
|
||||||
|
{ id: 'first_beat', label: 'First beat' },
|
||||||
|
{ id: 'intro_end', label: 'Intro end' },
|
||||||
|
{ id: 'build_1', label: 'Build 1' },
|
||||||
|
{ id: 'drop_1', label: 'Drop 1' },
|
||||||
|
{ id: 'breakdown_1', label: 'Breakdown 1' },
|
||||||
|
{ id: 'build_2', label: 'Build 2' },
|
||||||
|
{ id: 'drop_2', label: 'Drop 2' },
|
||||||
|
{ id: 'breakdown_2', label: 'Breakdown 2' },
|
||||||
|
{ id: 'build_3', label: 'Build 3' },
|
||||||
|
{ id: 'drop_3', label: 'Drop 3' },
|
||||||
|
{ id: 'breakdown_3', label: 'Breakdown 3' },
|
||||||
|
{ id: 'outro', label: 'Outro start' },
|
||||||
|
{ id: 'last_beat', label: 'Last beat' },
|
||||||
|
]
|
||||||
|
const EVENT_IDS = new Set<string>(AUTO_CUE_EVENTS.map((e) => e.id))
|
||||||
|
export const eventLabel = (id: AutoCueEvent) =>
|
||||||
|
AUTO_CUE_EVENTS.find((e) => e.id === id)?.label ?? id
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
event: AutoCueEvent | null
|
||||||
|
offset: number // beats
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_TEMPLATE: AutoCueEvent[] = [
|
||||||
|
'first_beat', 'build_1', 'drop_1', 'breakdown_1', 'build_2', 'drop_2', 'outro', 'last_beat',
|
||||||
|
]
|
||||||
|
const PREF_KEY = 'autoCueTemplate'
|
||||||
|
const MAX_OFFSET = 256
|
||||||
|
|
||||||
|
/** The remembered template, padded/truncated to this library's bank size.
|
||||||
|
* Anything malformed in prefs falls back to the default for that slot. */
|
||||||
|
function loadTemplate(prefs: Record<string, unknown> | undefined, slots: number): Row[] {
|
||||||
|
const saved = Array.isArray(prefs?.[PREF_KEY]) ? (prefs![PREF_KEY] as unknown[]) : null
|
||||||
|
return Array.from({ length: slots }, (_, i) => {
|
||||||
|
const r = saved?.[i] as { event?: unknown; offset_beats?: unknown } | undefined
|
||||||
|
if (saved && r && typeof r === 'object') {
|
||||||
|
const event = r.event === null ? null : EVENT_IDS.has(String(r.event)) ? (r.event as AutoCueEvent) : null
|
||||||
|
const off = typeof r.offset_beats === 'number' && isFinite(r.offset_beats) ? Math.round(r.offset_beats) : 0
|
||||||
|
return { event, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, off)) }
|
||||||
|
}
|
||||||
|
return { event: DEFAULT_TEMPLATE[i] ?? null, offset: 0 }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
track: Track
|
||||||
|
slotCount: number
|
||||||
|
slotLabel: (slot: number) => string
|
||||||
|
/** The track's current hotcues by slot, to mark occupied rows. */
|
||||||
|
existing: Map<number, CuePoint>
|
||||||
|
onClose: () => void
|
||||||
|
onDone: (result: AutoHotcuesResult) => void
|
||||||
|
onError: (msg: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, onDone, onError }: Props) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
|
||||||
|
const [rows, setRows] = useState<Row[] | null>(null)
|
||||||
|
const [replace, setReplace] = useState<Set<number>>(new Set())
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
// Hydrate once from prefs (the query is normally already cached by PrepStrip).
|
||||||
|
useEffect(() => {
|
||||||
|
if (rows === null && (prefs.data || prefs.isError)) setRows(loadTemplate(prefs.data, slotCount))
|
||||||
|
}, [prefs.data, prefs.isError, rows, slotCount])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape' && !busy) onClose()
|
||||||
|
}
|
||||||
|
window.addEventListener('keydown', onKey)
|
||||||
|
return () => window.removeEventListener('keydown', onKey)
|
||||||
|
}, [busy, onClose])
|
||||||
|
|
||||||
|
const setRow = (i: number, patch: Partial<Row>) =>
|
||||||
|
setRows((rs) => rs && rs.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
||||||
|
const nudge = (i: number, by: number) =>
|
||||||
|
setRows((rs) =>
|
||||||
|
rs && rs.map((r, j) => (j === i ? { ...r, offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, r.offset + by)) } : r)),
|
||||||
|
)
|
||||||
|
|
||||||
|
const active = (rows ?? []).filter((r) => r.event !== null).length
|
||||||
|
|
||||||
|
const confirm = async () => {
|
||||||
|
if (!rows || busy || active === 0) return
|
||||||
|
setBusy(true)
|
||||||
|
const template = rows.map((r) => ({ event: r.event, offset_beats: r.offset }))
|
||||||
|
// Remember the template whatever the analysis finds: it describes how the
|
||||||
|
// user cues, not this track.
|
||||||
|
api
|
||||||
|
.patchPrefs({ [PREF_KEY]: template })
|
||||||
|
.then((p) => qc.setQueryData(['prefs'], p))
|
||||||
|
.catch(() => {})
|
||||||
|
try {
|
||||||
|
const result = await api.autoCues(
|
||||||
|
track.id,
|
||||||
|
rows.flatMap((r, slot) =>
|
||||||
|
r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
onDone(result)
|
||||||
|
onClose()
|
||||||
|
} catch (e) {
|
||||||
|
onError((e as Error).message)
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6" onClick={() => !busy && onClose()}>
|
||||||
|
<div
|
||||||
|
className="flex max-h-[85vh] w-full max-w-xl flex-col overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="border-b border-line px-5 py-4">
|
||||||
|
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
|
||||||
|
<div className="truncate text-xs text-muted">
|
||||||
|
{track.artist} — {track.title}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-3">
|
||||||
|
<div className="mb-2 grid grid-cols-[2rem_1fr_9rem_7.5rem] gap-2 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||||
|
<span>Slot</span>
|
||||||
|
<span>Event</span>
|
||||||
|
<span className="text-center">Offset (beats)</span>
|
||||||
|
<span>Existing cue</span>
|
||||||
|
</div>
|
||||||
|
{rows === null ? (
|
||||||
|
<div className="py-6 text-center text-sm text-muted">Loading…</div>
|
||||||
|
) : (
|
||||||
|
rows.map((r, slot) => {
|
||||||
|
const cue = existing.get(slot)
|
||||||
|
return (
|
||||||
|
<div key={slot} className="grid grid-cols-[2rem_1fr_9rem_7.5rem] items-center gap-2 py-1">
|
||||||
|
<span className="flex h-7 w-7 items-center justify-center rounded bg-ink-800 text-xs font-bold text-text">
|
||||||
|
{slotLabel(slot)}
|
||||||
|
</span>
|
||||||
|
<select
|
||||||
|
value={r.event ?? ''}
|
||||||
|
onChange={(e) => setRow(slot, { event: (e.target.value || null) as AutoCueEvent | null })}
|
||||||
|
className="h-7 rounded-md border border-line bg-ink-850 px-2 text-sm text-text"
|
||||||
|
>
|
||||||
|
<option value="">— Leave empty —</option>
|
||||||
|
{AUTO_CUE_EVENTS.map((ev) => (
|
||||||
|
<option key={ev.id} value={ev.id}>
|
||||||
|
{ev.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<div className={`flex items-center gap-1 ${r.event ? '' : 'pointer-events-none opacity-30'}`}>
|
||||||
|
<button
|
||||||
|
onClick={() => nudge(slot, -4)}
|
||||||
|
title="4 beats earlier"
|
||||||
|
className="h-7 w-7 rounded-md border border-line bg-ink-850 text-sm text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={r.offset}
|
||||||
|
step={1}
|
||||||
|
onChange={(e) => {
|
||||||
|
const v = Math.round(Number(e.target.value))
|
||||||
|
if (isFinite(v)) setRow(slot, { offset: Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, v)) })
|
||||||
|
}}
|
||||||
|
className="h-7 w-12 rounded-md border border-line bg-ink-850 px-1 text-center text-sm tabular-nums text-text"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => nudge(slot, 4)}
|
||||||
|
title="4 beats later"
|
||||||
|
className="h-7 w-7 rounded-md border border-line bg-ink-850 text-sm text-muted hover:text-text"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{cue ? (
|
||||||
|
cue.editable ? (
|
||||||
|
<label className="flex min-w-0 items-center gap-1.5 text-xs text-muted" title={cue.name ?? ''}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={replace.has(slot)}
|
||||||
|
disabled={!r.event}
|
||||||
|
onChange={(e) =>
|
||||||
|
setReplace((s) => {
|
||||||
|
const n = new Set(s)
|
||||||
|
if (e.target.checked) n.add(slot)
|
||||||
|
else n.delete(slot)
|
||||||
|
return n
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<span className="truncate">
|
||||||
|
Replace {cue.name || formatDuration(cue.start)}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
) : (
|
||||||
|
<span className="truncate text-xs text-faint" title="This cue belongs to the beatgrid and is never replaced">
|
||||||
|
Grid cue (kept)
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-faint">Empty</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
<p className="mt-3 text-[11px] leading-relaxed text-faint">
|
||||||
|
Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a
|
||||||
|
bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept
|
||||||
|
unless you tick Replace. Your slot setup is remembered for the next track.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={busy}
|
||||||
|
className="rounded-md px-3 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={confirm}
|
||||||
|
disabled={busy || rows === null || active === 0}
|
||||||
|
className="rounded-md bg-accent px-4 py-1.5 text-sm font-semibold text-ink-950 hover:brightness-110 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{busy ? 'Analyzing…' : `Analyze & place ${active} cue${active === 1 ? '' : 's'}`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { api, type CueType, type GridMarker, type Track, type TrackCues } from '../api'
|
import {
|
||||||
|
api,
|
||||||
|
type AutoHotcuesResult,
|
||||||
|
type CuePoint,
|
||||||
|
type CueType,
|
||||||
|
type GridMarker,
|
||||||
|
type Track,
|
||||||
|
type TrackCues,
|
||||||
|
} from '../api'
|
||||||
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
|
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
|
||||||
import { slotLabeller, useCaps } from '../lib/capabilities'
|
import { slotLabeller, useCaps } from '../lib/capabilities'
|
||||||
import { CUE_TYPE_LABELS } from '../lib/cues'
|
import { CUE_TYPE_LABELS } from '../lib/cues'
|
||||||
@@ -8,6 +16,7 @@ import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
|
|||||||
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||||
import { ScratchEngine } from '../lib/scratchEngine'
|
import { ScratchEngine } from '../lib/scratchEngine'
|
||||||
import { PlaybackEngine } from '../lib/playbackEngine'
|
import { PlaybackEngine } from '../lib/playbackEngine'
|
||||||
|
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
|
||||||
import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls'
|
import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls'
|
||||||
import { GridControls } from './GridControls'
|
import { GridControls } from './GridControls'
|
||||||
import { HotcueBar } from './HotcueBar'
|
import { HotcueBar } from './HotcueBar'
|
||||||
@@ -99,7 +108,6 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
|
|||||||
const engagedRef = useRef(false) // scratch engine is dragging or coasting
|
const engagedRef = useRef(false) // scratch engine is dragging or coasting
|
||||||
const pendingPlayRef = useRef(false) // a play was requested; start once ready
|
const pendingPlayRef = useRef(false) // a play was requested; start once ready
|
||||||
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
|
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
|
||||||
const [autoBusy, setAutoBusy] = useState(false)
|
|
||||||
const [gridBusy, setGridBusy] = useState(false)
|
const [gridBusy, setGridBusy] = useState(false)
|
||||||
// Active momentary "cue preview": a hotcue OR the CUE button held while paused
|
// Active momentary "cue preview": a hotcue OR the CUE button held while paused
|
||||||
// plays from its point and stops on release, unless `latched` (play pressed
|
// plays from its point and stops on release, unless `latched` (play pressed
|
||||||
@@ -681,35 +689,31 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
|
|||||||
// Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview.
|
// Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview.
|
||||||
const onSlotRelease = (slot: number) => endPreview(`hc:${slot}`)
|
const onSlotRelease = (slot: number) => endPreview(`hc:${slot}`)
|
||||||
|
|
||||||
// Auto Hotcues: the backend analyses the track's audio (librosa structural
|
// Auto Hotcues: the button opens the slot-template dialog; the backend finds
|
||||||
// segmentation), snaps boundaries to the beatgrid, and fills empty slots only.
|
// the track's structure on its beatgrid and places the template. Requires a
|
||||||
// Requires a beatgrid (button disabled otherwise).
|
// beatgrid (button disabled otherwise) — every event is a bar on it.
|
||||||
const canAutoCue = grid != null
|
const canAutoCue = grid != null
|
||||||
const runAutoHotcues = async () => {
|
const [autoOpen, setAutoOpen] = useState(false)
|
||||||
if (!track || !canAutoCue || autoBusy) return
|
const openAutoHotcues = () => {
|
||||||
|
if (!track || !canAutoCue) return
|
||||||
if (refuseCueEdit()) return
|
if (refuseCueEdit()) return
|
||||||
const hotcueCount = (c: TrackCues | null) =>
|
setAutoOpen(true)
|
||||||
c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0
|
}
|
||||||
if (hotcueCount(cueData) >= slotCount) {
|
const existingHotcues = useMemo(() => {
|
||||||
onError?.(`No free hotcue slots (${slotCount} of ${slotCount} used) — delete some first`)
|
const m = new Map<number, CuePoint>()
|
||||||
return
|
for (const c of cueData?.cues ?? []) if (c.role === 'hotcue' && c.slot != null) m.set(c.slot, c)
|
||||||
}
|
return m
|
||||||
setAutoBusy(true)
|
}, [cueData])
|
||||||
try {
|
const autoHotcuesDone = (result: AutoHotcuesResult) => {
|
||||||
const before = hotcueCount(cueData)
|
applyCueEdit(result.cues)
|
||||||
const fresh = await api.autoCues(track.id)
|
const by = (st: string) => result.outcomes.filter((o) => o.status === st)
|
||||||
applyCueEdit(fresh)
|
const placed = by('placed').length
|
||||||
const placed = Math.max(0, hotcueCount(fresh) - before)
|
const missing = [...by('not_found'), ...by('out_of_range')].map((o) => eventLabel(o.event))
|
||||||
if (placed === 0) {
|
const kept = by('occupied').length + by('protected').length
|
||||||
onNotify?.('error', 'No clear structure found — no hotcues placed')
|
const parts = [`Placed ${placed} hotcue${placed === 1 ? '' : 's'}`]
|
||||||
} else {
|
if (missing.length) parts.push(`not in this track: ${missing.join(', ')}`)
|
||||||
onNotify?.('success', `Placed ${placed} auto hotcue${placed === 1 ? '' : 's'}`)
|
if (kept) parts.push(`${kept} occupied slot${kept === 1 ? '' : 's'} kept`)
|
||||||
}
|
onNotify?.(placed ? 'success' : 'error', parts.join(' · '))
|
||||||
} catch (e) {
|
|
||||||
onError?.((e as Error).message)
|
|
||||||
} finally {
|
|
||||||
setAutoBusy(false)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const changeSelectedType = async (type: CueType) => {
|
const changeSelectedType = async (type: CueType) => {
|
||||||
@@ -1144,16 +1148,16 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={runAutoHotcues}
|
onClick={openAutoHotcues}
|
||||||
disabled={!canAutoCue || autoBusy}
|
disabled={!canAutoCue}
|
||||||
title={
|
title={
|
||||||
canAutoCue
|
canAutoCue
|
||||||
? 'Auto-place hotcues at detected phrase boundaries (empty slots only)'
|
? 'Place hotcues on the track\'s drops, breakdowns and other sections'
|
||||||
: 'Set a beatgrid first'
|
: 'Set a beatgrid first'
|
||||||
}
|
}
|
||||||
className="flex w-16 items-center justify-center gap-1 bg-ink-900 text-[11px] font-semibold uppercase tracking-wider text-muted transition-colors hover:bg-ink-800 hover:text-accent disabled:opacity-30 disabled:hover:bg-ink-900 disabled:hover:text-muted"
|
className="flex w-16 items-center justify-center gap-1 bg-ink-900 text-[11px] font-semibold uppercase tracking-wider text-muted transition-colors hover:bg-ink-800 hover:text-accent disabled:opacity-30 disabled:hover:bg-ink-900 disabled:hover:text-muted"
|
||||||
>
|
>
|
||||||
{autoBusy ? '…' : '✨ Auto'}
|
✨ Auto
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={deleteSelected}
|
onClick={deleteSelected}
|
||||||
@@ -1167,6 +1171,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{autoOpen && track && (
|
||||||
|
<AutoCueDialog
|
||||||
|
track={track}
|
||||||
|
slotCount={slotCount}
|
||||||
|
slotLabel={slotLabel}
|
||||||
|
existing={existingHotcues}
|
||||||
|
onClose={() => setAutoOpen(false)}
|
||||||
|
onDone={autoHotcuesDone}
|
||||||
|
onError={(msg) => onError?.(msg)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user