Improved auto hot cue system

This commit is contained in:
patben8 committed 2026-09-24 13:53:42 +02:00
1 parent 6cc73267a6
commit 46ce3db916
12 files changed
+1199 -312

No files matched your search

+133
View File
@@ -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())
+86 -206
View File
@@ -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
implemented on top of librosa: beat-synchronous CQT features → a
sequence-augmented recurrence Laplacian → spectral clustering of beats into
section *types* → boundaries at type changes. This is repetition/homogeneity
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
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 user binds each hotcue slot to an EVENT ("first drop", "start of the second
breakdown", …) plus an offset in beats ("16 beats before the first drop"). The
events come from `core/structure.py`; this module is the pure part — which
slots get a cue, where, called what, and why a slot got nothing — so it is
testable without audio.
The module is split so the DSP (`detect_boundaries`, needs the audio) is
separate from the placement logic (`select_hotcues`, pure arithmetic on the
beatgrid) — the latter is unit-testable without audio.
Offsets are counted along the grid's own beats, not in seconds, so a -16 on a
flexible grid lands 16 BEATS earlier even across a tempo change.
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
import numpy as np
from dataclasses import dataclass
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
# grow if a future Traktor allows more than 8 triggerable hotcues.
MAX_HOTCUES = 8
from .structure import EVENTS, Structure
_SR = 22050
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
LABELS: dict[str, str] = {
"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]:
"""Detect structural boundaries in a track.
@dataclass(frozen=True)
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
``energy`` is that section's mean RMS normalised to 0..1 across the track
(used downstream for positional naming). Sorted by time.
@dataclass(frozen=True)
class SlotOutcome:
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
from scipy.ndimage import median_filter
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
from scipy.linalg import eigh
import sklearn.cluster
y, sr = librosa.load(audio_path, sr=sr, mono=True)
duration = len(y) / sr
if duration < 1.0:
return [], duration
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
if len(beats) < 4:
return [], duration
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
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]}")
out: list[SlotOutcome] = []
for r in requests:
if r.slot in existing and not existing[r.slot]:
out.append(SlotOutcome(r.slot, r.event, PROTECTED))
continue
if r.slot in existing and not r.overwrite:
out.append(SlotOutcome(r.slot, r.event, OCCUPIED))
continue
beat = structure.events.get(r.event)
if beat is None:
out.append(SlotOutcome(r.slot, r.event, NOT_FOUND))
continue
t = structure.beat_time(beat + r.offset_beats)
if t < 0 or t >= structure.duration:
out.append(SlotOutcome(r.slot, r.event, OUT_OF_RANGE))
continue
out.append(SlotOutcome(r.slot, r.event, PLACED, round(t, 4), cue_name(r.event, r.offset_beats)))
return out
+302
View File
@@ -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
View File
@@ -16,7 +16,7 @@ from fastapi.responses import FileResponse, JSONResponse
from . import __version__, exporter, exports, history, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect
from .core import grid_detect, structure
from . import importer
from .core import export as core_export
from .core import places, registry
@@ -33,8 +33,10 @@ from .jobs import JOBS
from .core.pathmap import PathMapping
from .schemas import (
AutoGridRequest,
AutoCueOutcome,
AutoHotcue,
AutoHotcuesRequest,
AutoHotcuesResult,
CollectionCandidate,
CollectionOptions,
CollectionStatus,
@@ -815,43 +817,58 @@ def create_cue(body: SetCue) -> TrackCues:
)
@app.post("/api/tracks/cue/auto", response_model=TrackCues)
def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
"""Analyze the track's audio and place structural hotcues into empty slots.
@app.post("/api/tracks/cue/auto", response_model=AutoHotcuesResult)
def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
"""Analyse the track's structure on its beatgrid and place the template.
Detects section boundaries (librosa Laplacian segmentation), snaps them to
the track's beatgrid phrases, names them positionally, and places up to
MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid."""
Each requested slot is bound to an event (``drop_1``, ``outro``, …) plus an
offset in beats. Every slot reports an outcome — placed, not found, out of
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()
cues = a.track_cues(body.track_id)
if cues is None:
raise HTTPException(404, "Track not found")
if not cues.grid_markers:
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)
if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
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
raise HTTPException(400, f"Analysis failed: {ex}")
slots = a.capabilities().cues.hotcue_slots
occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0}
free = [s for s in range(slots) if s not in occupied]
existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0]
specs = ah.select_hotcues(
boundaries,
markers=[(m.start, m.bpm) for m in cues.grid_markers],
duration=duration,
free_slots=free,
existing_times=existing_times,
max_cues=body.max_cues or slots,
existing = {c.slot: c.editable for c in cues.cues if c.role == "hotcue" and c.slot is not None}
outcomes = ah.plan(
found,
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots],
existing,
)
placed = [o for o in outcomes if o.status == ah.PLACED]
if placed:
# overwrite=True is safe: `plan` only passes an occupied slot when the
# user ticked it, and the adapter still refuses a protected one.
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)
+38 -1
View File
@@ -1,6 +1,8 @@
"""API response models (Pydantic)."""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
@@ -79,9 +81,37 @@ class SetCue(BaseModel):
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):
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):
@@ -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 ---------------------------------------------------
#
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
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 "▶ $t"
echo "──────────────────────────────────────────"
+210
View File
@@ -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)
+3 -44
View File
@@ -385,50 +385,9 @@ with tempfile.TemporaryDirectory() as d:
c is not None and abs(c.start - (30000.0 + i * 10000)) < 1,
)
# ---- Invariant G: select_hotcues placement logic (pure, no audio) ------
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
from konduktor.core import auto_hotcues as ah # noqa: E402
# 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 G: moved -------------------------------------------------
# Auto Hotcues' placement logic is tested in test_auto_hotcues.py, which also
# covers its structure analysis and its route.
# ---- Invariant H: path write-back is localized + round-trips -----------
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")