diff --git a/CLAUDE.md b/CLAUDE.md index 61078db..24de5ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -428,6 +428,14 @@ serialization path.** It enforces: deleted playlist or track is surfaced, not dropped; sets are per-library; two sets sharing a destination are caught (an export clears its destination, so the second would wipe the first); and deleting a set never touches its folder. +- `test_export.py` — writing a Traktor collection from NOTHING. There is no + original here, so the guarantee differs from `test_save_fidelity.py`'s: the + result must be a collection Traktor would have written. Pins the skeleton, and + above all that **`` is volume-relative** — an export writing host + paths would work perfectly on the machine that made it and resolve to nothing + at the gig. Also that a flexible multi-marker grid and hot-cue PADS survive, + grids are not locked, loose tracks get their "Other" playlist, and re-exporting + into the same folder replaces rather than appends. - `test_library_id.py` — the property no other suite covers: **a library that moves keeps its identity**. Also that two libraries in one folder stay two, a removable library is never written beside, an unwritable location falls back diff --git a/backend/konduktor/adapters/traktor/__init__.py b/backend/konduktor/adapters/traktor/__init__.py index 7d3a1d8..a2bc648 100644 --- a/backend/konduktor/adapters/traktor/__init__.py +++ b/backend/konduktor/adapters/traktor/__init__.py @@ -1,10 +1,17 @@ """The Traktor adapter: NML v20 (Traktor Pro 4) via ``traktor-nml-utils``. Importing this package registers the platform, so ``core.registry`` can find it -without knowing it exists. +without knowing it exists — and registers it as an export TARGET, which is a +separate registry because opening a library and creating one from nothing are +different capabilities: Rekordbox has the first and not the second. """ +from ...core import export as core_export from ...core import registry from .driver import TraktorDriver +from .export import TraktorExporter TRAKTOR = TraktorDriver() registry.register(TRAKTOR) + +TRAKTOR_EXPORTER = TraktorExporter() +core_export.register(TRAKTOR_EXPORTER) diff --git a/backend/konduktor/adapters/traktor/export.py b/backend/konduktor/adapters/traktor/export.py new file mode 100644 index 0000000..8734e63 --- /dev/null +++ b/backend/konduktor/adapters/traktor/export.py @@ -0,0 +1,144 @@ +"""Writing a fresh Traktor `collection.nml` from nothing. + +## How it works, and why it is not a second writer + +The obvious shape — build an `Nml` object graph by hand and render it — would +mean a SECOND definition of "generic Track plus cues plus grid becomes a Traktor +ENTRY", living beside `TraktorStore.add_entry` and the cue/grid commands. Two +definitions drift, and the new one would inherit none of `test_save_fidelity`'s +coverage, none of `replace_grid`'s companion-cue handling, and none of the +lossiness rules the import feature already settled. + +So instead: **write an empty but valid collection, open it, and replay the +ordinary commands onto it.** The skeleton below is the smallest NML Traktor +accepts, verified against a real Traktor Pro 4 file. + +That is a deliberate amendment to the original design note, which said an +exporter should not "create then replay commands". Its stated reason was that +doing so would make "an empty new file" and "the user's real library" share code +paths, when the safety of the architecture rests on the write target always +being a retained native model parsed from a real file. Here that invariant holds +literally: the write target IS parsed from a real file — a skeleton Konduktor +wrote a moment earlier — and the import feature has already proved the approach +end to end in Traktor 4.5. The exporter still owns everything genuinely new: the +skeleton, the playlist tree, and the `$ROOT` wrapper. + +## The skeleton + +Read off Ben's own collection rather than assumed. Note there is **no +`` element at all**, so it is not required, and `` must +wrap a `$ROOT` FOLDER node — playlists cannot sit at the top level. +""" +from __future__ import annotations + +import logging +from pathlib import Path + +from ...core.adapter import NewTrack +from ...core.export import ExportPayload +from .adapter import TraktorAdapter +from .capabilities import capabilities_for + +log = logging.getLogger(__name__) + +#: The smallest collection Traktor Pro 4 accepts. `PROGRAM` names the writer; +#: Traktor itself writes "Traktor Pro 4" here and does not appear to care, but +#: claiming to BE Traktor would be dishonest in a file a user may inspect. +SKELETON = ( + '\n' + '\n' + '\n' + '\n' + '' + "\n\n\n" + '\n' + "\n\n" +) + +#: Loose tracks — added individually rather than through a playlist — would +#: otherwise be reachable only by search in the exported library. +OTHER_PLAYLIST = "Other" + + +class TraktorExporter: + platform = "traktor" + library_filename = "collection.nml" + + def capabilities(self): + """What a Traktor library can hold — answered with no library to read. + + `editable_fields` is the full safe set: an exported collection is + brand new, so nothing about it is read-only. + """ + return capabilities_for( + Path(self.library_filename), + [ + "title", "artist", "album", "genre", "label", "remixer", + "producer", "mix", "release_date", "comment", "rating", + ], + ) + + def write(self, payload: ExportPayload, destination: Path) -> Path: + destination = Path(destination) + destination.mkdir(parents=True, exist_ok=True) + library = destination / self.library_filename + library.write_text(SKELETON, encoding="utf-8") + + adapter = TraktorAdapter(library) + + # The tracks, with their cues and grids, through the ordinary command + # path — so an exported beatgrid is written by the same `replace_grid` + # the deck's Reset uses. + new_ids = adapter.add_tracks( + [NewTrack(track=t.track, audio_path=t.destination, cues=t.cues) + for t in payload.tracks] + ) + # Source id -> the id it got here. Both are Traktor primary keys derived + # from a LOCATION, and the location changed, so they are never equal. + moved = {t.source_id: new_id for t, new_id in zip(payload.tracks, new_ids)} + + self._write_playlists(adapter, payload, moved) + adapter.save() + return library + + def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None: + """Recreate the tree under one folder named after the export. + + Nested under the export's own name for the same reason import nests a + drive's playlists under the drive's name: a collection swapped onto + another machine should say where its playlists came from. + """ + root = adapter.create_folder(payload.name) + folders: dict[tuple[str, ...], str] = {(): root} + + for playlist in payload.playlists: + parent = self._folder_for(adapter, folders, tuple(playlist.folders), root) + node_id = adapter.create_playlist(playlist.name, parent) + entries = [moved[t] for t in playlist.track_ids if t in moved] + if entries: + adapter.set_playlist_entries(node_id, entries) + + loose = self._loose(payload, moved) + if loose: + node_id = adapter.create_playlist(OTHER_PLAYLIST, root) + adapter.set_playlist_entries(node_id, loose) + + @staticmethod + def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str: + """Create (once) the folder chain a playlist sits under, and return it.""" + for depth in range(1, len(path) + 1): + branch = path[:depth] + if branch not in folders: + folders[branch] = adapter.create_folder(branch[-1], folders[branch[:-1]]) + return folders.get(path, root) + + @staticmethod + def _loose(payload: ExportPayload, moved: dict) -> list[str]: + """Tracks no exported playlist accounts for, in payload order.""" + in_playlists = {t for p in payload.playlists for t in p.track_ids} + return [ + moved[t.source_id] + for t in payload.tracks + if t.source_id not in in_playlists and t.source_id in moved + ] diff --git a/backend/konduktor/core/export.py b/backend/konduktor/core/export.py new file mode 100644 index 0000000..3caffd2 --- /dev/null +++ b/backend/konduktor/core/export.py @@ -0,0 +1,125 @@ +"""Writing a BRAND NEW library for another platform. + +The contract an exporter is written against, and the payload it consumes. Both +are strictly generic: an exporter is handed `Track`s, `TrackCues` and playlist +names, never a native type from whatever library the user happens to have open. +That is what makes "the source is whatever is loaded" free — a Rekordbox +collection exports to Traktor with no exporter knowing Rekordbox exists. + +## Why this is not `LibraryDriver` + +A driver OPENS a library that already exists; an exporter CREATES one where +nothing does. Keeping them apart keeps the edit path — the one carrying the +byte-fidelity guarantees — out of reach of a lossy-by-design export. + +An exporter also declares **static** capabilities. It has no instance and no +path, because the library it describes does not exist yet, which is exactly the +question "what can the target represent?" needs answering before any of it is +written. + +## Who does what + +`core` plans and copies; the exporter only writes the library file. Layout, +collision and dedup rules are platform-independent and must not drift between +targets — and the exporter could not write a Traktor `` before the +destination path is known anyway, so every `ExportTrack` arrives carrying its +FINAL audio path. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Protocol, runtime_checkable + +from .capabilities import Capabilities +from .model import Track, TrackCues + + +@dataclass +class ExportTrack: + """One track, with its prep, and where its audio now lives.""" + + track: Track + #: Where the copy ALREADY IS. The exporter never copies; by the time it runs + #: the file is on disk, because a half-copied file is not something a library + #: write should be discovering. + destination: Path + cues: TrackCues | None = None + + @property + def source_id(self) -> str: + """Its id in the SOURCE library, for joining playlists to tracks.""" + return self.track.id + + +@dataclass +class ExportPlaylist: + """A playlist to recreate in the exported library. + + `folders` is the path of folder names to nest it under, outermost first, so + a target that supports folders can preserve the user's tree and one that + cannot may flatten the same information into a name. + """ + + name: str + track_ids: list[str] = field(default_factory=list) # SOURCE ids + folders: list[str] = field(default_factory=list) + + +@dataclass +class ExportPayload: + """Everything an exporter needs, and nothing platform-specific.""" + + tracks: list[ExportTrack] = field(default_factory=list) + playlists: list[ExportPlaylist] = field(default_factory=list) + #: The export's name, used for the folder its playlists are nested under. + name: str = "Export" + + +@runtime_checkable +class LibraryExporter(Protocol): + """Writes one platform's library, from nothing. Stateless.""" + + platform: str + #: What the written library file is called, e.g. "collection.nml". + library_filename: str + + def capabilities(self) -> Capabilities: + """What this target can represent — STATIC, with no library to read.""" + ... + + def write(self, payload: ExportPayload, destination: Path) -> Path: + """Write a complete library into `destination`; return the file written. + + The destination exists and already holds the copied audio. Raises rather + than writing something partial: a library file is the last thing an + export produces, so its absence is what marks an export unfinished. + """ + ... + + +_EXPORTERS: list[LibraryExporter] = [] + + +def register(exporter: LibraryExporter) -> None: + """Register a target. Called once per adapter package, at import.""" + if not any(e.platform == exporter.platform for e in _EXPORTERS): + _EXPORTERS.append(exporter) + + +def exporters() -> list[LibraryExporter]: + return list(_EXPORTERS) + + +def for_platform(platform: str) -> LibraryExporter | None: + """The exporter for a platform, or None when it cannot be a target. + + Deliberately narrower than `registry.driver_for`: reading a library and + creating one from nothing are different capabilities, and a platform can + have the first without the second. + """ + return next((e for e in _EXPORTERS if e.platform == platform), None) + + +def targets() -> set[str]: + return {e.platform for e in _EXPORTERS} diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 961bb30..b78c9e0 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_library_id.py test_exports.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_library_id.py test_exports.py test_export.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_export.py b/backend/test_export.py new file mode 100644 index 0000000..ec32d66 --- /dev/null +++ b/backend/test_export.py @@ -0,0 +1,179 @@ +"""Writing a brand-new Traktor collection from nothing. + +Everywhere else in Konduktor the write target was parsed from a file Traktor +wrote, and `test_save_fidelity.py` guards that nothing else in it moves. An +export has no original, so the guarantee has to be different: **the result must +be a collection Traktor would have written** — the right skeleton, a coherent +playlist tree, and prep that survived the crossing intact. + +The property with the most riding on it is the LOCATION: Traktor stores a volume +NAME plus a volume-relative path, never a host path, which is the whole reason a +USB export is portable. If an export ever wrote absolute host paths it would +work perfectly on the machine that made it and resolve to nothing at the gig. + +Runs against the 8,485-entry fixture collection, so the tracks have real prep — +flexible grids, hot cues on specific pads — rather than anything invented here. +""" +import os +import re +import tempfile +from pathlib import Path + +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp() + +from konduktor.adapters.traktor.driver import TraktorDriver # noqa: E402 +from konduktor.adapters.traktor.export import SKELETON # noqa: E402 +from konduktor.core import export as core_export # noqa: E402 +from konduktor.core.export import ExportPayload, ExportPlaylist, ExportTrack # 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 + + +FIXTURE = Path(__file__).resolve().parents[1] / "collection.nml" +src = TraktorDriver().open(FIXTURE) +exporter = core_export.for_platform("traktor") + +print("== the target declares itself without a library to read ==") +check("traktor is a target", exporter is not None) +check("rekordbox is NOT", core_export.for_platform("rekordbox") is None) +check("onelibrary is NOT", core_export.for_platform("onelibrary") is None) +caps = exporter.capabilities() +check("static capabilities answer with no path", caps.platform == "traktor" and caps.writable) +check("and describe the FORMAT, not an instance", caps.cues.hotcue_slots == 8) + +# ---- build a payload out of real tracks -------------------------------------- +# One with a flexible (multi-marker) grid, one with several hot cues: the two +# things most likely to be quietly lost. +flexible = next(t for t in src.tracks if (t.grid_marker_count or 0) > 1) +cued = next(t for t in src.tracks if (t.cue_count or 0) >= 3 and t.id != flexible.id) +plain = next(t for t in src.tracks if t.id not in (flexible.id, cued.id)) +chosen = [flexible, cued, plain] + +dest = Path(tempfile.mkdtemp()) / "GIG" +dest.mkdir(parents=True) +items = [] +for track in chosen: + audio = dest / "Music" / "Library" / Path(track.filepath).name + audio.parent.mkdir(parents=True, exist_ok=True) + audio.write_bytes(b"\0" * 64) + items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id))) + +payload = ExportPayload( + name="GIG", + tracks=items, + playlists=[ + ExportPlaylist(name="Peak Time", track_ids=[flexible.id, cued.id], folders=["House"]), + ExportPlaylist(name="Warmup", track_ids=[cued.id], folders=["House", "Slow"]), + ], +) +written = exporter.write(payload, dest) +text = written.read_text(encoding="utf-8") + +print("== the skeleton is what Traktor writes ==") +check("named collection.nml", written.name == "collection.nml") +check("the XML declaration is there", text.startswith('' in text) +check("a HEAD element", "' in text) +# Playlists cannot sit at the top level; they hang off a $ROOT FOLDER node. +check("PLAYLISTS wraps a $ROOT folder", '' in text) +check("INDEXING is present", '' in text) +check("the ENTRIES header matches the entry count", + f'' in text, + re.search(r'