diff --git a/backend/konduktor/auto_hotcues.py b/backend/konduktor/auto_hotcues.py index b8afadd..55b5e45 100644 --- a/backend/konduktor/auto_hotcues.py +++ b/backend/konduktor/auto_hotcues.py @@ -96,6 +96,24 @@ def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, 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]], *, diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 0c9f7ec..a7d5885 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -19,6 +19,7 @@ from .collection_service import CollectionService from .discovery import describe, detect_collections from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( + AutoGridRequest, AutoHotcue, AutoHotcuesRequest, CollectionCandidate, @@ -480,6 +481,29 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues: 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/schemas.py b/backend/konduktor/schemas.py index 8acd3cf..2aa4fe8 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -168,6 +168,10 @@ class AutoHotcuesRequest(BaseModel): max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side +class AutoGridRequest(BaseModel): + track_id: str + + class SetHotcueType(BaseModel): track_id: str slot: int diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 233e9a2..bea43de 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -271,6 +271,9 @@ export const api = { track_id: trackId, max_cues: maxCues, }), + // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. + autoGrid: (trackId: string) => + send('POST', '/api/tracks/auto-grid', { track_id: trackId }), setHotcueType: (trackId: string, slot: number, type: number) => send('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }), deleteHotcue: (trackId: string, slot: number) => diff --git a/frontend/src/components/GridControls.tsx b/frontend/src/components/GridControls.tsx index 9b9a311..58f33a2 100644 --- a/frontend/src/components/GridControls.tsx +++ b/frontend/src/components/GridControls.tsx @@ -13,6 +13,9 @@ interface Props { onReset: () => void onToggleLock: () => void onDeleteGrid: () => void + /** Detect BPM + first beat and build the grid (sets hotcue 1 + anchor). */ + onAnalyze: () => void + analyzing: boolean } const BTN = @@ -39,6 +42,8 @@ export function GridControls({ onReset, onToggleLock, onDeleteGrid, + onAnalyze, + analyzing, }: Props) { const [editing, setEditing] = useState(false) const [val, setVal] = useState('') @@ -194,6 +199,18 @@ export function GridControls({ 🗑 Grid + + {/* analyze: detect BPM + first beat, set hotcue 1 + grid anchor */} +
+ +
) } diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 9422607..fd3d667 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -75,6 +75,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const pendingPlayRef = useRef(false) // a play was requested; start once ready const loadedIdRef = useRef(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 // plays from its point and stops on release, unless `latched` (play pressed // during the hold). `id` identifies the holder so its release matches. @@ -717,13 +718,26 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) 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 showWaves = track && cols && waveStatus === 'ready' const activeLoop = loopActive && loopRegion ? loopRegion : null return ( -
+
{/* Controls */}
@@ -755,6 +769,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) onReset={resetGrid} onToggleLock={toggleLock} onDeleteGrid={deleteGrid} + onAnalyze={runAnalyzeGrid} + analyzing={gridBusy} /> )}