Added context option to multi analyze

This commit is contained in:
patben8 committed 2026-09-25 10:46:31 +02:00
1 parent b71436fad6
commit 532dc5d6ac
11 files changed
+486 -12

No files matched your search

+70 -4
View File
@@ -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)
+7
View File
@@ -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
+1 -1
View File
@@ -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 "──────────────────────────────────────────"
+114
View File
@@ -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)