From 532dc5d6ac547caf3070b649ee4d2da016d0e75e Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Fri, 25 Sep 2026 10:46:31 +0200 Subject: [PATCH] Added context option to multi analyze --- CLAUDE.md | 7 ++ backend/konduktor/main.py | 74 ++++++++++- backend/konduktor/schemas.py | 7 ++ backend/run_tests.sh | 2 +- backend/test_grid_batch.py | 114 +++++++++++++++++ frontend/src/App.tsx | 118 +++++++++++++++++- frontend/src/api.ts | 16 +++ frontend/src/components/AnalyzeGridDialog.tsx | 83 ++++++++++++ frontend/src/components/ContextMenu.tsx | 11 +- frontend/src/components/PrepStrip.tsx | 25 +++- frontend/src/components/StatusBar.tsx | 41 +++++- 11 files changed, 486 insertions(+), 12 deletions(-) create mode 100644 backend/test_grid_batch.py create mode 100644 frontend/src/components/AnalyzeGridDialog.tsx diff --git a/CLAUDE.md b/CLAUDE.md index dc7119a..68c964d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -487,6 +487,13 @@ serialization path.** It enforces: (across a tempo change), and the ROUTE end to end on a temp copy of the real collection — the previous implementation's route returned 500 on every call for a week while its helper's tests passed. +- `test_grid_batch.py` — **batch grid analysis** (context menu → Analyze Grid & + BPM → `POST /api/tracks/grid/auto-batch`, a `jobs.py` job shown in the status + bar). Pins the batch-only decisions: locked grids are skipped always, existing + grids unless `replace_existing`, a failing track is reported not fatal, one + run at a time, a cancel KEEPS finished tracks (unsaved edits like any other) + and still returns its result, and opening another library cancels the run. + Shares `_analyse_grid` with the deck's single-track Analyze. - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it replaced was invisible: `/api/library/options` flattened every driver's detections and returned `[0]`, so a plugged-in USB stick could be offered as diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 651936f..dc4386b 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -32,6 +32,7 @@ from .core.capabilities import Capabilities from .jobs import JOBS from .core.pathmap import PathMapping from .schemas import ( + AutoGridBatchRequest, AutoGridRequest, AutoCueOutcome, AutoHotcue, @@ -147,6 +148,9 @@ def open_collection(body: OpenCollection) -> CollectionStatus: # This checks only that the path is there at all; `can_open()` decides. if not path.exists(): raise HTTPException(400, f"Not found: {path}") + # A running analysis writes into the library being replaced; stop it. + for job in JOBS.active(GRID_JOB): + JOBS.cancel(job.id) try: STATE.open(path) except AdapterError as ex: @@ -886,16 +890,78 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: a = require_adapter() if a.track(body.track_id) is None: raise HTTPException(404, "Track not found") - path = a.audio_path(body.track_id) + try: + return _analyse_grid(a, body.track_id) + except _GridAnalysisError as ex: + raise HTTPException(400, str(ex)) + + +class _GridAnalysisError(Exception): + """A track that could not be analysed; the message is user-facing.""" + + +def _analyse_grid(a, track_id: str) -> TrackCues: + """Detect and write one track's grid — shared by the deck's Analyze and the + batch job, so the two cannot come to mean different things.""" + path = a.audio_path(track_id) if path is None or not path.exists(): - raise HTTPException(400, "Audio file not found (is the drive mounted?)") + raise _GridAnalysisError("Audio file not found (is the drive mounted?)") try: found = grid_detect.detect_grid(str(path)) except Exception as ex: # analysis is best-effort; never 500 the UI - raise HTTPException(400, f"Analysis failed: {ex}") + raise _GridAnalysisError(f"Analysis failed: {ex}") from ex # "Analysed", not "replace": each platform writes an analysis result in its # own shape (Traktor pairs the first marker with a beat-1 cue). - return a.set_analysed_grid(body.track_id, [(found.anchor, found.bpm)]) + return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) + + +GRID_JOB = "grid-analysis" + + +@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) +def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: + """Analyse many tracks' grids as a JOB; poll `/api/jobs/{id}`. + + Each track is written as it finishes, into the in-memory model like any + other edit — so a cancel keeps what is done (it is all unsaved until Save), + and the result is returned even from a cancelled run. A track that fails is + reported and skipped, never fatal: one unmounted drive must not stop 400 + other tracks.""" + a = require_adapter() + if not a.capabilities().grid.editable: + raise HTTPException(422, "This library's beatgrids cannot be edited") + # One at a time: two runs over overlapping selections would analyse the + # same track twice and race on its grid. + if JOBS.active(GRID_JOB): + raise HTTPException(409, "Grid analysis is already running") + ids = list(dict.fromkeys(body.track_ids)) + + def run(handle) -> dict: + result = {"analysed": [], "locked": 0, "existing": 0, "failed": []} + handle.progress(done=0, total=len(ids)) + for i, track_id in enumerate(ids): + if handle.cancelled: + break # keep what is done; return it rather than raise + track = a.track(track_id) + title = (track.title or track_id) if track else track_id + handle.progress(message=title) + if track is None: + result["failed"].append({"title": title, "reason": "Track not found"}) + elif track.grid_locked: + result["locked"] += 1 + elif track.grid_marker_count > 0 and not body.replace_existing: + result["existing"] += 1 + else: + try: + _analyse_grid(a, track_id) + result["analysed"].append(track_id) + except (_GridAnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": str(ex)}) + handle.progress(done=i + 1) + return result + + job = JOBS.submit(GRID_JOB, run) + return JobStatus(**job.as_dict()) @app.patch("/api/tracks/cue", response_model=TrackCues) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index e740bd0..089b572 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -119,6 +119,13 @@ class AutoGridRequest(BaseModel): track_id: str +class AutoGridBatchRequest(BaseModel): + track_ids: list[str] + # False skips tracks that already have a grid. Locked grids are skipped + # either way: a lock is the user saying "never re-analyse this". + replace_existing: bool = False + + class SetCueType(BaseModel): track_id: str slot: int diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 8431183..f475c55 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -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_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 +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_grid_batch.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 "──────────────────────────────────────────" diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py new file mode 100644 index 0000000..c142c9a --- /dev/null +++ b/backend/test_grid_batch.py @@ -0,0 +1,114 @@ +"""Batch grid analysis — the route and its job, on a temp copy of the collection. + +Detection itself is `test_grid_detect.py`'s job; this pins the WIRING, and the +decisions only the batch makes: locked grids are skipped always, existing grids +only when asked, a failing track is reported and skipped rather than fatal, a +cancel keeps what is done, and nothing reaches disk before Save. +""" +from __future__ import annotations + +import os +import shutil +import tempfile +import time +from pathlib import Path +from types import SimpleNamespace + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" {'✓' if cond else '✗'} {label}" + ("" if cond else f" [{detail}]")) + if not cond: + failed = True + + +def wait(c, job_id, timeout=30.0): + end = time.time() + timeout + while time.time() < end: + j = c.get(f"/api/jobs/{job_id}").json() + if j["state"] != "running": + return j + time.sleep(0.02) + raise AssertionError("job did not finish") + + +print("== batch grid analysis ==") +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 + + detected: list[str] = [] + + def fake_detect(path, *a, **k): + detected.append(path) + return SimpleNamespace(anchor=0.123, bpm=127.5) + + main.grid_detect.detect_grid = fake_detect + + with TestClient(main.app, raise_server_exceptions=False) as c: + a = main.require_adapter() + missing = next(t.id for t in a.tracks if t.grid_marker_count == 0) + a.audio_path = lambda tid: None if tid == missing else Path(__file__) + + gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:2] + bare = [t.id for t in a.tracks if t.grid_marker_count == 0 and t.id != missing][:2] + locked = gridded[1] + a.set_grid_lock(locked, True) + ids = [gridded[0], locked, *bare, missing] + + # The deck's single-track Analyze shares the batch's helper. + r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]}) + check("single-track Analyze still answers 200", r.status_code == 200, r.text[:200]) + r = c.post("/api/tracks/grid/auto", json={"track_id": missing}) + check("…and 400 on a missing file", r.status_code == 400, r.text[:200]) + a.delete_grid(bare[1]) + + r = c.post("/api/tracks/grid/auto-batch", json={"track_ids": ids}) + check("the route starts a job", r.status_code == 200, r.text[:200]) + j = wait(c, r.json()["id"]) + res = j["result"] + check("the job finishes", j["state"] == "done", str(j)) + check("progress reaches the total", j["done"] == j["total"] == len(ids), str(j)) + check("tracks without a grid are analysed", res["analysed"] == bare, str(res)) + check("an existing grid is skipped by default", res["existing"] == 1, str(res)) + check("a locked grid is skipped", res["locked"] == 1, str(res)) + check("a missing file is reported, not fatal", + len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res)) + g = a.track_cues(bare[0]).grid_markers + check("the analysed grid is written", len(g) == 1 and abs(g[0].bpm - 127.5) < 1e-6, str(g)) + + r = c.post("/api/tracks/grid/auto-batch", + json={"track_ids": [gridded[0], locked], "replace_existing": True}) + res = wait(c, r.json()["id"])["result"] + check("replace_existing re-analyses an existing grid", res["analysed"] == [gridded[0]], str(res)) + check("…but never a locked one", res["locked"] == 1, str(res)) + + # Cancel: a slow detector gives the cancel time to land mid-run. + main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1] + many = [t.id for t in a.tracks if not t.grid_locked][:40] + r = c.post("/api/tracks/grid/auto-batch", + json={"track_ids": many, "replace_existing": True}) + jid = r.json()["id"] + r2 = c.post("/api/tracks/grid/auto-batch", json={"track_ids": many}) + check("a second run while one is going is refused", r2.status_code == 409, r2.text[:200]) + time.sleep(0.2) + c.post(f"/api/jobs/{jid}/cancel") + j = wait(c, jid) + check("a cancelled run says so", j["state"] == "cancelled", str(j)) + n = len(j["result"]["analysed"]) if j["result"] else -1 + check("…and still returns what it finished", 0 < n < len(many), str(n)) + + 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) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ca022bd..fe67572 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -3,7 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import { CapabilitiesContext } from './lib/capabilities' import { writeHint } from './lib/platformCopy' -import { api, type PlaylistNode, type Track } from './api' +import { api, type GridBatchResult, type PlaylistNode, type Track } from './api' import { DEFAULT_COLUMN_ORDER, DEFAULT_COLUMN_VISIBILITY, @@ -16,6 +16,7 @@ import { Toast, type ToastMsg } from './components/Toast' import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu, type MenuItem } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' +import { AnalyzeGridDialog } from './components/AnalyzeGridDialog' import { PathMappingDialog } from './components/PathMappingDialog' import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' @@ -58,6 +59,14 @@ export default function App() { const [prepTrack, setPrepTrack] = useState(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [importing, setImporting] = useState(false) + // Batch grid analysis: the confirm step (only when some tracks already have + // a grid), then the running job, polled into the status bar. + const [gridConfirm, setGridConfirm] = useState< + { ids: string[]; existing: number; locked: number } | null + >(null) + const [gridJobId, setGridJobId] = useState(null) + const [gridCancelling, setGridCancelling] = useState(false) + const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues const playTrack = useCallback((t: Track) => { setPrepTrack(t) @@ -387,10 +396,55 @@ export default function App() { [reorderPlaylist, tracks], ) + const gridJob = useQuery({ + queryKey: ['job', gridJobId], + queryFn: () => api.job(gridJobId!), + enabled: !!gridJobId, + refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400), + }) + const gridDone = gridJob.data?.done ?? 0 + useEffect(() => { + // Each finished track is an unsaved edit; let the Save button know as they land. + if (gridDone > 0) qc.invalidateQueries({ queryKey: ['state'] }) + }, [gridDone, qc]) + useEffect(() => { + const job = gridJob.data + if (!job || job.state === 'running') return + setGridJobId(null) + setGridCancelling(false) + if (job.state === 'failed') { + onError(`Grid analysis failed: ${job.error ?? 'unknown error'}`) + return + } + const r = job.result as unknown as GridBatchResult | null + if (!r) return + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['tracks'] }) + qc.invalidateQueries({ queryKey: ['playlist'] }) + qc.invalidateQueries({ queryKey: ['export-tracks'] }) + qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] }) + qc.invalidateQueries({ queryKey: ['export-loose'] }) + qc.invalidateQueries({ queryKey: ['facets'] }) + if (prepTrack && r.analysed.includes(prepTrack.id)) setCuesRefresh((n) => n + 1) + const n = r.analysed.length + const parts = [ + `${job.state === 'cancelled' ? 'Cancelled — analyzed' : 'Analyzed'} ${n} track${n === 1 ? '' : 's'}`, + r.existing ? `skipped ${r.existing} with a grid` : '', + r.locked ? `${r.locked} locked` : '', + r.failed.length + ? `${r.failed.length} failed (${r.failed[0].title}: ${r.failed[0].reason}${r.failed.length > 1 ? ', …' : ''})` + : '', + ].filter(Boolean) + notify(r.failed.length && n === 0 ? 'error' : 'success', parts.join(' · ')) + // Only the job's finish matters here; prepTrack is read, not tracked. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [gridJob.data]) + const handleOpened = () => { setForcePicker(false) setSource({ kind: 'all' }) setSelected(new Set()) + setGridJobId(null) // the backend cancels it; its result is for the old library setFilters(emptyFilters) setSorting([]) qc.invalidateQueries() // refetch everything for the newly-opened collection @@ -430,6 +484,33 @@ export default function App() { y, }) + const runGridAnalysis = async (ids: string[], replaceExisting: boolean) => { + setGridConfirm(null) + try { + const job = await api.autoGridBatch(ids, replaceExisting) + setGridCancelling(false) + setGridJobId(job.id) + } catch (e) { + onError((e as Error).message) + } + } + // Confirm only when the run would meet existing grids. Counted from the + // view's tracks, which is where the selection came from. + const startGridAnalysis = (ids: string[]) => { + const byId = new Map(tracks.map((t) => [t.id, t])) + const sel = ids.map((id) => byId.get(id)).filter((t): t is Track => !!t) + const locked = sel.filter((t) => t.grid_locked).length + const existing = sel.filter((t) => !t.grid_locked && t.grid_marker_count > 0).length + if (locked === ids.length) { + notify('error', `${locked === 1 ? 'That grid is' : `All ${locked} grids are`} locked — nothing to analyze`) + } else if (existing > 0) { + setGridConfirm({ ids, existing, locked }) + } else { + void runGridAnalysis(ids, false) + } + } + const canAnalyzeGrid = canEdit && !viewingDevice && !!capabilities.data?.grid.editable + // The "Add to" submenu. Exports are listed even on a read-only library: // adding to one touches no library data — an export is Konduktor's own // curation. The playlist being viewed is left out; adding a track to the @@ -473,6 +554,16 @@ export default function App() { ...(canEdit && menu.ids.length === 1 ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] : []), + ...(canAnalyzeGrid + ? [ + { + label: 'Analyze Grid & BPM', + hint: gridJobId ? 'running' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, + disabled: !!gridJobId, + onClick: () => startGridAnalysis(menu.ids), + }, + ] + : []), // A device's track ids belong to the stick, not the collection, so // there is nothing they could be added to. ...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]), @@ -504,6 +595,15 @@ export default function App() { onError={onError} /> )} + {gridConfirm && ( + runGridAnalysis(gridConfirm.ids, replace)} + onClose={() => setGridConfirm(null)} + /> + )} {showPaths && ( setShowPaths(false)} @@ -540,6 +640,7 @@ export default function App() { onError={onError} onNotify={notify} fromDevice={viewingDevice} + cuesRefresh={cuesRefresh} /> @@ -751,6 +852,21 @@ export default function App() { total={tracks.length} sourceName={viewName} selected={isAll || viewingExport ? selected.size : 0} + job={ + gridJobId + ? { + label: 'Analyzing', + done: gridJob.data?.done ?? 0, + total: gridJob.data?.total ?? 0, + detail: gridJob.data?.message, + cancelling: gridCancelling, + onCancel: () => { + setGridCancelling(true) + api.cancelJob(gridJobId).catch((e) => onError((e as Error).message)) + }, + } + : null + } loading={loading} collectionName={capabilities.data ? libraryName : null} onChangeCollection={() => setForcePicker(true)} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index c13a37e..1bcde25 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -345,6 +345,14 @@ export interface JobStatus { finished_at: number | null } +/** What a batch grid analysis did, per track outcome. */ +export interface GridBatchResult { + analysed: string[] + locked: number + existing: number + failed: { title: string; reason: string }[] +} + export interface SourceCandidate { path: string /** What a person recognises, e.g. "OneLibrary — Hardy". */ @@ -665,6 +673,14 @@ export const api = { // Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor. autoGrid: (trackId: string) => send('POST', '/api/tracks/grid/auto', { track_id: trackId }), + /** Many tracks at once, as a job — poll `job()`. Locked grids are always + * skipped; existing ones unless `replaceExisting`. The finished job's + * `result` is a `GridBatchResult`. */ + autoGridBatch: (trackIds: string[], replaceExisting: boolean) => + send('POST', '/api/tracks/grid/auto-batch', { + track_ids: trackIds, + replace_existing: replaceExisting, + }), setCueType: (trackId: string, slot: number, type: CueType) => send('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }), deleteCue: (trackId: string, slot: number) => diff --git a/frontend/src/components/AnalyzeGridDialog.tsx b/frontend/src/components/AnalyzeGridDialog.tsx new file mode 100644 index 0000000..8e18872 --- /dev/null +++ b/frontend/src/components/AnalyzeGridDialog.tsx @@ -0,0 +1,83 @@ +import { useEffect } from 'react' + +interface Props { + /** Tracks the user selected. */ + total: number + /** Unlocked tracks that already have a beatgrid. */ + existing: number + /** Tracks whose grid is locked — skipped whatever is chosen here. */ + locked: number + onChoose: (replaceExisting: boolean) => void + onClose: () => void +} + +/** Asked only when a batch analysis would meet existing grids: re-analysing a + * grid someone may have hand-fixed is a decision, not a default. */ +export function AnalyzeGridDialog({ total, existing, locked, onChoose, onClose }: Props) { + // "Skip them" would leave nothing to do when every unlocked track has a grid. + const canSkip = existing < total - locked + + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose]) + + return ( +
+
e.stopPropagation()} + > +
+
Analyze Grid & BPM
+
+ {total} track{total === 1 ? '' : 's'} selected +
+
+
+

+ {existing}{' '} + {existing === 1 ? 'already has a beatgrid' : 'already have a beatgrid'}. Replacing + discards any hand edits to {existing === 1 ? 'it' : 'them'}. +

+ {locked > 0 && ( +

+ {locked} {locked === 1 ? 'is' : 'are'} locked and will be skipped either way. +

+ )} +
+
+ + + {canSkip && ( + + )} +
+
+
+ ) +} diff --git a/frontend/src/components/ContextMenu.tsx b/frontend/src/components/ContextMenu.tsx index 2fdd5a7..574e87d 100644 --- a/frontend/src/components/ContextMenu.tsx +++ b/frontend/src/components/ContextMenu.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react' /** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */ export type MenuItem = - | { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: string } + | { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: string; disabled?: boolean } | { label: string; submenu: MenuItem[] } | { heading: string; empty?: string } @@ -122,15 +122,18 @@ function MenuPanel({ return ( + + )} {collectionName && (