mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
10 files changed
+522
-8
No files matched your search
@@ -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
|
||||||
@@ -13,11 +13,15 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from . import auto_hotcues as ah
|
||||||
from . import prefs
|
from . import prefs
|
||||||
from .collection_service import CollectionService
|
from .collection_service import CollectionService
|
||||||
from .discovery import describe, detect_collections
|
from .discovery import describe, detect_collections
|
||||||
from .playlist_store import PlaylistError, PlaylistStore
|
from .playlist_store import PlaylistError, PlaylistStore
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
|
AutoGridRequest,
|
||||||
|
AutoHotcue,
|
||||||
|
AutoHotcuesRequest,
|
||||||
CollectionCandidate,
|
CollectionCandidate,
|
||||||
CollectionOptions,
|
CollectionOptions,
|
||||||
CollectionStatus,
|
CollectionStatus,
|
||||||
@@ -426,13 +430,80 @@ def create_hotcue(body: SetHotcue) -> TrackCues:
|
|||||||
"""Create (or reposition + retype) the hotcue in a slot at a position."""
|
"""Create (or reposition + retype) the hotcue in a slot at a position."""
|
||||||
try:
|
try:
|
||||||
require_store().set_hotcue(
|
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:
|
except PlaylistError as ex:
|
||||||
raise HTTPException(400, str(ex))
|
raise HTTPException(400, str(ex))
|
||||||
return _sync_cue_edit(body.track_id)
|
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)
|
@app.patch("/api/tracks/hotcue", response_model=TrackCues)
|
||||||
def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
|
def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
|
||||||
"""Change the type of an existing hotcue (keeps its position)."""
|
"""Change the type of an existing hotcue (keeps its position)."""
|
||||||
|
|||||||
@@ -282,11 +282,18 @@ class PlaylistStore:
|
|||||||
return entry
|
return entry
|
||||||
|
|
||||||
def set_hotcue(
|
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:
|
) -> None:
|
||||||
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
|
"""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:
|
if not 0 <= slot <= 7:
|
||||||
raise PlaylistError(f"Invalid hotcue slot: {slot}")
|
raise PlaylistError(f"Invalid hotcue slot: {slot}")
|
||||||
if cue_type not in self.CREATABLE_TYPES:
|
if cue_type not in self.CREATABLE_TYPES:
|
||||||
@@ -307,7 +314,7 @@ class PlaylistStore:
|
|||||||
entry.cue_v2 = []
|
entry.cue_v2 = []
|
||||||
entry.cue_v2.append(
|
entry.cue_v2.append(
|
||||||
CueV2Type(
|
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,
|
displ_order=0,
|
||||||
type=cue_type,
|
type=cue_type,
|
||||||
start=start_ms,
|
start=start_ms,
|
||||||
@@ -320,6 +327,30 @@ class PlaylistStore:
|
|||||||
)
|
)
|
||||||
self.dirty = True
|
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:
|
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)."""
|
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||||
if cue_type not in self.POINT_CUE_TYPES:
|
if cue_type not in self.POINT_CUE_TYPES:
|
||||||
|
|||||||
@@ -152,6 +152,24 @@ class SetHotcue(BaseModel):
|
|||||||
start: float # seconds
|
start: float # seconds
|
||||||
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
|
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
|
||||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
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):
|
class SetHotcueType(BaseModel):
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ uvicorn[standard]>=0.34
|
|||||||
pydantic>=2.11
|
pydantic>=2.11
|
||||||
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
|
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
|
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),
|
# 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.
|
# 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
|
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
||||||
@@ -292,5 +292,99 @@ with tempfile.TemporaryDirectory() as d:
|
|||||||
store2.save()
|
store2.save()
|
||||||
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
|
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"<ENTRY ", 0, i)
|
||||||
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
# Establish a hand-placed hotcue as the baseline the batch must NOT overwrite.
|
||||||
|
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
||||||
|
hand_slot = next(s for s in range(8) if s not in used)
|
||||||
|
store.set_hotcue(track_id, hand_slot, 12.0, 0, name="HAND-PLACED")
|
||||||
|
store.save()
|
||||||
|
original = work.read_bytes()
|
||||||
|
|
||||||
|
# Batch: one spec targets the occupied slot (must be skipped), two fill free slots.
|
||||||
|
store2 = PlaylistStore(work)
|
||||||
|
e2 = store2._nml.collection.entry[0]
|
||||||
|
now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
||||||
|
free = [s for s in range(8) if s not in now_used][:2]
|
||||||
|
specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")]
|
||||||
|
specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
|
||||||
|
store2.place_hotcues(track_id, specs)
|
||||||
|
store2.save()
|
||||||
|
edited = work.read_bytes()
|
||||||
|
|
||||||
|
check("file actually changed", original != edited)
|
||||||
|
|
||||||
|
os_, oe = entry_span(original, loc.file)
|
||||||
|
es_, ee = entry_span(edited, loc.file)
|
||||||
|
check(
|
||||||
|
"everything outside the edited track's ENTRY is byte-identical",
|
||||||
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
||||||
|
)
|
||||||
|
n = diff_count(original[os_:oe], edited[es_:ee])
|
||||||
|
check(f"edited ENTRY diff is small (<= 6 tag-lines for {len(free)} cues)", n <= 6, f"got {n}")
|
||||||
|
|
||||||
|
reparsed = TraktorCollection(path=work)
|
||||||
|
e0 = reparsed.nml.collection.entry[0]
|
||||||
|
hand = next((c for c in (e0.cue_v2 or []) if c.hotcue == hand_slot), None)
|
||||||
|
check("hand-placed hotcue NOT overwritten (position)", hand is not None and abs(hand.start - 12000.0) < 1)
|
||||||
|
check("hand-placed hotcue NOT overwritten (name)", hand is not None and hand.name == "HAND-PLACED")
|
||||||
|
for i, s in enumerate(free):
|
||||||
|
c = next((c for c in (e0.cue_v2 or []) if c.hotcue == s), None)
|
||||||
|
check(f"auto hotcue slot {s} created", c is not None)
|
||||||
|
check(f"auto hotcue slot {s} name round-trips", c is not None and c.name == f"Auto {i}")
|
||||||
|
check(
|
||||||
|
f"auto hotcue slot {s} START in ms",
|
||||||
|
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 import auto_hotcues as ah # noqa: E402
|
||||||
|
|
||||||
|
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; anchor 0.0.
|
||||||
|
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
|
||||||
|
# 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, bpm=BPM, anchor=ANCHOR, 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, bpm=BPM, anchor=ANCHOR, 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, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
|
||||||
|
|
||||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||||
sys.exit(1 if failed else 0)
|
sys.exit(1 if failed else 0)
|
||||||
@@ -260,7 +260,7 @@ export default function App() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Prep strip spans the top of the window; the library sits below it. */}
|
{/* Prep strip spans the top of the window; the library sits below it. */}
|
||||||
<PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} />
|
<PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} onNotify={notify} />
|
||||||
|
|
||||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||||
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
||||||
|
|||||||
+18
-1
@@ -249,14 +249,31 @@ export const api = {
|
|||||||
`${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
|
`${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
|
||||||
trackCues: (trackId: string) =>
|
trackCues: (trackId: string) =>
|
||||||
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
|
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
|
||||||
createHotcue: (trackId: string, slot: number, start: number, type: number, length = 0) =>
|
createHotcue: (
|
||||||
|
trackId: string,
|
||||||
|
slot: number,
|
||||||
|
start: number,
|
||||||
|
type: number,
|
||||||
|
length = 0,
|
||||||
|
name?: string,
|
||||||
|
) =>
|
||||||
send<TrackCues>('POST', '/api/tracks/hotcue', {
|
send<TrackCues>('POST', '/api/tracks/hotcue', {
|
||||||
track_id: trackId,
|
track_id: trackId,
|
||||||
slot,
|
slot,
|
||||||
start,
|
start,
|
||||||
type,
|
type,
|
||||||
length,
|
length,
|
||||||
|
name,
|
||||||
}),
|
}),
|
||||||
|
// Backend analyses the audio and places structural hotcues into empty slots.
|
||||||
|
autoHotcues: (trackId: string, maxCues?: number) =>
|
||||||
|
send<TrackCues>('POST', '/api/tracks/auto-hotcues', {
|
||||||
|
track_id: trackId,
|
||||||
|
max_cues: maxCues,
|
||||||
|
}),
|
||||||
|
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
|
||||||
|
autoGrid: (trackId: string) =>
|
||||||
|
send<TrackCues>('POST', '/api/tracks/auto-grid', { track_id: trackId }),
|
||||||
setHotcueType: (trackId: string, slot: number, type: number) =>
|
setHotcueType: (trackId: string, slot: number, type: number) =>
|
||||||
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }),
|
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }),
|
||||||
deleteHotcue: (trackId: string, slot: number) =>
|
deleteHotcue: (trackId: string, slot: number) =>
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ interface Props {
|
|||||||
onReset: () => void
|
onReset: () => void
|
||||||
onToggleLock: () => void
|
onToggleLock: () => void
|
||||||
onDeleteGrid: () => void
|
onDeleteGrid: () => void
|
||||||
|
/** Detect BPM + first beat and build the grid (sets hotcue 1 + anchor). */
|
||||||
|
onAnalyze: () => void
|
||||||
|
analyzing: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const BTN =
|
const BTN =
|
||||||
@@ -39,6 +42,8 @@ export function GridControls({
|
|||||||
onReset,
|
onReset,
|
||||||
onToggleLock,
|
onToggleLock,
|
||||||
onDeleteGrid,
|
onDeleteGrid,
|
||||||
|
onAnalyze,
|
||||||
|
analyzing,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [editing, setEditing] = useState(false)
|
const [editing, setEditing] = useState(false)
|
||||||
const [val, setVal] = useState('')
|
const [val, setVal] = useState('')
|
||||||
@@ -194,6 +199,18 @@ export function GridControls({
|
|||||||
🗑 Grid
|
🗑 Grid
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* analyze: detect BPM + first beat, set hotcue 1 + grid anchor */}
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<button
|
||||||
|
className={BTN}
|
||||||
|
onClick={onAnalyze}
|
||||||
|
disabled={analyzing}
|
||||||
|
title="Detect BPM and first beat, then set the grid + hotcue 1 (fix octave with ÷2 / ×2)"
|
||||||
|
>
|
||||||
|
{analyzing ? '…' : 'Analyze'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -16,6 +16,8 @@ interface Props {
|
|||||||
/** Bumped by the library's per-row play button to load + auto-play. */
|
/** Bumped by the library's per-row play button to load + auto-play. */
|
||||||
playRequest?: number
|
playRequest?: number
|
||||||
onError?: (msg: string) => void
|
onError?: (msg: string) => void
|
||||||
|
/** Neutral/success feedback (e.g. Auto Hotcues result). */
|
||||||
|
onNotify?: (kind: 'success' | 'error', msg: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
function fmt(secs: number): string {
|
function fmt(secs: number): string {
|
||||||
@@ -41,7 +43,7 @@ const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32]
|
|||||||
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
|
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
|
||||||
* scratch engine and both waveform views.
|
* scratch engine and both waveform views.
|
||||||
*/
|
*/
|
||||||
export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) {
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient()
|
||||||
const [playing, setPlaying] = useState(false)
|
const [playing, setPlaying] = useState(false)
|
||||||
const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active
|
const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active
|
||||||
@@ -72,6 +74,8 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
|||||||
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)
|
||||||
// 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
|
||||||
// during the hold). `id` identifies the holder so its release matches.
|
// during the hold). `id` identifies the holder so its release matches.
|
||||||
@@ -553,6 +557,36 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
|||||||
// 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
|
||||||
|
// segmentation), snaps boundaries to the beatgrid, and fills empty slots only.
|
||||||
|
// Requires a beatgrid (button disabled otherwise).
|
||||||
|
const canAutoCue = !!(cueData?.bpm && cueData.bpm > 0 && cueData.grid_anchor != null)
|
||||||
|
const runAutoHotcues = async () => {
|
||||||
|
if (!track || !canAutoCue || autoBusy) return
|
||||||
|
const hotcueCount = (c: TrackCues | null) =>
|
||||||
|
c?.cues.filter((x) => x.hotcue >= 0).length ?? 0
|
||||||
|
if (hotcueCount(cueData) >= 8) {
|
||||||
|
onError?.('No free hotcue slots — delete some first')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setAutoBusy(true)
|
||||||
|
try {
|
||||||
|
const before = hotcueCount(cueData)
|
||||||
|
const fresh = await api.autoHotcues(track.id)
|
||||||
|
applyCueEdit(fresh)
|
||||||
|
const placed = Math.max(0, hotcueCount(fresh) - before)
|
||||||
|
if (placed === 0) {
|
||||||
|
onNotify?.('error', 'No clear structure found — no hotcues placed')
|
||||||
|
} else {
|
||||||
|
onNotify?.('success', `Placed ${placed} auto hotcue${placed === 1 ? '' : 's'}`)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
onError?.((e as Error).message)
|
||||||
|
} finally {
|
||||||
|
setAutoBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const changeSelectedType = async (type: number) => {
|
const changeSelectedType = async (type: number) => {
|
||||||
if (!track || selectedSlot == null) return
|
if (!track || selectedSlot == null) return
|
||||||
try {
|
try {
|
||||||
@@ -684,13 +718,26 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
|||||||
onError?.((e as Error).message)
|
onError?.((e as Error).message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1.
|
||||||
|
const runAnalyzeGrid = async () => {
|
||||||
|
if (!track || gridBusy) return
|
||||||
|
setGridBusy(true)
|
||||||
|
try {
|
||||||
|
applyCueEdit(await api.autoGrid(track.id))
|
||||||
|
onNotify?.('success', 'Analyzed — set BPM, grid, and hotcue 1')
|
||||||
|
} catch (e) {
|
||||||
|
onError?.((e as Error).message)
|
||||||
|
} finally {
|
||||||
|
setGridBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
|
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
|
||||||
const showWaves = track && cols && waveStatus === 'ready'
|
const showWaves = track && cols && waveStatus === 'ready'
|
||||||
const activeLoop = loopActive && loopRegion ? loopRegion : null
|
const activeLoop = loopActive && loopRegion ? loopRegion : null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-[21rem] shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
|
<div className="flex h-[23rem] shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
|
||||||
{/* Controls */}
|
{/* Controls */}
|
||||||
<div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3">
|
<div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
@@ -722,6 +769,8 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
|||||||
onReset={resetGrid}
|
onReset={resetGrid}
|
||||||
onToggleLock={toggleLock}
|
onToggleLock={toggleLock}
|
||||||
onDeleteGrid={deleteGrid}
|
onDeleteGrid={deleteGrid}
|
||||||
|
onAnalyze={runAnalyzeGrid}
|
||||||
|
analyzing={gridBusy}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -863,6 +912,18 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
|||||||
</select>
|
</select>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={runAutoHotcues}
|
||||||
|
disabled={!canAutoCue || autoBusy}
|
||||||
|
title={
|
||||||
|
canAutoCue
|
||||||
|
? 'Auto-place hotcues at detected phrase boundaries (empty slots only)'
|
||||||
|
: '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"
|
||||||
|
>
|
||||||
|
{autoBusy ? '…' : '✨ Auto'}
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={deleteSelected}
|
onClick={deleteSelected}
|
||||||
disabled={!selectedCue}
|
disabled={!selectedCue}
|
||||||
|
|||||||
Reference in new issue
Block a user