mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Added context option to multi analyze
This commit is contained in:
1 parent
b71436fad6
commit
532dc5d6ac
11 files changed
+486
-12
No files matched your search
@@ -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
|
(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
|
collection — the previous implementation's route returned 500 on every call
|
||||||
for a week while its helper's tests passed.
|
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
|
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
|
||||||
replaced was invisible: `/api/library/options` flattened every driver's
|
replaced was invisible: `/api/library/options` flattened every driver's
|
||||||
detections and returned `[0]`, so a plugged-in USB stick could be offered as
|
detections and returned `[0]`, so a plugged-in USB stick could be offered as
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from .core.capabilities import Capabilities
|
|||||||
from .jobs import JOBS
|
from .jobs import JOBS
|
||||||
from .core.pathmap import PathMapping
|
from .core.pathmap import PathMapping
|
||||||
from .schemas import (
|
from .schemas import (
|
||||||
|
AutoGridBatchRequest,
|
||||||
AutoGridRequest,
|
AutoGridRequest,
|
||||||
AutoCueOutcome,
|
AutoCueOutcome,
|
||||||
AutoHotcue,
|
AutoHotcue,
|
||||||
@@ -147,6 +148,9 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
|
|||||||
# This checks only that the path is there at all; `can_open()` decides.
|
# This checks only that the path is there at all; `can_open()` decides.
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
raise HTTPException(400, f"Not found: {path}")
|
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:
|
try:
|
||||||
STATE.open(path)
|
STATE.open(path)
|
||||||
except AdapterError as ex:
|
except AdapterError as ex:
|
||||||
@@ -886,16 +890,78 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
|
|||||||
a = require_adapter()
|
a = require_adapter()
|
||||||
if a.track(body.track_id) is None:
|
if a.track(body.track_id) is None:
|
||||||
raise HTTPException(404, "Track not found")
|
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():
|
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:
|
try:
|
||||||
found = grid_detect.detect_grid(str(path))
|
found = grid_detect.detect_grid(str(path))
|
||||||
except Exception as ex: # analysis is best-effort; never 500 the UI
|
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
|
# "Analysed", not "replace": each platform writes an analysis result in its
|
||||||
# own shape (Traktor pairs the first marker with a beat-1 cue).
|
# 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)
|
@app.patch("/api/tracks/cue", response_model=TrackCues)
|
||||||
|
|||||||
@@ -119,6 +119,13 @@ class AutoGridRequest(BaseModel):
|
|||||||
track_id: str
|
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):
|
class SetCueType(BaseModel):
|
||||||
track_id: str
|
track_id: str
|
||||||
slot: int
|
slot: int
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
|||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
|
|
||||||
fail=0
|
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 "──────────────────────────────────────────"
|
||||||
echo "▶ $t"
|
echo "▶ $t"
|
||||||
echo "──────────────────────────────────────────"
|
echo "──────────────────────────────────────────"
|
||||||
|
|||||||
@@ -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)
|
||||||
+117
-1
@@ -3,7 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
|
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
|
||||||
import { CapabilitiesContext } from './lib/capabilities'
|
import { CapabilitiesContext } from './lib/capabilities'
|
||||||
import { writeHint } from './lib/platformCopy'
|
import { writeHint } from './lib/platformCopy'
|
||||||
import { api, type PlaylistNode, type Track } from './api'
|
import { api, type GridBatchResult, type PlaylistNode, type Track } from './api'
|
||||||
import {
|
import {
|
||||||
DEFAULT_COLUMN_ORDER,
|
DEFAULT_COLUMN_ORDER,
|
||||||
DEFAULT_COLUMN_VISIBILITY,
|
DEFAULT_COLUMN_VISIBILITY,
|
||||||
@@ -16,6 +16,7 @@ import { Toast, type ToastMsg } from './components/Toast'
|
|||||||
import { CollectionPicker } from './components/CollectionPicker'
|
import { CollectionPicker } from './components/CollectionPicker'
|
||||||
import { ContextMenu, type MenuItem } from './components/ContextMenu'
|
import { ContextMenu, type MenuItem } from './components/ContextMenu'
|
||||||
import { EditTagsDialog } from './components/EditTagsDialog'
|
import { EditTagsDialog } from './components/EditTagsDialog'
|
||||||
|
import { AnalyzeGridDialog } from './components/AnalyzeGridDialog'
|
||||||
import { PathMappingDialog } from './components/PathMappingDialog'
|
import { PathMappingDialog } from './components/PathMappingDialog'
|
||||||
import { HistoryPanel } from './components/HistoryPanel'
|
import { HistoryPanel } from './components/HistoryPanel'
|
||||||
import { PrepStrip } from './components/PrepStrip'
|
import { PrepStrip } from './components/PrepStrip'
|
||||||
@@ -58,6 +59,14 @@ export default function App() {
|
|||||||
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
|
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
|
||||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
||||||
const [importing, setImporting] = useState(false)
|
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<string | null>(null)
|
||||||
|
const [gridCancelling, setGridCancelling] = useState(false)
|
||||||
|
const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues
|
||||||
|
|
||||||
const playTrack = useCallback((t: Track) => {
|
const playTrack = useCallback((t: Track) => {
|
||||||
setPrepTrack(t)
|
setPrepTrack(t)
|
||||||
@@ -387,10 +396,55 @@ export default function App() {
|
|||||||
[reorderPlaylist, tracks],
|
[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 = () => {
|
const handleOpened = () => {
|
||||||
setForcePicker(false)
|
setForcePicker(false)
|
||||||
setSource({ kind: 'all' })
|
setSource({ kind: 'all' })
|
||||||
setSelected(new Set())
|
setSelected(new Set())
|
||||||
|
setGridJobId(null) // the backend cancels it; its result is for the old library
|
||||||
setFilters(emptyFilters)
|
setFilters(emptyFilters)
|
||||||
setSorting([])
|
setSorting([])
|
||||||
qc.invalidateQueries() // refetch everything for the newly-opened collection
|
qc.invalidateQueries() // refetch everything for the newly-opened collection
|
||||||
@@ -430,6 +484,33 @@ export default function App() {
|
|||||||
y,
|
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:
|
// 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
|
// 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
|
// 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
|
...(canEdit && menu.ids.length === 1
|
||||||
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
|
? [{ 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
|
// A device's track ids belong to the stick, not the collection, so
|
||||||
// there is nothing they could be added to.
|
// there is nothing they could be added to.
|
||||||
...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
|
...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
|
||||||
@@ -504,6 +595,15 @@ export default function App() {
|
|||||||
onError={onError}
|
onError={onError}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{gridConfirm && (
|
||||||
|
<AnalyzeGridDialog
|
||||||
|
total={gridConfirm.ids.length}
|
||||||
|
existing={gridConfirm.existing}
|
||||||
|
locked={gridConfirm.locked}
|
||||||
|
onChoose={(replace) => runGridAnalysis(gridConfirm.ids, replace)}
|
||||||
|
onClose={() => setGridConfirm(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{showPaths && (
|
{showPaths && (
|
||||||
<PathMappingDialog
|
<PathMappingDialog
|
||||||
onClose={() => setShowPaths(false)}
|
onClose={() => setShowPaths(false)}
|
||||||
@@ -540,6 +640,7 @@ export default function App() {
|
|||||||
onError={onError}
|
onError={onError}
|
||||||
onNotify={notify}
|
onNotify={notify}
|
||||||
fromDevice={viewingDevice}
|
fromDevice={viewingDevice}
|
||||||
|
cuesRefresh={cuesRefresh}
|
||||||
/>
|
/>
|
||||||
</CapabilitiesContext.Provider>
|
</CapabilitiesContext.Provider>
|
||||||
|
|
||||||
@@ -751,6 +852,21 @@ export default function App() {
|
|||||||
total={tracks.length}
|
total={tracks.length}
|
||||||
sourceName={viewName}
|
sourceName={viewName}
|
||||||
selected={isAll || viewingExport ? selected.size : 0}
|
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}
|
loading={loading}
|
||||||
collectionName={capabilities.data ? libraryName : null}
|
collectionName={capabilities.data ? libraryName : null}
|
||||||
onChangeCollection={() => setForcePicker(true)}
|
onChangeCollection={() => setForcePicker(true)}
|
||||||
|
|||||||
@@ -345,6 +345,14 @@ export interface JobStatus {
|
|||||||
finished_at: number | null
|
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 {
|
export interface SourceCandidate {
|
||||||
path: string
|
path: string
|
||||||
/** What a person recognises, e.g. "OneLibrary — Hardy". */
|
/** 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.
|
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
|
||||||
autoGrid: (trackId: string) =>
|
autoGrid: (trackId: string) =>
|
||||||
send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }),
|
send<TrackCues>('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<JobStatus>('POST', '/api/tracks/grid/auto-batch', {
|
||||||
|
track_ids: trackIds,
|
||||||
|
replace_existing: replaceExisting,
|
||||||
|
}),
|
||||||
setCueType: (trackId: string, slot: number, type: CueType) =>
|
setCueType: (trackId: string, slot: number, type: CueType) =>
|
||||||
send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
|
send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
|
||||||
deleteCue: (trackId: string, slot: number) =>
|
deleteCue: (trackId: string, slot: number) =>
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div
|
||||||
|
aria-modal="true"
|
||||||
|
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-sm overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="border-b border-line px-5 py-4">
|
||||||
|
<div className="text-[15px] font-semibold tracking-tight">Analyze Grid & BPM</div>
|
||||||
|
<div className="text-xs text-muted">
|
||||||
|
{total} track{total === 1 ? '' : 's'} selected
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1 px-5 py-4 text-sm text-muted">
|
||||||
|
<p>
|
||||||
|
<span className="tabular-nums text-text">{existing}</span>{' '}
|
||||||
|
{existing === 1 ? 'already has a beatgrid' : 'already have a beatgrid'}. Replacing
|
||||||
|
discards any hand edits to {existing === 1 ? 'it' : 'them'}.
|
||||||
|
</p>
|
||||||
|
{locked > 0 && (
|
||||||
|
<p className="text-faint">
|
||||||
|
{locked} {locked === 1 ? 'is' : 'are'} locked and will be skipped either way.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => onChoose(true)}
|
||||||
|
className={
|
||||||
|
canSkip
|
||||||
|
? 'rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text'
|
||||||
|
: 'rounded-md bg-accent px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Replace {existing === 1 ? 'it' : 'them'}
|
||||||
|
</button>
|
||||||
|
{canSkip && (
|
||||||
|
<button
|
||||||
|
onClick={() => onChoose(false)}
|
||||||
|
className="rounded-md bg-accent px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
|
||||||
|
>
|
||||||
|
Skip {existing === 1 ? 'it' : 'them'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
|||||||
|
|
||||||
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
|
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
|
||||||
export type MenuItem =
|
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[] }
|
| { label: string; submenu: MenuItem[] }
|
||||||
| { heading: string; empty?: string }
|
| { heading: string; empty?: string }
|
||||||
|
|
||||||
@@ -122,15 +122,18 @@ function MenuPanel({
|
|||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={i}
|
key={i}
|
||||||
|
disabled={item.disabled}
|
||||||
onMouseEnter={() => setOpen(null)}
|
onMouseEnter={() => setOpen(null)}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
item.onClick()
|
item.onClick()
|
||||||
onClose()
|
onClose()
|
||||||
}}
|
}}
|
||||||
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${
|
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${
|
||||||
item.danger
|
item.disabled
|
||||||
? 'text-pink hover:bg-ink-800'
|
? 'cursor-default text-faint'
|
||||||
: 'text-muted hover:bg-ink-800 hover:text-text'
|
: item.danger
|
||||||
|
? 'text-pink hover:bg-ink-800'
|
||||||
|
: 'text-muted hover:bg-ink-800 hover:text-text'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{item.icon && <span className="shrink-0 text-[11px] text-gold">{item.icon}</span>}
|
{item.icon && <span className="shrink-0 text-[11px] text-gold">{item.icon}</span>}
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ interface Props {
|
|||||||
* deck gates on those — so this only needs to redirect the two READS.
|
* deck gates on those — so this only needs to redirect the two READS.
|
||||||
*/
|
*/
|
||||||
fromDevice?: boolean
|
fromDevice?: boolean
|
||||||
|
/** Bumped when something outside the deck (batch grid analysis) rewrote the
|
||||||
|
* loaded track's cues/grid, so the deck re-reads them. */
|
||||||
|
cuesRefresh?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function fmt(secs: number): string {
|
function fmt(secs: number): string {
|
||||||
@@ -73,7 +76,14 @@ 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, onNotify, fromDevice = false }: Props) {
|
export function PrepStrip({
|
||||||
|
track,
|
||||||
|
playRequest = 0,
|
||||||
|
onError,
|
||||||
|
onNotify,
|
||||||
|
fromDevice = false,
|
||||||
|
cuesRefresh = 0,
|
||||||
|
}: 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
|
||||||
@@ -287,6 +297,19 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevic
|
|||||||
}
|
}
|
||||||
}, [trackId, fromDevice])
|
}, [trackId, fromDevice])
|
||||||
|
|
||||||
|
// Re-read after an outside edit. Deliberately NOT the effect above: that one
|
||||||
|
// resets `originalGridRef`, and "Reset" should still restore the grid the
|
||||||
|
// track had before the outside edit replaced it.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!trackId || !cuesRefresh) return
|
||||||
|
let cancelled = false
|
||||||
|
api.trackCues(trackId).then((d) => !cancelled && setCueData(d)).catch(() => {})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [cuesRefresh])
|
||||||
|
|
||||||
const toggle = () => {
|
const toggle = () => {
|
||||||
const eng = playbackRef.current
|
const eng = playbackRef.current
|
||||||
if (!eng || !eng.ready) return
|
if (!eng || !eng.ready) return
|
||||||
|
|||||||
@@ -1,9 +1,22 @@
|
|||||||
|
/** A background job's progress, shown at the right of the bar. */
|
||||||
|
export interface StatusJob {
|
||||||
|
label: string
|
||||||
|
done: number
|
||||||
|
/** 0 until the job knows its size → indeterminate bar. */
|
||||||
|
total: number
|
||||||
|
/** What it is working on right now, e.g. the current track's title. */
|
||||||
|
detail?: string
|
||||||
|
cancelling?: boolean
|
||||||
|
onCancel: () => void
|
||||||
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
showing: number
|
showing: number
|
||||||
total: number
|
total: number
|
||||||
sourceName: string
|
sourceName: string
|
||||||
/** Rows currently selected; shown only when non-zero. */
|
/** Rows currently selected; shown only when non-zero. */
|
||||||
selected?: number
|
selected?: number
|
||||||
|
job?: StatusJob | null
|
||||||
loading?: boolean
|
loading?: boolean
|
||||||
collectionName?: string | null
|
collectionName?: string | null
|
||||||
onChangeCollection?: () => void
|
onChangeCollection?: () => void
|
||||||
@@ -14,6 +27,7 @@ export function StatusBar({
|
|||||||
total,
|
total,
|
||||||
sourceName,
|
sourceName,
|
||||||
selected = 0,
|
selected = 0,
|
||||||
|
job,
|
||||||
loading,
|
loading,
|
||||||
collectionName,
|
collectionName,
|
||||||
onChangeCollection,
|
onChangeCollection,
|
||||||
@@ -41,10 +55,35 @@ export function StatusBar({
|
|||||||
<span className="tabular-nums text-accent">{selected.toLocaleString()} selected</span>
|
<span className="tabular-nums text-accent">{selected.toLocaleString()} selected</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{job && (
|
||||||
|
<div className="ml-auto flex min-w-0 items-center gap-2">
|
||||||
|
<span className="shrink-0 tabular-nums text-text">
|
||||||
|
{job.cancelling ? 'Cancelling…' : job.label}
|
||||||
|
{job.total > 0 && ` ${Math.min(job.done + 1, job.total)}/${job.total}`}
|
||||||
|
</span>
|
||||||
|
<span className="h-1.5 w-32 shrink-0 overflow-hidden rounded-full bg-ink-800">
|
||||||
|
<span
|
||||||
|
className={`block h-full rounded-full bg-accent transition-[width] duration-300 ${
|
||||||
|
job.total > 0 ? '' : 'w-1/3 animate-pulse'
|
||||||
|
}`}
|
||||||
|
style={job.total > 0 ? { width: `${(job.done / job.total) * 100}%` } : undefined}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
{job.detail && <span className="max-w-[240px] truncate text-faint">{job.detail}</span>}
|
||||||
|
<button
|
||||||
|
onClick={job.onCancel}
|
||||||
|
disabled={job.cancelling}
|
||||||
|
className="shrink-0 rounded px-1.5 text-faint hover:bg-ink-800 hover:text-pink disabled:opacity-40"
|
||||||
|
title="Cancel"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{collectionName && (
|
{collectionName && (
|
||||||
<button
|
<button
|
||||||
onClick={onChangeCollection}
|
onClick={onChangeCollection}
|
||||||
className="ml-auto flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text"
|
className={`${job ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`}
|
||||||
title="Change collection"
|
title="Change collection"
|
||||||
>
|
>
|
||||||
<span className="text-[11px]">⎘</span>
|
<span className="text-[11px]">⎘</span>
|
||||||
|
|||||||
Reference in new issue
Block a user