Switched to more generic wording

This commit is contained in:
patben8 committed 2026-09-17 22:24:56 +02:00
1 parent c9e85bbdb5
commit 6e24f5ef1d
29 files changed
+796 -319

No files matched your search

+14 -6
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from ...core.adapter import InvalidCommand, NotFound, Unsupported
from ...core.capabilities import Capabilities
@@ -21,13 +22,10 @@ from ...core.pathmap import PathMapping
from ...core.query import TrackIndex
from . import capabilities as caps
from . import projection
from .cue_types import CUE_TYPE_TO_NATIVE
from .store import PlaylistError, TraktorStore
# 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}
NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()}
class TraktorAdapter:
@@ -186,8 +184,18 @@ class TraktorAdapter:
return self._refresh(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
native = [
SimpleNamespace(
slot=c.slot,
start=c.start,
name=c.name,
type=self._native_cue_type(getattr(c, "type", "cue")),
length=getattr(c, "length", 0.0),
)
for c in cues
]
with _translate():
self._store.place_hotcues(track_id, cues, overwrite=overwrite)
self._store.place_hotcues(track_id, native, overwrite=overwrite)
return self._refresh(track_id)
# ---- beatgrid ---------------------------------------------------------
@@ -0,0 +1,13 @@
"""Traktor's CUE_V2 TYPE encoding <-> the generic cue vocabulary.
The only place these integers are given meaning. Type 4 is a grid marker, not a
cue, so it has no generic name — grid markers are projected as beatgrid markers
and never appear in a track's cue list.
Lives in its own module so the projection and the adapter can both use it
without importing each other.
"""
from __future__ import annotations
CUE_TYPE_TO_NATIVE = {"cue": 0, "fade_in": 1, "fade_out": 2, "load": 3, "loop": 5}
NATIVE_TO_CUE_TYPE = {v: k for k, v in CUE_TYPE_TO_NATIVE.items()}
@@ -5,8 +5,49 @@ Everything above this file sees generic types exclusively.
"""
from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, Track, TrackCues
from . import beatgrid
from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
# depending on a user preference — so the library can contain either. Parsing
# notation is platform knowledge and belongs here, not in the UI.
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
def parse_key(key: str | None) -> tuple[int | None, str | None]:
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
Open Key numbers the wheel seven semitones round from Camelot, so
Open Key 1 == Camelot 8 (both are C major / A minor).
"""
if not key:
return None, None
k = key.strip()
if m := _CAMELOT.match(k):
n = int(m.group(1))
if 1 <= n <= 12:
return n, "minor" if m.group(2).lower() == "a" else "major"
if m := _OPEN_KEY.match(k):
n = int(m.group(1))
if 1 <= n <= 12:
return ((n + 6) % 12) + 1, "minor" if m.group(2).lower() == "m" else "major"
return None, None
def iso_date(value: str | None) -> str | None:
"""Traktor writes dates as "YYYY/M/D"; the model carries ISO-8601."""
if not value:
return None
m = _DATE.match(value.strip())
if not m:
return value
y, mo, d = m.groups()
return f"{y}-{int(mo):02d}-{int(d):02d}"
def primary_key(location) -> str:
@@ -38,6 +79,7 @@ def to_track(e) -> Track:
1 for c in cues if c.hotcue is not None and c.hotcue >= 0
)
markers = beatgrid.grid_markers(e)
wheel, mode = parse_key(info.key if info else None)
return Track(
id=primary_key(loc) if loc else (e.title or ""),
artist=e.artist,
@@ -51,19 +93,21 @@ def to_track(e) -> Track:
comment=info.comment if info else None,
bpm=beatgrid.effective_bpm(e),
key=info.key if info else None,
key_wheel=wheel,
key_mode=mode,
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,
import_date=iso_date(info.import_date if info else None),
last_played=iso_date(info.last_played if info else None),
release_date=iso_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,
grid_marker_count=len(markers),
grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
)
@@ -87,19 +131,31 @@ def to_track_cues(entry) -> TrackCues:
)
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)),
cues = []
for c in entry.cue_v2 or []:
if getattr(c, "grid", None) is not None:
continue # a grid marker is projected as a beatgrid marker, not a cue
marker = marker_of.get(id(c))
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
cues.append(
CuePoint(
name=c.name,
# An unknown TYPE is projected as a plain cue rather than dropped:
# preserving a cue we cannot name beats hiding it from the user.
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank.
role="hotcue",
start=(c.start or 0.0) / 1000.0,
length=(c.len or 0.0) / 1000.0,
slot=slot,
color=c.color,
# A grid marker's companion belongs to the beatgrid: the store
# refuses hotcue commands on it, so say so up front.
editable=marker is None,
readonly_reason="beatgrid_companion" if marker is not None else None,
grid_marker=marker,
)
)
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
grid_markers=grid_markers, grid_locked=bool(entry.lock), cues=cues
)
+10 -4
View File
@@ -154,20 +154,26 @@ class TraktorStore:
return PlaylistNode(
id=pl.uuid if pl and pl.uuid else name,
name=name,
type="PLAYLIST",
uuid=pl.uuid if pl else None,
kind="playlist",
count=len(keys),
selectable=True,
can_add_tracks=True,
can_reorder=True,
can_rename=True,
can_delete=True,
)
if ntype == "SMARTLIST" or node.smartplaylist is not None:
# Rule-based, so it has no static entry list to show or edit.
return PlaylistNode(
id="sl:" + "/".join(parent_path + [name]), name=name, type="SMARTLIST"
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart"
)
path = parent_path + [name]
return PlaylistNode(
id="fld:" + "/".join(path),
name=name,
type="FOLDER",
kind="folder",
children=[self._to_model(c, path) for c in self._children(node)],
can_contain_children=True,
)
@staticmethod
+72 -19
View File
@@ -9,13 +9,17 @@ is the shape a batch cue placement takes in generic terms.
"""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
class Track(BaseModel):
"""A single track, flattened from a Traktor collection ENTRY."""
"""A single track in the library, as the app sees it."""
id: str # primary key: "<VOLUME><DIR><FILE>", used to join playlist entries
id: str # the adapter's stable track key; opaque above the adapter
artist: str | None = None
title: str | None = None
album: str | None = None
@@ -26,20 +30,27 @@ class Track(BaseModel):
mix: str | None = None
comment: str | None = None
bpm: float | None = None
key: str | None = None # Traktor display key, e.g. "10m"
# The platform's own display string, shown verbatim ("10m", "8A", "Am").
key: str | None = None
# Camelot wheel position 1-12 + mode, parsed BY THE ADAPTER — notation is
# platform knowledge. None when the key is absent or unparseable.
key_wheel: int | None = None
key_mode: Literal["major", "minor"] | None = None
rating: int = 0 # 0-5 stars (derived from RANKING/51)
playcount: int | None = None
length: int | None = None # seconds
bitrate: int | None = None
# ISO-8601 "YYYY-MM-DD", normalised by the adapter.
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
# 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid.
grid_marker_count: int = 0
grid_locked: bool = False
media_kind: MediaKind = "audio"
class TrackPage(BaseModel):
@@ -79,15 +90,27 @@ class Stats(BaseModel):
class PlaylistNode(BaseModel):
"""A node in the playlist tree — either a FOLDER or a PLAYLIST/SMARTLIST."""
"""A node in the playlist tree.
id: str # stable synthetic id ("pl-<n>" / "fld-<n>")
`id` is OPAQUE: the adapter mints it and decodes it, and the UI never
constructs, parses or prefixes one. `kind` is for choosing an icon — every
behavioural question is answered by the flags, so the UI never has to infer
what a node can do from what it is called.
"""
id: str
name: str
type: str # "FOLDER" | "PLAYLIST" | "SMARTLIST"
uuid: str | None = None
kind: PlaylistKind = "playlist"
count: int = 0 # track count (for playlists)
children: list["PlaylistNode"] = []
selectable: bool = False # has a static, listable entry set
can_add_tracks: bool = False
can_reorder: bool = False
can_rename: bool = False
can_delete: bool = False
can_contain_children: bool = False # a valid parent for a new playlist
PlaylistNode.model_rebuild()
@@ -97,13 +120,20 @@ PlaylistNode.model_rebuild()
class CuePoint(BaseModel):
name: str | None = None
type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop
type: CueType = "cue"
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
# modelled and preserved but not yet editable anywhere.
role: CueRole = "hotcue"
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.
slot: int | None = None # bank slot; None for a cue not in a bank
color: str | None = None # "#RRGGBB" as the platform stored it
# False when the adapter refuses commands on this cue — the UI gates on THIS
# rather than on any platform-specific reason.
editable: bool = True
readonly_reason: Literal["beatgrid_companion", "platform_managed"] | None = None
# Index of the grid marker this cue mirrors, where the platform pairs them.
# A display hint only; None on platforms that do not.
grid_marker: int | None = None
@@ -121,16 +151,39 @@ class TrackCues(BaseModel):
# 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
grid_locked: bool = False
cues: list[CuePoint] = [] # cue/loop markers (grid markers themselves excluded)
class AutoHotcue(BaseModel):
slot: int # 0–7
"""One cue in a batch placement (Auto Hotcues)."""
slot: int
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)
type: CueType = "cue"
length: float = 0.0 # seconds (>0 for a loop cue)
class LibraryInfo(BaseModel):
"""Identity of the loaded library, for display and for composing copy."""
platform: str
name: str # the DJ app's name, e.g. "Traktor"
library_label: str # what the user thinks of the artefact as, e.g. "collection.nml"
path: str
display_name: str # short label for the status bar
version: str | None = None
class PlatformOption(BaseModel):
"""A platform the picker can offer before any library is open."""
platform: str
name: str
library_label: str
selects: Literal["file", "directory"] = "file"
installed: bool = False
class RemapSample(BaseModel):
+77 -42
View File
@@ -14,7 +14,6 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from . import __version__, history, prefs
from .adapters.traktor.adapter import NATIVE_TO_CUE_TYPE
from .adapters.traktor.discovery import describe
from .app_state import STATE
from .core import auto_hotcues as ah
@@ -38,6 +37,8 @@ from .schemas import (
CollectionStatus,
CreatePlaylist,
EditState,
LibraryInfo,
PlatformOption,
EditTrack,
Facets,
FileTagOutcome,
@@ -56,9 +57,9 @@ from .schemas import (
RenamePlaylist,
SaveResult,
SetEntries,
SetHotcue,
SetHotcueType,
SetLock,
SetCue,
SetCueType,
SetGridLock,
Stats,
Track,
TrackCues,
@@ -82,18 +83,6 @@ app.add_middleware(
)
def _cue_type_name(native: int) -> str:
"""Map the wire's Traktor cue integer onto the generic vocabulary.
Transitional: the HTTP contract still carries Traktor's encoding, so the
translation happens here at the boundary rather than in the adapter.
"""
name = NATIVE_TO_CUE_TYPE.get(native)
if name is None:
raise HTTPException(400, f"Unsupported cue type: {native}")
return name
def require_adapter() -> LibraryAdapter:
"""The loaded library, or a 409. Routes talk to this and nothing else."""
if not STATE.loaded:
@@ -118,7 +107,7 @@ def _adapter_error(_request, exc: AdapterError):
# ---- collection selection ---------------------------------------------
@app.get("/api/collection", response_model=CollectionStatus)
@app.get("/api/library", response_model=CollectionStatus)
def collection_status() -> CollectionStatus:
if not STATE.loaded:
return CollectionStatus(loaded=False)
@@ -127,10 +116,11 @@ def collection_status() -> CollectionStatus:
path=str(STATE.path),
tracks=len(require_adapter().tracks),
playlists=require_adapter().playlist_count(),
library=_library_info(),
)
@app.post("/api/collection/open", response_model=CollectionStatus)
@app.post("/api/library/open", response_model=CollectionStatus)
def open_collection(body: OpenCollection) -> CollectionStatus:
path = Path(body.path).expanduser()
if not path.exists() or not path.is_file():
@@ -145,7 +135,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
return collection_status()
@app.get("/api/collection/options", response_model=CollectionOptions)
@app.get("/api/library/options", response_model=CollectionOptions)
def collection_options() -> CollectionOptions:
"""Startup shortcuts for the picker: the best auto-detected Traktor
collection and the last one opened (may no longer exist → exists=False)."""
@@ -158,7 +148,7 @@ def collection_options() -> CollectionOptions:
return CollectionOptions(auto=auto, recent=recent)
@app.get("/api/collection/path-mapping", response_model=PathMappingInfo)
@app.get("/api/library/path-mapping", response_model=PathMappingInfo)
def get_path_mapping() -> PathMappingInfo:
"""The current collection's saved OS-path remapping (blank if none)."""
require_adapter()
@@ -168,7 +158,7 @@ def get_path_mapping() -> PathMappingInfo:
return PathMappingInfo()
@app.put("/api/collection/path-mapping", response_model=PathMappingInfo)
@app.put("/api/library/path-mapping", response_model=PathMappingInfo)
def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
"""Set (or, with blank prefixes, clear) the current collection's remapping.
Persists to userprefs AND updates the live store so playback/analysis
@@ -184,14 +174,14 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
)
@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions)
@app.get("/api/library/path-mapping/suggest", response_model=PrefixSuggestions)
def suggest_path_prefix() -> PrefixSuggestions:
"""Auto-detected `from` prefix candidates (common directory per volume),
so the editor can prefill the stored prefix."""
return PrefixSuggestions.model_validate(require_adapter().path_prefix_suggestions())
@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview)
@app.get("/api/library/path-mapping/preview", response_model=RemapPreview)
def preview_path_mapping(
from_: str = Query("", alias="from"), to: str = Query("")
) -> RemapPreview:
@@ -202,7 +192,7 @@ def preview_path_mapping(
)
@app.post("/api/collection/remap-paths", response_model=RemapResult)
@app.post("/api/library/remap-paths", response_model=RemapResult)
def remap_paths(body: PathMappingInfo) -> RemapResult:
"""Write-back: permanently rewrite matching track LOCATIONs (and the
playlist references that join to them) to the `to` prefix, then save (a
@@ -268,6 +258,42 @@ def health() -> dict:
return {"status": "ok", "loaded": STATE.loaded, "path": str(STATE.path) if STATE.path else None}
def _library_info() -> LibraryInfo:
"""Identity of the loaded library, for display and for composing warnings."""
caps = require_adapter().capabilities()
return LibraryInfo(
platform=caps.platform,
name=caps.save.app_name,
library_label=caps.save.library_label,
path=str(STATE.path),
display_name=Path(str(STATE.path)).name,
version=caps.version,
)
@app.get("/api/platforms", response_model=list[PlatformOption])
def platforms() -> list[PlatformOption]:
"""Every DJ platform Konduktor can open — used by the picker BEFORE a
library is loaded, where capabilities are not yet available."""
out = []
for d in registry.drivers():
found = []
try:
found = d.detect()
except OSError:
pass
out.append(
PlatformOption(
platform=d.platform,
name=d.display_name,
library_label=getattr(d, "library_label", ""),
selects="file",
installed=bool(found),
)
)
return out
@app.get("/api/capabilities", response_model=Capabilities)
def capabilities() -> Capabilities:
"""What the loaded library can persist, so the UI can gate its controls."""
@@ -276,7 +302,7 @@ def capabilities() -> Capabilities:
@app.get("/api/state", response_model=EditState)
def state() -> EditState:
return EditState(dirty=require_adapter().dirty, nml_path=str(STATE.path))
return EditState(dirty=require_adapter().dirty, library=_library_info())
@app.post("/api/reload")
@@ -346,7 +372,17 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
new_id = require_adapter().create_playlist(
body.name.strip() or "New Playlist", body.parent_id
)
return PlaylistNode(id=new_id, name=body.name, type="PLAYLIST", uuid=new_id, count=0)
return PlaylistNode(
id=new_id,
name=body.name,
kind="playlist",
count=0,
selectable=True,
can_add_tracks=True,
can_reorder=True,
can_rename=True,
can_delete=True,
)
@app.patch("/api/playlists/{playlist_uuid}")
@@ -438,20 +474,21 @@ def track_cues(track_id: str) -> TrackCues:
return _cues_for(track_id)
@app.post("/api/tracks/hotcue", response_model=TrackCues)
def create_hotcue(body: SetHotcue) -> TrackCues:
"""Create (or reposition + retype) the hotcue in a slot at a position."""
@app.post("/api/tracks/cue", response_model=TrackCues)
def create_cue(body: SetCue) -> TrackCues:
"""Create (or reposition + retype) the cue in a slot at a position."""
return require_adapter().set_cue(
body.track_id,
slot=body.slot,
start_sec=body.start,
cue_type=_cue_type_name(body.type),
cue_type=body.type,
role=body.role,
length_sec=body.length,
name=body.name,
)
@app.post("/api/tracks/auto-hotcues", response_model=TrackCues)
@app.post("/api/tracks/cue/auto", response_model=TrackCues)
def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
"""Analyze the track's audio and place structural hotcues into empty slots.
@@ -490,7 +527,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
return a.place_cues(body.track_id, [AutoHotcue(**s) for s in specs])
@app.post("/api/tracks/auto-grid", response_model=TrackCues)
@app.post("/api/tracks/grid/auto", response_model=TrackCues)
def auto_grid(body: AutoGridRequest) -> TrackCues:
"""Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1
(slot 0) to the first beat, and anchors the grid to that position. Octave
@@ -510,16 +547,14 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
return a.set_analysed_grid(body.track_id, [(first_beat, bpm)])
@app.patch("/api/tracks/hotcue", response_model=TrackCues)
def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
"""Change the type of an existing hotcue (keeps its position)."""
return require_adapter().set_cue_type(
body.track_id, body.slot, _cue_type_name(body.type)
)
@app.patch("/api/tracks/cue", response_model=TrackCues)
def edit_cue_type(body: SetCueType) -> TrackCues:
"""Change the type of an existing cue (keeps its position)."""
return require_adapter().set_cue_type(body.track_id, body.slot, body.type)
@app.delete("/api/tracks/hotcue", response_model=TrackCues)
def delete_hotcue(track_id: str, slot: int) -> TrackCues:
@app.delete("/api/tracks/cue", response_model=TrackCues)
def delete_cue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot."""
return require_adapter().delete_cue(track_id, slot)
@@ -568,8 +603,8 @@ def remove_grid(track_id: str) -> TrackCues:
return require_adapter().delete_grid(track_id)
@app.patch("/api/tracks/lock", response_model=TrackCues)
def edit_lock(body: SetLock) -> TrackCues:
@app.patch("/api/tracks/grid/lock", response_model=TrackCues)
def edit_grid_lock(body: SetGridLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track."""
return require_adapter().set_grid_lock(body.track_id, body.locked)
+19 -10
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
class CreatePlaylist(BaseModel):
name: str
@@ -61,18 +63,20 @@ class ReplaceGrid(BaseModel):
markers: list[GridMarker] = [] # [] is equivalent to deleting the grid
class SetLock(BaseModel):
class SetGridLock(BaseModel):
track_id: str
locked: bool
class SetHotcue(BaseModel):
class SetCue(BaseModel):
track_id: str
slot: int # 0–7
slot: int # bank slot; capabilities.cues.hotcue_slots bounds it
start: float # seconds
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
length: float = 0.0 # seconds (>0 for a loop hotcue)
name: str | None = None # cue label; defaults to Traktor's "n.n." when unset
type: CueType = "cue"
role: CueRole = "hotcue"
length: float = 0.0 # seconds (>0 for a loop cue)
name: str | None = None
color: str | None = None
class AutoHotcuesRequest(BaseModel):
@@ -84,15 +88,15 @@ class AutoGridRequest(BaseModel):
track_id: str
class SetHotcueType(BaseModel):
class SetCueType(BaseModel):
track_id: str
slot: int
type: int
type: CueType
class EditState(BaseModel):
dirty: bool # unsaved in-memory playlist changes exist
nml_path: str
dirty: bool # unsaved in-memory changes exist
library: LibraryInfo
# ---- collection selection ----
@@ -103,6 +107,9 @@ class CollectionStatus(BaseModel):
path: str | None = None
tracks: int | None = None
playlists: int | None = None
# Identity of the loaded library, so the UI can name it without parsing the
# path (a Serato library is a directory, not a file).
library: LibraryInfo | None = None
class OpenCollection(BaseModel):
@@ -157,6 +164,8 @@ class RemapResult(BaseModel):
# one import site. The dependency runs schemas -> core, never the reverse.
from .core.model import ( # noqa: E402,F401
AutoHotcue,
LibraryInfo,
PlatformOption,
CuePoint,
Facets,
GenreCount,
+1 -1
View File
@@ -49,7 +49,7 @@ client = TestClient(main.app)
def first_playlist(nodes):
for n in nodes:
if n["type"] == "PLAYLIST":
if n["kind"] == "playlist":
return n
if n.get("children"):
found = first_playlist(n["children"])
+2 -2
View File
@@ -53,7 +53,7 @@ check.failed = False
print("== initial read ==")
pls = client.get("/api/playlists").json()
flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))]
playlists = [n for n in flat(pls) if n["type"] == "PLAYLIST"]
playlists = [n for n in flat(pls) if n["kind"] == "playlist"]
print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}")
donor = next(p for p in playlists if p["count"] >= 5)
donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json()
@@ -64,7 +64,7 @@ collection_before = collection_span(WORK.read_bytes())
print("== create + add + reorder + rename ==")
created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json()
new_uuid = created["uuid"]
new_uuid = created["id"]
check("create returns uuid", bool(new_uuid))
r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids})
+9 -3
View File
@@ -23,6 +23,7 @@ import os
import shutil
import sys
import tempfile
from types import SimpleNamespace
import warnings
from pathlib import Path
@@ -318,9 +319,14 @@ with tempfile.TemporaryDirectory() as d:
# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
with tempfile.TemporaryDirectory() as d:
from konduktor.core.model import AutoHotcue
from traktor_nml_utils import TraktorCollection
# The store is the NATIVE layer, so its specs carry Traktor's own cue TYPE
# integer. The generic AutoHotcue (string types) is translated by the adapter
# before it gets here — test_traktor_adapter.py covers that path.
def spec(slot, start, name, type=0, length=0.0):
return SimpleNamespace(slot=slot, start=start, name=name, type=type, length=length)
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
@@ -348,8 +354,8 @@ with tempfile.TemporaryDirectory() as d:
e2 = store2._nml.collection.entry[0]
now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
free = [s for s in range(8) if s not in now_used][:2]
specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")]
specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
specs = [spec(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")]
specs += [spec(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
store2.place_hotcues(track_id, specs)
store2.save()
edited = work.read_bytes()
+11 -11
View File
@@ -105,21 +105,21 @@ with tempfile.TemporaryDirectory() as d:
# 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
if t.grid_marker_count and (cues := adapter.track_cues(t.id))
and len({c.slot for c in cues.cues if c.slot is not None}) < 7
)
before = adapter.track(tid2).hotcue_count
used = {c.hotcue for c in adapter.track_cues(tid2).cues if c.hotcue >= 0}
used = {c.slot for c in adapter.track_cues(tid2).cues if c.slot is not None}
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("set_cue returns fresh cues", any(c.slot == 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)
check("cue type round-trips through the generic vocabulary",
next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load")
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")
@@ -132,7 +132,7 @@ with tempfile.TemporaryDirectory() as d:
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)
adapter.track(tid2).grid_marker_count == grid_before + 1)
# ---- analysed grid vs plain replace --------------------------------------
print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==")
@@ -140,7 +140,7 @@ 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)
tid = next(t.id for t in adapter.tracks if t.grid_marker_count)
cues = adapter.replace_grid(tid, [(1.0, 128.0)])
check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1)
@@ -179,12 +179,12 @@ with tempfile.TemporaryDirectory() as d:
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
if len({c.slot for c in adapter.track_cues(t.id).cues if c.slot is not None}) < 6
)
used = {c.hotcue for c in adapter.track_cues(tid).cues if c.hotcue >= 0}
used = {c.slot for c in adapter.track_cues(tid).cues if c.slot is not None}
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)
placed = next((c for c in adapter.track_cues(tid).cues if c.slot == 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")