mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Refactored library system to support different libraries (adapters)
This commit is contained in:
1 parent
dd97f27ac7
commit
08c9b8121d
31 files changed
+3405
-2385
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""Per-platform adapters. Each owns a native library model and translates the
|
||||
generic commands onto it; nothing outside an adapter package sees a native type.
|
||||
"""
|
||||
@@ -0,0 +1 @@
|
||||
"""The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``."""
|
||||
@@ -0,0 +1,283 @@
|
||||
"""The Traktor adapter: owns the native NML model and the generic projection.
|
||||
|
||||
This is the object the app talks to. It holds:
|
||||
|
||||
* a ``PlaylistStore`` — the retained NATIVE model, which is the write target.
|
||||
Commands are replayed onto it; it is never regenerated from the projection.
|
||||
* a ``TrackIndex`` — the generic READ projection, rebuilt from the store.
|
||||
|
||||
Only one parse happens per open, and the projection is refreshed from the same
|
||||
object graph the commands mutate — so the two cannot drift.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import InvalidCommand, NotFound, Unsupported
|
||||
from ...core.capabilities import Capabilities
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import projection
|
||||
from .store import PlaylistError, PlaylistStore
|
||||
|
||||
# Generic cue vocabulary -> Traktor's CUE_V2 TYPE encoding. This table is the
|
||||
# only place the integers exist outside the store; type 4 is a grid marker and
|
||||
# is never a cue, so it has no generic name.
|
||||
CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5}
|
||||
|
||||
|
||||
class TraktorAdapter:
|
||||
platform = "traktor"
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = Path(path)
|
||||
self._store = PlaylistStore(self.path)
|
||||
self._index = TrackIndex()
|
||||
self._rebuild()
|
||||
|
||||
# ---- projection maintenance ----------------------------------------
|
||||
def _rebuild(self) -> None:
|
||||
"""Re-project every track. Needed after a save or a path remap, where
|
||||
track ids themselves change and a per-track patch is impossible."""
|
||||
self._index.rebuild([projection.to_track(e) for e in self._store.iter_entries()])
|
||||
|
||||
def _refresh(self, track_id: str) -> TrackCues:
|
||||
"""Re-project one track after a command, and return its fresh cues."""
|
||||
entry = self._store.model_entry(track_id)
|
||||
if entry is None:
|
||||
return TrackCues()
|
||||
self._index.replace(projection.to_track(entry))
|
||||
return projection.to_track_cues(entry)
|
||||
|
||||
# ---- read ------------------------------------------------------------
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return self._index.tracks
|
||||
|
||||
@property
|
||||
def by_key(self) -> dict[str, Track]:
|
||||
return self._index.by_key
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
return self._index.get(track_id)
|
||||
|
||||
def query_tracks(self, **kw):
|
||||
return self._index.query_tracks(**kw)
|
||||
|
||||
def facets(self):
|
||||
return self._index.facets()
|
||||
|
||||
def stats(self, playlist_count: int):
|
||||
return self._index.stats(playlist_count)
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
entry = self._store.model_entry(track_id)
|
||||
return projection.to_track_cues(entry) if entry is not None else None
|
||||
|
||||
# ---- transitional shims --------------------------------------------
|
||||
# main.py still drives the store directly and calls replace_track after each
|
||||
# command; both go away when the routes move onto the protocol (step 7).
|
||||
@property
|
||||
def store(self) -> PlaylistStore:
|
||||
return self._store
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
return self._store.entries_for(track_ids)
|
||||
|
||||
def replace_track(self, track_id: str, entry=None) -> None:
|
||||
self._refresh(track_id)
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
self._rebuild()
|
||||
|
||||
def capabilities(self) -> Capabilities:
|
||||
return caps.capabilities_for(self.path, sorted(PlaylistStore.EDITABLE_FIELDS))
|
||||
|
||||
# ---- playlists -------------------------------------------------------
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._store.tree()
|
||||
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None:
|
||||
return self._store.entry_keys(node_id)
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
keys = self._store.entry_keys(node_id)
|
||||
if keys is None:
|
||||
return None
|
||||
return [t for k in keys if (t := self._index.get(k)) is not None]
|
||||
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with _translate():
|
||||
return self._store.create_playlist(name, parent_id)
|
||||
|
||||
def rename_playlist(self, node_id: str, name: str) -> None:
|
||||
with _translate():
|
||||
self._store.rename_playlist(node_id, name)
|
||||
|
||||
def delete_playlist(self, node_id: str) -> None:
|
||||
with _translate():
|
||||
self._store.delete_playlist(node_id)
|
||||
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
|
||||
"""Replace a playlist's contents. The adapter resolves each id to its
|
||||
native entry kind, so callers never see Traktor's STEM/TRACK split."""
|
||||
entries = self._store.entries_for(track_ids)
|
||||
with _translate():
|
||||
self._store.set_entries(node_id, entries)
|
||||
return len(entries)
|
||||
|
||||
# ---- metadata / art --------------------------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_track_metadata(track_id, fields)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with _translate():
|
||||
self._store.set_track_art(track_id, data, mime)
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
# ---- cues -------------------------------------------------------------
|
||||
def _native_cue_type(self, cue_type: str) -> int:
|
||||
native = CUE_TYPE_TO_NATIVE.get(cue_type)
|
||||
if native is None:
|
||||
raise Unsupported(f"Traktor has no cue type {cue_type!r}")
|
||||
return native
|
||||
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
if role != "hotcue":
|
||||
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
|
||||
raise Unsupported("Traktor cues always occupy a hotcue slot")
|
||||
with _translate():
|
||||
self._store.set_hotcue(
|
||||
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.place_hotcues(track_id, cues, overwrite=overwrite)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- beatgrid ---------------------------------------------------------
|
||||
def add_grid_marker(self, track_id, start_sec, bpm=None) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.add_grid_marker(track_id, start_sec, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def move_grid_marker(self, track_id, index, start_sec) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.move_grid_marker(track_id, index, start_sec)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_marker_bpm(self, track_id, index, bpm) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_grid_marker_bpm(track_id, index, bpm)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid_marker(self, track_id, index) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid_marker(track_id, index)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def replace_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Set exactly these markers and nothing else (the deck's Reset)."""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_analysed_grid(self, track_id, markers: list[tuple[float, float]]) -> TrackCues:
|
||||
"""Write an analysis result the way this platform's own analyser would.
|
||||
|
||||
Traktor pairs its first grid marker with a white beat-1 cue, so a grid it
|
||||
wrote looks different from one merely assigned. Keeping that as a
|
||||
separate intent is what lets the companion convention stay inside this
|
||||
adapter instead of leaking into the generic vocabulary.
|
||||
"""
|
||||
with _translate():
|
||||
self._store.replace_grid(track_id, markers)
|
||||
self._store.place_grid_companion(track_id, 0, prefer_slot=0)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def delete_grid(self, track_id) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.delete_grid(track_id)
|
||||
return self._refresh(track_id)
|
||||
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues:
|
||||
with _translate():
|
||||
self._store.set_lock(track_id, locked)
|
||||
return self._refresh(track_id)
|
||||
|
||||
# ---- audio / paths ----------------------------------------------------
|
||||
def audio_path(self, track_id: str):
|
||||
return self._store.audio_path(track_id)
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
self._store.set_path_mapping(mapping)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
return self._store.path_prefix_suggestions()
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
return self._store.remap_preview(mapping)
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> int:
|
||||
with _translate():
|
||||
n = self._store.remap_locations(mapping)
|
||||
# A remap rewrites LOCATIONs, so track ids themselves change — there is
|
||||
# no per-track patch that could express this.
|
||||
self._rebuild()
|
||||
return n
|
||||
|
||||
# ---- save --------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return self._store.dirty
|
||||
|
||||
def save(self):
|
||||
outcome = self._store.save()
|
||||
self._rebuild() # save() re-parses, so every object identity changed
|
||||
return outcome
|
||||
|
||||
def snapshot(self) -> bytes:
|
||||
return self._store._render()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _translate():
|
||||
"""Map the store's native error onto the generic one the HTTP layer maps."""
|
||||
try:
|
||||
yield
|
||||
except PlaylistError as ex:
|
||||
msg = str(ex)
|
||||
if "not found" in msg.lower():
|
||||
raise NotFound(msg) from ex
|
||||
raise InvalidCommand(msg) from ex
|
||||
@@ -0,0 +1,117 @@
|
||||
"""The beatgrid model: an ORDERED LIST of grid markers.
|
||||
|
||||
A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2
|
||||
TYPE="4"` markers, each carrying its own `<GRID BPM>` child. Marker *i*'s tempo
|
||||
governs from its position until marker *i+1*. Traktor has stored grids this way
|
||||
since 3.4 (flexible beatgrids); a constant-tempo track is simply a list of
|
||||
length one, which is why this model is right for every track rather than a
|
||||
special case for flexible ones.
|
||||
|
||||
`<TEMPO BPM>` mirrors the FIRST marker by START.
|
||||
|
||||
Verified against the 8485-entry reference collection:
|
||||
* markers per entry: {1: 7966, 0: 517, 2: 2}
|
||||
* TEMPO.bpm == markers[0].grid.bpm in 7968/7968 entries with both
|
||||
* CUE_V2 is ascending by START in 8485/8485 entries
|
||||
* 53 entries have a TEMPO but no marker -> deleting a grid must KEEP TEMPO
|
||||
|
||||
Two rules that are easy to get wrong:
|
||||
|
||||
1. **Marker NAME is not a discriminator.** In the reference collection TYPE=4
|
||||
markers are named "AutoGrid" x7888, "n.n." x64, "Beat Marker" x14 and
|
||||
"Unnamed" x4. Identify a marker by having a `<GRID>` child, and order the
|
||||
list by START — never by name, never by document order.
|
||||
|
||||
2. **Companion cues are conventional, not structural.** Traktor usually writes a
|
||||
white TYPE=0 cue alongside each grid marker, at the same position, occupying
|
||||
a real hotcue slot. 7910 of 7970 markers have one; 60 do not, and one track
|
||||
has a companion on its first marker but not its second. So we follow them
|
||||
where they exist, keep them in sync, and NEVER invent one.
|
||||
|
||||
This module is pure and imports nothing else from the package, so it can be the
|
||||
single shared definition used by the store, the API projection and the read
|
||||
model — which previously each had their own and disagreed about BPM.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from traktor_nml_utils.models.collection import CueV2Type, Entrytype
|
||||
|
||||
# How close a cue must sit to a marker to be considered its companion. Traktor
|
||||
# writes them at the identical START; 71 markers in the reference collection are
|
||||
# a fraction of a millisecond off, which this absorbs.
|
||||
COMPANION_EPS_MS = 1.0
|
||||
|
||||
# Companions are always white. This test is LOAD-BEARING: 49 uncoloured cues and
|
||||
# 18 LOOPS also sit within 1 ms of a marker in the reference collection. Drop the
|
||||
# colour check and the marker commands would start dragging and deleting the
|
||||
# user's own loops.
|
||||
COMPANION_COLOR = "#FFFFFF"
|
||||
|
||||
|
||||
def grid_markers(entry: Entrytype) -> list[CueV2Type]:
|
||||
"""Every grid marker on `entry`, ordered by START.
|
||||
|
||||
Sorting is not cosmetic: the first marker by START is the one `<TEMPO BPM>`
|
||||
mirrors, and marker indices are the identity used by the edit commands.
|
||||
"""
|
||||
markers = [c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None]
|
||||
markers.sort(key=lambda c: c.start or 0.0)
|
||||
return markers
|
||||
|
||||
|
||||
def first_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
"""The marker `<TEMPO BPM>` mirrors, or None when the track has no grid."""
|
||||
markers = grid_markers(entry)
|
||||
return markers[0] if markers else None
|
||||
|
||||
|
||||
def effective_bpm(entry: Entrytype) -> float | None:
|
||||
"""The tempo the grid actually starts at.
|
||||
|
||||
Prefers the first marker's `<GRID BPM>` and falls back to `<TEMPO BPM>` so
|
||||
the 53 gridless-but-tempo'd entries still report a BPM. Routing both the
|
||||
library table and the prep deck through this makes them structurally
|
||||
incapable of disagreeing.
|
||||
"""
|
||||
marker = first_marker(entry)
|
||||
if marker is not None and marker.grid is not None and marker.grid.bpm:
|
||||
return marker.grid.bpm
|
||||
return entry.tempo.bpm if entry.tempo else None
|
||||
|
||||
|
||||
def companions(entry: Entrytype) -> dict[int, CueV2Type]:
|
||||
"""Map marker index -> the companion cue paired with it, where one exists.
|
||||
|
||||
Greedy nearest-unclaimed matching, so two markers close together can never
|
||||
both claim the same cue.
|
||||
"""
|
||||
markers = grid_markers(entry)
|
||||
if not markers:
|
||||
return {}
|
||||
pool = [
|
||||
c
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
and c.type == 0
|
||||
and c.color == COMPANION_COLOR
|
||||
and c.hotcue is not None
|
||||
and c.hotcue >= 0
|
||||
]
|
||||
out: dict[int, CueV2Type] = {}
|
||||
claimed: set[int] = set()
|
||||
for i, m in enumerate(markers):
|
||||
m_start = m.start or 0.0
|
||||
best = min(
|
||||
(c for c in pool if id(c) not in claimed),
|
||||
key=lambda c: abs((c.start or 0.0) - m_start),
|
||||
default=None,
|
||||
)
|
||||
if best is not None and abs((best.start or 0.0) - m_start) <= COMPANION_EPS_MS:
|
||||
out[i] = best
|
||||
claimed.add(id(best))
|
||||
return out
|
||||
|
||||
|
||||
def is_companion(entry: Entrytype, cue: CueV2Type) -> bool:
|
||||
"""True when `cue` is some grid marker's companion on this entry."""
|
||||
return any(c is cue for c in companions(entry).values())
|
||||
@@ -0,0 +1,75 @@
|
||||
"""What Traktor can persist.
|
||||
|
||||
Derived from the NML version where one is declared, which is the accurate way to
|
||||
report capabilities rather than assuming a floor that denies users features their
|
||||
install actually has. NML v19 (Traktor 3) and v20 (Traktor 4) are equivalent for
|
||||
everything Konduktor edits; flexible beatgrids arrived in Traktor 3.4, which is
|
||||
older than any NML version we can open, so the flag is unconditional.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.capabilities import (
|
||||
Capabilities,
|
||||
CueCapabilities,
|
||||
GridCapabilities,
|
||||
PlaylistCapabilities,
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
|
||||
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
|
||||
|
||||
# Traktor's cue vocabulary, in generic terms. The integer encoding lives in
|
||||
# projection.py / store.py and never leaves this package.
|
||||
CUE_TYPES = ["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
|
||||
|
||||
def nml_version(path: Path) -> str | None:
|
||||
"""The NML VERSION attribute, read from the file head without parsing it."""
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
m = _VERSION_RE.search(fh.read(4096))
|
||||
return m.group(1).decode() if m else None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
return Capabilities(
|
||||
platform="traktor",
|
||||
version=nml_version(path),
|
||||
cues=CueCapabilities(
|
||||
hotcue_slots=8,
|
||||
slot_labels="number",
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
types=CUE_TYPES,
|
||||
color="free",
|
||||
named=True,
|
||||
# A saved loop is a cue TYPE in Traktor, not a separate bank.
|
||||
loops="cue_type",
|
||||
),
|
||||
grid=GridCapabilities(editable=True, flexible=True, lockable=True),
|
||||
tracks=TrackCapabilities(
|
||||
rating_max=5,
|
||||
editable_fields=sorted(editable_fields),
|
||||
media_kinds=["audio", "stem"],
|
||||
artwork=True,
|
||||
artwork_note=(
|
||||
"Traktor caches its own cover thumbnail, so a replaced image may "
|
||||
"need a manual Import Cover Art to show up."
|
||||
),
|
||||
),
|
||||
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
|
||||
save=SaveCapabilities(
|
||||
app_name="Traktor",
|
||||
library_label="collection.nml",
|
||||
# Traktor rewrites collection.nml when it quits, so an edit made
|
||||
# while it is running is lost on exit.
|
||||
overwrite_risk="on_exit",
|
||||
history=True,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Locate Traktor collections in their default install locations.
|
||||
|
||||
Traktor stores each version's data under a versioned folder:
|
||||
~/Documents/Native Instruments/Traktor <version>/collection.nml
|
||||
This is the same relative path on macOS and Windows (both under the user's
|
||||
Documents folder), so a single glob covers both.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)")
|
||||
|
||||
|
||||
def _traktor_root() -> Path:
|
||||
return Path.home() / "Documents" / "Native Instruments"
|
||||
|
||||
|
||||
def _version_key(version: str | None) -> tuple[int, ...]:
|
||||
"""Sortable tuple for a dotted version string; missing/odd → lowest."""
|
||||
if not version:
|
||||
return (0,)
|
||||
try:
|
||||
return tuple(int(p) for p in version.split("."))
|
||||
except ValueError:
|
||||
return (0,)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""Build a candidate record for a collection.nml path. The label/version
|
||||
come from the parent folder name (e.g. 'Traktor 4.5.0')."""
|
||||
parent = path.parent.name
|
||||
m = _VERSION_RE.search(parent)
|
||||
exists = path.is_file()
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": parent or path.name,
|
||||
"version": m.group(1) if m else None,
|
||||
"modified": (path.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_collections() -> list[dict]:
|
||||
"""All Traktor collection.nml files found in default locations, newest
|
||||
Traktor version first (then most-recently-modified)."""
|
||||
root = _traktor_root()
|
||||
found: list[dict] = []
|
||||
if not root.is_dir():
|
||||
return found
|
||||
for d in sorted(root.iterdir()):
|
||||
if not d.is_dir() or not d.name.lower().startswith("traktor"):
|
||||
continue
|
||||
nml = d / "collection.nml"
|
||||
if nml.is_file():
|
||||
found.append(describe(nml))
|
||||
found.sort(
|
||||
key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0),
|
||||
reverse=True,
|
||||
)
|
||||
return found
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Traktor LOCATION <-> OS path conversion.
|
||||
|
||||
A Traktor ``<LOCATION>`` is a ``(VOLUME, DIR, FILE)`` triple using ``/:`` as its
|
||||
directory separator, with the boot volume spelled ``Macintosh HD``. These two
|
||||
functions are exact inverses of each other and are the only place that
|
||||
convention is encoded — keep them together, and keep them out of ``core``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Traktor native model -> the generic projection.
|
||||
|
||||
The only place an NML dataclass is turned into a generic `Track`/`TrackCues`.
|
||||
Everything above this file sees generic types exclusively.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import CuePoint, GridMarker, Track, TrackCues
|
||||
from . import beatgrid
|
||||
|
||||
|
||||
def primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
def to_track(e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
cues = e.cue_v2 or []
|
||||
hotcues = sum(
|
||||
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
|
||||
)
|
||||
markers = beatgrid.grid_markers(e)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=info.import_date if info else None,
|
||||
last_played=info.last_played if info else None,
|
||||
release_date=info.release_date if info else None,
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=hotcues,
|
||||
has_grid=bool(markers),
|
||||
grid_markers=len(markers),
|
||||
is_stem=getattr(e, "stems", None) is not None,
|
||||
)
|
||||
|
||||
|
||||
def to_track_cues(entry) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
The beatgrid is the FULL ordered marker list — a constant grid is a list of
|
||||
length one. Grid markers themselves are not cues; their companion cues are,
|
||||
because they occupy real hotcue slots, and each is tagged with the marker it
|
||||
belongs to so the UI can show it as beatgrid-owned rather than editable.
|
||||
"""
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
comps = beatgrid.companions(entry)
|
||||
marker_of = {id(c): i for i, c in comps.items()}
|
||||
grid_markers = [
|
||||
GridMarker(
|
||||
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms
|
||||
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
|
||||
name=m.name,
|
||||
companion=comps[i].hotcue if i in comps else None,
|
||||
)
|
||||
for i, m in enumerate(markers)
|
||||
]
|
||||
cues = [
|
||||
CuePoint(
|
||||
name=c.name,
|
||||
type=c.type if c.type is not None else 0,
|
||||
start=(c.start or 0.0) / 1000.0,
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
hotcue=c.hotcue if c.hotcue is not None else -1,
|
||||
color=c.color,
|
||||
grid_marker=marker_of.get(id(c)),
|
||||
)
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
]
|
||||
return TrackCues(
|
||||
grid_markers=grid_markers, locked=bool(entry.lock), cues=cues
|
||||
)
|
||||
@@ -0,0 +1,992 @@
|
||||
"""Editable playlist store backed by the traktor-nml-utils dataclass model.
|
||||
|
||||
Design goals:
|
||||
* minimal diff — unedited playlists must serialize byte-for-byte as Traktor
|
||||
wrote them (the xsdata serializer used by the library reproduces Traktor's
|
||||
exact formatting; lxml does not),
|
||||
* surgical — only the objects actually edited differ in the output; the rest
|
||||
of the ~14 MB file renders byte-identically,
|
||||
* safe — every save is committed to the collection's version history (see
|
||||
``history.py``); the commit is additive and never alters the saved bytes.
|
||||
|
||||
We edit the parsed dataclass model in memory and, on save, render the WHOLE
|
||||
model through the library's own pipeline — proven byte-identical for unedited
|
||||
content, so no splicing is needed.
|
||||
|
||||
Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
(``fld:<name>/<name>``). Smart playlists are read-only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import (
|
||||
TraktorCollection,
|
||||
format_traktor_layout,
|
||||
restore_traktor_float_format,
|
||||
)
|
||||
from traktor_nml_utils.models.collection import (
|
||||
Albumtype,
|
||||
CueV2Type,
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
Subnodestype,
|
||||
Tempotype,
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from ... import __version__, history
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.pathmap import common_dir_prefix
|
||||
from ...core.pathmap import PathMapping
|
||||
from ...schemas import PlaylistNode
|
||||
from . import beatgrid
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
|
||||
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
|
||||
# this email is what makes the stars show up in Traktor itself.
|
||||
TRAKTOR_POPM_EMAIL = "traktor@native-instruments.de"
|
||||
|
||||
|
||||
class PlaylistError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileTagResult:
|
||||
track_id: str
|
||||
file: str
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
commit: str | None # sha of the version-history commit (None if deduped/failed)
|
||||
tag_results: list[FileTagResult]
|
||||
|
||||
|
||||
class PlaylistStore:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.RLock()
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
self._load()
|
||||
|
||||
# ---- load ----------------------------------------------------------
|
||||
def _load(self) -> None:
|
||||
self._collection = TraktorCollection(path=self.nml_path)
|
||||
self._nml = self._collection.nml
|
||||
# Index collection entries by their Traktor primary key (volume+dir+file)
|
||||
# so track-metadata edits can find their ENTRY in O(1).
|
||||
self._entry_by_key: dict[str, Entrytype] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if loc:
|
||||
key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
self._entry_by_key[key] = e
|
||||
# Every edit this session, at field resolution: drives the file-tag sync,
|
||||
# the version-history message, and (later) undo.
|
||||
self._journal = EditJournal()
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
self.dirty = False
|
||||
|
||||
def _note(
|
||||
self,
|
||||
category: str,
|
||||
detail: str | None = None,
|
||||
track_id: str | None = None,
|
||||
target: str | None = None,
|
||||
) -> None:
|
||||
"""Record one command in the edit journal.
|
||||
|
||||
`category` names the scope and `detail` the operation; playlists carry
|
||||
their name as the target instead of a track id, and a remap carries its
|
||||
count. `target` optionally names the field/slot/marker touched.
|
||||
"""
|
||||
if category.startswith("playlist-"):
|
||||
self._journal.record("playlist", category.split("-", 1)[1], detail)
|
||||
elif category == "remap":
|
||||
self._journal.record("library", "remap", after=detail)
|
||||
elif category == "hotcue":
|
||||
self._journal.record("cue", detail or "modify", track_id, target)
|
||||
else:
|
||||
self._journal.record(category, detail or "edit", track_id, target)
|
||||
|
||||
def _root(self) -> Nodetype:
|
||||
node = self._nml.playlists.node if self._nml.playlists else None
|
||||
if node is None:
|
||||
raise PlaylistError("PLAYLISTS has no root NODE")
|
||||
return node
|
||||
|
||||
@staticmethod
|
||||
def _children(node: Nodetype) -> list[Nodetype]:
|
||||
return list(node.subnodes.node) if node.subnodes else []
|
||||
|
||||
# ---- tree walking --------------------------------------------------
|
||||
def tree(self) -> list[PlaylistNode]:
|
||||
with self._lock:
|
||||
return [self._to_model(c, []) for c in self._children(self._root())]
|
||||
|
||||
def _to_model(self, node: Nodetype, parent_path: list[str]) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
name = node.name or "(unnamed)"
|
||||
if ntype == "PLAYLIST" or node.playlist is not None:
|
||||
pl = node.playlist
|
||||
keys = self._entry_keys_of(pl) if pl is not None else []
|
||||
return PlaylistNode(
|
||||
id=pl.uuid if pl and pl.uuid else name,
|
||||
name=name,
|
||||
type="PLAYLIST",
|
||||
uuid=pl.uuid if pl else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or node.smartplaylist is not None:
|
||||
return PlaylistNode(
|
||||
id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST"
|
||||
)
|
||||
path = parent_path + [name]
|
||||
return PlaylistNode(
|
||||
id="fld:" + "/".join(path),
|
||||
name=name,
|
||||
type="FOLDER",
|
||||
children=[self._to_model(c, path) for c in self._children(node)],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _entry_keys_of(pl: Playlisttype) -> list[str]:
|
||||
return [
|
||||
e.primarykey.key
|
||||
for e in (pl.entry or [])
|
||||
if e.primarykey and e.primarykey.key
|
||||
]
|
||||
|
||||
# ---- lookups -------------------------------------------------------
|
||||
def _iter_nodes(self, node: Nodetype):
|
||||
yield node
|
||||
for c in self._children(node):
|
||||
yield from self._iter_nodes(c)
|
||||
|
||||
def _find_playlist_node(self, playlist_uuid: str) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.playlist is not None and n.playlist.uuid == playlist_uuid:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_parent_of(self, target: Nodetype) -> Nodetype | None:
|
||||
for n in self._iter_nodes(self._root()):
|
||||
if n.subnodes and target in n.subnodes.node:
|
||||
return n
|
||||
return None
|
||||
|
||||
def _find_folder(self, folder_id: str | None) -> Nodetype:
|
||||
root = self._root()
|
||||
if folder_id in (None, "", "fld:"):
|
||||
return root
|
||||
if not folder_id.startswith("fld:"):
|
||||
raise PlaylistError(f"Not a folder id: {folder_id}")
|
||||
cur = root
|
||||
for name in folder_id[len("fld:") :].split("/"):
|
||||
match = next(
|
||||
(
|
||||
c
|
||||
for c in self._children(cur)
|
||||
if (c.type or "FOLDER") == "FOLDER" and c.name == name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise PlaylistError(f"Folder not found: {folder_id}")
|
||||
cur = match
|
||||
return cur
|
||||
|
||||
def entry_keys(self, playlist_uuid: str) -> list[str] | None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
return None if node is None else self._entry_keys_of(node.playlist)
|
||||
|
||||
# ---- edits ---------------------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
with self._lock:
|
||||
folder = self._find_folder(parent_id)
|
||||
if folder.subnodes is None:
|
||||
folder.subnodes = Subnodestype(node=[], count=0)
|
||||
new_uuid = uuidlib.uuid4().hex
|
||||
node = Nodetype(
|
||||
type="PLAYLIST",
|
||||
name=name,
|
||||
playlist=Playlisttype(entry=[], entries=0, type="LIST", uuid=new_uuid),
|
||||
)
|
||||
folder.subnodes.node.append(node)
|
||||
folder.subnodes.count = len(folder.subnodes.node)
|
||||
self._note("playlist-create", name)
|
||||
self.dirty = True
|
||||
return new_uuid
|
||||
|
||||
def rename_playlist(self, playlist_uuid: str, name: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
node.name = name
|
||||
self._note("playlist-rename", name)
|
||||
self.dirty = True
|
||||
|
||||
def delete_playlist(self, playlist_uuid: str) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
parent = self._find_parent_of(node)
|
||||
if parent is None:
|
||||
raise PlaylistError("Cannot delete a top-level node")
|
||||
parent.subnodes.node.remove(node)
|
||||
parent.subnodes.count = len(parent.subnodes.node)
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
with self._lock:
|
||||
node = self._find_playlist_node(playlist_uuid)
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
pl = node.playlist
|
||||
pl.entry = [
|
||||
Entrytype(primarykey=Primarykeytype(type=ptype or "TRACK", key=key))
|
||||
for key, ptype in entries
|
||||
]
|
||||
pl.entries = len(pl.entry)
|
||||
self._note("playlist-entries", node.name)
|
||||
self.dirty = True
|
||||
|
||||
# ---- track metadata editing ---------------------------------------
|
||||
# Safe, free-text-ish fields only. Deliberately NOT editable here: file path
|
||||
# (it's the primary key), bpm/key (audio/grid territory), and read-only info
|
||||
# like bitrate/playcount.
|
||||
_INFO_FIELDS = {"genre", "label", "remixer", "producer", "comment", "mix", "release_date"}
|
||||
EDITABLE_FIELDS = {"title", "artist", "album", "rating"} | _INFO_FIELDS
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
if entry.info is None:
|
||||
entry.info = Infotype()
|
||||
for k, v in fields.items():
|
||||
if k in ("title", "artist"):
|
||||
setattr(entry, k, v or None)
|
||||
elif k == "album":
|
||||
if entry.album is None:
|
||||
entry.album = Albumtype()
|
||||
entry.album.title = v or None
|
||||
elif k in self._INFO_FIELDS:
|
||||
setattr(entry.info, k, v or None)
|
||||
elif k == "rating":
|
||||
stars = max(0, min(5, int(v))) if v is not None else 0
|
||||
# Traktor RANKING = stars * 51; unrated has no RANKING attr.
|
||||
entry.info.ranking = stars * 51 or None
|
||||
else:
|
||||
continue # unknown / read-only fields are ignored
|
||||
self._journal.record("track", "set", track_id, k)
|
||||
self.dirty = True
|
||||
|
||||
def iter_entries(self):
|
||||
"""Every collection ENTRY in document order.
|
||||
|
||||
Document order, not ``_entry_by_key.values()``: two entries can share a
|
||||
primary key, and the dict would silently drop one of them.
|
||||
"""
|
||||
with self._lock:
|
||||
return list(self._nml.collection.entry)
|
||||
|
||||
def stem_keys(self) -> set[str]:
|
||||
"""Track ids whose ENTRY has a <STEMS> child.
|
||||
|
||||
Playlist entries for these use ``PRIMARYKEY TYPE="STEM"`` (verified
|
||||
945/945 against the real collection); everything else uses ``TRACK``.
|
||||
"""
|
||||
with self._lock:
|
||||
return {
|
||||
f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}"
|
||||
for e in self._nml.collection.entry
|
||||
if e.location and getattr(e, "stems", None) is not None
|
||||
}
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""Pair each known track id with its PRIMARYKEY TYPE, dropping unknowns."""
|
||||
stems = self.stem_keys()
|
||||
with self._lock:
|
||||
known = self._entry_by_key
|
||||
return [
|
||||
(tid, "STEM" if tid in stems else "TRACK")
|
||||
for tid in track_ids
|
||||
if tid in known
|
||||
]
|
||||
|
||||
def model_entry(self, track_id: str) -> Entrytype | None:
|
||||
with self._lock:
|
||||
return self._entry_by_key.get(track_id)
|
||||
|
||||
# ---- hotcues ------------------------------------------------------
|
||||
# Creatable/editable types: 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop.
|
||||
# A loop (type 5) carries a length; the point types don't. Grid markers
|
||||
# (type 4, redefine the beatgrid) are excluded. Cues are NML-only.
|
||||
POINT_CUE_TYPES = {0, 1, 2, 3} # types the dropdown can switch between
|
||||
CREATABLE_TYPES = {0, 1, 2, 3, 5}
|
||||
|
||||
def _entry_or_raise(self, track_id: str) -> Entrytype:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
return entry
|
||||
|
||||
@staticmethod
|
||||
def _reject_if_companion(entry: Entrytype, slot: int) -> None:
|
||||
"""Refuse to touch a slot held by a grid marker's companion cue.
|
||||
|
||||
Traktor pairs most grid markers with a white cue in a real hotcue slot.
|
||||
Overwriting, retyping or deleting one desyncs it from its marker, so the
|
||||
beatgrid commands own these slots — move or delete the marker instead.
|
||||
"""
|
||||
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
|
||||
if cue is not None and beatgrid.is_companion(entry, cue):
|
||||
raise PlaylistError(
|
||||
f"Hotcue {slot + 1} belongs to a beatgrid marker — "
|
||||
"move or delete the marker instead"
|
||||
)
|
||||
|
||||
def set_hotcue(
|
||||
self,
|
||||
track_id: str,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: int,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""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."."""
|
||||
if not 0 <= slot <= 7:
|
||||
raise PlaylistError(f"Invalid hotcue slot: {slot}")
|
||||
if cue_type not in self.CREATABLE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._reject_if_companion(entry, slot)
|
||||
start_ms = max(0.0, start_sec * 1000.0) # Traktor stores START/LEN in ms
|
||||
len_ms = max(0.0, length_sec * 1000.0)
|
||||
existing = next(
|
||||
(c for c in (entry.cue_v2 or []) if c.hotcue == slot), None
|
||||
)
|
||||
if existing is not None:
|
||||
existing.start = start_ms
|
||||
existing.type = cue_type
|
||||
existing.len = len_ms
|
||||
else:
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name=name or "n.n.", # Traktor's default name for a manual cue
|
||||
displ_order=0,
|
||||
type=cue_type,
|
||||
start=start_ms,
|
||||
len=len_ms,
|
||||
repeats=-1,
|
||||
hotcue=slot,
|
||||
color=None,
|
||||
grid=None,
|
||||
)
|
||||
)
|
||||
# "add" only when it's a genuinely new hotcue; repositioning/retyping
|
||||
# an existing slot is a "modify" (keeps the net add/remove count honest).
|
||||
self._note(
|
||||
"hotcue", "modify" if existing is not None else "add", track_id, f"slot:{slot}"
|
||||
)
|
||||
self.dirty = True
|
||||
|
||||
def place_hotcues(
|
||||
self, track_id: str, specs: list, *, overwrite: bool = False
|
||||
) -> None:
|
||||
"""Batch-create hotcues from `specs` (each has .slot/.start/.name and
|
||||
optional .type/.length). With `overwrite` False (the default), slots that
|
||||
already hold a hotcue are skipped so hand-placed cues are never clobbered.
|
||||
Used by Auto Hotcues."""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
occupied = {
|
||||
c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
|
||||
}
|
||||
# Companion slots belong to the beatgrid — never fill them, even
|
||||
# with overwrite=True (occupied alone only guards them while False).
|
||||
protected = {
|
||||
c.hotcue for c in beatgrid.companions(entry).values() if c.hotcue is not None
|
||||
}
|
||||
for spec in specs:
|
||||
if spec.slot in protected or (not overwrite and spec.slot in occupied):
|
||||
continue
|
||||
self.set_hotcue(
|
||||
track_id,
|
||||
spec.slot,
|
||||
spec.start,
|
||||
getattr(spec, "type", 0),
|
||||
getattr(spec, "length", 0.0),
|
||||
name=getattr(spec, "name", None),
|
||||
)
|
||||
|
||||
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
|
||||
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
raise PlaylistError(f"Unsupported cue type: {cue_type}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._reject_if_companion(entry, slot)
|
||||
cue = next((c for c in (entry.cue_v2 or []) if c.hotcue == slot), None)
|
||||
if cue is None:
|
||||
raise PlaylistError(f"Hotcue {slot} is not set")
|
||||
cue.type = cue_type
|
||||
self._note("hotcue", "modify", track_id, f"slot:{slot}")
|
||||
self.dirty = True
|
||||
|
||||
def delete_hotcue(self, track_id: str, slot: int) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._reject_if_companion(entry, slot)
|
||||
before = entry.cue_v2 or []
|
||||
entry.cue_v2 = [c for c in before if c.hotcue != slot]
|
||||
if len(entry.cue_v2) != len(before): # only count an actual removal
|
||||
self._note("hotcue", "delete", track_id, f"slot:{slot}")
|
||||
self.dirty = True
|
||||
|
||||
# ---- beatgrid -----------------------------------------------------
|
||||
# A beatgrid is an ORDERED LIST of markers (see beatgrid.py); a constant
|
||||
# grid is a list of length one. Markers are addressed by their index in that
|
||||
# start-ordered list. CUE_V2 has no id attribute and save() reparses the
|
||||
# whole file, so any synthetic id would have to be rebuilt by position
|
||||
# anyway — the index IS the identity.
|
||||
_MARKER_MIN_GAP_MS = 1.0
|
||||
|
||||
@staticmethod
|
||||
def _grid_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
"""The first grid marker BY START — the one <TEMPO BPM> mirrors."""
|
||||
return beatgrid.first_marker(entry)
|
||||
|
||||
@staticmethod
|
||||
def _sync_tempo(entry: Entrytype) -> None:
|
||||
"""Mirror <TEMPO BPM> from the first marker (7968/7968 in the reference
|
||||
collection). Called last by every grid mutator, so a move that changes
|
||||
which marker is first re-mirrors for free.
|
||||
|
||||
With no markers left, TEMPO is LEFT ALONE: Traktor keeps the analysed
|
||||
BPM on gridless tracks (53 such entries exist in the reference file).
|
||||
"""
|
||||
marker = beatgrid.first_marker(entry)
|
||||
if marker is None or marker.grid is None or not marker.grid.bpm:
|
||||
return
|
||||
if entry.tempo is None:
|
||||
entry.tempo = Tempotype(bpm=marker.grid.bpm, bpm_quality=100.0)
|
||||
else:
|
||||
entry.tempo.bpm = marker.grid.bpm
|
||||
|
||||
@staticmethod
|
||||
def _sort_cues(entry: Entrytype) -> None:
|
||||
"""Keep CUE_V2 ascending by START — true for 8485/8485 reference
|
||||
entries, so an inserted marker must not become the one exception.
|
||||
Stable, so a marker stays ahead of a companion at an identical START.
|
||||
"""
|
||||
if entry.cue_v2:
|
||||
entry.cue_v2.sort(key=lambda c: c.start or 0.0)
|
||||
|
||||
def _markers_or_raise(
|
||||
self, entry: Entrytype, index: int
|
||||
) -> tuple[list[CueV2Type], CueV2Type]:
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
if not markers:
|
||||
raise PlaylistError("Track has no beatgrid")
|
||||
if not 0 <= index < len(markers):
|
||||
raise PlaylistError(
|
||||
f"Grid marker {index} out of range (track has {len(markers)})"
|
||||
)
|
||||
return markers, markers[index]
|
||||
|
||||
def _drop_grid(self, entry: Entrytype) -> None:
|
||||
"""Remove every marker AND every companion. No _note — callers do that."""
|
||||
doomed = {id(m) for m in beatgrid.grid_markers(entry)}
|
||||
doomed |= {id(c) for c in beatgrid.companions(entry).values()}
|
||||
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed]
|
||||
|
||||
def add_grid_marker(
|
||||
self,
|
||||
track_id: str,
|
||||
start_sec: float,
|
||||
bpm: float | None = None,
|
||||
name: str | None = None,
|
||||
) -> int:
|
||||
"""Add a beatgrid marker at `start_sec`; returns its index.
|
||||
|
||||
With `bpm` unset the marker INHERITS the tempo of the section it lands
|
||||
in, so splitting a section is musically a no-op until it's retempoed.
|
||||
Creates no companion cue — Traktor tolerates markers without one, and
|
||||
inventing them would silently consume the user's hotcue slots.
|
||||
"""
|
||||
if bpm is not None and bpm <= 0:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
start_ms = max(0.0, start_sec * 1000.0)
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
for m in markers:
|
||||
if abs((m.start or 0.0) - start_ms) < self._MARKER_MIN_GAP_MS:
|
||||
raise PlaylistError("A grid marker already exists at that position")
|
||||
if bpm is None:
|
||||
bpm = self._bpm_governing(entry, start_ms)
|
||||
if bpm is None:
|
||||
raise PlaylistError("No BPM available to create a beatgrid")
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name=name or ("AutoGrid" if not markers else "n.n."),
|
||||
displ_order=0,
|
||||
type=4,
|
||||
start=start_ms,
|
||||
len=0.0,
|
||||
repeats=-1,
|
||||
hotcue=-1,
|
||||
color=None,
|
||||
grid=GridType(bpm=bpm),
|
||||
)
|
||||
)
|
||||
self._sort_cues(entry)
|
||||
self._sync_tempo(entry)
|
||||
self._note("grid", "marker-add", track_id)
|
||||
self.dirty = True
|
||||
return next(
|
||||
i
|
||||
for i, m in enumerate(beatgrid.grid_markers(entry))
|
||||
if abs((m.start or 0.0) - start_ms) < 1e-9
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _bpm_governing(entry: Entrytype, start_ms: float) -> float | None:
|
||||
"""The tempo in force at `start_ms`: the last marker at or before it,
|
||||
else the first marker (extrapolated backwards), else <TEMPO BPM>."""
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
if not markers:
|
||||
return entry.tempo.bpm if entry.tempo else None
|
||||
governing = markers[0]
|
||||
for m in markers:
|
||||
if (m.start or 0.0) <= start_ms:
|
||||
governing = m
|
||||
else:
|
||||
break
|
||||
return governing.grid.bpm if governing.grid else None
|
||||
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> None:
|
||||
"""Move marker `index`, DRAGGING ITS COMPANION with it.
|
||||
|
||||
The new position is CLAMPED between the neighbouring markers rather than
|
||||
allowed to reorder them, so an index can never go stale mid-edit. Phase
|
||||
nudges are +/-1 and +/-10 ms, so this is no practical constraint;
|
||||
restructuring a grid is add-then-delete.
|
||||
"""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
markers, marker = self._markers_or_raise(entry, index)
|
||||
start_ms = max(0.0, start_sec * 1000.0)
|
||||
if index > 0:
|
||||
lo = (markers[index - 1].start or 0.0) + self._MARKER_MIN_GAP_MS
|
||||
start_ms = max(start_ms, lo)
|
||||
if index < len(markers) - 1:
|
||||
hi = (markers[index + 1].start or 0.0) - self._MARKER_MIN_GAP_MS
|
||||
start_ms = min(start_ms, hi)
|
||||
companion = beatgrid.companions(entry).get(index)
|
||||
marker.start = start_ms
|
||||
if companion is not None:
|
||||
# Copy the float — never recompute from seconds. A 1-ULP drift
|
||||
# here would change the rendered bytes and break byte-reverts.
|
||||
companion.start = marker.start
|
||||
self._sync_tempo(entry)
|
||||
self._note("grid", "marker-move", track_id, f"marker:{index}")
|
||||
self.dirty = True
|
||||
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> None:
|
||||
"""Set marker `index`'s tempo (governs until the next marker)."""
|
||||
if bpm <= 0:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
_, marker = self._markers_or_raise(entry, index)
|
||||
if marker.grid is None:
|
||||
marker.grid = GridType(bpm=bpm)
|
||||
else:
|
||||
marker.grid.bpm = bpm
|
||||
self._sync_tempo(entry)
|
||||
self._note("grid", "marker-bpm", track_id, f"marker:{index}")
|
||||
self.dirty = True
|
||||
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> None:
|
||||
"""Remove marker `index` and its companion (freeing that hotcue slot)."""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
markers, marker = self._markers_or_raise(entry, index)
|
||||
companion = beatgrid.companions(entry).get(index)
|
||||
doomed = {id(marker)} | ({id(companion)} if companion is not None else set())
|
||||
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if id(c) not in doomed]
|
||||
self._sync_tempo(entry)
|
||||
# Removing the last marker IS deleting the grid — report it as one.
|
||||
self._note(
|
||||
"grid",
|
||||
"delete" if len(markers) == 1 else "marker-delete",
|
||||
track_id,
|
||||
f"marker:{index}",
|
||||
)
|
||||
self.dirty = True
|
||||
|
||||
def replace_grid(
|
||||
self, track_id: str, markers: list[tuple[float, float]]
|
||||
) -> None:
|
||||
"""Throw the grid away and rebuild it from `markers` [(start_sec, bpm)].
|
||||
|
||||
Serves both Auto Grid (a single marker) and the deck's Reset (restore
|
||||
the list as loaded) as one atomic, single-event command. Companions of
|
||||
the old grid go with it; none are created.
|
||||
"""
|
||||
for start_sec, bpm in markers:
|
||||
if bpm <= 0:
|
||||
raise PlaylistError(f"BPM must be positive: {bpm}")
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._drop_grid(entry)
|
||||
if entry.cue_v2 is None:
|
||||
entry.cue_v2 = []
|
||||
for i, (start_sec, bpm) in enumerate(
|
||||
sorted(markers, key=lambda m: m[0])
|
||||
):
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name="AutoGrid" if i == 0 else "n.n.",
|
||||
displ_order=0,
|
||||
type=4,
|
||||
start=max(0.0, start_sec * 1000.0),
|
||||
len=0.0,
|
||||
repeats=-1,
|
||||
hotcue=-1,
|
||||
color=None,
|
||||
grid=GridType(bpm=bpm),
|
||||
)
|
||||
)
|
||||
self._sort_cues(entry)
|
||||
self._sync_tempo(entry)
|
||||
self._note("grid", "replace", track_id)
|
||||
self.dirty = True
|
||||
|
||||
def place_grid_companion(
|
||||
self, track_id: str, index: int, *, prefer_slot: int = 0
|
||||
) -> int | None:
|
||||
"""Give marker `index` the white beat-1 hotcue Traktor writes beside its
|
||||
own markers: `prefer_slot` when free, else the lowest free slot.
|
||||
|
||||
Returns the slot used, or None when the bank is full or the marker
|
||||
already has a companion. NEVER overwrites. This is the ONLY place
|
||||
Konduktor creates a companion — grid edits never do — because it is a
|
||||
deliberate, user-invoked feature (Auto Grid), not a side effect.
|
||||
"""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
_, marker = self._markers_or_raise(entry, index)
|
||||
if index in beatgrid.companions(entry):
|
||||
return None
|
||||
used = {
|
||||
c.hotcue
|
||||
for c in (entry.cue_v2 or [])
|
||||
if c.hotcue is not None and c.hotcue >= 0
|
||||
}
|
||||
slot = next(
|
||||
(s for s in [prefer_slot, *range(8)] if 0 <= s <= 7 and s not in used),
|
||||
None,
|
||||
)
|
||||
if slot is None:
|
||||
return None
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name=marker.name or "AutoGrid",
|
||||
displ_order=0,
|
||||
type=0,
|
||||
start=marker.start, # copy the float, not start_sec * 1000
|
||||
len=0.0,
|
||||
repeats=-1,
|
||||
hotcue=slot,
|
||||
color=beatgrid.COMPANION_COLOR,
|
||||
grid=None,
|
||||
)
|
||||
)
|
||||
self._sort_cues(entry)
|
||||
self._note("grid", "marker-add", track_id)
|
||||
self.dirty = True
|
||||
return slot
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
"""Remove EVERY grid marker AND EVERY companion; <TEMPO> is kept.
|
||||
|
||||
Dropping companions is the debris fix: the old code stripped markers
|
||||
only, leaving orphan white cues squatting in hotcue slots.
|
||||
"""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
self._drop_grid(entry)
|
||||
self._note("grid", "delete", track_id)
|
||||
self.dirty = True
|
||||
|
||||
def set_lock(self, track_id: str, locked: bool) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.lock = 1 if locked else None
|
||||
self._note("lock", "on" if locked else "off", track_id)
|
||||
self.dirty = True
|
||||
|
||||
# ---- cover art -----------------------------------------------------
|
||||
def set_track_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with self._lock:
|
||||
if track_id not in self._entry_by_key:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
self._track_art[track_id] = (data, mime)
|
||||
self.dirty = True
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Set the active OS-path prefix remapping (applied at resolve time)."""
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def _resolve(self, loc) -> "Path | None":
|
||||
"""Resolve a LOCATION to an OS path, applying the active path mapping.
|
||||
|
||||
The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap.
|
||||
Falls back to the un-remapped path when the remapped target doesn't
|
||||
exist, so a misconfigured mapping never makes a present file unreachable.
|
||||
"""
|
||||
|
||||
if loc is None:
|
||||
return None
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if self._path_mapping.empty:
|
||||
return base
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped == base:
|
||||
return base
|
||||
return remapped if remapped.exists() else base
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""Staged replacement if present, else the file's current embedded art."""
|
||||
from ...core import audio_tags as file_tags
|
||||
|
||||
with self._lock:
|
||||
if track_id in self._track_art:
|
||||
return self._track_art[track_id]
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
path = self._resolve(entry.location)
|
||||
return file_tags.read_cover(path) if path else None
|
||||
|
||||
def audio_path(self, track_id: str) -> "Path | None":
|
||||
"""Resolve a track's audio file to an OS path (for playback streaming)."""
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
return self._resolve(entry.location)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
"""Auto-suggest ``from`` prefixes by resolving every track's LOCATION and
|
||||
finding the common directory prefix per volume. Returns a ``primary``
|
||||
(the largest group's prefix) plus per-group prefixes ranked by track
|
||||
count, so the editor can prefill and offer alternatives."""
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
with self._lock:
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
groups[loc.volume or ""].append(
|
||||
str(resolve_path(loc.volume, loc.dir, loc.file))
|
||||
)
|
||||
ranked = sorted(
|
||||
(
|
||||
{"prefix": common_dir_prefix(paths), "count": len(paths)}
|
||||
for paths in groups.values()
|
||||
),
|
||||
key=lambda g: g["count"],
|
||||
reverse=True,
|
||||
)
|
||||
ranked = [g for g in ranked if g["prefix"]]
|
||||
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
"""How a mapping would affect the collection, without changing anything:
|
||||
total tracks, how many match ``from``, and how many exist at ``to``
|
||||
(plus a few samples). Powers the mapping editor's validation line."""
|
||||
|
||||
with self._lock:
|
||||
total = matched = existing = 0
|
||||
samples: list[dict] = []
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
total += 1
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if mapping.matches(base):
|
||||
matched += 1
|
||||
target = mapping.apply(base)
|
||||
ok = target.exists()
|
||||
if ok:
|
||||
existing += 1
|
||||
if len(samples) < 5:
|
||||
samples.append({"from": str(base), "to": str(target), "exists": ok})
|
||||
return {"total": total, "matched": matched, "existing": existing, "samples": samples}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> int:
|
||||
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to``
|
||||
prefix — a deliberate library move (write-back).
|
||||
|
||||
Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every
|
||||
playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too,
|
||||
so playlists keep pointing at their tracks. Non-matching entries are
|
||||
untouched. Returns the number of tracks rewritten; the caller saves.
|
||||
"""
|
||||
|
||||
if mapping.empty:
|
||||
return 0
|
||||
with self._lock:
|
||||
key_remap: dict[str, str] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
target = mapping.apply(base)
|
||||
volume, dir_, file = os_path_to_location(target)
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key == new_key:
|
||||
continue # no-op (e.g. from == to); leave byte-identical
|
||||
loc.volume, loc.dir, loc.file = volume, dir_, file
|
||||
key_remap[old_key] = new_key
|
||||
if not key_remap:
|
||||
return 0
|
||||
# Rewrite playlist entry primary keys that referenced moved tracks.
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
if pl is None or not pl.entry:
|
||||
continue
|
||||
for entry in pl.entry:
|
||||
pk = entry.primarykey
|
||||
if pk and pk.key in key_remap:
|
||||
pk.key = key_remap[pk.key]
|
||||
# Track ids derive from the LOCATION, so a remap renames them. Carry
|
||||
# this session's journal entries across or their file-tag sync is lost.
|
||||
for old_key, new_key in key_remap.items():
|
||||
self._journal.retarget(old_key, new_key)
|
||||
self._note("remap", str(len(key_remap)))
|
||||
self.dirty = True
|
||||
return len(key_remap)
|
||||
|
||||
def _entry_field_value(self, entry: Entrytype, field: str):
|
||||
"""Read a single editable field's current value from the model, in the
|
||||
shape file_tags expects (rating as 0–5 stars)."""
|
||||
if field == "title":
|
||||
return entry.title
|
||||
if field == "artist":
|
||||
return entry.artist
|
||||
if field == "album":
|
||||
return entry.album.title if entry.album else None
|
||||
if field == "rating":
|
||||
r = entry.info.ranking if entry.info else None
|
||||
return round(r / 51) if r else 0
|
||||
return getattr(entry.info, field, None) if entry.info else None
|
||||
|
||||
def count_playlists(self) -> int:
|
||||
with self._lock:
|
||||
return sum(1 for n in self._iter_nodes(self._root()) if n.playlist is not None)
|
||||
|
||||
# ---- persistence ---------------------------------------------------
|
||||
def save(self) -> "SaveOutcome":
|
||||
with self._lock:
|
||||
new_data = self._render()
|
||||
tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp")
|
||||
tmp.write_bytes(new_data)
|
||||
tmp.replace(self.nml_path)
|
||||
# Best-effort: sync the edited fields into each edited track's file.
|
||||
tag_results = self._sync_file_tags()
|
||||
# Version history: commit the saved bytes (additive — never touches the
|
||||
# file we just wrote). Summary is computed before _load() clears state.
|
||||
commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__)
|
||||
self._load() # clears dirty + the edit journal + staged art
|
||||
return SaveOutcome(commit=commit, tag_results=tag_results)
|
||||
|
||||
def _edit_summary(self) -> str:
|
||||
"""Delegates to the journal; kept as a method because save() and the
|
||||
tests reach for it by this name."""
|
||||
return self._journal.summary(extra_tracks=set(self._track_art))
|
||||
|
||||
def _sync_file_tags(self) -> list["FileTagResult"]:
|
||||
from ...core import audio_tags as file_tags
|
||||
|
||||
results: list[FileTagResult] = []
|
||||
# Union of tracks with edited fields and/or replaced art.
|
||||
for track_id in self._journal.edited_tracks() | self._track_art.keys():
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
continue
|
||||
path = self._resolve(entry.location)
|
||||
if path is None:
|
||||
continue
|
||||
# Report BOTH writes: a failed tag write must not be masked by a
|
||||
# successful art write on the same track.
|
||||
written = []
|
||||
if fields := self._journal.fields_for(track_id):
|
||||
meta = {f: self._entry_field_value(entry, f) for f in fields}
|
||||
written.append(file_tags.write_tags(path, meta, popm_email=TRAKTOR_POPM_EMAIL))
|
||||
if track_id in self._track_art:
|
||||
data, mime = self._track_art[track_id]
|
||||
written.append(file_tags.write_cover(path, data, mime))
|
||||
for r in written:
|
||||
results.append(
|
||||
FileTagResult(
|
||||
track_id=track_id, file=str(path), ok=r.ok, status=r.status, detail=r.detail
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def _render(self) -> bytes:
|
||||
"""Render the whole model exactly as the library's save() does.
|
||||
|
||||
The two post-processing steps restore Traktor's precise layout (expanded
|
||||
empty tags, 6-decimal floats, newlines), so a no-op render reproduces the
|
||||
file byte-for-byte and only the objects we actually edited (playlists
|
||||
AND/OR track entries) diff. Verified by backend/test_save_fidelity.py.
|
||||
"""
|
||||
s = XmlSerializer().render(self._nml)
|
||||
s = restore_traktor_float_format(s, self._nml)
|
||||
s = format_traktor_layout(s)
|
||||
return s.encode("utf-8")
|
||||
@@ -1,236 +1,11 @@
|
||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
||||
"""Compatibility shim — this module moved to ``konduktor.core.auto_hotcues``.
|
||||
|
||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
||||
implemented on top of librosa: beat-synchronous CQT features → a
|
||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
||||
|
||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
||||
beatgrid) — the latter is unit-testable without audio.
|
||||
Kept so the existing test suite keeps importing the old path unchanged while the
|
||||
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
|
||||
``sys.modules`` makes this module *be* the new one, so private names resolve too.
|
||||
"""
|
||||
import sys
|
||||
|
||||
from __future__ import annotations
|
||||
from .core import auto_hotcues as _moved
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
||||
MAX_HOTCUES = 8
|
||||
|
||||
_SR = 22050
|
||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
||||
|
||||
|
||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
||||
"""Detect structural boundaries in a track.
|
||||
|
||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
||||
(used downstream for positional naming). Sorted by time.
|
||||
"""
|
||||
import librosa
|
||||
from scipy.ndimage import median_filter
|
||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
||||
from scipy.linalg import eigh
|
||||
import sklearn.cluster
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.0:
|
||||
return [], duration
|
||||
|
||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
if len(beats) < 4:
|
||||
return [], duration
|
||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
||||
|
||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
||||
# a repetition graph (which beats sound alike) blended with a local path
|
||||
# graph (consecutive-beat timbral continuity).
|
||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
||||
rec = median_filter(rec, size=(1, 7))
|
||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
||||
msync = librosa.util.sync(mfcc, beats)
|
||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
||||
graph = mu * rec + (1 - mu) * path
|
||||
|
||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
||||
lap = csgraph_laplacian(graph, normed=True)
|
||||
_, evecs = eigh(lap)
|
||||
evecs = median_filter(evecs, size=(9, 1))
|
||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
||||
|
||||
# Boundaries = beats where the section-type label changes (plus the start).
|
||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
||||
|
||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
||||
rms = librosa.feature.rms(y=y)[0]
|
||||
rms_t = librosa.times_like(rms, sr=sr)
|
||||
rms_max = float(rms.max()) or 1.0
|
||||
out: list[tuple[float, float]] = []
|
||||
for j, bi in enumerate(bound_beats):
|
||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
||||
t_next = (
|
||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
||||
if j + 1 < len(bound_beats)
|
||||
else duration
|
||||
)
|
||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
||||
out.append((t, energy))
|
||||
return out, duration
|
||||
|
||||
|
||||
def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
|
||||
"""Detect a track's tempo and the time of its first beat.
|
||||
|
||||
Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
|
||||
anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
|
||||
left for the user to fix with the ×2 / ÷2 controls (per product decision).
|
||||
"""
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
bpm = float(np.ravel(tempo)[0])
|
||||
if bpm <= 0 or len(beats) == 0:
|
||||
raise ValueError("Could not detect a tempo/beat")
|
||||
first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
|
||||
return bpm, first_beat
|
||||
|
||||
|
||||
def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]:
|
||||
"""The ``(start, bpm)`` of the beatgrid segment containing ``t``.
|
||||
|
||||
Times before the first marker use the first segment, extrapolated backwards
|
||||
— the same convention the deck draws with.
|
||||
"""
|
||||
seg = markers[0]
|
||||
for m in markers:
|
||||
if m[0] <= t:
|
||||
seg = m
|
||||
else:
|
||||
break
|
||||
return seg
|
||||
|
||||
|
||||
def snap_to_phrase(
|
||||
t: float, markers: list[tuple[float, float]], phrase_bars: int = 16
|
||||
) -> float:
|
||||
"""Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT.
|
||||
|
||||
Snapping is deliberately segment-local rather than a running phrase count
|
||||
across the whole track: a flexible grid exists precisely because the tempo
|
||||
drifted, so carrying a phrase count across a marker seam would propagate the
|
||||
very error the marker was placed to correct. With a single marker this is
|
||||
exactly the old ``anchor + round((t - anchor) / phrase) * phrase``.
|
||||
"""
|
||||
anchor, bpm = _segment_for(t, markers)
|
||||
phrase = phrase_bars * 4 * (60.0 / bpm)
|
||||
return anchor + round((t - anchor) / phrase) * phrase
|
||||
|
||||
|
||||
def select_hotcues(
|
||||
boundaries: list[tuple[float, float]],
|
||||
*,
|
||||
markers: list[tuple[float, float]],
|
||||
duration: float,
|
||||
free_slots: list[int],
|
||||
existing_times: list[float],
|
||||
max_cues: int = MAX_HOTCUES,
|
||||
phrase_bars: int = 16,
|
||||
) -> list[dict]:
|
||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
||||
|
||||
``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start —
|
||||
a constant-tempo track is simply a one-element list.
|
||||
|
||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own
|
||||
tempo segment (which also merges near-duplicates), drops any coinciding with
|
||||
an existing hotcue, caps to the free slots (down-sampling evenly if there
|
||||
are too many), and assigns positional names. Returns dicts with
|
||||
slot/start/name/type/length.
|
||||
"""
|
||||
if not boundaries or not free_slots or not markers or markers[0][1] <= 0:
|
||||
return []
|
||||
|
||||
# Tolerance for "same place as an existing cue" and the end clamp. Marker
|
||||
# BPMs differ by well under 1% in practice, so the first is representative.
|
||||
beat = 60.0 / markers[0][1]
|
||||
|
||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
||||
snapped: dict[float, float] = {}
|
||||
for t, energy in boundaries:
|
||||
p = snap_to_phrase(t, markers, phrase_bars)
|
||||
p = max(0.0, min(p, duration - beat))
|
||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
||||
|
||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
||||
def near_existing(t: float) -> bool:
|
||||
return any(abs(t - e) < beat for e in existing_times)
|
||||
|
||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
||||
if not points:
|
||||
return []
|
||||
|
||||
# If more candidates than free slots, down-sample evenly across the track
|
||||
# (keeps intro..outro coverage rather than just the first N).
|
||||
n = min(len(free_slots), max_cues)
|
||||
if len(points) > n:
|
||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
||||
points = [points[i] for i in sorted(set(idx))]
|
||||
|
||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
||||
slots = sorted(free_slots)[: len(points)]
|
||||
return [
|
||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
||||
for slot, (t, _), name in zip(slots, points, names)
|
||||
]
|
||||
|
||||
|
||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
||||
"""Positional-hint names from track position + energy trend (not true
|
||||
structural classification — the names are hints; value is the position)."""
|
||||
if not times:
|
||||
return []
|
||||
med = float(np.median(energies))
|
||||
raw: list[str] = []
|
||||
n = len(times)
|
||||
for i, (t, e) in enumerate(zip(times, energies)):
|
||||
frac = t / duration if duration else 0.0
|
||||
prev = energies[i - 1] if i > 0 else e
|
||||
if i == 0 or frac < 0.08:
|
||||
name = "Intro"
|
||||
elif i == n - 1 or frac > 0.85:
|
||||
name = "Outro"
|
||||
elif e - prev > 0.12 and e >= med:
|
||||
name = "Drop"
|
||||
elif prev - e > 0.12:
|
||||
name = "Break"
|
||||
elif e > prev:
|
||||
name = "Build"
|
||||
else:
|
||||
name = "Mid"
|
||||
raw.append(name)
|
||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
||||
counts: dict[str, int] = {}
|
||||
out: list[str] = []
|
||||
for name in raw:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
||||
return out
|
||||
sys.modules[__name__] = _moved
|
||||
@@ -1,117 +1,11 @@
|
||||
"""The beatgrid model: an ORDERED LIST of grid markers.
|
||||
"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.beatgrid``.
|
||||
|
||||
A Traktor beatgrid is not "a BPM and an anchor" — it is a list of `CUE_V2
|
||||
TYPE="4"` markers, each carrying its own `<GRID BPM>` child. Marker *i*'s tempo
|
||||
governs from its position until marker *i+1*. Traktor has stored grids this way
|
||||
since 3.4 (flexible beatgrids); a constant-tempo track is simply a list of
|
||||
length one, which is why this model is right for every track rather than a
|
||||
special case for flexible ones.
|
||||
|
||||
`<TEMPO BPM>` mirrors the FIRST marker by START.
|
||||
|
||||
Verified against the 8485-entry reference collection:
|
||||
* markers per entry: {1: 7966, 0: 517, 2: 2}
|
||||
* TEMPO.bpm == markers[0].grid.bpm in 7968/7968 entries with both
|
||||
* CUE_V2 is ascending by START in 8485/8485 entries
|
||||
* 53 entries have a TEMPO but no marker -> deleting a grid must KEEP TEMPO
|
||||
|
||||
Two rules that are easy to get wrong:
|
||||
|
||||
1. **Marker NAME is not a discriminator.** In the reference collection TYPE=4
|
||||
markers are named "AutoGrid" x7888, "n.n." x64, "Beat Marker" x14 and
|
||||
"Unnamed" x4. Identify a marker by having a `<GRID>` child, and order the
|
||||
list by START — never by name, never by document order.
|
||||
|
||||
2. **Companion cues are conventional, not structural.** Traktor usually writes a
|
||||
white TYPE=0 cue alongside each grid marker, at the same position, occupying
|
||||
a real hotcue slot. 7910 of 7970 markers have one; 60 do not, and one track
|
||||
has a companion on its first marker but not its second. So we follow them
|
||||
where they exist, keep them in sync, and NEVER invent one.
|
||||
|
||||
This module is pure and imports nothing else from the package, so it can be the
|
||||
single shared definition used by the store, the API projection and the read
|
||||
model — which previously each had their own and disagreed about BPM.
|
||||
Kept so the existing test suite keeps importing the old path unchanged while the
|
||||
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
|
||||
``sys.modules`` makes this module *be* the new one, so private names resolve too.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
|
||||
from traktor_nml_utils.models.collection import CueV2Type, Entrytype
|
||||
from .adapters.traktor import beatgrid as _moved
|
||||
|
||||
# How close a cue must sit to a marker to be considered its companion. Traktor
|
||||
# writes them at the identical START; 71 markers in the reference collection are
|
||||
# a fraction of a millisecond off, which this absorbs.
|
||||
COMPANION_EPS_MS = 1.0
|
||||
|
||||
# Companions are always white. This test is LOAD-BEARING: 49 uncoloured cues and
|
||||
# 18 LOOPS also sit within 1 ms of a marker in the reference collection. Drop the
|
||||
# colour check and the marker commands would start dragging and deleting the
|
||||
# user's own loops.
|
||||
COMPANION_COLOR = "#FFFFFF"
|
||||
|
||||
|
||||
def grid_markers(entry: Entrytype) -> list[CueV2Type]:
|
||||
"""Every grid marker on `entry`, ordered by START.
|
||||
|
||||
Sorting is not cosmetic: the first marker by START is the one `<TEMPO BPM>`
|
||||
mirrors, and marker indices are the identity used by the edit commands.
|
||||
"""
|
||||
markers = [c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is not None]
|
||||
markers.sort(key=lambda c: c.start or 0.0)
|
||||
return markers
|
||||
|
||||
|
||||
def first_marker(entry: Entrytype) -> CueV2Type | None:
|
||||
"""The marker `<TEMPO BPM>` mirrors, or None when the track has no grid."""
|
||||
markers = grid_markers(entry)
|
||||
return markers[0] if markers else None
|
||||
|
||||
|
||||
def effective_bpm(entry: Entrytype) -> float | None:
|
||||
"""The tempo the grid actually starts at.
|
||||
|
||||
Prefers the first marker's `<GRID BPM>` and falls back to `<TEMPO BPM>` so
|
||||
the 53 gridless-but-tempo'd entries still report a BPM. Routing both the
|
||||
library table and the prep deck through this makes them structurally
|
||||
incapable of disagreeing.
|
||||
"""
|
||||
marker = first_marker(entry)
|
||||
if marker is not None and marker.grid is not None and marker.grid.bpm:
|
||||
return marker.grid.bpm
|
||||
return entry.tempo.bpm if entry.tempo else None
|
||||
|
||||
|
||||
def companions(entry: Entrytype) -> dict[int, CueV2Type]:
|
||||
"""Map marker index -> the companion cue paired with it, where one exists.
|
||||
|
||||
Greedy nearest-unclaimed matching, so two markers close together can never
|
||||
both claim the same cue.
|
||||
"""
|
||||
markers = grid_markers(entry)
|
||||
if not markers:
|
||||
return {}
|
||||
pool = [
|
||||
c
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
and c.type == 0
|
||||
and c.color == COMPANION_COLOR
|
||||
and c.hotcue is not None
|
||||
and c.hotcue >= 0
|
||||
]
|
||||
out: dict[int, CueV2Type] = {}
|
||||
claimed: set[int] = set()
|
||||
for i, m in enumerate(markers):
|
||||
m_start = m.start or 0.0
|
||||
best = min(
|
||||
(c for c in pool if id(c) not in claimed),
|
||||
key=lambda c: abs((c.start or 0.0) - m_start),
|
||||
default=None,
|
||||
)
|
||||
if best is not None and abs((best.start or 0.0) - m_start) <= COMPANION_EPS_MS:
|
||||
out[i] = best
|
||||
claimed.add(id(best))
|
||||
return out
|
||||
|
||||
|
||||
def is_companion(entry: Entrytype, cue: CueV2Type) -> bool:
|
||||
"""True when `cue` is some grid marker's companion on this entry."""
|
||||
return any(c is cue for c in companions(entry).values())
|
||||
sys.modules[__name__] = _moved
|
||||
@@ -1,319 +0,0 @@
|
||||
"""Loads a Traktor collection and serves query-friendly views of it.
|
||||
|
||||
Phase 1 is read-only. The service parses the .nml once into memory, builds a
|
||||
flat list of Track objects, a primary-key index (so playlist entries can be
|
||||
joined to full track metadata), and the playlist tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from traktor_nml_utils import TraktorCollection
|
||||
|
||||
from . import beatgrid
|
||||
|
||||
from .schemas import (
|
||||
Facets,
|
||||
GenreCount,
|
||||
PlaylistNode,
|
||||
Stats,
|
||||
Track,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
|
||||
def _primary_key(location) -> str:
|
||||
"""Reconstruct the Traktor primary key used by playlist entries."""
|
||||
vol = location.volume or ""
|
||||
d = location.dir or ""
|
||||
f = location.file or ""
|
||||
return f"{vol}{d}{f}"
|
||||
|
||||
|
||||
def _display_path(location) -> str:
|
||||
"""Human-readable OS-ish path from Traktor's '/:'-separated dir."""
|
||||
d = (location.dir or "").replace("/:", "/")
|
||||
f = location.file or ""
|
||||
return f"{d}{f}"
|
||||
|
||||
|
||||
def _rating_stars(ranking) -> int:
|
||||
if not ranking:
|
||||
return 0
|
||||
return max(0, min(5, round(ranking / 51)))
|
||||
|
||||
|
||||
class CollectionService:
|
||||
def __init__(self, nml_path: Path):
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
self.stem_keys: set[str] = set()
|
||||
self._playlist_entries: dict[str, list[str]] = {} # id -> ordered primary keys
|
||||
self._tree: list[PlaylistNode] = []
|
||||
self._playlist_count = 0
|
||||
self.load()
|
||||
|
||||
# ---- loading -------------------------------------------------------
|
||||
def load(self) -> None:
|
||||
with self._lock:
|
||||
collection = TraktorCollection(path=self.nml_path)
|
||||
self.tracks = [self._to_track(e) for e in collection.nml.collection.entry]
|
||||
self.by_key = {t.id: t for t in self.tracks}
|
||||
# Tracks with stems use PRIMARYKEY TYPE="STEM" in playlists (verified
|
||||
# 945/945 against the real collection); all others use "TRACK".
|
||||
self.stem_keys = {
|
||||
_primary_key(e.location)
|
||||
for e in collection.nml.collection.entry
|
||||
if e.location and getattr(e, "stems", None) is not None
|
||||
}
|
||||
self._playlist_entries = {}
|
||||
self._playlist_count = 0
|
||||
counter = {"n": 0}
|
||||
root = collection.nml.playlists.node if collection.nml.playlists else None
|
||||
self._tree = self._build_tree(root, counter) if root else []
|
||||
|
||||
def _to_track(self, e) -> Track:
|
||||
info = e.info
|
||||
loc = e.location
|
||||
cues = e.cue_v2 or []
|
||||
hotcues = sum(
|
||||
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
|
||||
)
|
||||
markers = beatgrid.grid_markers(e)
|
||||
return Track(
|
||||
id=_primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
title=e.title,
|
||||
album=e.album.title if e.album else None,
|
||||
genre=info.genre if info else None,
|
||||
label=info.label if info else None,
|
||||
remixer=info.remixer if info else None,
|
||||
producer=info.producer if info else None,
|
||||
mix=info.mix if info else None,
|
||||
comment=info.comment if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
playcount=info.playcount if info else None,
|
||||
length=info.playtime if info else None,
|
||||
bitrate=info.bitrate if info else None,
|
||||
import_date=info.import_date if info else None,
|
||||
last_played=info.last_played if info else None,
|
||||
release_date=info.release_date if info else None,
|
||||
filepath=_display_path(loc) if loc else None,
|
||||
cue_count=len(cues),
|
||||
hotcue_count=hotcues,
|
||||
has_grid=bool(markers),
|
||||
grid_markers=len(markers),
|
||||
is_stem=getattr(e, "stems", None) is not None,
|
||||
)
|
||||
|
||||
def _build_tree(self, node, counter, is_root=True) -> list[PlaylistNode]:
|
||||
"""Return the children of the $ROOT folder as the top-level tree."""
|
||||
if node is None:
|
||||
return []
|
||||
# Root ($ROOT) is a wrapper folder; expose its children as top level.
|
||||
if is_root and node.subnodes:
|
||||
out = []
|
||||
for child in node.subnodes.node:
|
||||
out.append(self._node_to_model(child, counter))
|
||||
return out
|
||||
return [self._node_to_model(node, counter)]
|
||||
|
||||
def _node_to_model(self, node, counter) -> PlaylistNode:
|
||||
ntype = node.type or "FOLDER"
|
||||
if ntype == "PLAYLIST" or (node.playlist is not None):
|
||||
nid = f"pl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
self._playlist_count += 1
|
||||
keys = []
|
||||
if node.playlist and node.playlist.entry:
|
||||
for en in node.playlist.entry:
|
||||
if en.primarykey and en.primarykey.key:
|
||||
keys.append(en.primarykey.key)
|
||||
self._playlist_entries[nid] = keys
|
||||
return PlaylistNode(
|
||||
id=nid,
|
||||
name=node.name or "(unnamed)",
|
||||
type="PLAYLIST",
|
||||
uuid=node.playlist.uuid if node.playlist else None,
|
||||
count=len(keys),
|
||||
)
|
||||
if ntype == "SMARTLIST" or getattr(node, "smartlist", None) is not None:
|
||||
# Smart playlists are dynamic (rule-based); no static entry list.
|
||||
nid = f"sl-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
return PlaylistNode(id=nid, name=node.name or "(smart)", type="SMARTLIST")
|
||||
# FOLDER
|
||||
nid = f"fld-{counter['n']}"
|
||||
counter["n"] += 1
|
||||
children = []
|
||||
if node.subnodes:
|
||||
for child in node.subnodes.node:
|
||||
children.append(self._node_to_model(child, counter))
|
||||
return PlaylistNode(
|
||||
id=nid, name=node.name or "(folder)", type="FOLDER", children=children
|
||||
)
|
||||
|
||||
# ---- queries -------------------------------------------------------
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def replace_track(self, track_id: str, entry) -> None:
|
||||
"""Refresh the read projection for one track from its (edited) model
|
||||
entry, mutating the existing Track object in place so both `tracks` and
|
||||
`by_key` reflect it. Bridges the store (edit model) and this read model
|
||||
until they're consolidated."""
|
||||
old = self.by_key.get(track_id)
|
||||
if old is None:
|
||||
return
|
||||
new = self._to_track(entry)
|
||||
for field in type(new).model_fields:
|
||||
setattr(old, field, getattr(new, field))
|
||||
|
||||
def entries_for(self, track_ids: list[str]) -> list[tuple[str, str]]:
|
||||
"""Map track ids to (key, PRIMARYKEY-type) pairs for playlist writing.
|
||||
Unknown ids are skipped (can't reference a track not in the collection)."""
|
||||
out = []
|
||||
for tid in track_ids:
|
||||
if tid in self.by_key:
|
||||
out.append((tid, "STEM" if tid in self.stem_keys else "TRACK"))
|
||||
return out
|
||||
|
||||
def stats(self, playlist_count: int | None = None) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=self._playlist_count if playlist_count is None else playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return self._tree
|
||||
|
||||
def playlist_tracks(self, playlist_id: str) -> list[Track] | None:
|
||||
if playlist_id not in self._playlist_entries:
|
||||
return None
|
||||
out = []
|
||||
for k in self._playlist_entries[playlist_id]:
|
||||
t = self.by_key.get(k)
|
||||
if t is not None:
|
||||
out.append(t)
|
||||
return out
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Platform-independent core: the generic model, the query/projection layer and
|
||||
the format-agnostic helpers.
|
||||
|
||||
Nothing in here may import ``traktor_nml_utils`` or ``konduktor.adapters`` —
|
||||
``test_layering.py`` enforces that. This package is what a Rekordbox or Serato
|
||||
adapter will be written against.
|
||||
"""
|
||||
@@ -0,0 +1,133 @@
|
||||
"""The adapter contract: what the app needs from a DJ library, generically.
|
||||
|
||||
Konduktor's save model is **projection + command replay**. The generic model is
|
||||
a READ PROJECTION; edits are commands an adapter replays onto its RETAINED
|
||||
NATIVE MODEL, which stays the write target. The generic model is never
|
||||
serialized back over a library — that is what preserves byte-exact saves, and
|
||||
it is also the only model that works for formats you cannot regenerate at all
|
||||
(a Rekordbox SQLite row, a Serato tag inside an audio file).
|
||||
|
||||
Two rules keep this honest:
|
||||
|
||||
* **No native type appears in any signature here.** If a concept cannot be
|
||||
expressed generically it does not belong on the protocol.
|
||||
* **Every mutating command returns its refreshed projection.** That makes the
|
||||
refresh an adapter-internal invariant rather than something each route has
|
||||
to remember; a forgotten refresh is a silently stale UI that no byte-level
|
||||
test would catch.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
|
||||
from .pathmap import PathMapping
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
"""Base for every failure an adapter reports to the HTTP layer."""
|
||||
|
||||
|
||||
class LibraryNotSupported(AdapterError):
|
||||
"""No driver can open this path, or it failed to parse."""
|
||||
|
||||
|
||||
class NotFound(AdapterError):
|
||||
"""Unknown track, playlist or marker index."""
|
||||
|
||||
|
||||
class InvalidCommand(AdapterError):
|
||||
"""Well-formed request the library cannot accept (bad slot, BPM <= 0, ...)."""
|
||||
|
||||
|
||||
class Unsupported(AdapterError):
|
||||
"""The platform cannot represent this edit at all."""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryAdapter(Protocol):
|
||||
"""One open library. Stateful; exactly one is loaded at a time."""
|
||||
|
||||
platform: str
|
||||
path: Path
|
||||
|
||||
# ---- identity -------------------------------------------------------
|
||||
def capabilities(self) -> Capabilities: ...
|
||||
def reload(self) -> None: ...
|
||||
|
||||
# ---- read projection -------------------------------------------------
|
||||
def tracks(self) -> list[Track]: ...
|
||||
def track(self, track_id: str) -> Track | None: ...
|
||||
def query_tracks(self, **kw) -> TrackPage: ...
|
||||
def facets(self) -> Facets: ...
|
||||
def stats(self, playlist_count: int) -> Stats: ...
|
||||
def playlist_tree(self) -> list[PlaylistNode]: ...
|
||||
def playlist_entries(self, node_id: str) -> list[str] | None: ...
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
|
||||
def track_cues(self, track_id: str) -> TrackCues | None: ...
|
||||
|
||||
# ---- commands: playlists --------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str: ...
|
||||
def rename_playlist(self, node_id: str, name: str) -> None: ...
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
def set_playlist_entries(self, node_id: str, 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: ...
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
|
||||
|
||||
# ---- commands: cues --------------------------------------------------
|
||||
def set_cue(
|
||||
self,
|
||||
track_id: str,
|
||||
*,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: str,
|
||||
length_sec: float = 0.0,
|
||||
role: str = "hotcue",
|
||||
name: str | None = None,
|
||||
) -> TrackCues: ...
|
||||
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
|
||||
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
|
||||
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
|
||||
|
||||
# ---- commands: beatgrid ---------------------------------------------
|
||||
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ...
|
||||
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: ...
|
||||
def set_grid_marker_bpm(self, track_id: str, index: int, bpm: float) -> TrackCues: ...
|
||||
def delete_grid_marker(self, track_id: str, index: int) -> TrackCues: ...
|
||||
def replace_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def set_analysed_grid(self, track_id: str, markers: list[tuple[float, float]]) -> TrackCues: ...
|
||||
def delete_grid(self, track_id: str) -> TrackCues: ...
|
||||
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
|
||||
|
||||
# ---- audio / paths ---------------------------------------------------
|
||||
def audio_path(self, track_id: str) -> Path | None: ...
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None: ...
|
||||
def path_prefix_suggestions(self) -> dict: ...
|
||||
def remap_preview(self, mapping: PathMapping) -> dict: ...
|
||||
def remap_locations(self, mapping: PathMapping) -> int: ...
|
||||
|
||||
# ---- save -------------------------------------------------------------
|
||||
@property
|
||||
def dirty(self) -> bool: ...
|
||||
def save(self): ...
|
||||
def snapshot(self) -> bytes: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class LibraryDriver(Protocol):
|
||||
"""Opens libraries of one platform. Stateless; one instance per platform."""
|
||||
|
||||
platform: str
|
||||
display_name: str
|
||||
suffixes: tuple[str, ...]
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
def detect(self) -> list: ...
|
||||
def describe(self, path: Path) -> object: ...
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Write track metadata into audio files' embedded tags (best-effort).
|
||||
|
||||
Konduktor's source of truth is the library file; this module additionally syncs the
|
||||
safe metadata fields into the audio file itself so the data travels with the
|
||||
file (portability to other apps). It is best-effort: if the file isn't present
|
||||
(e.g. the drive isn't mounted) or the format doesn't support a field, it reports
|
||||
that rather than failing the whole save.
|
||||
|
||||
Field writes are frame/atom-level, so unrelated tags (cover art, beatgrid BPM,
|
||||
key, track number, private frames) are preserved — verified against real files.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# Whose POPM frame we claim when writing an ID3 rating. The frame is per-owner,
|
||||
# so writing under the DJ app's own email is what makes the rating visible there.
|
||||
# The *51 scaling below is the POPM convention itself, not a platform quirk.
|
||||
DEFAULT_POPM_EMAIL = "no@email"
|
||||
|
||||
# The safe, editable metadata we sync to files (the adapter's editable field set).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagResult:
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
def read_cover(path: Path) -> tuple[bytes, str] | None:
|
||||
"""Return (image_bytes, mime) of the file's embedded front cover, or None."""
|
||||
if not path.exists():
|
||||
return None
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext in (".mp3", ".aif", ".aiff"):
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
return None
|
||||
apics = id3.getall("APIC")
|
||||
if not apics:
|
||||
return None
|
||||
front = next((a for a in apics if a.type == 3), apics[0])
|
||||
return bytes(front.data), (front.mime or "image/jpeg")
|
||||
if ext in (".m4a", ".mp4"):
|
||||
from mutagen.mp4 import MP4
|
||||
|
||||
covr = MP4(path).tags.get("covr") if MP4(path).tags else None
|
||||
if not covr:
|
||||
return None
|
||||
c = covr[0]
|
||||
from mutagen.mp4 import MP4Cover
|
||||
|
||||
mime = "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg"
|
||||
return bytes(c), mime
|
||||
if ext == ".flac":
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
pics = FLAC(path).pictures
|
||||
if not pics:
|
||||
return None
|
||||
front = next((p for p in pics if p.type == 3), pics[0])
|
||||
return bytes(front.data), (front.mime or "image/jpeg")
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def write_cover(path: Path, data: bytes, mime: str) -> TagResult:
|
||||
"""Replace the file's embedded front cover art. Best-effort."""
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
mime = mime if mime in ("image/jpeg", "image/png") else "image/jpeg"
|
||||
try:
|
||||
if ext in (".mp3", ".aif", ".aiff"):
|
||||
from mutagen.id3 import APIC
|
||||
|
||||
if ext == ".mp3":
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
tags = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
tags = ID3()
|
||||
tags.delall("APIC")
|
||||
tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
|
||||
tags.save(path)
|
||||
else:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
audio.tags.delall("APIC")
|
||||
audio.tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
|
||||
audio.save()
|
||||
elif ext in (".m4a", ".mp4"):
|
||||
from mutagen.mp4 import MP4, MP4Cover
|
||||
|
||||
audio = MP4(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG
|
||||
audio.tags["covr"] = [MP4Cover(data, imageformat=fmt)]
|
||||
audio.save()
|
||||
elif ext == ".flac":
|
||||
from mutagen.flac import FLAC, Picture
|
||||
|
||||
audio = FLAC(path)
|
||||
audio.clear_pictures()
|
||||
pic = Picture()
|
||||
pic.type = 3
|
||||
pic.mime = mime
|
||||
pic.data = data
|
||||
audio.add_picture(pic)
|
||||
audio.save()
|
||||
else:
|
||||
return TagResult(False, "unsupported-format", ext)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
|
||||
return TagResult(True, "written")
|
||||
|
||||
|
||||
def _clean(v) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def write_tags(
|
||||
path: Path, meta: TagMeta, *, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> TagResult:
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext == ".mp3":
|
||||
_write_id3(path, meta, id3_only=False, popm_email=popm_email)
|
||||
elif ext in (".aif", ".aiff"):
|
||||
_write_aiff(path, meta, popm_email=popm_email)
|
||||
elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"):
|
||||
_write_mp4(path, meta)
|
||||
elif ext == ".flac":
|
||||
_write_flac(path, meta)
|
||||
else:
|
||||
# WAV and anything else: tag support is weak/inconsistent — skip.
|
||||
return TagResult(False, "unsupported-format", ext)
|
||||
except Exception as ex: # noqa: BLE001 — best-effort; report, don't crash save
|
||||
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
|
||||
return TagResult(True, "written")
|
||||
|
||||
|
||||
# ---- ID3 (mp3 / aiff) --------------------------------------------------
|
||||
def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.id3 import (
|
||||
COMM,
|
||||
POPM,
|
||||
TALB,
|
||||
TCON,
|
||||
TDRC,
|
||||
TIT2,
|
||||
TIT3,
|
||||
TPE1,
|
||||
TPE4,
|
||||
TPUB,
|
||||
TXXX,
|
||||
)
|
||||
|
||||
simple = {
|
||||
"title": TIT2,
|
||||
"artist": TPE1,
|
||||
"album": TALB,
|
||||
"genre": TCON,
|
||||
"label": TPUB,
|
||||
"remixer": TPE4,
|
||||
"mix": TIT3,
|
||||
"release_date": TDRC,
|
||||
}
|
||||
for field, frame in simple.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
id3.delall(frame.__name__)
|
||||
if val is not None:
|
||||
id3.add(frame(encoding=3, text=[val]))
|
||||
if "producer" in meta:
|
||||
id3.delall("TXXX:PRODUCER")
|
||||
val = _clean(meta["producer"])
|
||||
if val is not None:
|
||||
id3.add(TXXX(encoding=3, desc="PRODUCER", text=[val]))
|
||||
if "comment" in meta:
|
||||
id3.delall("COMM")
|
||||
val = _clean(meta["comment"])
|
||||
if val is not None:
|
||||
id3.add(COMM(encoding=3, lang="eng", desc="", text=[val]))
|
||||
if "rating" in meta:
|
||||
id3.delall("POPM")
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
id3.add(
|
||||
POPM(
|
||||
email=popm_email,
|
||||
rating=max(0, min(5, stars)) * 51,
|
||||
count=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _write_id3(
|
||||
path: Path, meta: TagMeta, id3_only: bool, popm_email: str = DEFAULT_POPM_EMAIL
|
||||
) -> None:
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
id3 = ID3()
|
||||
_apply_id3(id3, meta, popm_email)
|
||||
id3.save(path)
|
||||
|
||||
|
||||
def _write_aiff(path: Path, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
_apply_id3(audio.tags, meta, popm_email)
|
||||
audio.save()
|
||||
|
||||
|
||||
# ---- MP4 (m4a / stem) --------------------------------------------------
|
||||
def _write_mp4(path: Path, meta: TagMeta) -> None:
|
||||
from mutagen.mp4 import MP4, MP4FreeForm
|
||||
|
||||
audio = MP4(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
t = audio.tags
|
||||
standard = {
|
||||
"title": "\xa9nam",
|
||||
"artist": "\xa9ART",
|
||||
"album": "\xa9alb",
|
||||
"genre": "\xa9gen",
|
||||
"comment": "\xa9cmt",
|
||||
"release_date": "\xa9day",
|
||||
}
|
||||
for field, atom in standard.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
t.pop(atom, None)
|
||||
else:
|
||||
t[atom] = [val]
|
||||
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
|
||||
for field, name in freeform.items():
|
||||
if field in meta:
|
||||
key = f"----:com.apple.iTunes:{name}"
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
t.pop(key, None)
|
||||
else:
|
||||
t[key] = [MP4FreeForm(val.encode("utf-8"))]
|
||||
if "rating" in meta:
|
||||
key = "----:com.apple.iTunes:RATING"
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
t[key] = [MP4FreeForm(str(max(0, min(5, stars)) * 51).encode("utf-8"))]
|
||||
else:
|
||||
t.pop(key, None)
|
||||
audio.save()
|
||||
|
||||
|
||||
# ---- FLAC --------------------------------------------------------------
|
||||
def _write_flac(path: Path, meta: TagMeta) -> None:
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
audio = FLAC(path)
|
||||
mapping = {
|
||||
"title": "title",
|
||||
"artist": "artist",
|
||||
"album": "album",
|
||||
"genre": "genre",
|
||||
"label": "label",
|
||||
"remixer": "remixer",
|
||||
"producer": "producer",
|
||||
"comment": "comment",
|
||||
"mix": "mixname",
|
||||
"release_date": "date",
|
||||
}
|
||||
for field, vc in mapping.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
audio.pop(vc, None)
|
||||
else:
|
||||
audio[vc] = [val]
|
||||
if "rating" in meta:
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
audio["rating"] = [str(max(0, min(5, stars)) * 51)]
|
||||
else:
|
||||
audio.pop("rating", None)
|
||||
audio.save()
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
||||
|
||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
||||
implemented on top of librosa: beat-synchronous CQT features → a
|
||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
||||
|
||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
||||
beatgrid) — the latter is unit-testable without audio.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
||||
MAX_HOTCUES = 8
|
||||
|
||||
_SR = 22050
|
||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
||||
|
||||
|
||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
||||
"""Detect structural boundaries in a track.
|
||||
|
||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
||||
(used downstream for positional naming). Sorted by time.
|
||||
"""
|
||||
import librosa
|
||||
from scipy.ndimage import median_filter
|
||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
||||
from scipy.linalg import eigh
|
||||
import sklearn.cluster
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.0:
|
||||
return [], duration
|
||||
|
||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
if len(beats) < 4:
|
||||
return [], duration
|
||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
||||
|
||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
||||
# a repetition graph (which beats sound alike) blended with a local path
|
||||
# graph (consecutive-beat timbral continuity).
|
||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
||||
rec = median_filter(rec, size=(1, 7))
|
||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
||||
msync = librosa.util.sync(mfcc, beats)
|
||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
||||
graph = mu * rec + (1 - mu) * path
|
||||
|
||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
||||
lap = csgraph_laplacian(graph, normed=True)
|
||||
_, evecs = eigh(lap)
|
||||
evecs = median_filter(evecs, size=(9, 1))
|
||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
||||
|
||||
# Boundaries = beats where the section-type label changes (plus the start).
|
||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
||||
|
||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
||||
rms = librosa.feature.rms(y=y)[0]
|
||||
rms_t = librosa.times_like(rms, sr=sr)
|
||||
rms_max = float(rms.max()) or 1.0
|
||||
out: list[tuple[float, float]] = []
|
||||
for j, bi in enumerate(bound_beats):
|
||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
||||
t_next = (
|
||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
||||
if j + 1 < len(bound_beats)
|
||||
else duration
|
||||
)
|
||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
||||
out.append((t, energy))
|
||||
return out, duration
|
||||
|
||||
|
||||
def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
|
||||
"""Detect a track's tempo and the time of its first beat.
|
||||
|
||||
Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
|
||||
anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
|
||||
left for the user to fix with the ×2 / ÷2 controls (per product decision).
|
||||
"""
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
bpm = float(np.ravel(tempo)[0])
|
||||
if bpm <= 0 or len(beats) == 0:
|
||||
raise ValueError("Could not detect a tempo/beat")
|
||||
first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
|
||||
return bpm, first_beat
|
||||
|
||||
|
||||
def _segment_for(t: float, markers: list[tuple[float, float]]) -> tuple[float, float]:
|
||||
"""The ``(start, bpm)`` of the beatgrid segment containing ``t``.
|
||||
|
||||
Times before the first marker use the first segment, extrapolated backwards
|
||||
— the same convention the deck draws with.
|
||||
"""
|
||||
seg = markers[0]
|
||||
for m in markers:
|
||||
if m[0] <= t:
|
||||
seg = m
|
||||
else:
|
||||
break
|
||||
return seg
|
||||
|
||||
|
||||
def snap_to_phrase(
|
||||
t: float, markers: list[tuple[float, float]], phrase_bars: int = 16
|
||||
) -> float:
|
||||
"""Snap ``t`` to the nearest phrase boundary OF ITS OWN SEGMENT.
|
||||
|
||||
Snapping is deliberately segment-local rather than a running phrase count
|
||||
across the whole track: a flexible grid exists precisely because the tempo
|
||||
drifted, so carrying a phrase count across a marker seam would propagate the
|
||||
very error the marker was placed to correct. With a single marker this is
|
||||
exactly the old ``anchor + round((t - anchor) / phrase) * phrase``.
|
||||
"""
|
||||
anchor, bpm = _segment_for(t, markers)
|
||||
phrase = phrase_bars * 4 * (60.0 / bpm)
|
||||
return anchor + round((t - anchor) / phrase) * phrase
|
||||
|
||||
|
||||
def select_hotcues(
|
||||
boundaries: list[tuple[float, float]],
|
||||
*,
|
||||
markers: list[tuple[float, float]],
|
||||
duration: float,
|
||||
free_slots: list[int],
|
||||
existing_times: list[float],
|
||||
max_cues: int = MAX_HOTCUES,
|
||||
phrase_bars: int = 16,
|
||||
) -> list[dict]:
|
||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
||||
|
||||
``markers`` is the beatgrid as ``[(start_sec, bpm), ...]`` ordered by start —
|
||||
a constant-tempo track is simply a one-element list.
|
||||
|
||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point of its own
|
||||
tempo segment (which also merges near-duplicates), drops any coinciding with
|
||||
an existing hotcue, caps to the free slots (down-sampling evenly if there
|
||||
are too many), and assigns positional names. Returns dicts with
|
||||
slot/start/name/type/length.
|
||||
"""
|
||||
if not boundaries or not free_slots or not markers or markers[0][1] <= 0:
|
||||
return []
|
||||
|
||||
# Tolerance for "same place as an existing cue" and the end clamp. Marker
|
||||
# BPMs differ by well under 1% in practice, so the first is representative.
|
||||
beat = 60.0 / markers[0][1]
|
||||
|
||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
||||
snapped: dict[float, float] = {}
|
||||
for t, energy in boundaries:
|
||||
p = snap_to_phrase(t, markers, phrase_bars)
|
||||
p = max(0.0, min(p, duration - beat))
|
||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
||||
|
||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
||||
def near_existing(t: float) -> bool:
|
||||
return any(abs(t - e) < beat for e in existing_times)
|
||||
|
||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
||||
if not points:
|
||||
return []
|
||||
|
||||
# If more candidates than free slots, down-sample evenly across the track
|
||||
# (keeps intro..outro coverage rather than just the first N).
|
||||
n = min(len(free_slots), max_cues)
|
||||
if len(points) > n:
|
||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
||||
points = [points[i] for i in sorted(set(idx))]
|
||||
|
||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
||||
slots = sorted(free_slots)[: len(points)]
|
||||
return [
|
||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
||||
for slot, (t, _), name in zip(slots, points, names)
|
||||
]
|
||||
|
||||
|
||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
||||
"""Positional-hint names from track position + energy trend (not true
|
||||
structural classification — the names are hints; value is the position)."""
|
||||
if not times:
|
||||
return []
|
||||
med = float(np.median(energies))
|
||||
raw: list[str] = []
|
||||
n = len(times)
|
||||
for i, (t, e) in enumerate(zip(times, energies)):
|
||||
frac = t / duration if duration else 0.0
|
||||
prev = energies[i - 1] if i > 0 else e
|
||||
if i == 0 or frac < 0.08:
|
||||
name = "Intro"
|
||||
elif i == n - 1 or frac > 0.85:
|
||||
name = "Outro"
|
||||
elif e - prev > 0.12 and e >= med:
|
||||
name = "Drop"
|
||||
elif prev - e > 0.12:
|
||||
name = "Break"
|
||||
elif e > prev:
|
||||
name = "Build"
|
||||
else:
|
||||
name = "Mid"
|
||||
raw.append(name)
|
||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
||||
counts: dict[str, int] = {}
|
||||
out: list[str] = []
|
||||
for name in raw:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
||||
return out
|
||||
@@ -0,0 +1,81 @@
|
||||
"""What a loaded library can actually do.
|
||||
|
||||
Capabilities are ``f(platform, version)``: the UI reads them and disables or
|
||||
hides the controls the loaded platform cannot persist, so a user is never
|
||||
offered an edit that will silently vanish on save. No component branches on the
|
||||
platform name — that is the whole point.
|
||||
|
||||
With a single adapter most of these are constants, and several keys exist purely
|
||||
so the second adapter has somewhere to answer. That is deliberate: the shape is
|
||||
cheap now and expensive to retrofit once components depend on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
MediaKind = Literal["audio", "stem", "video"]
|
||||
PlaylistKind = Literal["folder", "playlist", "smart"]
|
||||
|
||||
|
||||
class CueCapabilities(BaseModel):
|
||||
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
|
||||
slot_labels: Literal["number", "letter"] = "number"
|
||||
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
|
||||
# but not editable anywhere yet (the two-platform promotion rule).
|
||||
memory_cues: bool = False
|
||||
max_memory_cues: int | None = None
|
||||
types: list[CueType] = ["cue"]
|
||||
color: Literal["none", "free", "palette"] = "none"
|
||||
palette: list[str] = []
|
||||
named: bool = False
|
||||
# Where a saved loop lives: a cue type (Traktor) or its own bank (Serato).
|
||||
loops: Literal["none", "cue_type", "separate_bank"] = "none"
|
||||
loop_slots: int | None = None
|
||||
|
||||
|
||||
class GridCapabilities(BaseModel):
|
||||
editable: bool = False
|
||||
flexible: bool = False # multi-marker (variable-tempo) grids can be written
|
||||
lockable: bool = False # a per-track grid/analysis lock exists
|
||||
|
||||
|
||||
class TrackCapabilities(BaseModel):
|
||||
rating_max: int = 5
|
||||
editable_fields: list[str] = []
|
||||
media_kinds: list[MediaKind] = ["audio"]
|
||||
artwork: bool = False
|
||||
artwork_note: str | None = None
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
folders: bool = False
|
||||
smart: Literal["none", "read_only"] = "none"
|
||||
reorder: bool = False
|
||||
|
||||
|
||||
class SaveCapabilities(BaseModel):
|
||||
"""Structured facts, never finished sentences.
|
||||
|
||||
The warning a user needs before saving is genuinely per-platform, so the
|
||||
adapter supplies the facts and the UI composes the wording — which keeps the
|
||||
copy (and any future translation) in the UI without making it vague.
|
||||
"""
|
||||
|
||||
app_name: str
|
||||
library_label: str
|
||||
overwrite_risk: Literal["none", "on_exit", "while_running"] = "none"
|
||||
history: bool = True
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
platform: str
|
||||
version: str | None = None
|
||||
cues: CueCapabilities = CueCapabilities()
|
||||
grid: GridCapabilities = GridCapabilities()
|
||||
tracks: TrackCapabilities = TrackCapabilities()
|
||||
playlists: PlaylistCapabilities = PlaylistCapabilities()
|
||||
save: SaveCapabilities
|
||||
@@ -0,0 +1,170 @@
|
||||
"""What changed this session, at field resolution.
|
||||
|
||||
Three things need to know about an edit, and they need different views of it:
|
||||
|
||||
* the file-tag sync wants *which metadata fields* of which track changed, so it
|
||||
writes only those and leaves everything else in the file alone;
|
||||
* the version history wants a human sentence;
|
||||
* a future undo wants the value a field held before.
|
||||
|
||||
The journal records one `Change` per command and derives all three. Recording it
|
||||
at field resolution has to happen from the start: reconstructed afterwards by
|
||||
diffing, an edit that set a field back to its original value is indistinguishable
|
||||
from one that never happened — which is exactly the case where rewriting the
|
||||
field would lose the platform's own formatting of it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Change:
|
||||
scope: str # "track" | "cue" | "grid" | "lock" | "playlist" | "library"
|
||||
op: str # "set" | "add" | "delete" | "modify" | "create" | "rename" | ...
|
||||
target: str | None = None # track id, or a playlist's name
|
||||
detail: str | None = None # field name, "slot:3", "marker:1", "art", ...
|
||||
before: Any = None
|
||||
after: Any = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EditJournal:
|
||||
changes: list[Change] = field(default_factory=list)
|
||||
|
||||
# ---- recording --------------------------------------------------------
|
||||
def record(
|
||||
self,
|
||||
scope: str,
|
||||
op: str,
|
||||
target: str | None = None,
|
||||
detail: str | None = None,
|
||||
before: Any = None,
|
||||
after: Any = None,
|
||||
) -> None:
|
||||
self.changes.append(Change(scope, op, target, detail, before, after))
|
||||
|
||||
def clear(self) -> None:
|
||||
self.changes.clear()
|
||||
|
||||
@property
|
||||
def dirty(self) -> bool:
|
||||
return bool(self.changes)
|
||||
|
||||
# ---- views ------------------------------------------------------------
|
||||
def fields_for(self, track_id: str) -> set[str]:
|
||||
"""Metadata field names edited on this track (drives the file-tag sync)."""
|
||||
return {
|
||||
c.detail
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.op == "set" and c.target == track_id and c.detail
|
||||
}
|
||||
|
||||
def edited_tracks(self) -> set[str]:
|
||||
"""Tracks whose metadata or artwork changed."""
|
||||
return {c.target for c in self.changes if c.scope == "track" and c.target}
|
||||
|
||||
def retarget(self, old_id: str, new_id: str) -> None:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
the id is derived from the location). Without this, edits made earlier in
|
||||
the session would silently stop syncing to the file."""
|
||||
if old_id == new_id:
|
||||
return
|
||||
for i, c in enumerate(self.changes):
|
||||
if c.target == old_id and c.scope in ("track", "cue", "grid", "lock"):
|
||||
self.changes[i] = Change(c.scope, c.op, new_id, c.detail, c.before, c.after)
|
||||
|
||||
# ---- the version-history message --------------------------------------
|
||||
def summary(self, extra_tracks: set[str] | None = None) -> str:
|
||||
"""A one-line, human-readable summary of this session's edits, used as the
|
||||
version-history commit message (e.g. "Edited 3 tracks; renamed playlist
|
||||
'House'; added 6 hotcues; edited beatgrid on 2 tracks").
|
||||
|
||||
Prep edits are collapsed to meaningful aggregates rather than raw op
|
||||
counts: hotcues report their NET change (created − removed), and beatgrid/
|
||||
lock edits report how many distinct tracks were affected — so tweaking one
|
||||
grid ten times reads as "1 track", not "10 edits".
|
||||
"""
|
||||
parts: list[str] = []
|
||||
|
||||
def tracks(n: int) -> str:
|
||||
return f"{n} track{'' if n == 1 else 's'}"
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
|
||||
if n_meta:
|
||||
parts.append(f"edited {tracks(n_meta)}")
|
||||
|
||||
# --- playlists (name-bearing) ---
|
||||
pl_names: dict[str, list[str]] = {}
|
||||
for c in self.changes:
|
||||
if c.scope == "playlist" and c.target:
|
||||
pl_names.setdefault(c.op, []).append(c.target)
|
||||
for op, verb in (
|
||||
("create", "created"),
|
||||
("rename", "renamed"),
|
||||
("delete", "deleted"),
|
||||
("entries", "reordered"),
|
||||
):
|
||||
names = pl_names.get(op, [])
|
||||
if not names:
|
||||
continue
|
||||
if len(names) <= 2:
|
||||
joined = ", ".join(f"'{n}'" for n in names)
|
||||
parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}")
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} playlists")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
grid_edit: set[str] = set()
|
||||
grid_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for c in self.changes:
|
||||
if c.scope == "cue":
|
||||
if c.target:
|
||||
hc_tracks.add(c.target)
|
||||
if c.op == "add":
|
||||
hc_add += 1
|
||||
elif c.op == "delete":
|
||||
hc_del += 1
|
||||
elif c.scope == "grid":
|
||||
# "delete" is the ONLY deletion op. Everything else — including
|
||||
# ops added later — counts as an edit, because mis-labelling an
|
||||
# edit as a deletion in the history summary is the damaging direction.
|
||||
(grid_del if c.op == "delete" else grid_edit).add(c.target or "")
|
||||
elif c.scope == "lock":
|
||||
(lock_on if c.op == "on" else lock_off).add(c.target or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
if net > 0:
|
||||
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
|
||||
elif net < 0:
|
||||
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
|
||||
else: # net zero but there was activity (moves / retypes / add-then-delete)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
parts.append(f"edited beatgrid on {tracks(len(grid_edit))}")
|
||||
if grid_del:
|
||||
parts.append(f"deleted beatgrid on {tracks(len(grid_del))}")
|
||||
if lock_on:
|
||||
parts.append(f"locked {tracks(len(lock_on))}")
|
||||
if lock_off:
|
||||
parts.append(f"unlocked {tracks(len(lock_off))}")
|
||||
|
||||
# --- path remap ---
|
||||
for c in self.changes:
|
||||
if c.scope == "library" and c.op == "remap" and c.after:
|
||||
parts.append(f"remapped {c.after} file paths")
|
||||
|
||||
if not parts:
|
||||
return "Saved changes"
|
||||
summary = "; ".join(parts)
|
||||
return summary[0].upper() + summary[1:]
|
||||
@@ -0,0 +1,157 @@
|
||||
"""The generic model — Konduktor's platform-independent read projection.
|
||||
|
||||
Every adapter projects its native library into these types, and the HTTP layer
|
||||
serves them directly. Nothing here may reference a platform's own encodings: a
|
||||
value that only makes sense for one format belongs in that adapter, not here.
|
||||
|
||||
`AutoHotcue` is the one command-input type that lives alongside them, because it
|
||||
is the shape a batch cue placement takes in generic terms.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
"""A single track, flattened from a Traktor collection ENTRY."""
|
||||
|
||||
id: str # primary key: "<VOLUME><DIR><FILE>", used to join playlist entries
|
||||
artist: str | None = None
|
||||
title: str | None = None
|
||||
album: str | None = None
|
||||
genre: str | None = None
|
||||
label: str | None = None
|
||||
remixer: str | None = None
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
bpm: float | None = None
|
||||
key: str | None = None # Traktor display key, e.g. "10m"
|
||||
rating: int = 0 # 0-5 stars (derived from RANKING/51)
|
||||
playcount: int | None = None
|
||||
length: int | None = None # seconds
|
||||
bitrate: int | None = None
|
||||
import_date: str | None = None
|
||||
last_played: str | None = None
|
||||
release_date: str | None = None
|
||||
filepath: str | None = None # human-readable OS path
|
||||
cue_count: int = 0
|
||||
hotcue_count: int = 0
|
||||
has_grid: bool = False
|
||||
grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid
|
||||
is_stem: bool = False # a Stem file (<STEMS> child) vs a normal audio track
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
total: int # total matching the filter (before pagination)
|
||||
offset: int
|
||||
limit: int
|
||||
items: list[Track]
|
||||
|
||||
|
||||
class GenreCount(BaseModel):
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
"""Distinct values available for building filter UI."""
|
||||
|
||||
genres: list[GenreCount]
|
||||
keys: list[GenreCount]
|
||||
bpm_min: float | None
|
||||
bpm_max: float | None
|
||||
total_tracks: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
total_tracks: int
|
||||
total_playlists: int
|
||||
rated: int
|
||||
unrated: int
|
||||
missing_key: int
|
||||
missing_genre: int
|
||||
missing_bpm: int
|
||||
no_cues: int
|
||||
rating_breakdown: dict[int, int] # stars -> count
|
||||
bpm_histogram: list[dict] # [{bucket: "120-130", count: n}]
|
||||
top_genres: list[GenreCount]
|
||||
|
||||
|
||||
class PlaylistNode(BaseModel):
|
||||
"""A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST."""
|
||||
|
||||
id: str # stable synthetic id ("pl-<n>" / "fld-<n>")
|
||||
name: str
|
||||
type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST"
|
||||
uuid: str | None = None
|
||||
count: int = 0 # track count (for playlists)
|
||||
children: list["PlaylistNode"] = []
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
hotcue: int # -1 if not assigned to a hotcue slot
|
||||
color: str | None = None # "#RRGGBB" if set
|
||||
# Index of the grid marker this cue is the companion of, if any. Such a cue
|
||||
# holds a real hotcue slot but belongs to the beatgrid and is not editable.
|
||||
grid_marker: int | None = None
|
||||
|
||||
|
||||
class GridMarker(BaseModel):
|
||||
"""One beatgrid marker. Its position in the list IS its index/identity."""
|
||||
|
||||
start: float # seconds
|
||||
bpm: float # governs from this marker until the next one
|
||||
name: str | None = None # Traktor's label — display only, NOT a discriminator
|
||||
companion: int | None = None # hotcue slot of the paired white cue, if any
|
||||
|
||||
|
||||
class TrackCues(BaseModel):
|
||||
# THE beatgrid, ordered by start. Empty = no grid; one marker = constant
|
||||
# tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
|
||||
# is what made flexible grids render and edit wrongly.
|
||||
grid_markers: list[GridMarker] = []
|
||||
locked: bool = False # Traktor LOCK flag
|
||||
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
slot: int # 0–7
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: int = 0 # plain cue
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Per-collection OS-path prefix remapping.
|
||||
|
||||
A Traktor collection stores absolute audio-file paths. When the same collection
|
||||
is used on another machine (a portable USB that mounts elsewhere, a relocated
|
||||
library), those paths aren't reachable. A ``PathMapping`` translates a stored
|
||||
path prefix (``from_prefix``) to a local one (``to_prefix``).
|
||||
|
||||
This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be
|
||||
unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the
|
||||
write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path
|
||||
step this composes with.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
|
||||
def _norm(prefix: str | None) -> str:
|
||||
"""Normalize a prefix for matching: expand ``~``, strip a trailing slash."""
|
||||
if not prefix:
|
||||
return ""
|
||||
p = os.path.expanduser(prefix.strip())
|
||||
# Strip a single trailing separator (both / and \) but keep a bare root.
|
||||
if len(p) > 1:
|
||||
p = p.rstrip("/\\")
|
||||
return p
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PathMapping:
|
||||
"""A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution."""
|
||||
|
||||
from_prefix: str = ""
|
||||
to_prefix: str = ""
|
||||
|
||||
@classmethod
|
||||
def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping":
|
||||
return cls(_norm(from_prefix), _norm(to_prefix))
|
||||
|
||||
@property
|
||||
def empty(self) -> bool:
|
||||
return not self.from_prefix or not self.to_prefix
|
||||
|
||||
def matches(self, os_path: Path) -> bool:
|
||||
"""True if ``os_path`` is at or under ``from_prefix`` (segment-aware,
|
||||
so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``)."""
|
||||
if self.empty:
|
||||
return False
|
||||
s = str(os_path)
|
||||
if s == self.from_prefix:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
if not self.matches(os_path):
|
||||
return os_path
|
||||
rest = str(os_path)[len(self.from_prefix):]
|
||||
# `rest` starts with a separator (or is empty when the path == from_prefix).
|
||||
return Path(self.to_prefix + rest)
|
||||
|
||||
|
||||
def common_dir_prefix(paths: list[str]) -> str:
|
||||
"""Longest directory prefix shared by all ``paths`` (segment-aware).
|
||||
|
||||
Operates on each path's parent directory, so the result is always a folder
|
||||
(never a partial filename), and degrades to ``""`` when the paths share no
|
||||
common root. Used to auto-suggest the ``from`` prefix in the remap editor.
|
||||
"""
|
||||
if not paths:
|
||||
return ""
|
||||
dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths]
|
||||
common: list[str] = []
|
||||
for segs in zip(*(d.split("/") for d in dirs)):
|
||||
if len(set(segs)) == 1:
|
||||
common.append(segs[0])
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Query, facet and statistics layer over the generic model.
|
||||
|
||||
This is deliberately platform-independent: it reads nothing but `Track`
|
||||
attributes. Keeping it in `core` rather than per-adapter is what stops "sort by
|
||||
artist" quietly meaning different things on different platforms behind one UI —
|
||||
if a filter needs something the projection cannot express, the fix is to add the
|
||||
field to the projection, where every adapter must then answer for it.
|
||||
|
||||
An adapter owns its `TrackIndex` instance and refreshes it after each command.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from .model import Facets, GenreCount, Stats, Track, TrackPage
|
||||
|
||||
|
||||
class TrackIndex:
|
||||
"""An ordered list of projected tracks plus a primary-key index."""
|
||||
|
||||
def __init__(self, tracks: list[Track] | None = None):
|
||||
self._lock = threading.Lock()
|
||||
self.tracks: list[Track] = []
|
||||
self.by_key: dict[str, Track] = {}
|
||||
if tracks is not None:
|
||||
self.rebuild(tracks)
|
||||
|
||||
def rebuild(self, tracks: list[Track]) -> None:
|
||||
"""Replace the whole projection — after a save or a path remap, where
|
||||
track ids themselves may have changed."""
|
||||
with self._lock:
|
||||
self.tracks = tracks
|
||||
self.by_key = {t.id: t for t in tracks}
|
||||
|
||||
def all(self) -> list[Track]:
|
||||
return self.tracks
|
||||
|
||||
def get(self, track_id: str) -> Track | None:
|
||||
return self.by_key.get(track_id)
|
||||
|
||||
def replace(self, track: Track) -> None:
|
||||
"""Refresh one track's projection in place.
|
||||
|
||||
Mutating the existing object rather than replacing it keeps `tracks`,
|
||||
`by_key` and any list a caller is already holding consistent.
|
||||
"""
|
||||
old = self.by_key.get(track.id)
|
||||
if old is None:
|
||||
return
|
||||
for field in type(track).model_fields:
|
||||
setattr(old, field, getattr(track, field))
|
||||
|
||||
_SORT_KEYS = {
|
||||
"artist": lambda t: (t.artist or "").lower(),
|
||||
"title": lambda t: (t.title or "").lower(),
|
||||
"album": lambda t: (t.album or "").lower(),
|
||||
"genre": lambda t: (t.genre or "").lower(),
|
||||
"key": lambda t: (t.key or ""),
|
||||
"bpm": lambda t: (t.bpm if t.bpm is not None else -1),
|
||||
"rating": lambda t: t.rating,
|
||||
"playcount": lambda t: (t.playcount or 0),
|
||||
"import_date": lambda t: (t.import_date or ""),
|
||||
"length": lambda t: (t.length or 0),
|
||||
}
|
||||
|
||||
def query_tracks(
|
||||
self,
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = None,
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = "asc",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> TrackPage:
|
||||
items = self.tracks
|
||||
if q:
|
||||
ql = q.lower()
|
||||
items = [
|
||||
t
|
||||
for t in items
|
||||
if (t.artist and ql in t.artist.lower())
|
||||
or (t.title and ql in t.title.lower())
|
||||
or (t.album and ql in t.album.lower())
|
||||
]
|
||||
if genre:
|
||||
items = [t for t in items if t.genre == genre]
|
||||
if key:
|
||||
items = [t for t in items if t.key == key]
|
||||
if bpm_min is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm >= bpm_min]
|
||||
if bpm_max is not None:
|
||||
items = [t for t in items if t.bpm is not None and t.bpm <= bpm_max]
|
||||
if rating_min is not None:
|
||||
items = [t for t in items if t.rating >= rating_min]
|
||||
if has_cues is not None:
|
||||
items = [t for t in items if (t.cue_count > 0) == has_cues]
|
||||
|
||||
keyfn = self._SORT_KEYS.get(sort, self._SORT_KEYS["artist"])
|
||||
items = sorted(items, key=keyfn, reverse=(order == "desc"))
|
||||
|
||||
total = len(items)
|
||||
page = items[offset : offset + limit]
|
||||
return TrackPage(total=total, offset=offset, limit=limit, items=page)
|
||||
|
||||
def facets(self) -> Facets:
|
||||
genres: dict[str, int] = {}
|
||||
keys: dict[str, int] = {}
|
||||
bpms = []
|
||||
for t in self.tracks:
|
||||
if t.genre:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.key:
|
||||
keys[t.key] = keys.get(t.key, 0) + 1
|
||||
if t.bpm is not None:
|
||||
bpms.append(t.bpm)
|
||||
return Facets(
|
||||
genres=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(genres.items(), key=lambda x: -x[1])
|
||||
],
|
||||
keys=[
|
||||
GenreCount(name=k, count=v)
|
||||
for k, v in sorted(keys.items(), key=lambda x: -x[1])
|
||||
],
|
||||
bpm_min=min(bpms) if bpms else None,
|
||||
bpm_max=max(bpms) if bpms else None,
|
||||
total_tracks=len(self.tracks),
|
||||
)
|
||||
|
||||
def stats(self, playlist_count: int) -> Stats:
|
||||
rating_breakdown = {i: 0 for i in range(6)}
|
||||
genres: dict[str, int] = {}
|
||||
bpm_buckets: dict[str, int] = {}
|
||||
rated = missing_key = missing_genre = missing_bpm = no_cues = 0
|
||||
for t in self.tracks:
|
||||
rating_breakdown[t.rating] += 1
|
||||
if t.rating > 0:
|
||||
rated += 1
|
||||
if not t.key:
|
||||
missing_key += 1
|
||||
if not t.genre:
|
||||
missing_genre += 1
|
||||
else:
|
||||
genres[t.genre] = genres.get(t.genre, 0) + 1
|
||||
if t.bpm is None:
|
||||
missing_bpm += 1
|
||||
else:
|
||||
lo = int(t.bpm // 10 * 10)
|
||||
bucket = f"{lo}-{lo + 10}"
|
||||
bpm_buckets[bucket] = bpm_buckets.get(bucket, 0) + 1
|
||||
if t.cue_count == 0:
|
||||
no_cues += 1
|
||||
total = len(self.tracks)
|
||||
histogram = [
|
||||
{"bucket": b, "count": c}
|
||||
for b, c in sorted(bpm_buckets.items(), key=lambda x: int(x[0].split("-")[0]))
|
||||
]
|
||||
top = sorted(genres.items(), key=lambda x: -x[1])[:10]
|
||||
return Stats(
|
||||
total_tracks=total,
|
||||
total_playlists=playlist_count,
|
||||
rated=rated,
|
||||
unrated=total - rated,
|
||||
missing_key=missing_key,
|
||||
missing_genre=missing_genre,
|
||||
missing_bpm=missing_bpm,
|
||||
no_cues=no_cues,
|
||||
rating_breakdown=rating_breakdown,
|
||||
bpm_histogram=histogram,
|
||||
top_genres=[GenreCount(name=k, count=v) for k, v in top],
|
||||
)
|
||||
@@ -1,62 +1,11 @@
|
||||
"""Locate Traktor collections in their default install locations.
|
||||
"""Compatibility shim — this module moved to ``konduktor.adapters.traktor.discovery``.
|
||||
|
||||
Traktor stores each version's data under a versioned folder:
|
||||
~/Documents/Native Instruments/Traktor <version>/collection.nml
|
||||
This is the same relative path on macOS and Windows (both under the user's
|
||||
Documents folder), so a single glob covers both.
|
||||
Kept so the existing test suite keeps importing the old path unchanged while the
|
||||
adapter refactor lands; removed in the final cleanup step. Replacing the entry in
|
||||
``sys.modules`` makes this module *be* the new one, so private names resolve too.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from .adapters.traktor import discovery as _moved
|
||||
|
||||
_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)")
|
||||
|
||||
|
||||
def _traktor_root() -> Path:
|
||||
return Path.home() / "Documents" / "Native Instruments"
|
||||
|
||||
|
||||
def _version_key(version: str | None) -> tuple[int, ...]:
|
||||
"""Sortable tuple for a dotted version string; missing/odd → lowest."""
|
||||
if not version:
|
||||
return (0,)
|
||||
try:
|
||||
return tuple(int(p) for p in version.split("."))
|
||||
except ValueError:
|
||||
return (0,)
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
"""Build a candidate record for a collection.nml path. The label/version
|
||||
come from the parent folder name (e.g. 'Traktor 4.5.0')."""
|
||||
parent = path.parent.name
|
||||
m = _VERSION_RE.search(parent)
|
||||
exists = path.is_file()
|
||||
return {
|
||||
"path": str(path),
|
||||
"label": parent or path.name,
|
||||
"version": m.group(1) if m else None,
|
||||
"modified": (path.stat().st_mtime if exists else None),
|
||||
"exists": exists,
|
||||
}
|
||||
|
||||
|
||||
def detect_collections() -> list[dict]:
|
||||
"""All Traktor collection.nml files found in default locations, newest
|
||||
Traktor version first (then most-recently-modified)."""
|
||||
root = _traktor_root()
|
||||
found: list[dict] = []
|
||||
if not root.is_dir():
|
||||
return found
|
||||
for d in sorted(root.iterdir()):
|
||||
if not d.is_dir() or not d.name.lower().startswith("traktor"):
|
||||
continue
|
||||
nml = d / "collection.nml"
|
||||
if nml.is_file():
|
||||
found.append(describe(nml))
|
||||
found.sort(
|
||||
key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0),
|
||||
reverse=True,
|
||||
)
|
||||
return found
|
||||
sys.modules[__name__] = _moved
|
||||
+15
-319
@@ -1,321 +1,17 @@
|
||||
"""Write track metadata into audio files' embedded tags (best-effort).
|
||||
"""Compatibility shim — this module was split.
|
||||
|
||||
Konduktor's source of truth is the `.nml`; this module additionally syncs the
|
||||
safe metadata fields into the audio file itself so the data travels with the
|
||||
file (portability to other apps). It is best-effort: if the file isn't present
|
||||
(e.g. the drive isn't mounted) or the format doesn't support a field, it reports
|
||||
that rather than failing the whole save.
|
||||
|
||||
Field writes are frame/atom-level, so unrelated tags (cover art, beatgrid BPM,
|
||||
key, track number, private frames) are preserved — verified against real files.
|
||||
The mutagen read/write half is format-agnostic and moved to
|
||||
``konduktor.core.audio_tags``; ``resolve_path`` encodes Traktor's LOCATION
|
||||
convention and moved to ``konduktor.adapters.traktor.locations``. Kept so the
|
||||
existing test suite keeps importing the old path unchanged; removed in the final
|
||||
cleanup step.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# The safe, editable metadata we sync to files (mirrors PlaylistStore.EDITABLE_FIELDS).
|
||||
# rating is 0–5 stars.
|
||||
TagMeta = dict # keys: title, artist, album, genre, label, remixer, producer,
|
||||
# comment, mix, release_date, rating
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagResult:
|
||||
ok: bool
|
||||
status: str # "written" | "file-not-found" | "unsupported-format" | "error"
|
||||
detail: str = ""
|
||||
|
||||
|
||||
def resolve_path(volume: str | None, dir_: str | None, file: str | None) -> Path:
|
||||
"""Map a Traktor LOCATION to an OS path.
|
||||
|
||||
Paths are trusted (per project decision): boot volume 'Macintosh HD' -> '/',
|
||||
a Windows drive like 'X:' stays a drive path, other volumes -> /Volumes/<v>.
|
||||
"""
|
||||
d = (dir_ or "").replace("/:", "/")
|
||||
name = file or ""
|
||||
vol = volume or ""
|
||||
if vol.endswith(":"): # Windows drive letter, e.g. "X:"
|
||||
return Path(vol + d + name)
|
||||
if vol and vol != "Macintosh HD": # other mounted volume (macOS/*nix)
|
||||
return Path("/Volumes") / vol / (d.lstrip("/") + name)
|
||||
return Path(d + name) # boot volume
|
||||
|
||||
|
||||
def read_cover(path: Path) -> tuple[bytes, str] | None:
|
||||
"""Return (image_bytes, mime) of the file's embedded front cover, or None."""
|
||||
if not path.exists():
|
||||
return None
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext in (".mp3", ".aif", ".aiff"):
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
return None
|
||||
apics = id3.getall("APIC")
|
||||
if not apics:
|
||||
return None
|
||||
front = next((a for a in apics if a.type == 3), apics[0])
|
||||
return bytes(front.data), (front.mime or "image/jpeg")
|
||||
if ext in (".m4a", ".mp4"):
|
||||
from mutagen.mp4 import MP4
|
||||
|
||||
covr = MP4(path).tags.get("covr") if MP4(path).tags else None
|
||||
if not covr:
|
||||
return None
|
||||
c = covr[0]
|
||||
from mutagen.mp4 import MP4Cover
|
||||
|
||||
mime = "image/png" if c.imageformat == MP4Cover.FORMAT_PNG else "image/jpeg"
|
||||
return bytes(c), mime
|
||||
if ext == ".flac":
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
pics = FLAC(path).pictures
|
||||
if not pics:
|
||||
return None
|
||||
front = next((p for p in pics if p.type == 3), pics[0])
|
||||
return bytes(front.data), (front.mime or "image/jpeg")
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def write_cover(path: Path, data: bytes, mime: str) -> TagResult:
|
||||
"""Replace the file's embedded front cover art. Best-effort."""
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
mime = mime if mime in ("image/jpeg", "image/png") else "image/jpeg"
|
||||
try:
|
||||
if ext in (".mp3", ".aif", ".aiff"):
|
||||
from mutagen.id3 import APIC
|
||||
|
||||
if ext == ".mp3":
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
tags = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
tags = ID3()
|
||||
tags.delall("APIC")
|
||||
tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
|
||||
tags.save(path)
|
||||
else:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
audio.tags.delall("APIC")
|
||||
audio.tags.add(APIC(encoding=3, mime=mime, type=3, desc="", data=data))
|
||||
audio.save()
|
||||
elif ext in (".m4a", ".mp4"):
|
||||
from mutagen.mp4 import MP4, MP4Cover
|
||||
|
||||
audio = MP4(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
fmt = MP4Cover.FORMAT_PNG if mime == "image/png" else MP4Cover.FORMAT_JPEG
|
||||
audio.tags["covr"] = [MP4Cover(data, imageformat=fmt)]
|
||||
audio.save()
|
||||
elif ext == ".flac":
|
||||
from mutagen.flac import FLAC, Picture
|
||||
|
||||
audio = FLAC(path)
|
||||
audio.clear_pictures()
|
||||
pic = Picture()
|
||||
pic.type = 3
|
||||
pic.mime = mime
|
||||
pic.data = data
|
||||
audio.add_picture(pic)
|
||||
audio.save()
|
||||
else:
|
||||
return TagResult(False, "unsupported-format", ext)
|
||||
except Exception as ex: # noqa: BLE001
|
||||
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
|
||||
return TagResult(True, "written")
|
||||
|
||||
|
||||
def _clean(v) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def write_tags(path: Path, meta: TagMeta) -> TagResult:
|
||||
if not path.exists():
|
||||
return TagResult(False, "file-not-found", str(path))
|
||||
ext = path.suffix.lower()
|
||||
try:
|
||||
if ext == ".mp3":
|
||||
_write_id3(path, meta, id3_only=False)
|
||||
elif ext in (".aif", ".aiff"):
|
||||
_write_aiff(path, meta)
|
||||
elif ext in (".m4a", ".mp4") or path.name.lower().endswith(".stem.m4a"):
|
||||
_write_mp4(path, meta)
|
||||
elif ext == ".flac":
|
||||
_write_flac(path, meta)
|
||||
else:
|
||||
# WAV and anything else: tag support is weak/inconsistent — skip.
|
||||
return TagResult(False, "unsupported-format", ext)
|
||||
except Exception as ex: # noqa: BLE001 — best-effort; report, don't crash save
|
||||
return TagResult(False, "error", f"{type(ex).__name__}: {ex}")
|
||||
return TagResult(True, "written")
|
||||
|
||||
|
||||
# ---- ID3 (mp3 / aiff) --------------------------------------------------
|
||||
def _apply_id3(id3, meta: TagMeta) -> None:
|
||||
from mutagen.id3 import (
|
||||
COMM,
|
||||
POPM,
|
||||
TALB,
|
||||
TCON,
|
||||
TDRC,
|
||||
TIT2,
|
||||
TIT3,
|
||||
TPE1,
|
||||
TPE4,
|
||||
TPUB,
|
||||
TXXX,
|
||||
)
|
||||
|
||||
simple = {
|
||||
"title": TIT2,
|
||||
"artist": TPE1,
|
||||
"album": TALB,
|
||||
"genre": TCON,
|
||||
"label": TPUB,
|
||||
"remixer": TPE4,
|
||||
"mix": TIT3,
|
||||
"release_date": TDRC,
|
||||
}
|
||||
for field, frame in simple.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
id3.delall(frame.__name__)
|
||||
if val is not None:
|
||||
id3.add(frame(encoding=3, text=[val]))
|
||||
if "producer" in meta:
|
||||
id3.delall("TXXX:PRODUCER")
|
||||
val = _clean(meta["producer"])
|
||||
if val is not None:
|
||||
id3.add(TXXX(encoding=3, desc="PRODUCER", text=[val]))
|
||||
if "comment" in meta:
|
||||
id3.delall("COMM")
|
||||
val = _clean(meta["comment"])
|
||||
if val is not None:
|
||||
id3.add(COMM(encoding=3, lang="eng", desc="", text=[val]))
|
||||
if "rating" in meta:
|
||||
id3.delall("POPM")
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
id3.add(
|
||||
POPM(
|
||||
email="traktor@native-instruments.de",
|
||||
rating=max(0, min(5, stars)) * 51,
|
||||
count=0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _write_id3(path: Path, meta: TagMeta, id3_only: bool) -> None:
|
||||
from mutagen.id3 import ID3, ID3NoHeaderError
|
||||
|
||||
try:
|
||||
id3 = ID3(path)
|
||||
except ID3NoHeaderError:
|
||||
id3 = ID3()
|
||||
_apply_id3(id3, meta)
|
||||
id3.save(path)
|
||||
|
||||
|
||||
def _write_aiff(path: Path, meta: TagMeta) -> None:
|
||||
from mutagen.aiff import AIFF
|
||||
|
||||
audio = AIFF(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
_apply_id3(audio.tags, meta)
|
||||
audio.save()
|
||||
|
||||
|
||||
# ---- MP4 (m4a / stem) --------------------------------------------------
|
||||
def _write_mp4(path: Path, meta: TagMeta) -> None:
|
||||
from mutagen.mp4 import MP4, MP4FreeForm
|
||||
|
||||
audio = MP4(path)
|
||||
if audio.tags is None:
|
||||
audio.add_tags()
|
||||
t = audio.tags
|
||||
standard = {
|
||||
"title": "\xa9nam",
|
||||
"artist": "\xa9ART",
|
||||
"album": "\xa9alb",
|
||||
"genre": "\xa9gen",
|
||||
"comment": "\xa9cmt",
|
||||
"release_date": "\xa9day",
|
||||
}
|
||||
for field, atom in standard.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
t.pop(atom, None)
|
||||
else:
|
||||
t[atom] = [val]
|
||||
# No standard MP4 atoms for these — use iTunes-style freeform atoms.
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX"}
|
||||
for field, name in freeform.items():
|
||||
if field in meta:
|
||||
key = f"----:com.apple.iTunes:{name}"
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
t.pop(key, None)
|
||||
else:
|
||||
t[key] = [MP4FreeForm(val.encode("utf-8"))]
|
||||
if "rating" in meta:
|
||||
key = "----:com.apple.iTunes:RATING"
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
t[key] = [MP4FreeForm(str(max(0, min(5, stars)) * 51).encode("utf-8"))]
|
||||
else:
|
||||
t.pop(key, None)
|
||||
audio.save()
|
||||
|
||||
|
||||
# ---- FLAC --------------------------------------------------------------
|
||||
def _write_flac(path: Path, meta: TagMeta) -> None:
|
||||
from mutagen.flac import FLAC
|
||||
|
||||
audio = FLAC(path)
|
||||
mapping = {
|
||||
"title": "title",
|
||||
"artist": "artist",
|
||||
"album": "album",
|
||||
"genre": "genre",
|
||||
"label": "label",
|
||||
"remixer": "remixer",
|
||||
"producer": "producer",
|
||||
"comment": "comment",
|
||||
"mix": "mixname",
|
||||
"release_date": "date",
|
||||
}
|
||||
for field, vc in mapping.items():
|
||||
if field in meta:
|
||||
val = _clean(meta[field])
|
||||
if val is None:
|
||||
audio.pop(vc, None)
|
||||
else:
|
||||
audio[vc] = [val]
|
||||
if "rating" in meta:
|
||||
stars = int(meta["rating"] or 0)
|
||||
if stars > 0:
|
||||
audio["rating"] = [str(max(0, min(5, stars)) * 51)]
|
||||
else:
|
||||
audio.pop("rating", None)
|
||||
audio.save()
|
||||
from .adapters.traktor.locations import resolve_path # noqa: F401
|
||||
from .core.audio_tags import ( # noqa: F401
|
||||
DEFAULT_POPM_EMAIL,
|
||||
TagMeta,
|
||||
TagResult,
|
||||
read_cover,
|
||||
write_cover,
|
||||
write_tags,
|
||||
)
|
||||
+27
-59
@@ -13,13 +13,14 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from . import __version__, beatgrid
|
||||
from . import auto_hotcues as ah
|
||||
from . import __version__
|
||||
from .adapters.traktor import projection
|
||||
from .core import auto_hotcues as ah
|
||||
from . import history, prefs
|
||||
from .collection_service import CollectionService
|
||||
from .discovery import describe, detect_collections
|
||||
from .path_mapping import PathMapping
|
||||
from .playlist_store import PlaylistError, PlaylistStore
|
||||
from .adapters.traktor.adapter import TraktorAdapter
|
||||
from .adapters.traktor.discovery import describe, detect_collections
|
||||
from .core.pathmap import PathMapping
|
||||
from .adapters.traktor.store import PlaylistError, PlaylistStore
|
||||
from .schemas import (
|
||||
AutoGridRequest,
|
||||
AutoHotcue,
|
||||
@@ -80,24 +81,23 @@ class AppState:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self.service: CollectionService | None = None
|
||||
self.store: PlaylistStore | None = None
|
||||
self.adapter: TraktorAdapter | None = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
return self.service is not None
|
||||
return self.adapter is not None
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
# Both raise on an invalid/parse-incompatible or playlist-less file;
|
||||
# only commit to the new collection if BOTH succeed.
|
||||
service = CollectionService(path)
|
||||
store = PlaylistStore(path)
|
||||
# Raises on an invalid/parse-incompatible file; only commit to the new
|
||||
# collection once it has parsed. One parse — the adapter builds its read
|
||||
# projection from the same object graph the commands mutate.
|
||||
adapter = TraktorAdapter(path)
|
||||
# Apply this collection's saved OS-path remapping (per-machine, keyed by
|
||||
# the collection's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
if saved:
|
||||
store.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.service, self.store = path, service, store
|
||||
adapter.store.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.adapter = path, adapter
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged collection is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
@@ -114,18 +114,18 @@ if _env_nml and Path(_env_nml).exists():
|
||||
pass
|
||||
|
||||
|
||||
def require_service() -> CollectionService:
|
||||
def require_service() -> TraktorAdapter:
|
||||
if not STATE.loaded:
|
||||
raise HTTPException(409, "No collection loaded")
|
||||
assert STATE.service is not None
|
||||
return STATE.service
|
||||
assert STATE.adapter is not None
|
||||
return STATE.adapter
|
||||
|
||||
|
||||
def require_store() -> PlaylistStore:
|
||||
if not STATE.loaded:
|
||||
raise HTTPException(409, "No collection loaded")
|
||||
assert STATE.store is not None
|
||||
return STATE.store
|
||||
assert STATE.adapter is not None
|
||||
return STATE.adapter.store
|
||||
|
||||
|
||||
# ---- collection selection ---------------------------------------------
|
||||
@@ -454,49 +454,17 @@ def track_audio(track_id: str) -> FileResponse:
|
||||
return FileResponse(path, media_type=mime)
|
||||
|
||||
|
||||
def _build_track_cues(entry) -> TrackCues:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
The beatgrid is the FULL ordered marker list — a constant grid is a list of
|
||||
length one. Grid markers themselves are not cues; their companion cues are,
|
||||
because they occupy real hotcue slots, and each is tagged with the marker it
|
||||
belongs to so the UI can show it as beatgrid-owned rather than editable.
|
||||
"""
|
||||
markers = beatgrid.grid_markers(entry)
|
||||
comps = beatgrid.companions(entry)
|
||||
marker_of = {id(c): i for i, c in comps.items()}
|
||||
grid_markers = [
|
||||
GridMarker(
|
||||
start=(m.start or 0.0) / 1000.0, # Traktor stores START in ms
|
||||
bpm=m.grid.bpm if m.grid and m.grid.bpm else 0.0,
|
||||
name=m.name,
|
||||
companion=comps[i].hotcue if i in comps else None,
|
||||
)
|
||||
for i, m in enumerate(markers)
|
||||
]
|
||||
cues = [
|
||||
CuePoint(
|
||||
name=c.name,
|
||||
type=c.type if c.type is not None else 0,
|
||||
start=(c.start or 0.0) / 1000.0,
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
hotcue=c.hotcue if c.hotcue is not None else -1,
|
||||
color=c.color,
|
||||
grid_marker=marker_of.get(id(c)),
|
||||
)
|
||||
for c in (entry.cue_v2 or [])
|
||||
if getattr(c, "grid", None) is None
|
||||
]
|
||||
return TrackCues(
|
||||
grid_markers=grid_markers, locked=bool(entry.lock), cues=cues
|
||||
)
|
||||
# Compatibility alias — the cue projection moved into the Traktor adapter.
|
||||
# Kept so test_save_fidelity's invariant K imports the old name unchanged while
|
||||
# the refactor lands; removed in the final cleanup step.
|
||||
_build_track_cues = projection.to_track_cues
|
||||
|
||||
|
||||
def _cues_for(track_id: str) -> TrackCues:
|
||||
entry = require_store().model_entry(track_id)
|
||||
if entry is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
return _build_track_cues(entry)
|
||||
return projection.to_track_cues(entry)
|
||||
|
||||
|
||||
@app.get("/api/tracks/cues", response_model=TrackCues)
|
||||
@@ -511,7 +479,7 @@ def _sync_cue_edit(track_id: str) -> TrackCues:
|
||||
entry = store.model_entry(track_id)
|
||||
if entry is not None:
|
||||
require_service().replace_track(track_id, entry)
|
||||
return _build_track_cues(entry) if entry is not None else TrackCues()
|
||||
return projection.to_track_cues(entry) if entry is not None else TrackCues()
|
||||
|
||||
|
||||
@app.post("/api/tracks/hotcue", response_model=TrackCues)
|
||||
@@ -537,7 +505,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
|
||||
entry = store.model_entry(body.track_id)
|
||||
if entry is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
cues = _build_track_cues(entry)
|
||||
cues = projection.to_track_cues(entry)
|
||||
if not cues.grid_markers:
|
||||
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
|
||||
path = store.audio_path(body.track_id)
|
||||
|
||||
@@ -1,127 +1,10 @@
|
||||
"""Per-collection OS-path prefix remapping.
|
||||
"""Compatibility shim — this module was split.
|
||||
|
||||
A Traktor collection stores absolute audio-file paths. When the same collection
|
||||
is used on another machine (a portable USB that mounts elsewhere, a relocated
|
||||
library), those paths aren't reachable. A ``PathMapping`` translates a stored
|
||||
path prefix (``from_prefix``) to a local one (``to_prefix``).
|
||||
|
||||
This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be
|
||||
unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the
|
||||
write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path
|
||||
step this composes with.
|
||||
``PathMapping``/``common_dir_prefix`` are format-agnostic and moved to
|
||||
``konduktor.core.pathmap``; ``os_path_to_location`` is the inverse of Traktor's
|
||||
``resolve_path`` and moved to ``konduktor.adapters.traktor.locations``. Kept so
|
||||
the existing test suite keeps importing the old path unchanged; removed in the
|
||||
final cleanup step.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def _norm(prefix: str | None) -> str:
|
||||
"""Normalize a prefix for matching: expand ``~``, strip a trailing slash."""
|
||||
if not prefix:
|
||||
return ""
|
||||
p = os.path.expanduser(prefix.strip())
|
||||
# Strip a single trailing separator (both / and \) but keep a bare root.
|
||||
if len(p) > 1:
|
||||
p = p.rstrip("/\\")
|
||||
return p
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PathMapping:
|
||||
"""A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution."""
|
||||
|
||||
from_prefix: str = ""
|
||||
to_prefix: str = ""
|
||||
|
||||
@classmethod
|
||||
def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping":
|
||||
return cls(_norm(from_prefix), _norm(to_prefix))
|
||||
|
||||
@property
|
||||
def empty(self) -> bool:
|
||||
return not self.from_prefix or not self.to_prefix
|
||||
|
||||
def matches(self, os_path: Path) -> bool:
|
||||
"""True if ``os_path`` is at or under ``from_prefix`` (segment-aware,
|
||||
so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``)."""
|
||||
if self.empty:
|
||||
return False
|
||||
s = str(os_path)
|
||||
if s == self.from_prefix:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
if not self.matches(os_path):
|
||||
return os_path
|
||||
rest = str(os_path)[len(self.from_prefix):]
|
||||
# `rest` starts with a separator (or is empty when the path == from_prefix).
|
||||
return Path(self.to_prefix + rest)
|
||||
|
||||
|
||||
def common_dir_prefix(paths: list[str]) -> str:
|
||||
"""Longest directory prefix shared by all ``paths`` (segment-aware).
|
||||
|
||||
Operates on each path's parent directory, so the result is always a folder
|
||||
(never a partial filename), and degrades to ``""`` when the paths share no
|
||||
common root. Used to auto-suggest the ``from`` prefix in the remap editor.
|
||||
"""
|
||||
if not paths:
|
||||
return ""
|
||||
dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths]
|
||||
common: list[str] = []
|
||||
for segs in zip(*(d.split("/") for d in dirs)):
|
||||
if len(set(segs)) == 1:
|
||||
common.append(segs[0])
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
from .adapters.traktor.locations import os_path_to_location # noqa: F401
|
||||
from .core.pathmap import PathMapping, common_dir_prefix # noqa: F401
|
||||
File diff suppressed because it is too large.
Load diff
+18
-143
@@ -4,89 +4,6 @@ from __future__ import annotations
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
"""A single track, flattened from a Traktor collection ENTRY."""
|
||||
|
||||
id: str # primary key: "<VOLUME><DIR><FILE>", used to join playlist entries
|
||||
artist: str | None = None
|
||||
title: str | None = None
|
||||
album: str | None = None
|
||||
genre: str | None = None
|
||||
label: str | None = None
|
||||
remixer: str | None = None
|
||||
producer: str | None = None
|
||||
mix: str | None = None
|
||||
comment: str | None = None
|
||||
bpm: float | None = None
|
||||
key: str | None = None # Traktor display key, e.g. "10m"
|
||||
rating: int = 0 # 0-5 stars (derived from RANKING/51)
|
||||
playcount: int | None = None
|
||||
length: int | None = None # seconds
|
||||
bitrate: int | None = None
|
||||
import_date: str | None = None
|
||||
last_played: str | None = None
|
||||
release_date: str | None = None
|
||||
filepath: str | None = None # human-readable OS path
|
||||
cue_count: int = 0
|
||||
hotcue_count: int = 0
|
||||
has_grid: bool = False
|
||||
grid_markers: int = 0 # >1 = a flexible (multi-tempo) beatgrid
|
||||
is_stem: bool = False # a Stem file (<STEMS> child) vs a normal audio track
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
total: int # total matching the filter (before pagination)
|
||||
offset: int
|
||||
limit: int
|
||||
items: list[Track]
|
||||
|
||||
|
||||
class GenreCount(BaseModel):
|
||||
name: str
|
||||
count: int
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
"""Distinct values available for building filter UI."""
|
||||
|
||||
genres: list[GenreCount]
|
||||
keys: list[GenreCount]
|
||||
bpm_min: float | None
|
||||
bpm_max: float | None
|
||||
total_tracks: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
total_tracks: int
|
||||
total_playlists: int
|
||||
rated: int
|
||||
unrated: int
|
||||
missing_key: int
|
||||
missing_genre: int
|
||||
missing_bpm: int
|
||||
no_cues: int
|
||||
rating_breakdown: dict[int, int] # stars -> count
|
||||
bpm_histogram: list[dict] # [{bucket: "120-130", count: n}]
|
||||
top_genres: list[GenreCount]
|
||||
|
||||
|
||||
class PlaylistNode(BaseModel):
|
||||
"""A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST."""
|
||||
|
||||
id: str # stable synthetic id ("pl-<n>" / "fld-<n>")
|
||||
name: str
|
||||
type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST"
|
||||
uuid: str | None = None
|
||||
count: int = 0 # track count (for playlists)
|
||||
children: list["PlaylistNode"] = []
|
||||
|
||||
|
||||
PlaylistNode.model_rebuild()
|
||||
|
||||
|
||||
# ---- write request bodies ----
|
||||
|
||||
|
||||
class CreatePlaylist(BaseModel):
|
||||
name: str
|
||||
parent_id: str | None = None # folder id ("fld:..."); None = root
|
||||
@@ -126,36 +43,6 @@ class HistoryEntry(BaseModel):
|
||||
summary: str # human-readable edit summary
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
hotcue: int # -1 if not assigned to a hotcue slot
|
||||
color: str | None = None # "#RRGGBB" if set
|
||||
# Index of the grid marker this cue is the companion of, if any. Such a cue
|
||||
# holds a real hotcue slot but belongs to the beatgrid and is not editable.
|
||||
grid_marker: int | None = None
|
||||
|
||||
|
||||
class GridMarker(BaseModel):
|
||||
"""One beatgrid marker. Its position in the list IS its index/identity."""
|
||||
|
||||
start: float # seconds
|
||||
bpm: float # governs from this marker until the next one
|
||||
name: str | None = None # Traktor's label — display only, NOT a discriminator
|
||||
companion: int | None = None # hotcue slot of the paired white cue, if any
|
||||
|
||||
|
||||
class TrackCues(BaseModel):
|
||||
# THE beatgrid, ordered by start. Empty = no grid; one marker = constant
|
||||
# tempo. There is deliberately no scalar bpm/anchor here: a single "the BPM"
|
||||
# is what made flexible grids render and edit wrongly.
|
||||
grid_markers: list[GridMarker] = []
|
||||
locked: bool = False # Traktor LOCK flag
|
||||
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
|
||||
|
||||
|
||||
class AddGridMarker(BaseModel):
|
||||
track_id: str
|
||||
start: float # seconds
|
||||
@@ -188,14 +75,6 @@ class SetHotcue(BaseModel):
|
||||
name: str | None = None # cue label; defaults to Traktor's "n.n." when unset
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
slot: int # 0–7
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: int = 0 # plain cue
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
|
||||
|
||||
class AutoHotcuesRequest(BaseModel):
|
||||
track_id: str
|
||||
max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side
|
||||
@@ -269,30 +148,26 @@ class PathMappingInfo(BaseModel):
|
||||
to: str = ""
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
|
||||
|
||||
class RemapResult(BaseModel):
|
||||
rewritten: int # tracks whose LOCATION was rewritten
|
||||
commit: str | None = None # sha of the version-history commit for the rewrite
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
# The generic model lives in core.model; re-exported here so the HTTP layer has
|
||||
# one import site. The dependency runs schemas -> core, never the reverse.
|
||||
from .core.model import ( # noqa: E402,F401
|
||||
AutoHotcue,
|
||||
CuePoint,
|
||||
Facets,
|
||||
GenreCount,
|
||||
GridMarker,
|
||||
PlaylistNode,
|
||||
PrefixGroup,
|
||||
PrefixSuggestions,
|
||||
RemapPreview,
|
||||
RemapSample,
|
||||
Stats,
|
||||
Track,
|
||||
TrackCues,
|
||||
TrackPage,
|
||||
)
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_save_fidelity.py test_phase3.py test_history.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_phase3.py test_history.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Layering guard: `core` must not know any platform exists.
|
||||
|
||||
The whole value of the adapter split is that `konduktor.core` can be read as the
|
||||
contract a future Rekordbox or Serato adapter is written against. One stray
|
||||
import of a native type would quietly make it Traktor-shaped again, and nothing
|
||||
else in the suite would notice.
|
||||
"""
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CORE = Path(__file__).resolve().parent / "konduktor" / "core"
|
||||
FORBIDDEN = ("traktor_nml_utils", "konduktor.adapters", "xsdata")
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
print("== core/ imports nothing platform-specific ==")
|
||||
offences: list[str] = []
|
||||
for src in sorted(CORE.rglob("*.py")):
|
||||
tree = ast.parse(src.read_text())
|
||||
for node in ast.walk(tree):
|
||||
names: list[str] = []
|
||||
if isinstance(node, ast.Import):
|
||||
names = [a.name for a in node.names]
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
# level > 0 is a relative import; ".." from core/ reaches konduktor,
|
||||
# which is allowed (paths, prefs), but "...adapters" is not.
|
||||
names = [node.module or ""]
|
||||
if node.level and "adapters" in (node.module or ""):
|
||||
offences.append(f"{src.name}: relative import of {node.module}")
|
||||
for n in names:
|
||||
if any(n == f or n.startswith(f + ".") for f in FORBIDDEN):
|
||||
offences.append(f"{src.name}: {n}")
|
||||
|
||||
check("no core module imports a native library type", not offences, "; ".join(offences))
|
||||
|
||||
print("== adapters own their native model ==")
|
||||
store = (CORE.parent / "adapters" / "traktor" / "store.py").read_text()
|
||||
check("the Traktor store is where traktor_nml_utils lives", "traktor_nml_utils" in store)
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -30,7 +30,6 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-a
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
from konduktor.collection_service import CollectionService # noqa: E402
|
||||
from konduktor.playlist_store import PlaylistError, PlaylistStore # noqa: E402
|
||||
|
||||
failed = False
|
||||
@@ -92,7 +91,6 @@ with tempfile.TemporaryDirectory() as d:
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
|
||||
svc = CollectionService(work)
|
||||
store = PlaylistStore(work)
|
||||
|
||||
def walk(n):
|
||||
@@ -107,7 +105,7 @@ with tempfile.TemporaryDirectory() as d:
|
||||
uuid = target.playlist.uuid
|
||||
keys = store.entry_keys(uuid)
|
||||
|
||||
store.set_entries(uuid, svc.entries_for(list(reversed(keys))))
|
||||
store.set_entries(uuid, store.entries_for(list(reversed(keys))))
|
||||
store.save()
|
||||
edited = work.read_bytes()
|
||||
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Tests for the generic adapter layer.
|
||||
|
||||
`test_save_fidelity.py` exercises the Traktor STORE and the bytes it writes;
|
||||
nothing there touches the projection. Without this file the entire generic layer
|
||||
— the single parse, the index refresh after each command, the cue-type
|
||||
translation, capabilities — would be untested by the suite that gates saves.
|
||||
|
||||
Runs against a temp copy of the real collection, like the other suites.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-adapter-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
import traktor_nml_utils as tnu # noqa: E402
|
||||
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402
|
||||
from konduktor.core.model import AutoHotcue # noqa: E402
|
||||
from konduktor.core.pathmap import PathMapping # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
# ---- opening: exactly one parse ---------------------------------------
|
||||
print("== opening a library parses it exactly once ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
|
||||
parses = {"n": 0}
|
||||
original_init = tnu.TraktorCollection.__init__
|
||||
|
||||
def counting_init(self, *a, **kw):
|
||||
parses["n"] += 1
|
||||
return original_init(self, *a, **kw)
|
||||
|
||||
tnu.TraktorCollection.__init__ = counting_init
|
||||
try:
|
||||
adapter = TraktorAdapter(work)
|
||||
finally:
|
||||
tnu.TraktorCollection.__init__ = original_init
|
||||
|
||||
# The whole point of collapsing the read model into the adapter: the 14MB
|
||||
# file used to be parsed twice into two graphs that could drift apart.
|
||||
check("parsed once, not twice", parses["n"] == 1, f"{parses['n']} parses")
|
||||
check("projection is populated", len(adapter.tracks) == 8485, str(len(adapter.tracks)))
|
||||
check("primary-key index agrees with the list", len(adapter.by_key) > 8000)
|
||||
check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter))
|
||||
|
||||
# runtime_checkable only verifies method PRESENCE, so check a signature too.
|
||||
import inspect
|
||||
|
||||
sig = inspect.signature(adapter.set_cue)
|
||||
check(
|
||||
"set_cue takes the generic cue vocabulary",
|
||||
{"slot", "start_sec", "cue_type", "role"} <= set(sig.parameters),
|
||||
str(list(sig.parameters)),
|
||||
)
|
||||
|
||||
# ---- capabilities -------------------------------------------------------
|
||||
print("== capabilities describe Traktor, not an assumed floor ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
caps = adapter.capabilities()
|
||||
check("platform reported", caps.platform == "traktor")
|
||||
check("version read from the NML header", caps.version == "20", str(caps.version))
|
||||
check("8 hotcue slots", caps.cues.hotcue_slots == 8)
|
||||
check("no memory cues on Traktor", caps.cues.memory_cues is False)
|
||||
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
|
||||
check("flexible beatgrids supported", caps.grid.flexible is True)
|
||||
check("grid is lockable", caps.grid.lockable is True)
|
||||
check("save facts present for the UI to compose copy from",
|
||||
caps.save.app_name == "Traktor" and caps.save.overwrite_risk == "on_exit")
|
||||
|
||||
# ---- commands refresh the projection ------------------------------------
|
||||
print("== every command refreshes the read projection ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
|
||||
# metadata
|
||||
tid = next(t.id for t in adapter.tracks if t.title)
|
||||
adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"})
|
||||
check("metadata edit is visible in the projection",
|
||||
adapter.track(tid).genre == "Konduktor Test Genre")
|
||||
|
||||
# cues — a free slot on a track with a grid, so the companion guard is clear
|
||||
tid2 = next(
|
||||
t.id for t in adapter.tracks
|
||||
if t.has_grid and (cues := adapter.track_cues(t.id))
|
||||
and len({c.hotcue for c in cues.cues if c.hotcue >= 0}) < 7
|
||||
)
|
||||
before = adapter.track(tid2).hotcue_count
|
||||
used = {c.hotcue for c in adapter.track_cues(tid2).cues if c.hotcue >= 0}
|
||||
free = next(s for s in range(8) if s not in used)
|
||||
fresh = adapter.set_cue(tid2, slot=free, start_sec=12.5, cue_type="cue")
|
||||
check("set_cue returns fresh cues", any(c.hotcue == free for c in fresh.cues))
|
||||
check("hotcue count in the projection incremented",
|
||||
adapter.track(tid2).hotcue_count == before + 1)
|
||||
|
||||
# cue type translation, both directions
|
||||
adapter.set_cue_type(tid2, free, "load")
|
||||
check("generic cue type maps to Traktor's encoding",
|
||||
next(c.type for c in adapter.track_cues(tid2).cues if c.hotcue == free) == 3)
|
||||
try:
|
||||
adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory")
|
||||
check("memory cues are refused on Traktor", False, "no error raised")
|
||||
except Unsupported:
|
||||
check("memory cues are refused on Traktor", True)
|
||||
|
||||
# grid
|
||||
grid_before = len(adapter.track_cues(tid2).grid_markers)
|
||||
adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0)
|
||||
check("grid marker added and projected",
|
||||
len(adapter.track_cues(tid2).grid_markers) == grid_before + 1)
|
||||
check("marker count reached the track projection",
|
||||
adapter.track(tid2).grid_markers == grid_before + 1)
|
||||
|
||||
# ---- analysed grid vs plain replace --------------------------------------
|
||||
print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
tid = next(t.id for t in adapter.tracks if t.has_grid)
|
||||
|
||||
cues = adapter.replace_grid(tid, [(1.0, 128.0)])
|
||||
check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1)
|
||||
check("replace_grid creates no companion cue", cues.grid_markers[0].companion is None)
|
||||
|
||||
cues = adapter.set_analysed_grid(tid, [(1.0, 128.0)])
|
||||
check("set_analysed_grid pairs the marker with a companion",
|
||||
cues.grid_markers[0].companion is not None)
|
||||
|
||||
# ---- remap rebuilds the index (track ids change) --------------------------
|
||||
print("== a path remap rebuilds the projection, because track ids change ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
|
||||
# Use the adapter's own suggestion: the remap matches RESOLVED OS paths,
|
||||
# which is not the same string as Track.filepath (a display path).
|
||||
prefix = adapter.path_prefix_suggestions()["primary"]
|
||||
matched = {
|
||||
t.id
|
||||
for t in adapter.tracks
|
||||
if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix)
|
||||
}
|
||||
old_id = next(iter(matched))
|
||||
n = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest"))
|
||||
check("remap rewrote some locations", n > 0, str(n))
|
||||
check("the old track id is gone from the index", adapter.track(old_id) is None)
|
||||
check("the index still holds every track", len(adapter.tracks) == 8485)
|
||||
|
||||
# ---- place_cues takes the generic spec ------------------------------------
|
||||
print("== batch cue placement takes a typed spec ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
adapter = TraktorAdapter(work)
|
||||
tid = next(
|
||||
t.id for t in adapter.tracks
|
||||
if len({c.hotcue for c in adapter.track_cues(t.id).cues if c.hotcue >= 0}) < 6
|
||||
)
|
||||
used = {c.hotcue for c in adapter.track_cues(tid).cues if c.hotcue >= 0}
|
||||
free = [s for s in range(8) if s not in used][:2]
|
||||
adapter.place_cues(tid, [AutoHotcue(slot=free[0], start=30.0, name="Drop")])
|
||||
placed = next((c for c in adapter.track_cues(tid).cues if c.hotcue == free[0]), None)
|
||||
check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Reference in new issue
Block a user