Added batch auto hot cue and reworked remove context menu

This commit is contained in:
patben8 committed 2026-09-25 11:54:09 +02:00
1 parent 76bf142fb4
commit d18db9566c
21 files changed
+1044 -150

No files matched your search

@@ -239,6 +239,9 @@ class OneLibraryAdapter:
def add_tracks(self, items: list) -> list[str]:
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
@@ -400,6 +400,12 @@ class RekordboxAdapter:
# import target for now.
self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
# Same shape as adding: a track is a djmdContent row plus its cues,
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
# which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -150,6 +150,16 @@ class TraktorAdapter:
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return self._store.cover_art(track_id)
# ---- removing tracks ---------------------------------------------------
def remove_tracks(self, track_ids: list[str]) -> int:
with _translate():
n = self._store.remove_entries(track_ids)
if n:
# Rebuilt rather than patched: an entry sharing a removed key went
# too, and the index would otherwise still hold its projection.
self._rebuild()
return n
# ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
@@ -59,6 +59,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
rating_max=5,
editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"],
removable=True,
artwork=True,
artwork_note=(
"Traktor caches its own cover thumbnail, so a replaced image may "
+56 -1
View File
@@ -418,6 +418,56 @@ class TraktorStore:
self.dirty = True
return key
def remove_entries(self, track_ids: list[str]) -> int:
"""Remove tracks from the collection AND from every playlist; return
how many ENTRYs went.
The mirror of `add_entry`, with the same care about bytes: only the
removed ENTRYs, the `<COLLECTION ENTRIES>` count and the playlists that
actually referenced a removed track change — any other playlist is left
alone rather than rebuilt, so it still renders what it was parsed from.
Playlists must be purged too: a PRIMARYKEY naming a track that is no
longer in COLLECTION is a dangling reference, not an empty slot. The
audio file is never touched — this is the library's record of the track,
like Traktor's own "Delete from Collection".
Matches by primary key in DOCUMENT order, so two ENTRYs sharing a key
(which `iter_entries` warns can happen) both go, where the key→entry
dict would have found only one.
"""
gone = set(track_ids)
with self._lock:
before = self._nml.collection.entry
kept = [e for e in before if self._key_of(e) not in gone]
removed = len(before) - len(kept)
if removed == 0:
return 0
self._nml.collection.entry = kept
self._nml.collection.entries = len(kept)
for key in gone:
if self._entry_by_key.pop(key, None) is not None:
self._track_art.pop(key, None)
self._note("track", "remove", key)
for n in self._iter_nodes(self._root()):
pl = n.playlist
if pl is None or not pl.entry:
continue
entries = [
e for e in pl.entry
if not (e.primarykey is not None and e.primarykey.key in gone)
]
if len(entries) != len(pl.entry):
pl.entry = entries
pl.entries = len(entries)
self.dirty = True
return removed
@staticmethod
def _key_of(entry) -> str | None:
loc = entry.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else None
def iter_entries(self):
"""Every collection ENTRY in document order.
@@ -480,7 +530,10 @@ class TraktorStore:
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
`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."."""
label: on create it falls back to Traktor's "n.n."; on a replace, None
keeps the old label (a hand move is still the same cue) while a name
renames it (Auto Hotcues' Replace puts a DIFFERENT cue in the slot, and
keeping "Drop 1" on a cue now at "Drop 1 -16" would mislabel it)."""
if not 0 <= slot <= 7:
raise PlaylistError(f"Invalid hotcue slot: {slot}")
if cue_type not in self.CREATABLE_TYPES:
@@ -496,6 +549,8 @@ class TraktorStore:
existing.start = start_ms
existing.type = cue_type
existing.len = len_ms
if name is not None:
existing.name = name
else:
if entry.cue_v2 is None:
entry.cue_v2 = []
+6
View File
@@ -135,6 +135,12 @@ class LibraryAdapter(Protocol):
# what `test_save_fidelity.py` checks rather than taking on trust.
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# ---- commands: track metadata / art ---------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
+3
View File
@@ -58,6 +58,9 @@ class TrackCapabilities(BaseModel):
rating_max: int = 5
editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
removable: bool = False
artwork: bool = False
artwork_note: str | None = None
+14 -2
View File
@@ -68,12 +68,21 @@ class EditJournal:
changed, they simply did not exist before. Counting them here would both
mislabel the version-history message and drag them through the file-tag
sync, which has nothing to write for a track whose fields were never
touched.
touched. Excludes tracks REMOVED from the library for the same reason:
"edited 40 tracks" would describe a deletion as an edit.
"""
removed = self.removed_tracks()
return {
c.target
for c in self.changes
if c.scope == "track" and c.target and c.op != "add"
if c.scope == "track" and c.target and c.op not in ("add", "remove")
and c.target not in removed
}
def removed_tracks(self) -> set[str]:
"""Tracks taken out of the library this session."""
return {
c.target for c in self.changes if c.scope == "track" and c.op == "remove" and c.target
}
def added_tracks(self) -> set[str]:
@@ -115,6 +124,9 @@ class EditJournal:
n_added = len(self.added_tracks())
if n_added:
parts.append(f"added {tracks(n_added)}")
n_removed = len(self.removed_tracks())
if n_removed:
parts.append(f"removed {tracks(n_removed)} from the collection")
# --- track metadata + cover art (already counted per-track) ---
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
+164 -23
View File
@@ -36,6 +36,8 @@ from .schemas import (
AutoGridRequest,
AutoCueOutcome,
AutoHotcue,
AutoHotcuesBatchRequest,
TrackIds,
AutoHotcuesRequest,
AutoHotcuesResult,
CollectionCandidate,
@@ -149,8 +151,9 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
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)
for kind in BATCH_JOBS:
for job in JOBS.active(kind):
JOBS.cancel(job.id)
try:
STATE.open(path)
except AdapterError as ex:
@@ -838,22 +841,35 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
raise HTTPException(404, "Track not found")
if not cues.grid_markers:
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
slots = a.capabilities().cues.hotcue_slots
_check_cue_slots(a, body.slots)
try:
return _place_auto_cues(a, body.track_id, cues, body.slots)
except _AnalysisError as ex:
raise HTTPException(400, str(ex))
def _check_cue_slots(a, slots: list) -> None:
"""Refuse a template the bank cannot hold — once, before any track is touched."""
n = a.capabilities().cues.hotcue_slots
seen: set[int] = set()
for r in body.slots:
if not 0 <= r.slot < slots:
raise HTTPException(400, f"Slot {r.slot} is outside this library's {slots} hotcues")
for r in slots:
if not 0 <= r.slot < n:
raise HTTPException(400, f"Slot {r.slot} is outside this library's {n} hotcues")
if r.slot in seen:
raise HTTPException(400, f"Slot {r.slot} is requested twice")
seen.add(r.slot)
path = a.audio_path(body.track_id)
if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotcuesResult:
"""Analyse one gridded track's structure and place the template — shared by
the deck's Auto button and the batch job, so the two cannot drift."""
path = a.audio_path(track_id)
if path is None or not path.exists():
raise _AnalysisError("Audio file not found (is the drive mounted?)")
try:
found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers])
except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}")
raise _AnalysisError(f"Analysis failed: {ex}") from ex
existing = {
c.slot: ah.ExistingCue(c.editable, c.start)
@@ -862,7 +878,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
}
outcomes = ah.plan(
found,
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots],
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in slots],
existing,
)
placed = [o for o in outcomes if o.status == ah.PLACED]
@@ -870,7 +886,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
# overwrite=True is safe: `plan` only passes an occupied slot when the
# user ticked it, and the adapter still refuses a protected one.
cues = a.place_cues(
body.track_id,
track_id,
[AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed],
overwrite=True,
)
@@ -892,31 +908,42 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
raise HTTPException(404, "Track not found")
try:
return _analyse_grid(a, body.track_id)
except _GridAnalysisError as ex:
except _AnalysisError as ex:
raise HTTPException(400, str(ex))
class _GridAnalysisError(Exception):
class _AnalysisError(Exception):
"""A track that could not be analysed; the message is user-facing."""
# Batch analysis jobs. ONE at a time across both kinds: a grid run replacing a
# track's grid while a hotcue run places cues on the old one would put cues on
# beats that no longer exist.
GRID_JOB = "grid-analysis"
CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB)
def _require_no_batch() -> None:
if any(JOBS.active(k) for k in BATCH_JOBS):
raise HTTPException(409, "A batch analysis is already running")
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 _GridAnalysisError("Audio file not found (is the drive mounted?)")
raise _AnalysisError("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 _GridAnalysisError(f"Analysis failed: {ex}") from ex
raise _AnalysisError(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(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:
@@ -930,10 +957,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
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")
_require_no_batch()
ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict:
@@ -955,7 +979,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
try:
_analyse_grid(a, track_id)
result["analysed"].append(track_id)
except (_GridAnalysisError, AdapterError) as ex:
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": str(ex)})
handle.progress(done=i + 1)
return result
@@ -964,6 +988,57 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
return JobStatus(**job.as_dict())
@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus)
def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
"""Place one Auto Hotcues template on many tracks, as a JOB.
A track with no beatgrid gets one analysed first (as "Analyze Grid & BPM"
would), since the events are found on the grid; a track that has one keeps
it untouched. Same contract as the grid batch: written as each track
finishes, a cancel keeps what is done, a failing track is reported and
skipped."""
a = require_adapter()
caps = a.capabilities()
if not caps.writable or caps.cues.hotcue_slots == 0:
raise HTTPException(422, "This library's hotcues cannot be edited")
_check_cue_slots(a, body.slots)
if not body.slots:
raise HTTPException(400, "The template places no cues")
_require_no_batch()
ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict:
result = {"tracks": [], "cues_placed": 0, "grids_created": 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)
try:
cues = a.track_cues(track_id) if track else None
if cues is None:
raise _AnalysisError("Track not found")
if not cues.grid_markers:
if track.grid_locked:
raise _AnalysisError("No beatgrid, and the grid is locked")
if not caps.grid.editable:
raise _AnalysisError("No beatgrid")
cues = _analyse_grid(a, track_id)
result["grids_created"] += 1
placed = _place_auto_cues(a, track_id, cues, body.slots)
result["tracks"].append(track_id)
result["cues_placed"] += sum(o.status == ah.PLACED for o in placed.outcomes)
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": str(ex)})
handle.progress(done=i + 1)
return result
job = JOBS.submit(CUE_JOB, run)
return JobStatus(**job.as_dict())
@app.patch("/api/tracks/cue", response_model=TrackCues)
def edit_cue_type(body: SetCueType) -> TrackCues:
"""Change the type of an existing cue (keeps its position)."""
@@ -1020,6 +1095,72 @@ def remove_grid(track_id: str) -> TrackCues:
return require_adapter().delete_grid(track_id)
# ---- bulk Remove (the context menu's Remove ▸ submenu) --------------------
#
# Quick in-memory edits, so requests rather than jobs — but refused while a
# batch analysis runs: it would write cues/grids onto a track removed under it.
@app.post("/api/tracks/grid/clear")
def clear_grids(body: TrackIds) -> dict:
"""Delete the beatgrid of every given track. Locked grids are skipped —
a lock is the user saying "leave this grid alone" — and reported."""
a = require_adapter()
if not a.capabilities().grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited")
_require_no_batch()
out = {"cleared": 0, "locked": 0, "empty": 0}
for tid in dict.fromkeys(body.track_ids):
track = a.track(tid)
if track is None:
continue
if track.grid_locked:
out["locked"] += 1
elif not (a.track_cues(tid) or TrackCues()).grid_markers:
out["empty"] += 1 # counted from the cues: the projection's count can be approximate
else:
a.delete_grid(tid)
out["cleared"] += 1
return out
@app.post("/api/tracks/cue/clear")
def clear_hotcues(body: TrackIds) -> dict:
"""Empty the whole hotcue bank of every given track — point cues, loops
and the grid's paired beat-1 cue alike (the grid itself is untouched).
Cues the adapter will not edit — Rekordbox memory cues — are kept."""
a = require_adapter()
caps = a.capabilities()
if not caps.writable or caps.cues.hotcue_slots == 0:
raise HTTPException(422, "This library's hotcues cannot be edited")
_require_no_batch()
out = {"tracks": 0, "cues": 0}
for tid in dict.fromkeys(body.track_ids):
cues = a.track_cues(tid)
slots = sorted({
c.slot for c in (cues.cues if cues else [])
if c.role == "hotcue" and c.slot is not None and c.editable
})
for slot in slots:
a.delete_cue(tid, slot)
if slots:
out["tracks"] += 1
out["cues"] += len(slots)
return out
@app.post("/api/tracks/remove")
def remove_tracks(body: TrackIds) -> dict:
"""Remove tracks from the library and every playlist. Audio files are
never touched. An export set referencing one will report it as missing,
which is what export sets do with any track that has gone."""
a = require_adapter()
if not a.capabilities().tracks.removable:
raise HTTPException(422, "Tracks cannot be removed from this library")
_require_no_batch()
return {"removed": a.remove_tracks(list(dict.fromkeys(body.track_ids)))}
@app.patch("/api/tracks/grid/lock", response_model=TrackCues)
def edit_grid_lock(body: SetGridLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track."""
+14
View File
@@ -105,6 +105,20 @@ class AutoHotcuesRequest(BaseModel):
slots: list[AutoCueSlot]
class TrackIds(BaseModel):
"""A body naming a set of tracks — the bulk Remove commands."""
track_ids: list[str]
class AutoHotcuesBatchRequest(BaseModel):
"""The same template applied to every track. `overwrite` on a slot means
"replace this slot's cue on every track that has one"."""
track_ids: list[str]
slots: list[AutoCueSlot]
class AutoCueOutcome(BaseModel):
slot: int
event: AutoCueEvent
+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_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
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_bulk_remove.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 "──────────────────────────────────────────"
+126
View File
@@ -0,0 +1,126 @@
"""The context menu's Remove ▸ commands, through their routes, on a temp copy.
Removing from the COLLECTION is new — the protocol's only destroying verb for
tracks — and its bytes are pinned by invariant L in `test_save_fidelity.py`.
This pins what the routes decide: which tracks each command skips (locked
grids, memory cues), that "clear hotcues" empties the whole bank but leaves the
grid, that a removed track leaves the projection AND every playlist while its
audio file is untouched, that the capability gates the route, and that a
running batch analysis blocks all three.
"""
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
print("== bulk remove ==")
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
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:3]
locked = gridded[2]
a.set_grid_lock(locked, True)
bare = next(t.id for t in a.tracks if t.grid_marker_count == 0)
# ---- grids ----------------------------------------------------------
r = c.post("/api/tracks/grid/clear", json={"track_ids": [*gridded, bare]})
check("grid clear answers 200", r.status_code == 200, r.text[:200])
check("…counts cleared / locked / empty",
r.json() == {"cleared": 2, "locked": 1, "empty": 1}, r.text)
check("the grids are gone", all(not a.track_cues(t).grid_markers for t in gridded[:2]))
check("a locked grid is kept", bool(a.track_cues(locked).grid_markers))
# ---- hotcues --------------------------------------------------------
with_cues = [t.id for t in a.tracks
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) > 0
and any(q.slot is not None and q.grid_marker is not None for q in cu.cues)
and sum(q.slot is not None for q in cu.cues) >= 2][:2]
before = {t: a.track_cues(t) for t in with_cues}
n_cues = sum(sum(q.slot is not None for q in cu.cues) for cu in before.values())
r = c.post("/api/tracks/cue/clear", json={"track_ids": with_cues})
check("hotcue clear answers 200", r.status_code == 200, r.text[:200])
check("…counts tracks and cues", r.json() == {"tracks": 2, "cues": n_cues}, f"{r.text} vs {n_cues}")
check("the whole bank is empty, incl. the grid's beat-1 cue",
all(not any(q.slot is not None for q in a.track_cues(t).cues) for t in with_cues))
# Positions and tempos, not the whole marker: its `companion` slot is
# SUPPOSED to become None, since the paired cue was just deleted.
def grid(cu):
return [(m.start, m.bpm) for m in cu.grid_markers]
check("…and the grid itself is untouched (only its pairing ends)",
all(grid(a.track_cues(t)) == grid(before[t]) for t in with_cues)
and all(m.companion is None for t in with_cues for m in a.track_cues(t).grid_markers))
# ---- from collection ------------------------------------------------
caps = c.get("/api/capabilities").json()
check("Traktor advertises removable tracks", caps["tracks"]["removable"] is True)
tree = c.get("/api/playlists").json()
def lists(nodes):
for n in nodes:
yield n
yield from lists(n["children"])
pl = next(n for n in lists(tree) if n.get("count") and n.get("can_add_tracks"))
in_pl = c.get(f"/api/playlists/{pl['id']}/tracks").json()
in_pl = in_pl["tracks"] if isinstance(in_pl, dict) else in_pl
victim = in_pl[0]["id"]
audio = a.audio_path(victim)
existed = audio is not None and audio.exists()
n_before = len(a.tracks)
r = c.post("/api/tracks/remove", json={"track_ids": [victim, victim, "nope"]})
check("remove answers 200", r.status_code == 200, r.text[:200])
check("…and removes exactly one (duplicates / unknowns ignored)", r.json() == {"removed": 1}, r.text)
check("the track leaves the projection", a.track(victim) is None and len(a.tracks) == n_before - 1)
after = c.get(f"/api/playlists/{pl['id']}/tracks").json()
after = after["tracks"] if isinstance(after, dict) else after
check("…and the playlist", all(t["id"] != victim for t in after) and len(after) == len(in_pl) - 1)
check("the audio file is untouched", not existed or audio.exists())
check("the edit is unsaved (Save lights up)", c.get("/api/state").json().get("dirty") is True)
# ---- gating ----------------------------------------------------------
orig_caps = a.capabilities
a.capabilities = lambda: orig_caps().model_copy(update={
"tracks": orig_caps().tracks.model_copy(update={"removable": False})})
r = c.post("/api/tracks/remove", json={"track_ids": [gridded[0]]})
check("remove is refused without the capability", r.status_code == 422, r.text[:200])
a.capabilities = orig_caps
main.grid_detect.detect_grid = lambda p, *a_, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1]
a.audio_path = lambda tid: Path(__file__)
jid = c.post("/api/tracks/grid/auto-batch",
json={"track_ids": [t.id for t in a.tracks][:40], "replace_existing": True}).json()["id"]
for route in ("/api/tracks/grid/clear", "/api/tracks/cue/clear", "/api/tracks/remove"):
r = c.post(route, json={"track_ids": [gridded[0]]})
check(f"{route} is refused while a batch runs", r.status_code == 409, r.text[:200])
c.post(f"/api/jobs/{jid}/cancel")
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)
+91 -2
View File
@@ -1,9 +1,12 @@
"""Batch grid analysis — the route and its job, on a temp copy of the collection.
"""Batch analysis — grid and Auto Hotcues jobs, 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.
cancel keeps what is done, and nothing reaches disk before Save. Batch Auto
Hotcues adds: one template on every track, a grid analysed first where there is
none (and an existing one left alone), Replace applying to every track, and one
batch job at a time ACROSS both kinds.
"""
from __future__ import annotations
@@ -14,6 +17,8 @@ import time
from pathlib import Path
from types import SimpleNamespace
import numpy as np
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
@@ -106,6 +111,90 @@ with tempfile.TemporaryDirectory() as d:
n = len(j["result"]["analysed"]) if j["result"] else -1
check("…and still returns what it finished", 0 < n < len(many), str(n))
# ---- batch Auto Hotcues --------------------------------------------
print("== batch auto hotcues ==")
main.grid_detect.detect_grid = fake_detect
from konduktor.core import structure
def fake_analyse(path, markers):
bpm = markers[0][1]
st = structure.Structure(beats=np.arange(400) * 60.0 / bpm, bar0=0,
n_bars=100, duration=400 * 60.0 / bpm)
st.events = {"drop_1": 129, "outro": 353} # clear of any beat-0 grid cue
return st
main.structure.analyse = fake_analyse
def free(tid, n):
cu = a.track_cues(tid)
used = {q.slot for q in cu.cues if q.slot is not None}
return [k for k in range(8) if k not in used][:n]
gridded = next(t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked
and len(free(t.id, 2)) == 2 and t.id not in many)
nogrid = next(t.id for t in a.tracks if t.grid_marker_count == 0
and t.id not in (missing, *bare, *many))
before_grid = a.track_cues(gridded).grid_markers
s0, s1 = free(gridded, 2)
tmpl = [{"slot": s0, "event": "drop_1"}, {"slot": s1, "event": "outro"}]
r = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded, nogrid, missing], "slots": tmpl})
check("the batch 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("both tracks got cues", res["tracks"] == [gridded, nogrid], str(res))
check("a grid is created only where there was none", res["grids_created"] == 1, str(res))
check("an existing grid is left untouched",
a.track_cues(gridded).grid_markers == before_grid)
check("the track without a grid now has one", len(a.track_cues(nogrid).grid_markers) == 1)
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
check("the template's cues are placed", names.get(s0) == "Drop 1" and names.get(s1) == "Outro", str(names))
check("placed cues are counted", res["cues_placed"] == 4, str(res))
check("a missing file is reported, not fatal",
len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res))
# Occupied slots: kept, unless ticked — and then replaced on every track.
# A fresh beat (16 before the drop), so the one-cue-per-beat rule cannot
# be what decides it.
tmpl2 = [{"slot": s0, "event": "drop_1", "offset_beats": -16}]
res = wait(c, c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
check("an occupied slot is kept without Replace", res["cues_placed"] == 0, str(res))
tmpl2[0]["overwrite"] = True
res = wait(c, c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
check("…and replaced with it", names.get(s0) == "Drop 1 -16" and res["cues_placed"] == 1,
f"{names} {res}")
r = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": [{"slot": 99, "event": "outro"}]})
check("a template the bank cannot hold is refused up front", r.status_code == 400, r.text[:200])
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": []})
check("an empty template is refused", r.status_code == 400, r.text[:200])
# One batch at a time ACROSS kinds.
main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1]
jid = c.post("/api/tracks/grid/auto-batch",
json={"track_ids": many, "replace_existing": True}).json()["id"]
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": tmpl})
check("hotcues are refused while a grid run is going", r.status_code == 409, r.text[:200])
c.post(f"/api/jobs/{jid}/cancel")
wait(c, jid)
# Opening another library cancels a running batch.
main.structure.analyse = lambda p, m: (time.sleep(0.05), fake_analyse(p, m))[1]
gridded_many = [t.id for t in a.tracks if t.grid_marker_count > 0][:40]
jid = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": gridded_many, "slots": tmpl}).json()["id"]
time.sleep(0.1)
other = Path(d) / "other.nml"
shutil.copy2(REAL, other)
c.post("/api/library/open", json={"path": str(other)})
check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled")
check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes())
+1
View File
@@ -307,6 +307,7 @@ print("== every command is refused ==")
COMMANDS = [
("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})),
("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")),
("remove_tracks", lambda: adapter.remove_tracks([one.id])),
("create_playlist", lambda: adapter.create_playlist("x")),
("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")),
("delete_playlist", lambda: adapter.delete_playlist(node.id)),
+3
View File
@@ -296,6 +296,9 @@ with tempfile.TemporaryDirectory() as d:
print("== what Rekordbox genuinely cannot do still refuses, with a reason ==")
commands = {
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
# A track spans rows in several tables plus ANLZ files; which of them
# Rekordbox expects deleted together is unmeasured.
"remove_tracks": lambda: adapter.remove_tracks([sample.id]),
# Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK.
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
+49
View File
@@ -687,5 +687,54 @@ else:
check("K: a marker without a companion projects None", ok_comp)
# ---- Invariant L: removing a track from the collection is localized ---------
print("== L. remove_entries drops the ENTRY and its playlist references, nothing else ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
store = TraktorStore(work)
original = store._render()
def pl_nodes(st):
return [n for n in st._iter_nodes(st._root()) if n.playlist is not None]
in_pl = {k for n in pl_nodes(store) for k in store._entry_keys_of(n.playlist)}
target = next(e for e in store._nml.collection.entry
if e.location and store._key_of(e) in in_pl)
key = store._key_of(target)
touched = {n.playlist.uuid for n in pl_nodes(store) if key in store._entry_keys_of(n.playlist)}
untouched = [n.playlist.uuid for n in pl_nodes(store) if n.playlist.uuid not in touched]
n_before = len(store._nml.collection.entry)
removed = store.remove_entries([key, "no/such/track.mp3"])
after = store._render()
check("L: exactly one ENTRY removed (an unknown id is ignored)", removed == 1, str(removed))
import difflib
plus = [d for d in difflib.unified_diff(tag_lines(original), tag_lines(after), n=0)
if d.startswith("+") and not d.startswith("+++")]
# Every ADDED line is a recount — the collection's or a touched playlist's.
# Nothing is rewritten, only removed.
check("L: the only added lines are ENTRIES recounts",
all("ENTRIES=" in d for d in plus) and len(plus) == 1 + len(touched), "\n".join(plus[:6]))
check("L: every other playlist is byte-identical",
all(original[slice(*playlist_block_span(original, u))] == after[slice(*playlist_block_span(after, u))]
for u in untouched))
check("L: the edit journal records a removal, not an edit",
store._journal.removed_tracks() == {key} and not store._journal.edited_tracks())
summary = store._journal.summary()
check("L: …and the history message says so", "removed 1 track from the collection" in summary.lower(), summary)
store.save()
re = TraktorStore(work)
keys = [re._key_of(e) for e in re._nml.collection.entry]
check("L: the track is gone from the collection", key not in keys)
check("L: <COLLECTION ENTRIES> matches the entries", re._nml.collection.entries == len(keys) == n_before - 1)
check("L: …and from every playlist", all(key not in re._entry_keys_of(n.playlist) for n in pl_nodes(re)))
check("L: every playlist's ENTRIES count matches",
all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re)))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)