Built core and traktor exporter

This commit is contained in:
patben8 committed 2026-09-23 15:14:04 +02:00
1 parent 7160fa3978
commit 4aeb5d65d3
6 files changed
+465 -2

No files matched your search

+8
View File
@@ -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 **`<LOCATION>` 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
@@ -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)
@@ -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
`<MUSICFOLDERS>` element at all**, so it is not required, and `<PLAYLISTS>` 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 = (
'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n'
'<NML VERSION="20"><HEAD COMPANY="www.native-instruments.com" '
'PROGRAM="Konduktor"></HEAD>\n'
'<COLLECTION ENTRIES="0"></COLLECTION>\n'
'<SETS ENTRIES="0"></SETS>\n'
'<PLAYLISTS><NODE TYPE="FOLDER" NAME="$ROOT"><SUBNODES COUNT="0">'
"</SUBNODES>\n</NODE>\n</PLAYLISTS>\n"
'<INDEXING><SORTING_INFO PATH="$COLLECTION"></SORTING_INFO>\n'
"</INDEXING>\n</NML>\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
]
+125
View File
@@ -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 `<LOCATION>` 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}
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_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 "──────────────────────────────────────────"
+179
View File
@@ -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('<?xml version="1.0" encoding="UTF-8"'))
check("NML VERSION 20", '<NML VERSION="20">' in text)
check("a HEAD element", "<HEAD " in text)
# Measured from a real Traktor file: it has no MUSICFOLDERS at all.
check("no MUSICFOLDERS is required", "<MUSICFOLDERS" not in SKELETON)
check("SETS is present and empty", '<SETS ENTRIES="0">' in text)
# Playlists cannot sit at the top level; they hang off a $ROOT FOLDER node.
check("PLAYLISTS wraps a $ROOT folder", '<NODE TYPE="FOLDER" NAME="$ROOT">' in text)
check("INDEXING is present", '<SORTING_INFO PATH="$COLLECTION">' in text)
check("the ENTRIES header matches the entry count",
f'<COLLECTION ENTRIES="{len(chosen)}">' in text,
re.search(r'<COLLECTION ENTRIES="\d+"', text).group(0))
print("== LOCATION is volume-relative — the reason a stick is portable ==")
locations = re.findall(r'<LOCATION DIR="([^"]*)" FILE="([^"]*)" VOLUME="([^"]*)"', text)
check("every track has a location", len(locations) == len(chosen))
check("no host path leaks into DIR",
all(not d.startswith("/:Users/:") or "/:Music/:Library/:" in d for d, _f, _v in locations),
[d for d, _f, _v in locations])
check("DIR is volume-relative, ending at the audio folder",
all(d.endswith("/:Music/:Library/:") for d, _f, _v in locations),
[d for d, _f, _v in locations])
check("VOLUME is a name, not a path",
all("/" not in v for _d, _f, v in locations), [v for _d, _f, v in locations])
check("FILE is just the filename",
all("/" not in f for _d, f, _v in locations))
print("== it re-opens as a library ==")
back = TraktorDriver().open(written)
check("every track came across", len(back.tracks) == len(chosen))
by_title = {t.title: t for t in back.tracks}
check("titles survived", all(t.title in by_title for t in chosen),
sorted(set(t.title for t in chosen) - set(by_title)))
check("artist survived", by_title[plain.title].artist == plain.artist)
# Traktor→Traktor copies the key string verbatim: a user's notation is a
# preference their exported library should not silently change.
if plain.key:
check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
print("== the playlist tree ==")
tree = {}
def walk(nodes, path=()):
for n in nodes:
tree[path + (n.name,)] = n
walk(n.children, path + (n.name,))
walk(back.playlist_tree())
check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder")
check("nested folders are preserved", ("GIG", "House") in tree)
check("and nest further", ("GIG", "House", "Slow") in tree)
check("playlists land in their folder",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
check("with the right counts",
tree[("GIG", "House", "Peak Time")].count == 2
and tree[("GIG", "House", "Slow", "Warmup")].count == 1)
# A track added individually would otherwise be reachable only by search.
check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree)
check("holding exactly the ones no playlist claimed",
tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count)
other_ids = back.playlist_entries(tree[("GIG", "Other")].id)
check("and it is the right track",
back.track(other_ids[0]).title == plain.title)
print("== the prep crossed intact ==")
src_grid = src.track_cues(flexible.id)
out_grid = back.track_cues(by_title[flexible.title].id)
check("a flexible multi-marker grid survives",
len(out_grid.grid_markers) == len(src_grid.grid_markers),
f"{len(out_grid.grid_markers)} vs {len(src_grid.grid_markers)}")
check("with its tempo changes",
[round(m.bpm, 3) for m in out_grid.grid_markers]
== [round(m.bpm, 3) for m in src_grid.grid_markers])
check("and its marker positions",
[round(m.start, 3) for m in out_grid.grid_markers]
== [round(m.start, 3) for m in src_grid.grid_markers])
# Ben's decision: exported grids are NOT locked, so they stay editable like any
# other track. If Traktor turns out to re-analyse and flatten them, this is what
# makes that visible rather than hidden behind a lock.
check("grids are not locked", not by_title[flexible.title].grid_locked)
src_cues = src.track_cues(cued.id)
out_cues = back.track_cues(by_title[cued.title].id)
src_hot = {c.slot: round(c.start, 3) for c in src_cues.cues if c.role == "hotcue"}
out_hot = {c.slot: round(c.start, 3) for c in out_cues.cues if c.role == "hotcue"}
check("hot cues keep their PAD, not just their position", out_hot == src_hot,
f"{out_hot} vs {src_hot}")
print("== writing twice into the same folder replaces, never appends ==")
again = exporter.write(payload, dest)
check("the entry count did not double",
f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8"))
check("and the tree did not duplicate",
len(TraktorDriver().open(again).playlist_tree()) == 1)
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
raise SystemExit(1 if failed else 0)