diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py
new file mode 100644
index 0000000..55b5e45
--- /dev/null
+++ b/backend/konduktor/auto_hotcues.py
@@ -0,0 +1,201 @@
+"""Auto Hotcues — structural boundary detection for DJ cue placement.
+
+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 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.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+
+# 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
+
+_SR = 22050
+_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
+
+
+def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
+ """Detect structural boundaries in a track.
+
+ 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.
+ """
+ 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 detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
+ """Detect a track's tempo and the time of its first beat.
+
+ Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
+ anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
+ left for the user to fix with the ×2 / ÷2 controls (per product decision).
+ """
+ import librosa
+
+ y, sr = librosa.load(audio_path, sr=sr, mono=True)
+ tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
+ bpm = float(np.ravel(tempo)[0])
+ if bpm <= 0 or len(beats) == 0:
+ raise ValueError("Could not detect a tempo/beat")
+ first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
+ return bpm, first_beat
+
+
+def select_hotcues(
+ boundaries: list[tuple[float, float]],
+ *,
+ bpm: float,
+ anchor: 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.
+
+ Snaps each boundary to the nearest ``phrase_bars``-bar grid point (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 bpm <= 0:
+ return []
+
+ beat = 60.0 / bpm
+ phrase = phrase_bars * 4 * beat # seconds per phrase
+
+ # Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
+ snapped: dict[float, float] = {}
+ for t, energy in boundaries:
+ p = anchor + round((t - anchor) / phrase) * phrase
+ 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
diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py
index 3b9fc72..a7d5885 100644
--- a/backend/konduktor/main.py
+++ b/backend/konduktor/main.py
@@ -13,11 +13,15 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
+from . import auto_hotcues as ah
from . import prefs
from .collection_service import CollectionService
from .discovery import describe, detect_collections
from .playlist_store import PlaylistError, PlaylistStore
from .schemas import (
+ AutoGridRequest,
+ AutoHotcue,
+ AutoHotcuesRequest,
CollectionCandidate,
CollectionOptions,
CollectionStatus,
@@ -426,13 +430,80 @@ def create_hotcue(body: SetHotcue) -> TrackCues:
"""Create (or reposition + retype) the hotcue in a slot at a position."""
try:
require_store().set_hotcue(
- body.track_id, body.slot, body.start, body.type, body.length
+ body.track_id, body.slot, body.start, body.type, body.length, name=body.name
)
except PlaylistError as ex:
raise HTTPException(400, str(ex))
return _sync_cue_edit(body.track_id)
+@app.post("/api/tracks/auto-hotcues", response_model=TrackCues)
+def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
+ """Analyze the track's audio and place structural hotcues into empty slots.
+
+ 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."""
+ store = require_store()
+ entry = store.model_entry(body.track_id)
+ if entry is None:
+ raise HTTPException(404, "Track not found")
+ cues = _build_track_cues(entry)
+ if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None:
+ raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
+ path = store.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))
+ except Exception as ex: # analysis is best-effort; never 500 the UI
+ raise HTTPException(400, f"Analysis failed: {ex}")
+
+ occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0}
+ free = [s for s in range(ah.MAX_HOTCUES) 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,
+ bpm=cues.bpm,
+ anchor=cues.grid_anchor,
+ duration=duration,
+ free_slots=free,
+ existing_times=existing_times,
+ max_cues=body.max_cues or ah.MAX_HOTCUES,
+ )
+ if not specs:
+ return cues # no confident structure / no free slots — leave untouched
+ try:
+ store.place_hotcues(body.track_id, [AutoHotcue(**s) for s in specs])
+ except PlaylistError as ex:
+ raise HTTPException(400, str(ex))
+ return _sync_cue_edit(body.track_id)
+
+
+@app.post("/api/tracks/auto-grid", response_model=TrackCues)
+def auto_grid(body: AutoGridRequest) -> TrackCues:
+ """Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1
+ (slot 0) to the first beat, and anchors the grid to that position. Octave
+ (half/double) errors are left for the user to fix with the ×2/÷2 controls."""
+ store = require_store()
+ if store.model_entry(body.track_id) is None:
+ raise HTTPException(404, "Track not found")
+ path = store.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:
+ bpm, first_beat = ah.detect_grid(str(path))
+ except Exception as ex: # analysis is best-effort; never 500 the UI
+ raise HTTPException(400, f"Analysis failed: {ex}")
+ try:
+ store.set_grid(body.track_id, bpm=bpm, anchor_sec=first_beat)
+ store.set_hotcue(body.track_id, 0, first_beat, 0) # hotcue 1 = slot 0
+ except PlaylistError as ex:
+ raise HTTPException(400, str(ex))
+ return _sync_cue_edit(body.track_id)
+
+
@app.patch("/api/tracks/hotcue", response_model=TrackCues)
def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
"""Change the type of an existing hotcue (keeps its position)."""
diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py
index c1b9715..b89d7f2 100644
--- a/backend/konduktor/playlist_store.py
+++ b/backend/konduktor/playlist_store.py
@@ -282,11 +282,18 @@ class PlaylistStore:
return entry
def set_hotcue(
- self, track_id: str, slot: int, start_sec: float, cue_type: int, length_sec: float = 0.0
+ self,
+ track_id: str,
+ slot: int,
+ start_sec: float,
+ cue_type: int,
+ length_sec: float = 0.0,
+ name: str | None = None,
) -> None:
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
- `length_sec` > 0 makes it a loop (used with cue_type 5)."""
+ `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the
+ cue label on create; when unset it falls back to Traktor's "n.n."."""
if not 0 <= slot <= 7:
raise PlaylistError(f"Invalid hotcue slot: {slot}")
if cue_type not in self.CREATABLE_TYPES:
@@ -307,7 +314,7 @@ class PlaylistStore:
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
- name="n.n.", # Traktor's default name for a manual cue
+ name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
@@ -320,6 +327,30 @@ class PlaylistStore:
)
self.dirty = True
+ def place_hotcues(
+ self, track_id: str, specs: list, *, overwrite: bool = False
+ ) -> None:
+ """Batch-create hotcues from `specs` (each has .slot/.start/.name and
+ optional .type/.length). With `overwrite` False (the default), slots that
+ already hold a hotcue are skipped so hand-placed cues are never clobbered.
+ Used by Auto Hotcues."""
+ with self._lock:
+ entry = self._entry_or_raise(track_id)
+ occupied = {
+ c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
+ }
+ for spec in specs:
+ if not overwrite and spec.slot in occupied:
+ continue
+ self.set_hotcue(
+ track_id,
+ spec.slot,
+ spec.start,
+ getattr(spec, "type", 0),
+ getattr(spec, "length", 0.0),
+ name=getattr(spec, "name", None),
+ )
+
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
if cue_type not in self.POINT_CUE_TYPES:
diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py
index a33d461..2aa4fe8 100644
--- a/backend/konduktor/schemas.py
+++ b/backend/konduktor/schemas.py
@@ -152,6 +152,24 @@ class SetHotcue(BaseModel):
start: float # seconds
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
length: float = 0.0 # seconds (>0 for a loop hotcue)
+ name: str | None = None # cue label; defaults to Traktor's "n.n." when unset
+
+
+class AutoHotcue(BaseModel):
+ slot: int # 0–7
+ start: float # seconds
+ name: str | None = None # positional label (e.g. "Drop")
+ type: int = 0 # plain cue
+ length: float = 0.0 # seconds (>0 for a loop hotcue)
+
+
+class AutoHotcuesRequest(BaseModel):
+ track_id: str
+ max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side
+
+
+class AutoGridRequest(BaseModel):
+ track_id: str
class SetHotcueType(BaseModel):
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 8551c76..ce709d3 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -5,6 +5,10 @@ uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
+# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
+# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
+librosa>=0.11
+scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py
index 1d140cf..6e335fb 100644
--- a/backend/test_save_fidelity.py
+++ b/backend/test_save_fidelity.py
@@ -292,5 +292,99 @@ with tempfile.TemporaryDirectory() as d:
store2.save()
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
+# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
+print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
+with tempfile.TemporaryDirectory() as d:
+ from konduktor.schemas import AutoHotcue
+ from traktor_nml_utils import TraktorCollection
+
+ work = Path(d) / "collection.nml"
+ shutil.copy2(REAL, work)
+
+ store = PlaylistStore(work)
+ entry = store._nml.collection.entry[0]
+ loc = entry.location
+ track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
+
+ def entry_span(data: bytes, file_name: str):
+ marker = f'FILE="{file_name}"'.encode()
+ i = data.find(marker)
+ start = data.rfind(b"