Implemented key setting into adapters

This commit is contained in:
patben8 committed 2026-10-04 16:06:36 +02:00
1 parent b5b3dd04c3
commit c3571fd054
23 files changed
+656 -101

No files matched your search

@@ -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
+32 -5
View File
@@ -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:
+43 -5
View File
@@ -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),
+74 -2
View File
@@ -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,
)
+4
View File
@@ -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: ...
+9 -2
View File
@@ -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:
+3
View File
@@ -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.
+4 -2
View File
@@ -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:
+95
View File
@@ -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