mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented key setting into adapters
This commit is contained in:
1 parent
b5b3dd04c3
commit
c3571fd054
23 files changed
+656
-101
No files matched your search
@@ -114,6 +114,26 @@ Two independent apps that talk over HTTP:
|
||||
`backend/bench_grid_detect.py` scores it against any library's
|
||||
single-marker grids and reports that constant separately from detection
|
||||
error (29 Rekordbox references: old 1/29 BPMs, new 27/29).
|
||||
- `key_detect.py` + `key_model.npz` — **musical key detection**: a small
|
||||
CNN (Korzeniowski & Widmer 2017 — five 5x5 convs, a per-frame dense layer
|
||||
over the WHOLE pitch axis, since a key is not pitch-invariant, logits
|
||||
averaged over time), an ensemble of three, run in NUMPY — torch only
|
||||
trains it (`backend/train_key_model.py`, engine venv), the backend never
|
||||
imports it. Input is a 7-octave CQT at 36 bins/octave (C1–C8); the net
|
||||
sees C2–C7, the spare octaves are for pitch-shift augmentation. Trained
|
||||
on GiantSteps MTG, scored on the separate GiantSteps key set
|
||||
(`bench_key_detect.py`): **69.4% exact, 83.4% harmonically mixable**;
|
||||
key templates (Krumhansl/Temperley/KeyFinder/EDM) topped out at 49.5% on
|
||||
the same features. ~0.6 s per track beside the decode. Always returns a
|
||||
key for music (confidence tracks accuracy, but even the lowest band is
|
||||
~10x chance); None only for silence / under 5 s. The datasets are NOT on
|
||||
the machine by default — fetch steps are in the training script.
|
||||
- `musical_key.py` — the generic key (Camelot wheel 1-12 + mode) and the
|
||||
three notations libraries STORE: `camelot` (8A), `open_key` (1m — Traktor's
|
||||
default, Open Key n = Camelot n+7) and `musical` (Am, spelt as rekordbox
|
||||
spells its own rows: flats for Db/Eb/Ab/Bb, F#). `parse` accepts all
|
||||
three (and "Amin", "F# minor"), because a library holds what imported
|
||||
tags said: a rekordbox stick's key table had "12A" beside "Abm".
|
||||
- `stem_file.py` + `tag_copy.py` — **writing a native-instruments STEM
|
||||
file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz
|
||||
streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0,
|
||||
@@ -891,7 +911,12 @@ serialization path.** It enforces:
|
||||
— onto a staying track's path, or two differently-keyed entries for one file
|
||||
— which the preview reports first, while a chain (A onto B's old path, B
|
||||
onward) and a pre-existing duplicate are allowed, each track's staged art
|
||||
and edits following the TRACK (H4).
|
||||
and edits following the TRACK (H4). And **`set_key`** (N): on a keyed
|
||||
entry only its INFO and MUSICAL_KEY lines change; an unkeyed one gains the
|
||||
KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in
|
||||
Traktor's layout; the encoding matches the real collection; a Camelot
|
||||
collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the
|
||||
key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A.
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched.
|
||||
@@ -980,6 +1005,11 @@ serialization path.** It enforces:
|
||||
(pad, colour), loop and memory cue cross as themselves; and removing it
|
||||
deletes its analysis files. `test_folders.py` drives the same through
|
||||
`/api/folder/add` on a Rekordbox copy, and a non-addable library 422s.
|
||||
And **`set_key`** (K): a key the library has changes exactly the track row
|
||||
and the counter, pointing at its OWN row (found by meaning, not name); a
|
||||
missing key adds one `djmdKey` row as rekordbox creates its own — its
|
||||
spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is
|
||||
left unstamped) — which the next `set_key` reuses.
|
||||
- `test_onelibrary_adapter.py` — the third adapter against the same contract.
|
||||
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
|
||||
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
|
||||
@@ -998,7 +1028,10 @@ serialization path.** It enforces:
|
||||
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
|
||||
from 1; and the stick hazards — another app's write refused, an unplugged
|
||||
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
|
||||
the drive never held open, file tags written (title yes, rating no).
|
||||
the drive never held open, file tags written (title yes, rating no). And
|
||||
`set_key`: an existing key changes only `content.key_id` and reaches TKEY as
|
||||
the stick names it; a missing one adds a key row in rekordbox's spelling;
|
||||
on Goober, "12A" projects a key and setting 12A reuses that row.
|
||||
- `test_onelibrary_anlz.py` — cue and grid edits in the ANLZ files. First
|
||||
against **rekordbox's own edit** of the same thing
|
||||
(`fixtures/onelibrary-goober/after/`): a recolour's `PCO2` and a grid edit's
|
||||
@@ -1036,6 +1069,11 @@ serialization path.** It enforces:
|
||||
return, octave choice, and the loud off-beat hat and syncopated bassline that
|
||||
each fooled one band on real music. Accuracy on REAL music is
|
||||
`bench_grid_detect.py`'s job (not in `run_tests.sh`: it needs audio).
|
||||
- `test_key_detect.py` — key detection on SYNTHETIC cadences in all 24 keys
|
||||
(I-IV-V-I / i-iv-V-i — a pop I-V-vi-IV is fairly called minor by an EDM
|
||||
model), loudness / sample-rate invariance, None for silence, and the numpy
|
||||
convolution against a direct implementation. Accuracy on real music is
|
||||
`bench_key_detect.py`'s job (GiantSteps + any folder of key-tagged files).
|
||||
- `test_auto_hotcues.py` — Auto Hotcues in three layers: `structure.analyse`
|
||||
on SYNTHETIC audio with known sections (the intro with a kick is not a drop;
|
||||
no breakdown after the last drop), `plan`'s outcomes and beat-counted offsets
|
||||
@@ -1175,7 +1213,15 @@ frontend at `http://localhost:5173`.
|
||||
e.g. `Macintosh HD/:Music/:one.mp3`. This is how playlist entries
|
||||
(`PRIMARYKEY.KEY`) join to collection tracks. `Track.id` uses this.
|
||||
- **Rating** = `RANKING / 51`, giving 0–5 stars (`_rating_stars`).
|
||||
- **Key** is Traktor's display key string, e.g. `"10m"` (Open Key notation).
|
||||
- **Key** = two fields. `INFO@KEY` is the display text Traktor shows and tags
|
||||
files with, in the user's notation (Open Key `"10m"` in the real
|
||||
collection); `<MUSICAL_KEY VALUE>` is the analysed key, pitch class + 12 for
|
||||
minor (`12` = C minor = `10m`; 6,628 of 6,641 entries carrying both agree).
|
||||
1,354 entries have ONLY `MUSICAL_KEY` — analysed, never given text — so
|
||||
`projection.entry_key` falls back to it (rendered Open Key). `set_key` and
|
||||
`add_entry` write BOTH, the text in the collection's majority notation
|
||||
(`TraktorStore.key_notation()`; an empty collection — an export — takes a
|
||||
Traktor-native source's own, so Traktor→Traktor keeps the user's).
|
||||
- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor.
|
||||
Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child
|
||||
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
|
||||
@@ -1600,7 +1646,12 @@ that number and nothing else — everything derives from it:
|
||||
**Key notation crosses via the wheel**, never by copying the string:
|
||||
`projection.render_key()` is the inverse of `parse_key`, shared by both Pioneer
|
||||
targets, so Traktor's `"10m"` becomes `"Cm"` rather than a literal `"10m"` in a
|
||||
Pioneer library. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path,
|
||||
Pioneer library. Both are now `core/musical_key`; until 2026-10-04
|
||||
`render_key` spelt with SHARPS ("G#m", "D#", "C#m") where rekordbox's own rows
|
||||
say "Abm", "Eb", "Dbm" — measured from the key rows rekordbox 7 created in
|
||||
the local library. In-place writes (`set_key`, adds) find a key row by
|
||||
MEANING, so a library's existing "12A" or "G#m" row is reused, never
|
||||
duplicated. **Caveat**: `djmdContent.FolderPath` is an ABSOLUTE host path,
|
||||
so unlike Traktor and OneLibrary a Rekordbox export is not portable by copying
|
||||
the folder. Still unwritten and documented as unknown: OneLibrary's waveform
|
||||
tags and the `cue` table's MPEG seek columns.
|
||||
|
||||
@@ -31,9 +31,7 @@ from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from konduktor.adapters.rekordbox.projection import parse_key as parse_named # noqa: E402
|
||||
from konduktor.adapters.traktor.projection import parse_key as parse_wheel # noqa: E402
|
||||
from konduktor.core import key_detect # noqa: E402
|
||||
from konduktor.core import key_detect, musical_key # noqa: E402
|
||||
|
||||
WEIGHT = {"exact": 1.0, "fifth": 0.5, "relative": 0.3, "parallel": 0.2, "other": 0.0}
|
||||
AUDIO = {".mp3", ".m4a", ".mp4", ".flac", ".aif", ".aiff", ".wav", ".ogg"}
|
||||
@@ -57,13 +55,7 @@ def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
|
||||
|
||||
def parse_any(text: str) -> tuple[int, str] | None:
|
||||
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
|
||||
s = text.strip()
|
||||
w, m = parse_wheel(s)
|
||||
if w:
|
||||
return w, m
|
||||
s = re.sub(r"\s*(minor|min)$", "m", s, flags=re.I)
|
||||
s = re.sub(r"\s*(major|maj)$", "", s, flags=re.I)
|
||||
w, m = parse_named(s)
|
||||
w, m = musical_key.parse(text)
|
||||
return (w, m) if w else None
|
||||
|
||||
|
||||
@@ -121,12 +113,10 @@ def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
|
||||
out = []
|
||||
for f in sorted((gs / "annotations/key").glob("*.key")):
|
||||
name, mode = f.read_text().split()
|
||||
pc = key_detect.PITCH_NAMES.index({"C#": "C#", "Db": "C#", "D#": "Eb", "Gb": "F#",
|
||||
"G#": "Ab", "A#": "Bb"}.get(name, name))
|
||||
audio = gs / "audio" / f"{f.stem}.mp3"
|
||||
if audio.exists():
|
||||
out.append((audio, (key_detect.camelot_wheel(pc, mode), mode), f.stem))
|
||||
ref = parse_any(f.read_text()) # "C minor"
|
||||
if audio.exists() and ref:
|
||||
out.append((audio, ref, f.stem))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -392,6 +392,12 @@ class OneLibraryAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
|
||||
@@ -84,6 +84,7 @@ def capabilities_for(
|
||||
# with it, at Save — so the library, not the user, places the audio.
|
||||
addable=not read_only,
|
||||
removable=not read_only,
|
||||
key_writable=not read_only,
|
||||
places_audio=True,
|
||||
# `artwork` gates EDITING, which Rekordbox does not do yet either
|
||||
# (parity). Reading works: `store.cover_art` follows
|
||||
|
||||
@@ -133,8 +133,8 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating", "release_date"}
|
||||
# Written into the audio file's own tags at Save, as rekordbox does when it
|
||||
# edits a stick (measured: the title reached the MP3's TIT2, the rating did
|
||||
# not). Everything editable except the rating.
|
||||
FILE_TAG_FIELDS = EDITABLE_FIELDS - {"rating"}
|
||||
# not). Everything editable except the rating, plus the key `set_key` sets.
|
||||
FILE_TAG_FIELDS = (EDITABLE_FIELDS - {"rating"}) | {"key"}
|
||||
|
||||
def __init__(self, path: Path, *, read_only: bool = False):
|
||||
layout = DriveLayout.locate(Path(path))
|
||||
@@ -490,6 +490,34 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
pass
|
||||
raise InvalidCommand(f"Release date must be a year or YYYY-MM-DD, got {text!r}")
|
||||
|
||||
def _key_id(self, wheel: int | None, mode: str | None) -> int | None:
|
||||
"""The `key` row for a key, found by what it MEANS: a stick's table holds
|
||||
rekordbox's names ("Abm") beside imported tag text ("12A" — the goober
|
||||
fixture has both), so a rendered-name match would duplicate a key the
|
||||
stick already has. A new key gets rekordbox's own spelling."""
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
from pyrekordbox.devicelib_plus import models
|
||||
|
||||
from ..rekordbox.projection import parse_key, render_key
|
||||
|
||||
for k in self._require_db().query(models.Key).all():
|
||||
if parse_key(k.name) == (wheel, mode):
|
||||
return int(k.key_id)
|
||||
return self._lookup_id("Key", render_key(wheel, mode))
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
db = self._require_db()
|
||||
row = self.content(track_id)
|
||||
before = row.key_id
|
||||
row.key_id = self._key_id(wheel, mode)
|
||||
self._journal.record("track", "set", track_id, "key", before, row.key_id)
|
||||
# A foreign key: flush + expire, or re-projecting reads the old name.
|
||||
db.flush()
|
||||
db.session.expire(row)
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
from sqlalchemy import text
|
||||
|
||||
@@ -1026,7 +1054,6 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"""
|
||||
from sqlalchemy import text
|
||||
|
||||
from ..rekordbox.projection import render_key
|
||||
from .export import ANALYSED_BITS, CONTENT_LINK, _audio_format, _file_type, _kbps, art_files
|
||||
|
||||
if rel in (self._by_id or {}) or any(self.track_id(r) == rel for r in self.iter_content()):
|
||||
@@ -1070,7 +1097,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"album": lookup("Album", track.album), "genre": lookup("Genre", track.genre),
|
||||
"label": lookup("Label", track.label),
|
||||
# Rendered from the parsed wheel: a source's "10m" means nothing here.
|
||||
"key": lookup("Key", render_key(track.key_wheel, track.key_mode)),
|
||||
"key": self._key_id(track.key_wheel, track.key_mode),
|
||||
"image": image_id, "comment": track.comment or "",
|
||||
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
|
||||
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
|
||||
@@ -1375,7 +1402,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
t = projection.to_track(self.content(track_id))
|
||||
return {"title": t.title, "artist": t.artist, "album": t.album, "genre": t.genre,
|
||||
"label": t.label, "remixer": t.remixer, "comment": t.comment,
|
||||
"release_date": t.release_date}
|
||||
"release_date": t.release_date, "key": t.key}
|
||||
|
||||
|
||||
def _prune_empty(folder: Path, *, stop: Path) -> None:
|
||||
|
||||
@@ -245,6 +245,12 @@ class RekordboxAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
self._require_writable("Setting the key")
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
# ---- commands: playlists ----------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlists")
|
||||
|
||||
@@ -91,6 +91,7 @@ def capabilities_for(
|
||||
media_kinds=["audio", "stem"],
|
||||
removable=True,
|
||||
addable=True,
|
||||
key_writable=True,
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -5,65 +5,32 @@ The only place a ``pyrekordbox`` ORM object becomes a generic `Track` /
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
|
||||
# Open Key notation. Parsing that is platform knowledge and belongs here.
|
||||
_KEY_RE = re.compile(r"^([A-G])([#b]?)(m?)$", re.I)
|
||||
|
||||
# Camelot wheel position for each pitch class, per mode.
|
||||
_CAMELOT_MINOR = {
|
||||
"A": 8, "E": 9, "B": 10, "F#": 11, "Gb": 11, "C#": 12, "Db": 12,
|
||||
"G#": 1, "Ab": 1, "D#": 2, "Eb": 2, "A#": 3, "Bb": 3,
|
||||
"F": 4, "C": 5, "G": 6, "D": 7,
|
||||
}
|
||||
_CAMELOT_MAJOR = {
|
||||
"C": 8, "G": 9, "D": 10, "A": 11, "E": 12, "B": 1, "F#": 2, "Gb": 2,
|
||||
"C#": 3, "Db": 3, "G#": 4, "Ab": 4, "D#": 5, "Eb": 5, "A#": 6, "Bb": 6,
|
||||
"F": 7,
|
||||
}
|
||||
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
|
||||
# holds whatever text a track's key TAG carried when it was imported, so a real
|
||||
# stick has "12A" beside "Abm". Parsing therefore accepts every notation.
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Rekordbox key name."""
|
||||
if not key:
|
||||
return None, None
|
||||
m = _KEY_RE.match(key.strip())
|
||||
if not m:
|
||||
return None, None
|
||||
letter, accidental, minor = m.group(1).upper(), m.group(2), m.group(3)
|
||||
pitch = letter + (accidental.replace("B", "b") if accidental else "")
|
||||
table = _CAMELOT_MINOR if minor else _CAMELOT_MAJOR
|
||||
n = table.get(pitch)
|
||||
return (n, "minor" if minor else "major") if n else (None, None)
|
||||
"""(Camelot wheel position 1-12, mode) for a key name in any notation."""
|
||||
return musical_key.parse(key)
|
||||
|
||||
|
||||
# The inverse, for EXPORT. A track arriving from Traktor carries `key` as
|
||||
# The inverse, for writing. A track arriving from Traktor carries `key` as
|
||||
# Traktor's own display string ("10m") and `key_wheel`/`key_mode` as the parsed
|
||||
# position — so writing the string verbatim into a Pioneer library would show
|
||||
# "10m" where the deck expects "Abm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared with the OneLibrary exporter: same vendor, same
|
||||
# notation, and two tables would drift.
|
||||
_MINOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MINOR.items()))}
|
||||
_MAJOR_NAMES = {v: k for k, v in reversed(list(_CAMELOT_MAJOR.items()))}
|
||||
|
||||
|
||||
# "10m" where the deck expects "Cm". Rendering from the wheel is the only
|
||||
# correct crossing. Shared by the adapter and both Pioneer exporters.
|
||||
def render_key(wheel: int | None, mode: str | None) -> str | None:
|
||||
"""A Pioneer-style key name ("Abm", "F") for a Camelot position + mode.
|
||||
"""A Pioneer key name ("Abm", "F") for a Camelot position + mode, spelt as
|
||||
rekordbox spells its own (flats; see `core/musical_key`).
|
||||
|
||||
Returns None when the position is unknown, which is honest: a made-up key is
|
||||
worse than a blank one, and Pioneer software shows blanks without complaint.
|
||||
"""
|
||||
if not wheel or not (1 <= wheel <= 12):
|
||||
return None
|
||||
if mode == "minor":
|
||||
name = _MINOR_NAMES.get(wheel)
|
||||
return f"{name}m" if name else None
|
||||
return _MAJOR_NAMES.get(wheel)
|
||||
return musical_key.render(wheel, mode, "musical")
|
||||
|
||||
|
||||
def _iso_date(value) -> str | None:
|
||||
|
||||
@@ -506,6 +506,46 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: musical key ---------------------------------------------
|
||||
def _key_id(self, wheel: int | None, mode: str | None) -> str | None:
|
||||
"""The `djmdKey` row for a key, found by what it MEANS, not its text.
|
||||
|
||||
A library's key table holds rekordbox's own names ("Abm") and whatever
|
||||
key tags imported ("12A"), so matching on a rendered name would add a
|
||||
second row for a key the library already has. Only a key it has never
|
||||
seen gets a row — created as rekordbox creates its own (measured on the
|
||||
local library, which rekordbox fills lazily as it analyses): named in
|
||||
its spelling, `Seq` NULL, and through the ORM so `commit()` stamps the
|
||||
row's `rb_local_usn` like any other change. (The exporters' raw insert
|
||||
would leave it unstamped.)"""
|
||||
from .projection import parse_key, render_key
|
||||
|
||||
if wheel is None or mode is None:
|
||||
return None
|
||||
for k in self._db.query(self._tables.DjmdKey).all():
|
||||
if parse_key(k.ScaleName) == (wheel, mode):
|
||||
return str(k.ID)
|
||||
row = self._tables.DjmdKey(
|
||||
ID=str(uuid.uuid4().int % 2_147_483_647),
|
||||
ScaleName=render_key(wheel, mode),
|
||||
UUID=str(uuid.uuid4()),
|
||||
)
|
||||
self._db.add(row)
|
||||
self._db.flush()
|
||||
return str(row.ID)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
row = self.content(track_id)
|
||||
before = row.KeyID
|
||||
row.KeyID = self._key_id(wheel, mode)
|
||||
self._journal.record("track", "set", track_id, "key", before, row.KeyID)
|
||||
# A foreign key, like artist: flush + expire, or the re-projection
|
||||
# reads the old key back through the cached relationship.
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists ------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
t = self._tables
|
||||
@@ -604,7 +644,6 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
through the ordinary commands. `with_grid` reserves an empty `PQTZ`
|
||||
in the `.DAT` for `replace_grid` to fill."""
|
||||
from . import new_content
|
||||
from .projection import render_key
|
||||
|
||||
audio = Path(audio)
|
||||
if not audio.is_file():
|
||||
@@ -633,10 +672,9 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
content.AlbumID = new_content.lookup(self._db, "album", track.album)
|
||||
content.GenreID = new_content.lookup(self._db, "genre", track.genre)
|
||||
content.LabelID = new_content.lookup(self._db, "label", track.label)
|
||||
# Rendered from the wheel, never copied: the source's notation is not
|
||||
# Rekordbox's ("10m" is "Cm" here).
|
||||
content.KeyID = new_content.lookup(
|
||||
self._db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
# From the wheel, never the source's text: its notation is not
|
||||
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
|
||||
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
|
||||
content.ContentLink = new_content.CONTENT_LINK
|
||||
|
||||
track_uuid = str(content.UUID)
|
||||
|
||||
@@ -146,6 +146,12 @@ class TraktorAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_key(track_id, wheel, mode)
|
||||
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)
|
||||
|
||||
@@ -64,6 +64,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
removable=True,
|
||||
addable=True,
|
||||
stem_convertible=True,
|
||||
key_writable=True,
|
||||
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
|
||||
# but only on Windows, and a file added on one OS must play on both.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
|
||||
@@ -7,15 +7,14 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, timebase
|
||||
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)
|
||||
# depending on a user preference, and INFO@KEY also holds whatever a file's key
|
||||
# tag said ("Gm", "Amin") — so every notation is parsed (`core/musical_key`).
|
||||
_DATE = re.compile(r"^(\d{4})/(\d{1,2})/(\d{1,2})$")
|
||||
# "YYYY", "YYYY-MM" or "YYYY-MM-DD", optionally followed by a time (a
|
||||
# timestamp's date part is the date).
|
||||
@@ -23,23 +22,42 @@ _ISO_DATE = re.compile(r"^(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:[T ].*)?$")
|
||||
|
||||
|
||||
def parse_key(key: str | None) -> tuple[int | None, str | None]:
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor display key.
|
||||
"""(Camelot wheel position 1-12, mode) for a Traktor key string."""
|
||||
return musical_key.parse(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:
|
||||
|
||||
def musical_key_value(wheel: int, mode: str) -> int:
|
||||
"""`<MUSICAL_KEY VALUE>`: the tonic's pitch class (C = 0), plus 12 for minor
|
||||
— read off the real collection, where 12 pairs with "10m" (C minor) and 21
|
||||
with "1m" (A minor) on every entry carrying both."""
|
||||
return musical_key.pitch_class_of(wheel, mode) + (12 if mode == "minor" else 0)
|
||||
|
||||
|
||||
def _from_musical_key(value: int | None) -> tuple[int | None, str | None]:
|
||||
if value is None or not 0 <= value <= 23:
|
||||
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
|
||||
mode = "minor" if value >= 12 else "major"
|
||||
return musical_key.wheel_of(value % 12, mode), mode
|
||||
|
||||
|
||||
def entry_key(e) -> tuple[str | None, int | None, str | None]:
|
||||
"""(display string, wheel, mode) for an ENTRY.
|
||||
|
||||
INFO@KEY is the text Traktor shows and writes to the file's tag; the
|
||||
analysed key itself is `<MUSICAL_KEY>`. 1,354 of the real collection's
|
||||
8,485 entries carry only the latter — analysed, with every value 0-23
|
||||
present, just never given a text — and Traktor shows a key for them, so
|
||||
they fall back to it, rendered in Open Key (Traktor's own default).
|
||||
"""
|
||||
info = e.info
|
||||
text = info.key if info else None
|
||||
wheel, mode = parse_key(text)
|
||||
if wheel is None:
|
||||
mk = e.musical_key.value_attribute if e.musical_key is not None else None
|
||||
wheel, mode = _from_musical_key(mk)
|
||||
if wheel is not None and not text:
|
||||
text = musical_key.render(wheel, mode, "open_key")
|
||||
return text, wheel, mode
|
||||
|
||||
|
||||
def iso_date(value: str | None) -> str | None:
|
||||
@@ -122,7 +140,7 @@ def to_track(e) -> Track:
|
||||
),
|
||||
key=lambda chip: chip.slot,
|
||||
)
|
||||
wheel, mode = parse_key(info.key if info else None)
|
||||
key_text, wheel, mode = entry_key(e)
|
||||
return Track(
|
||||
id=primary_key(loc) if loc else (e.title or ""),
|
||||
artist=e.artist,
|
||||
@@ -137,7 +155,7 @@ def to_track(e) -> Track:
|
||||
# Traktor's "Comment 2" is stored in INFO@RATING (stars are RANKING).
|
||||
comment2=info.rating if info else None,
|
||||
bpm=beatgrid.effective_bpm(e),
|
||||
key=info.key if info else None,
|
||||
key=key_text,
|
||||
key_wheel=wheel,
|
||||
key_mode=mode,
|
||||
rating=_rating_stars(info.ranking if info else None),
|
||||
|
||||
@@ -35,6 +35,7 @@ from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
MusicalKeytype,
|
||||
Locationtype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
@@ -54,7 +55,8 @@ from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
|
||||
from ...schemas import PlaylistNode
|
||||
from . import beatgrid, timebase
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
from .projection import iso_date, traktor_date
|
||||
from ...core import musical_key
|
||||
from .projection import iso_date, musical_key_value, traktor_date
|
||||
|
||||
# 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.
|
||||
@@ -99,6 +101,7 @@ class TraktorStore:
|
||||
self._journal = EditJournal()
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
self._notation: str | None = None
|
||||
self.dirty = False
|
||||
|
||||
def _note(
|
||||
@@ -399,6 +402,69 @@ class TraktorStore:
|
||||
self._journal.record("track", "set", track_id, k)
|
||||
self.dirty = True
|
||||
|
||||
# ---- musical key ----------------------------------------------------
|
||||
def _collection_notation(self) -> str | None:
|
||||
"""The notation this collection's INFO@KEY values are written in — a
|
||||
Traktor preference (Open Key / Camelot / musical) the NML does not
|
||||
record, so it is read off the keys themselves; the majority wins. None
|
||||
when the collection holds no keys — never cached, since adding entries
|
||||
to an empty collection (an export) is exactly when it changes. Once
|
||||
known it is kept for the session: every key Konduktor writes is in it,
|
||||
so it can only move if one could out-vote thousands."""
|
||||
from collections import Counter
|
||||
|
||||
if self._notation is not None:
|
||||
return self._notation
|
||||
seen = Counter(
|
||||
musical_key.notation_of(e.info.key)
|
||||
for e in self._nml.collection.entry
|
||||
if e.info is not None and e.info.key
|
||||
)
|
||||
seen.pop(None, None)
|
||||
self._notation = seen.most_common(1)[0][0] if seen else None
|
||||
return self._notation
|
||||
|
||||
def key_notation(self) -> str:
|
||||
"""`_collection_notation`, or Open Key (Traktor's default) when there
|
||||
are no keys to go by. A key in another notation would display fine but
|
||||
read as foreign beside its neighbours."""
|
||||
return self._collection_notation() or "open_key"
|
||||
|
||||
def _added_key_text(self, track) -> str | None:
|
||||
"""INFO@KEY for an entry `add_entry` creates: rendered from the wheel in
|
||||
this collection's notation, never copied — a Pioneer source says "Abm",
|
||||
which reads as foreign beside "9m". A collection with no keys yet (an
|
||||
export's fresh skeleton) takes a Traktor-native source's own notation,
|
||||
so Traktor -> Traktor keeps the user's (the export decision). Text that
|
||||
names no key is kept as it was: dropping it would lose information."""
|
||||
text = getattr(track, "key", None) or None
|
||||
wheel, mode = getattr(track, "key_wheel", None), getattr(track, "key_mode", None)
|
||||
if not (wheel and mode):
|
||||
return text
|
||||
notation = self._collection_notation()
|
||||
if notation is None:
|
||||
own = musical_key.notation_of(text)
|
||||
notation = own if own in ("open_key", "camelot") else "open_key"
|
||||
return musical_key.render(wheel, mode, notation)
|
||||
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> None:
|
||||
"""Set a track's key as Traktor's analysis writes one: the display
|
||||
text in INFO@KEY (in the collection's notation; also what reaches the
|
||||
file's tag at Save) AND the analysed value in `<MUSICAL_KEY>`."""
|
||||
if not (isinstance(wheel, int) and 1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
raise InvalidCommand(f"Not a key: wheel {wheel!r}, mode {mode!r}")
|
||||
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()
|
||||
before = entry.info.key
|
||||
entry.info.key = musical_key.render(wheel, mode, self.key_notation())
|
||||
entry.musical_key = MusicalKeytype(value_attribute=musical_key_value(wheel, mode))
|
||||
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
|
||||
self.dirty = True
|
||||
|
||||
# ---- adding tracks --------------------------------------------------
|
||||
def add_entry(self, track, audio_path: Path) -> str:
|
||||
"""Append a brand-new ENTRY for `audio_path` and return its track id.
|
||||
@@ -443,7 +509,7 @@ class TraktorStore:
|
||||
remixer=getattr(track, "remixer", None) or None,
|
||||
producer=getattr(track, "producer", None) or None,
|
||||
mix=getattr(track, "mix", None) or None,
|
||||
key=getattr(track, "key", None) or None,
|
||||
key=self._added_key_text(track),
|
||||
bitrate=getattr(track, "bitrate", None) or None,
|
||||
playcount=getattr(track, "playcount", None) or None,
|
||||
# The generic model carries ISO dates; Traktor writes "YYYY/M/D".
|
||||
@@ -469,6 +535,12 @@ class TraktorStore:
|
||||
# projected BPM so a track with no grid still shows a tempo;
|
||||
# `replace_grid` overwrites it from the markers when they land.
|
||||
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
|
||||
# The analysed key, as Traktor's own analysis stores it.
|
||||
musical_key=(
|
||||
MusicalKeytype(value_attribute=musical_key_value(track.key_wheel, track.key_mode))
|
||||
if getattr(track, "key_wheel", None) and getattr(track, "key_mode", None)
|
||||
else None
|
||||
),
|
||||
cue_v2=[],
|
||||
stems=Stemstype(stems=stems) if stems else None,
|
||||
)
|
||||
|
||||
@@ -223,6 +223,10 @@ class LibraryAdapter(Protocol):
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
# The musical key, as a Camelot wheel position (1-12) + mode — what key
|
||||
# analysis writes. Each platform renders it in its own notation (and its own
|
||||
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> 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: ...
|
||||
|
||||
|
||||
@@ -22,7 +22,10 @@ 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
|
||||
# comment, mix, release_date, rating, key
|
||||
# `key` is written as the library holds it ("9m", "Abm") into the frame DJ
|
||||
# software reads: ID3 TKEY, MP4/FLAC `initialkey` — where Traktor writes its
|
||||
# own (every key-tagged file on the dev machine has it there).
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -170,6 +173,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
TDRC,
|
||||
TIT2,
|
||||
TIT3,
|
||||
TKEY,
|
||||
TPE1,
|
||||
TPE4,
|
||||
TPUB,
|
||||
@@ -185,6 +189,7 @@ def _apply_id3(id3, meta: TagMeta, popm_email: str = DEFAULT_POPM_EMAIL) -> None
|
||||
"remixer": TPE4,
|
||||
"mix": TIT3,
|
||||
"release_date": TDRC,
|
||||
"key": TKEY,
|
||||
}
|
||||
for field, frame in simple.items():
|
||||
if field in meta:
|
||||
@@ -262,7 +267,8 @@ def _write_mp4(path: Path, meta: TagMeta) -> 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"}
|
||||
freeform = {"label": "LABEL", "remixer": "REMIXER", "producer": "PRODUCER", "mix": "MIX",
|
||||
"key": "initialkey"}
|
||||
for field, name in freeform.items():
|
||||
if field in meta:
|
||||
key = f"----:com.apple.iTunes:{name}"
|
||||
@@ -297,6 +303,7 @@ def _write_flac(path: Path, meta: TagMeta) -> None:
|
||||
"comment": "comment",
|
||||
"mix": "mixname",
|
||||
"release_date": "date",
|
||||
"key": "initialkey",
|
||||
}
|
||||
for field, vc in mapping.items():
|
||||
if field in meta:
|
||||
|
||||
@@ -78,6 +78,9 @@ class TrackCapabilities(BaseModel):
|
||||
# Tracks can be converted to native-instruments STEM files, which this
|
||||
# platform plays as stems (`apply_stem_swaps`).
|
||||
stem_convertible: bool = False
|
||||
# The musical key can be set (`set_key`) — what key analysis writes. Not
|
||||
# in `editable_fields`: a key is a wheel position, not free text.
|
||||
key_writable: bool = False
|
||||
# The audio files this library can hold, as lower-case suffixes. What a
|
||||
# browsed folder offers to add — a file the library would refuse, or that
|
||||
# the DJ app cannot play, is not worth listing as addable.
|
||||
|
||||
@@ -38,6 +38,8 @@ from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import musical_key
|
||||
|
||||
SR = 22050
|
||||
HOP = 4096 # ~5.4 frames/s: key is a slow property
|
||||
BINS_PER_OCTAVE = 36 # three per semitone, so a detuned track still lands in one
|
||||
@@ -51,7 +53,7 @@ WINDOW = (36, 216)
|
||||
_MODEL = Path(__file__).with_name("key_model.npz")
|
||||
_TIME_CHUNK = 256 # frames per im2col block: bounds memory to tens of MB
|
||||
|
||||
PITCH_NAMES = ("C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
|
||||
PITCH_NAMES = musical_key.SPELLING
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -68,7 +70,7 @@ class KeyResult:
|
||||
|
||||
def camelot_wheel(pitch_class: int, mode: str) -> int:
|
||||
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
|
||||
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
|
||||
return musical_key.wheel_of(pitch_class, mode)
|
||||
|
||||
|
||||
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Musical keys: the generic form and the notations DJ software writes.
|
||||
|
||||
The generic model carries a key as a Camelot wheel position (1-12) plus a mode
|
||||
(`Track.key_wheel` / `key_mode`); one step round the wheel is a fifth, and the
|
||||
minor key on a number is the relative of the major one. Each platform STORES a
|
||||
key in its own notation, and a library also holds whatever another tool put
|
||||
there — a rekordbox stick's key table carries "12A" beside "Abm" when tracks
|
||||
arrived with Camelot tags. So parsing accepts every notation, and rendering is
|
||||
always explicit about which one it writes.
|
||||
|
||||
Notations:
|
||||
- "camelot": 8A / 8B (Mixed In Key's wheel; A = minor)
|
||||
- "open_key": 1m / 1d (Traktor's default; Open Key 1 = Camelot 8)
|
||||
- "musical": Am / C, with rekordbox's spelling: flats for Db Eb Ab Bb, and
|
||||
F# — measured from the key rows rekordbox 7 itself created (Abm, Dbm, Ebm,
|
||||
Eb; the six-sharp key was not among them).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
Mode = Literal["major", "minor"]
|
||||
Notation = Literal["camelot", "open_key", "musical"]
|
||||
|
||||
_CAMELOT = re.compile(r"^(\d{1,2})\s*([ab])$", re.I)
|
||||
_OPEN_KEY = re.compile(r"^(\d{1,2})\s*([md])$", re.I)
|
||||
_MUSICAL = re.compile(r"^([A-G])\s*([#b♯♭]?)\s*(m|min|minor|maj|major)?$", re.I)
|
||||
|
||||
_PITCH = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
|
||||
SPELLING = ("C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
|
||||
|
||||
|
||||
def wheel_of(pitch_class: int, mode: Mode) -> int:
|
||||
"""Camelot position of a tonic: C major = 8B, A minor = 8A."""
|
||||
return (((7 * pitch_class) % 12 + (7 if mode == "major" else 4)) % 12) + 1
|
||||
|
||||
|
||||
def pitch_class_of(wheel: int, mode: Mode) -> int:
|
||||
"""The tonic (0 = C) at a Camelot position — `wheel_of`'s inverse."""
|
||||
return (7 * ((wheel - 1) - (7 if mode == "major" else 4))) % 12
|
||||
|
||||
|
||||
def parse(text: str | None) -> tuple[int | None, Mode | None]:
|
||||
"""(wheel, mode) for a key in any notation; (None, None) if unreadable.
|
||||
|
||||
A bare number-and-letter is ambiguous only in principle: Camelot uses A/B
|
||||
and Open Key m/d, so the letter says which."""
|
||||
if not text:
|
||||
return None, None
|
||||
s = text.strip()
|
||||
if m := _CAMELOT.match(s):
|
||||
n = int(m.group(1))
|
||||
if 1 <= n <= 12:
|
||||
return n, "minor" if m.group(2).lower() == "a" else "major"
|
||||
return None, None
|
||||
if m := _OPEN_KEY.match(s):
|
||||
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
|
||||
if m := _MUSICAL.match(s):
|
||||
letter, accidental, quality = m.group(1).upper(), m.group(2), (m.group(3) or "")
|
||||
pc = _PITCH[letter] + {"#": 1, "♯": 1, "b": -1, "♭": -1}.get(accidental, 0)
|
||||
# "m" alone is minor; "maj"/"major" major; "min"/"minor" minor.
|
||||
q = quality.lower()
|
||||
mode: Mode = "minor" if q in ("m", "min", "minor") else "major"
|
||||
return wheel_of(pc % 12, mode), mode
|
||||
return None, None
|
||||
|
||||
|
||||
def render(wheel: int | None, mode: str | None, notation: Notation) -> str | None:
|
||||
"""A key in `notation`, or None when the position is unknown — a made-up
|
||||
key is worse than a blank one."""
|
||||
if not wheel or not (1 <= wheel <= 12) or mode not in ("major", "minor"):
|
||||
return None
|
||||
if notation == "camelot":
|
||||
return f"{wheel}{'A' if mode == 'minor' else 'B'}"
|
||||
if notation == "open_key":
|
||||
return f"{((wheel + 4) % 12) + 1}{'m' if mode == 'minor' else 'd'}"
|
||||
return SPELLING[pitch_class_of(wheel, mode)] + ("m" if mode == "minor" else "")
|
||||
|
||||
|
||||
def notation_of(text: str | None) -> Notation | None:
|
||||
"""Which notation a stored key string is written in."""
|
||||
if not text:
|
||||
return None
|
||||
s = text.strip()
|
||||
if _CAMELOT.match(s):
|
||||
return "camelot"
|
||||
if _OPEN_KEY.match(s):
|
||||
return "open_key"
|
||||
if _MUSICAL.match(s):
|
||||
return "musical"
|
||||
return None
|
||||
@@ -349,6 +349,61 @@ check("a missing audio file is reported, not fatal",
|
||||
and dump(db_of(drive))["content"]["2"]["title"] == "Missing", str(outcome.tag_results))
|
||||
a.close()
|
||||
|
||||
# ---- the key: found by meaning, created in rekordbox's spelling, tagged -------
|
||||
print("== set_key ==")
|
||||
from konduktor.adapters.rekordbox.projection import parse_key, render_key # noqa: E402
|
||||
|
||||
drive = fresh_drive()
|
||||
audio = drive / TRACK_1.lstrip("/")
|
||||
make_mp3(audio)
|
||||
before = dump(db_of(drive))
|
||||
keys = {parse_key(r["name"]): pk for pk, r in before["key"].items()}
|
||||
a = OneLibraryAdapter(drive)
|
||||
check("the key can be written on an editable stick", a.capabilities().tracks.key_writable is True)
|
||||
have = next(iter(keys))
|
||||
t = a.set_key(TRACK_1, *have)
|
||||
check("the projection shows it at once", (t.key_wheel, t.key_mode) == have, str(t))
|
||||
a.save()
|
||||
changes = diff(before, dump(db_of(drive)))
|
||||
check("an existing key: exactly content.key_id changes, pointing at the stick's own row",
|
||||
len(changes) == 1 and set(changes[0][3]) == {"key_id"}
|
||||
and str(changes[0][3]["key_id"][1]) == keys[have], str(changes))
|
||||
check("and reaches the file's TKEY as the stick names it",
|
||||
str(mutagen.File(str(audio)).tags.get("TKEY")) == before["key"][keys[have]]["name"],
|
||||
str(mutagen.File(str(audio)).tags.get("TKEY")))
|
||||
before = dump(db_of(drive))
|
||||
lack = next((w, m) for w in range(1, 13) for m in ("major", "minor") if (w, m) not in keys)
|
||||
a.set_key(TRACK_2, *lack)
|
||||
a.save()
|
||||
changes = diff(before, dump(db_of(drive)))
|
||||
added = [c for c in changes if c[0] == "key"]
|
||||
check("a missing key adds one key row, in rekordbox's spelling",
|
||||
len(added) == 1 and added[0][2] == "INSERT" and added[0][3]["name"] == render_key(*lack),
|
||||
describe(changes))
|
||||
check("a read-only stick may not", OneLibraryAdapter(drive, read_only=True).capabilities().tracks.key_writable is False)
|
||||
a.close()
|
||||
|
||||
print("== imported key names (a rekordbox stick holds '12A' beside 'Abm') ==")
|
||||
goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-goober-")) / "Goober"
|
||||
shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after"))
|
||||
before = dump(db_of(goober))
|
||||
names = {r["name"]: pk for pk, r in before["key"].items()}
|
||||
g = OneLibraryAdapter(goober)
|
||||
camelot_keyed = [t for t in g.tracks if t.key in ("12A", "11A", "10A")]
|
||||
check("a track keyed '12A' projects its wheel (it read as no key before)",
|
||||
camelot_keyed and all(t.key_wheel is not None for t in camelot_keyed),
|
||||
str([(t.key, t.key_wheel) for t in camelot_keyed]))
|
||||
target = next(t for t in g.tracks if t.key != "12A")
|
||||
g.set_key(target.id, 12, "minor")
|
||||
g.save()
|
||||
after = dump(db_of(goober))
|
||||
check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'",
|
||||
len(after["key"]) == len(before["key"])
|
||||
and str(next(r for r in after["content"].values()
|
||||
if r["content_id"] == next(r2["content_id"] for r2 in before["content"].values()
|
||||
if r2["title"] == target.title))["key_id"]) == names["12A"])
|
||||
g.close()
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -736,5 +736,53 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("removing it again deletes its analysis files", not dat.exists())
|
||||
reopened.close()
|
||||
|
||||
# ---- K: setting the key ------------------------------------------------
|
||||
# Rekordbox fills djmdKey lazily, one row per key it has met, named "Abm" —
|
||||
# and an imported tag can add "12A". So the key is found by MEANING, a row
|
||||
# is only ever added for a key the library lacks, and that row looks like
|
||||
# rekordbox's own: Seq NULL, its own USN.
|
||||
print("== K: set_key reuses the library's key rows and creates missing ones as rekordbox does ==")
|
||||
from konduktor.adapters.rekordbox.projection import parse_key as rb_parse_key, render_key
|
||||
|
||||
clean_copy(REAL, work)
|
||||
before = dump(work)
|
||||
by_meaning = {rb_parse_key(r["ScaleName"]): pk for pk, r in before["djmdKey"].items()}
|
||||
adapter = RekordboxAdapter(work)
|
||||
have = next(((w, m) for (w, m) in by_meaning if w), None)
|
||||
lack = next(((w, m) for w in range(1, 13) for m in ("major", "minor") if (w, m) not in by_meaning))
|
||||
t1, t2 = adapter.tracks[0], adapter.tracks[1]
|
||||
if have is None:
|
||||
print(" (skipped the reuse half: this library has no key rows)")
|
||||
else:
|
||||
got = adapter.set_key(t1.id, *have)
|
||||
check("the projection updates immediately", (got.key_wheel, got.key_mode) == have, str(got))
|
||||
adapter.save()
|
||||
changes = diff(before, dump(work))
|
||||
check("an existing key: exactly the track row and the counter change",
|
||||
{t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2,
|
||||
describe(changes))
|
||||
content = [c for c in changes if c[0] == "djmdContent"]
|
||||
check("…pointing at the library's own row for that key",
|
||||
content and content[0][3].get("KeyID", (None, None))[1] == by_meaning[have],
|
||||
str(content and content[0][3]))
|
||||
before = dump(work)
|
||||
got = adapter.set_key(t2.id, *lack)
|
||||
adapter.save()
|
||||
after = dump(work)
|
||||
changes = diff(before, after)
|
||||
new_keys = [c for c in changes if c[0] == "djmdKey"]
|
||||
check("a missing key adds exactly one key row", len(new_keys) == 1 and new_keys[0][2] == "INSERT",
|
||||
describe(changes))
|
||||
if new_keys:
|
||||
row = new_keys[0][3]
|
||||
check("named in rekordbox's spelling, Seq NULL, stamped with a USN",
|
||||
rb_parse_key(row["ScaleName"]) == lack and row["ScaleName"] == render_key(*lack)
|
||||
and row["Seq"] is None and row["rb_local_usn"] is not None, str(row))
|
||||
adapter.set_key(t1.id, *lack)
|
||||
adapter.save()
|
||||
check("setting that key again reuses the new row",
|
||||
len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
|
||||
adapter.close()
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -940,5 +940,151 @@ with tempfile.TemporaryDirectory() as d:
|
||||
f"{info.release_date!r} {info.import_date!r}")
|
||||
|
||||
|
||||
# ---- Invariant N: setting a key is localized, in Traktor's two fields -------
|
||||
# Traktor keeps the analysed key in <MUSICAL_KEY VALUE> (pitch class, +12 for
|
||||
# minor) and the text it shows / tags files with in INFO@KEY. `set_key` writes
|
||||
# both, as Traktor's analysis does, in the collection's own notation.
|
||||
print("== N. set_key writes INFO@KEY + MUSICAL_KEY, localized, in the collection's notation ==")
|
||||
import re # noqa: E402
|
||||
|
||||
from konduktor.adapters.traktor.projection import entry_key, musical_key_value, parse_key # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
||||
|
||||
real = TraktorCollection(path=REAL).nml.collection.entry
|
||||
both = [e for e in real if e.info and e.info.key and e.musical_key is not None
|
||||
and parse_key(e.info.key)[0] is not None]
|
||||
agree = sum(musical_key_value(*parse_key(e.info.key)) == e.musical_key.value_attribute for e in both)
|
||||
check(f"N: MUSICAL_KEY encoding matches INFO@KEY on the real collection ({agree}/{len(both)})",
|
||||
agree >= 0.995 * len(both), f"{len(both) - agree} disagree")
|
||||
mk_only = [e for e in real if e.musical_key is not None and not (e.info and e.info.key)]
|
||||
check(f"N: the {len(mk_only)} MUSICAL_KEY-only entries project a key",
|
||||
mk_only and all(entry_key(e)[1] is not None for e in mk_only))
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
store = TraktorStore(work)
|
||||
check("N: the real collection's notation is Open Key", store.key_notation() == "open_key",
|
||||
store.key_notation())
|
||||
|
||||
def changed_lines(before: bytes, after: bytes) -> list[str]:
|
||||
return [dl for dl in difflib.unified_diff(tag_lines(before), tag_lines(after), n=0)
|
||||
if dl[:1] in "+-" and dl[:3] not in ("+++", "---")]
|
||||
|
||||
# A track that has both: the two existing lines change, nothing else.
|
||||
keyed = next(e for e in store._nml.collection.entry
|
||||
if e.location and e.info and e.info.key == "10m" and e.musical_key is not None)
|
||||
original = store._render()
|
||||
store.set_key(store._key_of(keyed), 1, "minor") # Camelot 1A = Ab minor = Open Key 6m
|
||||
changed = changed_lines(original, store._render())
|
||||
check("N: a keyed track: only its INFO and MUSICAL_KEY lines change",
|
||||
len(changed) == 4 and 'KEY="6m"' in changed[1] and changed[3] == '+<MUSICAL_KEY VALUE="20">',
|
||||
"\n".join(changed))
|
||||
|
||||
# A track that has neither: MUSICAL_KEY appears where Traktor puts it.
|
||||
bare = next(e for e in store._nml.collection.entry
|
||||
if e.location and e.info and not e.info.key and e.musical_key is None
|
||||
and e.loudness is not None and e.cue_v2)
|
||||
bare_id = store._key_of(bare)
|
||||
original = store._render()
|
||||
store.set_key(bare_id, 8, "major") # C major
|
||||
after = store._render()
|
||||
changed = changed_lines(original, after)
|
||||
check("N: an unkeyed track gains KEY on INFO plus one MUSICAL_KEY element",
|
||||
len(changed) == 4 and 'KEY="1d"' in changed[1]
|
||||
and changed[2] == '+<MUSICAL_KEY VALUE="0">' and changed[3] == "+</MUSICAL_KEY>",
|
||||
"\n".join(changed))
|
||||
i = after.find(f'FILE="{bare.location.file}"'.encode())
|
||||
span = after[after.rfind(b"<ENTRY ", 0, i):after.find(b"</ENTRY>", i)].decode()
|
||||
check("N: …between LOUDNESS and the first CUE_V2, as Traktor writes it",
|
||||
span.index("<LOUDNESS") < span.index("<MUSICAL_KEY") < span.index("<CUE_V2"))
|
||||
check("N: …in Traktor's exact layout",
|
||||
re.search(r'</LOUDNESS>\n<MUSICAL_KEY VALUE="0"></MUSICAL_KEY>\n', span) is not None)
|
||||
|
||||
check("N: the file tag is given the INFO text", store._entry_field_value(bare, "key") == "1d")
|
||||
try:
|
||||
store.set_key(bare_id, 13, "minor")
|
||||
check("N: an impossible key is refused", False)
|
||||
except InvalidCommand:
|
||||
check("N: an impossible key is refused", True)
|
||||
|
||||
store.save()
|
||||
e = TraktorCollection(path=work).nml.collection.entry
|
||||
saved = next(x for x in e if x.location and x.location.file == bare.location.file
|
||||
and x.location.dir == bare.location.dir)
|
||||
check("N: survives a save + re-parse",
|
||||
saved.info.key == "1d" and saved.musical_key.value_attribute == 0
|
||||
and entry_key(saved)[1:] == (8, "major"))
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
# An ADDED entry's key is rendered too: a Pioneer source's "Abm" is not
|
||||
# copied into an Open Key collection, and MUSICAL_KEY is written.
|
||||
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
||||
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
store = TraktorStore(work)
|
||||
pioneer = SimpleNamespace(title="N add", key="Abm", key_wheel=1, key_mode="minor")
|
||||
added = store._entry_by_key[store.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/a.mp3"))]
|
||||
check("N: an added Pioneer key is rendered in the collection's notation, with MUSICAL_KEY",
|
||||
added.info.key == "6m" and added.musical_key.value_attribute == 20,
|
||||
f"{added.info.key} {added.musical_key}")
|
||||
odd = SimpleNamespace(title="N odd", key="DANCEDJ.CLUB", key_wheel=None, key_mode=None)
|
||||
kept = store._entry_by_key[store.add_entry(odd, Path("/Volumes/KONDUKTOR_TEST_N/b.mp3"))]
|
||||
check("N: text that names no key is kept, with no MUSICAL_KEY",
|
||||
kept.info.key == "DANCEDJ.CLUB" and kept.musical_key is None)
|
||||
|
||||
empty = Path(d) / "export.nml"
|
||||
empty.write_text(SKELETON, encoding="utf-8")
|
||||
fresh = TraktorStore(empty)
|
||||
camelot = SimpleNamespace(title="N cam", key="8A", key_wheel=8, key_mode="minor")
|
||||
first = fresh._entry_by_key[fresh.add_entry(camelot, Path("/Volumes/KONDUKTOR_TEST_N/c.mp3"))]
|
||||
check("N: an empty collection (an export) keeps a Traktor-native source's notation",
|
||||
first.info.key == "8A", first.info.key)
|
||||
nxt = fresh._entry_by_key[fresh.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/d.mp3"))]
|
||||
check("N: …and follows it from then on", nxt.info.key == "1A", nxt.info.key)
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
# The key reaches the frame DJ software reads, in every container written.
|
||||
import av # noqa: E402
|
||||
import mutagen # noqa: E402
|
||||
import numpy as np # noqa: E402
|
||||
import soundfile # noqa: E402
|
||||
|
||||
from konduktor.core import audio_tags # noqa: E402
|
||||
from stem_test_support import make_mp3 # noqa: E402
|
||||
|
||||
mp3 = make_mp3(Path(d) / "k.mp3", seconds=1)
|
||||
flac = Path(d) / "k.flac"
|
||||
soundfile.write(flac, np.zeros((44100, 2), np.float32), 44100)
|
||||
m4a = Path(d) / "k.m4a"
|
||||
with av.open(str(m4a), "w", format="ipod") as c:
|
||||
st = c.add_stream("aac", rate=44100, layout="stereo")
|
||||
fr = av.AudioFrame.from_ndarray(np.zeros((2, 1024), np.float32), format="fltp", layout="stereo")
|
||||
fr.sample_rate = 44100
|
||||
for pkt in list(st.encode(fr)) + list(st.encode(None)):
|
||||
c.mux(pkt)
|
||||
for path, frame in ((mp3, "TKEY"), (flac, "initialkey"), (m4a, "----:com.apple.iTunes:initialkey")):
|
||||
r = audio_tags.write_tags(path, {"key": "9m"})
|
||||
tags = mutagen.File(str(path)).tags
|
||||
v = tags.get(frame)
|
||||
v = v.text[0] if hasattr(v, "text") else (v[0] if v else None)
|
||||
v = v.decode() if isinstance(v, bytes) else v
|
||||
check(f"N: {path.suffix} key tag lands in {frame}", r.ok and v == "9m", f"{r} {v!r}")
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
# A collection keyed in Camelot gets Camelot.
|
||||
work = Path(d) / "collection.nml"
|
||||
data = REAL.read_text(encoding="utf-8")
|
||||
data = re.sub(r'KEY="(\d{1,2})([md])"',
|
||||
lambda m: f'KEY="{((int(m.group(1)) + 6) % 12) + 1}{"A" if m.group(2) == "m" else "B"}"', data)
|
||||
work.write_text(data, encoding="utf-8")
|
||||
store = TraktorStore(work)
|
||||
check("N: a Camelot collection is detected as one", store.key_notation() == "camelot", store.key_notation())
|
||||
target = next(e for e in store._nml.collection.entry if e.location and e.info)
|
||||
store.set_key(store._key_of(target), 1, "minor")
|
||||
check("N: …and written in Camelot", target.info.key == "1A", target.info.key)
|
||||
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -90,6 +90,7 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == [])
|
||||
check("flexible beatgrids supported", caps.grid.flexible is True)
|
||||
check("grid is lockable", caps.grid.lockable is True)
|
||||
check("the key can be written", caps.tracks.key_writable 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")
|
||||
|
||||
@@ -106,6 +107,14 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("metadata edit is visible in the projection",
|
||||
adapter.track(tid).genre == "Konduktor Test Genre")
|
||||
|
||||
# key — the projection's wheel, mode AND display text all follow
|
||||
t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m
|
||||
check("set_key returns the refreshed track",
|
||||
t is not None and (t.key, t.key_wheel, t.key_mode) == ("9m", 4, "minor"),
|
||||
f"{t and (t.key, t.key_wheel, t.key_mode)}")
|
||||
check("…and the index holds it (the key filter finds it)",
|
||||
any(x.id == tid for x in adapter.query_tracks(key="9m", limit=20000).items))
|
||||
|
||||
# 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
|
||||
|
||||
@@ -255,6 +255,8 @@ export interface Capabilities {
|
||||
places_audio: boolean
|
||||
/** Tracks can be converted to native-instruments STEM files. */
|
||||
stem_convertible: boolean
|
||||
/** The musical key can be set — what key analysis writes. */
|
||||
key_writable: boolean
|
||||
/** Lower-case suffixes this library can hold — what a browsed folder lists. */
|
||||
audio_formats: string[]
|
||||
artwork: boolean
|
||||
|
||||
Reference in new issue
Block a user