Compare commits

..
Author SHA1 Message Date
patben8 1464b1e211 Merge pull request #9 from MrPatben8/dev
Fixed issues on Windows, Implemented drag & drop importing, Improved STEM encoding speed
2026-10-13 17:47:09 +02:00
patben8 10f175b206 Bumped version number 2026-10-13 17:43:20 +02:00
patben8 a65ef959b2 Implemented drag to import 2026-10-13 17:42:24 +02:00
patben8 87cbd3720e Fixed STEM analysis not working on Windows 2026-10-13 10:59:22 +02:00
patben8 591f2bc791 Pararellized STEM aac encoding 2026-10-13 10:45:52 +02:00
patben8 ebe30c1128 Fixed analysis not working on windows 2026-10-12 23:49:19 +02:00
patben8 cd1914216f Fixed library options not appearing in windows 2026-10-12 23:26:33 +02:00
patben8 d10b11f8eb Merge pull request #8 from MrPatben8/dev
Fixed Rekordbox exports
2026-10-12 19:12:41 +02:00
patben8 79a8a843c5 Bumped version number 2026-10-12 19:12:09 +02:00
patben8 0204a322ff Fixed and pinned rekordbox exports 2026-10-12 19:10:20 +02:00
patben8 05051e7056 Merge pull request #7 from MrPatben8/dev
Implemented remote file exploring, fixed STEM playback and improved startup time.
2026-10-12 15:04:40 +02:00
patben8 b5dabbc8a0 Updated the readme 2026-10-12 15:02:46 +02:00
patben8 86bbb7b961 Bumped version number 2026-10-12 13:51:23 +02:00
patben8 d474c662db Fixed slow build startup time and implemented loading screen 2026-10-12 13:20:00 +02:00
patben8 a0df683fee Fixed stem playback not working in build 2026-10-12 11:31:44 +02:00
patben8 3385b794e9 Added setting for export playlist root folder toggle 2026-10-12 10:56:32 +02:00
patben8 2c352b76a1 Added konduktor settings menu 2026-10-12 10:15:14 +02:00
patben8 40630ff78e Added support for remote file exploring 2026-10-12 09:23:34 +02:00
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
patben8 ba7b662b93 Fixed port assumption 2026-10-04 17:13:24 +02:00
patben8 e5fb0f0dbb Initial implementation of remote library system 2026-10-04 17:13:24 +02:00
patben8 e8a53eee07 Added analyze dialog 2026-10-04 17:00:33 +02:00
patben8 36a6df4d3b Build analyze backend 2026-10-04 16:33:37 +02:00
patben8 72a52d3291 Reworked analysis menu 2026-10-04 16:18:43 +02:00
patben8 c3571fd054 Implemented key setting into adapters 2026-10-04 16:06:36 +02:00
patben8 b5b3dd04c3 Implemented key analysis system 2026-10-04 15:26:34 +02:00
patben8 4e9472c14a Unified prefs writing 2026-10-03 10:31:32 +02:00
patben8 957525393b Merge pull request #4 from MrPatben8/dev
Implemented STEM generation & OneLibrary editing support
2026-10-01 17:18:05 +02:00
161 changed files with 13567 additions and 1290 deletions

No files matched your search

+53 -3
View File
@@ -55,10 +55,11 @@ jobs:
with:
python-version: "3.12"
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
# --- Step 1: freeze the FastAPI backend into a onedir sidecar folder ---
# build_sidecar.* stages it as
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
# which tauri.conf.json's externalBin bundles into the app.
# frontend/src-tauri/binaries/konduktor-sidecar/
# which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) /
# tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`.
- name: Install backend deps
working-directory: backend
run: |
@@ -114,6 +115,52 @@ jobs:
if-no-files-found: error
path: installer/*
# The Konduktor SERVER image (server/Dockerfile): a remote library's half,
# pushed to GHCR with the same version as the desktop app, so a TrueNAS app
# can name the tag that matches the app it is opened from.
server-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # push to ghcr.io
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and image name
id: meta
run: |
echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
# GHCR names must be lower-case; the owner may not be.
echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/konduktor-server" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with:
context: .
file: server/Dockerfile
platforms: linux/amd64
push: true
tags: |
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}-b${{ github.run_number }}
${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
${{ steps.meta.outputs.image }}:latest
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
# Gather both platforms' installers and publish them as a single new Release.
# Runs once, after both builds succeed, so the two matrix jobs never race to
# create the same tag/release.
@@ -136,6 +183,9 @@ jobs:
- name: Download installers from both builds
uses: actions/download-artifact@v4
with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
- name: Publish release
+101 -29
View File
@@ -1,21 +1,27 @@
# Building Konduktor for Windows
The desktop app can't be cross-compiled — a Windows build must be produced **on
Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the
backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac.
The desktop app can't be cross-compiled. A Windows build must be produced **on
Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must
freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately
on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)).
This mirrors the macOS build exactly; only the toolchain install and the
sidecar-build command differ.
The recipe is the same as on macOS. Only the toolchain install and the
sidecar-build command differ. CI does exactly this on `windows-latest`
([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build
disagrees with CI, check that workflow first.
## One-time setup
1. **Rust** — install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
1. **Rust**: install via <https://rustup.rs> (gives the `x86_64-pc-windows-msvc`
toolchain). You also need the **MSVC C++ build tools**: install "Desktop
development with C++" from the Visual Studio Build Tools installer.
2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get
the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it).
3. **Python 3.11–3.14** — <https://python.org> (tick "Add to PATH").
4. **Node 18+** — <https://nodejs.org>.
2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing,
get the Evergreen runtime from Microsoft (Tauri's installer can also
bootstrap it).
3. **Python 3.11–3.14**: <https://python.org> (tick "Add to PATH"). CI builds
with **3.12**, the safest choice.
4. **Node 20.19+ or 22.12+**: <https://nodejs.org>. Vite 8 refuses older
versions, so Node 18 no longer works. CI uses Node 20.
Then, from the repo root:
@@ -33,49 +39,115 @@ npm install
cd ..
```
## Build
If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is
disabled on this system"), either allow local scripts once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with
`powershell -ExecutionPolicy Bypass -File .\dev.ps1`.
## Develop (no build)
```powershell
.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both
```
Then open <http://localhost:5173> in a browser. `dev.ps1` is the Windows
counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules`
from the setup above. It runs the Python source, not the frozen sidecar, so it
can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file
drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this
still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend
changes need `build_sidecar.ps1` first.
### Tests
`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't
run as-is on Windows. Run a suite directly with the venv's Python instead:
```powershell
# 1) Freeze + stage the backend sidecar (from the activated backend venv)
cd backend
.\.venv\Scripts\Activate.ps1 # if not already active
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-<triple>.exe
.\.venv\Scripts\python.exe test_save_fidelity.py
```
## Build
One command does both steps and lists the installers it produced:
```powershell
.\build.ps1 # sidecar + app
.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
.\build.ps1 --debug # any other argument is passed on to `tauri build`
```
By hand, that is:
```powershell
# 1) Freeze + stage the backend sidecar
cd backend
.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder)
cd ..
# 2) Build the app
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
```
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus
`_internal\`), not a single `.exe`. Don't switch it back to onefile; see
gotcha 4 in [CLAUDE.md](CLAUDE.md).
## Output
Installers land in:
```
frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi
frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe
frontend\src-tauri\target\release\bundle\nsis\Konduktor_<version>_x64-setup.exe
frontend\src-tauri\target\release\bundle\msi\Konduktor_<version>_x64_en-US.msi
```
Either one installs the app (bundling the sidecar `.exe` alongside it).
`<version>` is the `version` in [frontend/package.json](frontend/package.json),
the app's only version source. Either installer works. Releases ship only the
NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource
folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
`sidecar\konduktor-sidecar.exe`.
## Rebuilding after changes
Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1`
first; then `npx tauri build`. Frontend-only changes just need `npx tauri build`
(its `beforeBuildCommand` rebuilds the web app).
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
## Not part of this build: the stem engine
Convert to Stems uses a separate program, `engine/` (torch + demucs), built and
released on its own channel by
[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu`
and `windows-x64-cuda`). The app downloads it at runtime into a short
`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path
limit. You don't need it to build or run the app.
## Known Windows caveats
- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch
shows a "Windows protected your PC" prompt. Click **More info → Run anyway**.
(Signing is a future step.)
- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first
launch shows a "Windows protected your PC" prompt. Click **More info → Run
anyway**.
- **Mixed content is already handled.** The webview is forced to the `http`
custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so
it can fetch the sidecar at `http://127.0.0.1:<port>` without being blocked.
Leave that setting as-is.
- **Sidecar console window.** The sidecar is frozen as a console app (needed for
the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it
without a visible window; if a console flashes on launch, tell me and we'll add
the `CREATE_NO_WINDOW` spawn flag.
- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run.
- **The sidecar is a console app, but no console appears.** It's frozen with
`console=True` because the shell reads the `KONDUKTOR_PORT=<n>` line from its
stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window
flashes.
- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its
stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS
DLL, which hung the first analysis, so it waits on the parent process instead
(`backend/sidecar.py`). Keep this in mind before touching that watcher.
- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads
AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` /
`.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg.
- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run.
`build_sidecar.ps1` handles this; just don't copy binaries between OSes.
+455 -32
View File
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
mapped to status codes once in `main.py` rather than per route.
**`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop,
`POST /api/playlists/move`) moves any tree node; `index` counts the new
parent's children WITHOUT the node, and it returns the node's id AFTER
the move — a Traktor folder's / smart playlist's id is its path, so it
changes (playlists keep their UUID, so export sets never need
retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a
folder or smart playlist landing beside a namesake (as rename does);
Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the
top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step;
OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save.
`POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask`
(nothing changes, the count comes back so the UI can ask and resend);
`add` only where `capabilities.playlists.duplicates` — Traktor only, since
OneLibrary's `playlist_content` is keyed on (playlist, content) and
rekordbox's tolerance of a repeat is unmeasured.
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so
the UI can gate controls instead of branching on the platform.
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
@@ -114,11 +129,55 @@ 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).
Either half can be HELD — the Analyze dialog's BPM / Grid ticks:
`bpm=` keeps that tempo (no search, no round snap, no re-octave) and
finds only the phase; `anchor=` detects the tempo and returns the anchor
untouched, `drift_ms` then measuring how well the kept anchor fits.
`bench_grid_detect.py --hold bpm|anchor` scores each alone (2026-10-04,
15 local refs: phase given the right BPM 15/15; tempo given the right
anchor 14/15, the same miss as full analysis).
- `grid_plan.py` — **what an analysis does to one track's grid**, as one
pure function (`plan_grid` → `GridStep`) so the batch, the dialog's
counts and the tests agree. BPM+Grid = full, an existing grid replaced
only with Replace ticked; BPM alone keeps the first marker's anchor; Grid
alone keeps its BPM (else the track's TEMPO). With ONE tick, Replace does
not apply (adjusting is the point) and a track with nothing to keep is
analysed in full; a flexible grid is skipped, never flattened; locked is
always skipped. `main._analyse_grid` writes each through the hand-edit
command for the same thing — `set_grid_marker_bpm(0)` / `move_grid_marker(0)`
— so companions, marker names and time bases behave as for a hand edit.
- `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,
muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place
(moov is last, so only two sizes change). The separation is a CALLBACK —
(moov is last, so only two sizes change). **Each stream encodes on its
own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`,
104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in
the single-threaded order, so the file is byte-identical; every codec is
opened and the header written before a worker starts, since the first
`mux()` would otherwise open codecs a worker is using. `aac_coder=fast`
was measured and rejected: 3-4x faster per stream, but it drops whole
8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK —
the backend never imports torch; the engine (below) supplies it, the
tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB,
so mono is duplicated by hand; resampling does not move time; both
@@ -487,6 +546,124 @@ Two independent apps that talk over HTTP:
open / save / discard (and, next, a stem batch's swap step).
History is app-level: the adapter returns the bytes it wrote plus a summary,
and `AppState.save()` versions them. Every write path must go through it.
**Where** it is versioned is the open library's `services` (`services.py`):
`LocalServices` is the history repo in this computer's app-data, keyed by
path (what it always was); a remote library's live on its server. Routes
reach history through `STATE.services` / `STATE.restore_version`, never the
`history` module with `STATE.path`. `open_hooks` run at the end of every
open (and restore) — how the server re-applies its configured path mapping.
- **Remote libraries** (decided 2026-10-01/02 —
[the discussion](.claude/discussions/discuss-remote-library-2026-10-01.md)):
the whole library on the user's NAS, a Konduktor SERVER in a container
holding it, the desktop app opening it as "Remote". Three pieces:
- `remote_protocol.py` — the wire contract BOTH sides import: the
`LibraryAdapter` protocol itself as RPC (`RPC` table, `MUTATING` flag,
`EXCLUDED` with a reason for every member that does not travel —
`test_remote_protocol.py` fails on a protocol member that is neither),
args/results (de)serialised by pydantic `TypeAdapter`s built from the
protocol's own hints (a misspelt argument is refused, not defaulted),
`API_VERSION` (same major, server minor ≥ client's), the lease
(`LEASE_SECONDS` 120 / `HEARTBEAT_SECONDS` 15), `WireNewTrack` and the
prepared-analysis `.npz` packing. Bytes never travel as JSON.
- `server/` — `python -m konduktor.server` (the container's command;
`server/Dockerfile`, `compose.yaml`, `.env.example`). NOT `main.py`
behind a password. `config.py` reads the env (`KONDUKTOR_PLATFORM`
checked against the file, `_LIBRARY`, `_CONTENT`, `_USERNAME`,
`_PASSWORD`, `_PATH_MAP` "stored => here; …") and fails fast with one
line. `app.py`: HTTP Basic on every route; `/v1/hello`, `session/*`,
`rpc/{method}` (every answer carries `rev` plus the tracks it `changed`
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
to the content folder — resolve then `is_relative_to`, so neither `..`
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
(the content folder as a Files tree: tags via the shared `FolderScanner`,
file facts, `held` = file → the library's id; audio only for a file a
listing returned, confined; `leads` = the analysis lead per file, None
unless the platform analyses), `save`, `discard`,
`history`, `export-sets`, and the stems routes below. Capabilities are
the adapter's plus `tracks.audio_destination="library"`,
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
`session.py`: ONE holder; a 409 names who holds it (machine, since,
running batch) and `takeover` replaces it; the old token is 423 from
then on; a lapsed lease is renewed silently for the SAME client if
nobody took it. Unsaved edits are the native model's, not the
session's: the next holder inherits them and `pending_edits`
(`last_editor` + the adapter's optional `edit_summary()`) asks them to
save or discard. A container restart loses them — accepted.
**Lightweight by decision: the server never decodes audio** — its
image ships `requirements-server.txt` without librosa / scikit-learn /
PyAV, and `test_layering.py` checks importing it pulls none in
(`stem_file._audio_stream_count` counts `soun` traks when PyAV is
absent). With a path mapping configured the server calls the
adapter's optional `set_write_stored_paths(True)`: a file added (or a
stem file swapped in) through the mapping is written in the library's
STORED form (`pathmap.stored_form`), so the collection keeps one
convention and still opens where it was made.
- `adapters/remote/` — the client, imports no platform adapter.
`RemoteAdapter` IS a `LibraryAdapter`: the frontend, export, import and
batches never learn a library is remote. It mirrors the projection in a
local `TrackIndex` (same query code), folds each command's `changed`
into it, and re-fetches on any `rev` gap. **`audio_path` downloads**
into the shared `cache.py` (keyed by the server's `AudioFacts` — path,
size, mtime — partial-then-rename, LRU under `remoteCacheBytes`, the
recently used never evicted); anything that needs only a file's
IDENTITY asks the new protocol member **`audio_facts`**, which never
downloads (`exporter.plan`, `importer._existing_files`). `client.py`
tries the address that last worked, then the others (primary →
fallback) on CONNECT failures only, and maps status codes back onto the
adapter error classes (423 → `SessionLost`, unreachable → `Unavailable`,
503 in `main.py`). `session.py` heartbeats (reporting the running batch)
and moves `connected / reconnecting / offline / taken_over`; anything
but connected/reconnecting makes `capabilities()` read-only with cause
`taken_over` / `offline`, and a 423 on any command flips it at once;
taken over cancels this computer's batches (`_on_remote_change`).
`config.py`: saved remotes in prefs (`remotes`, plus a stable
`remoteClientId`), passwords in the OS keychain via `keyring`
(`use_password_store` is the test seam). `services.py`: history, export
sets (`exports.use_store`, keyed by `remote:<server id>` so nothing on
this computer is mistaken for the server's) and the stems ledger
(`RemotePending`) all on the server. Imports UPLOAD
(`importer.uploads_audio` → `upload_audio`, cleaned up on failure; free
space from the server) into a folder the user picks on the server;
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
(`core/add_analysis.prepare` with the lead the upload reports, sent as
`NewTrack.analysis`).
**The content folder browsed like a drive** (decided 2026-10-10,
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
"server"`, path `server:`) while a remote is open, and the ordinary
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
the path ON THE SERVER — so the folder view, deck and add dialog need no
second set of routes, and a server path is never taken for the same path
here. `RemoteAdapter.folder_listing` remembers what was listed
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
shared cache by the same facts as a library track's. Adding one is IN
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
nothing uploaded, nothing asked; files the library holds map to their
ids; where the server reports a lead the file is fetched and analysed
here, as an upload is. Server paths go back to the server in its own
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
Windows.
**Convert to Stems** (`stems/remote_convert.py`): the server plans
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
separates and encodes, uploads each verified file (`/v1/stems/stage`,
sha-256 checked, kept on the server as a LEFTOVER), and the server runs
the ordinary `convert._end_step` under its mutation lock with its own
ledger (`/v1/stems/publish`). Cancel abandons this run's uploads; a
takeover cannot, so they stay and the next run reuses them. The preview
adds `transfer` (download / upload / measured speed) and space lines for
both machines.
UI: the picker's platform list ends with **Remote** (`selects:
"remote"`) → `RemotePicker` (saved remotes; the form saves only after
`handshake` — a wrong password or version refuses, an unreachable
fallback alone does not; the in-use → Take over and the leftover-edits
Save / Discard / Decide-later prompts happen before the library shows).
`App` polls `['state']` every 5 s for a remote (`remote` in `EditState`),
re-reads capabilities on a change and toasts it; `StatusBar` shows the
connection. `FileBrowser`/`FolderPicker` take `listing="library"` for the
server's folders; Import / Add Files / Convert to Stems use it when
`tracks.audio_destination === 'library'` (folders remembered per remote:
`remoteImportFolders`, `remoteStemFolders`). Settings → Remote audio is
the cache. Path remapping hides on `paths.remappable === false`.
- `library_id.py` — a **stable identity for a library that survives it being
moved**. Everything else keys off the OS path (`history` hashes it, `prefs`
stores it), which is fine for things a user shrugs at losing and NOT fine for
@@ -533,7 +710,13 @@ Two independent apps that talk over HTTP:
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column
layout, prep-deck zoom, import destination. Best-effort.
layout, prep-deck zoom, import destination. Best-effort, but **every
read-modify-write holds `_LOCK` and every write is atomic**
(`paths.write_json`): the UI sends several PATCHes at once on launch, and
unlocked, with a truncating write, a reader caught the file empty and wrote
back only its own key — wiping every pref, the column layout included. A
file that will not parse is moved to `userprefs.json.corrupt`, never
silently overwritten. New helpers that read then write must take the lock.
- `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the
adapter. Starts **unloaded**; the library is chosen at runtime via
@@ -634,9 +817,17 @@ Two independent apps that talk over HTTP:
expandable Local Storage. A drive carrying a OneLibrary library opens as a
device as before, and EVERY drive has a lazily-fetched **Files** tree;
clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s
`marked`). A browsed device is read-only (cause `browsing`); **"Open for
table, with files the collection already holds checked off in the #
column (`TrackTable`'s `marked`). **A held file's row IS the collection
track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
its collection id back to the folder id that adding takes): it shows the
collection's key/rating/cues/plays, loads into the deck as origin
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
a playlist directly. The table runs on the COLLECTION's capabilities; a
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
it first (`askToAdd`), and in the deck it stays read-only
(`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for
editing…"** — the drive row's right-click menu, and a button while browsing
a device whose caps say `browsing` — opens it as THE library via App's
`openForEditing` (unsaved-edits confirm, source closed, library opened).
@@ -669,6 +860,21 @@ Two independent apps that talk over HTTP:
space below the rows creates at the top level, and the new node is named
in place (Esc or an empty name creates nothing). Rename/Delete are on the
same menu and the row's hover buttons, which share one set of actions.
**Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop
target with ZONES — a playlist's upper/lower half is before/after; a
folder's top/bottom quarter before/after and its middle INTO (appended),
except the bottom quarter of an OPEN folder, which is "first inside"; the
empty space below the rows is "end of the top level". Never into the
dragged node's own subtree, and a drop that would change nothing shows no
indicator. Holding over a collapsed folder opens it after 0.6 s (tracks
too, so nested playlists are reachable). Tracks dropped on a playlist go
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
which ASKS about duplicates where the platform can hold them (decided:
ask each time), and Option/Alt moves them out of the editable playlist
they came from. A device's or Files folder's tracks open `ImportDialog`
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
collection's tracks and any playlist/folder (as "Add to export" does).
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
playlist routes take a `:path` param, a folder name may not contain `/`,
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
@@ -676,8 +882,18 @@ Two independent apps that talk over HTTP:
shell quits anyway after ~2 s without one, so a hung page cannot trap the
user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard
· Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer;
browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx`
around everything but `AmbientBackdrop`: the shell opens the window AT ONCE
and starts the sidecar beside it, so nothing that calls the API mounts
until `backend_status` / `konduktor://backend` says ready, which is when
`setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows
the icon with a generated waveform scrolling under a fixed playhead, a
"first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s,
and if the sidecar exits its last 30 output lines with Copy details / Quit
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
ready it answers quit requests itself — nothing can be unsaved — and stops
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
devices. TanStack Table + **virtualized** grid; per-row play button,
configurable columns, header sorting, inline double-click editing, and
@@ -696,7 +912,43 @@ Two independent apps that talk over HTTP:
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
flushSync-driven measurement — which is why playlists were once a separate,
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.)
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
says whose ids they are and which editable playlist an Option-drag leaves);
the in-table reorder is just the table's own drop target.)
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5
DnD — Tauri's webview captures native drag events for file drops on
Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag`
for plain elements); targets register with `useDropTarget({ hint, label,
onDrop })` and are found by `elementFromPoint` then up the ancestors, the
innermost whose `hint` is non-null winning, so a target declines a spot by
returning null. A module-level store read through narrow
`useSyncExternalStore` selectors: a move re-renders only the target under
the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the
table. Esc cancels (before every other Esc handler); the click after a drop
is swallowed; `data-drag-scroll="<top inset>"` makes an element scroll at a
20 px edge after a 250 ms dwell — any less and the first/last visible row
could not be dropped on. Targets: playlist + export rows (Sidebar,
ExportsSection), the tree's zones, the table's reorder, and the DECK
(App), which loads the grabbed row paused, in its own origin.
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through
`nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal`
dialog is open or no library is loaded. A playlist/export row opens
`AddFilesDialog` with its target, ONE audio file on the deck loads it to
listen to, anywhere else (App's root target, with a window overlay) adds
to the collection — or says why the library cannot. `POST
/api/folder/dropped` resolves the paths first (`FolderScanner.dropped`:
folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart
from the folder cache so a partial listing never hides a folder's other
files from the sidebar) and makes each file addable and playable through
the folder routes. Copy vs in place is asked as for a browsed folder; the
add preview counts external-drive files PER FILE (`removable_count` /
`removable_drives`, a drop can mix drives) and `in_destination`.
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
Replace the originals (its option STATES that Save deletes them, since
the choice is remembered and may be preselected) or Save to a folder; In
@@ -719,6 +971,18 @@ Two independent apps that talk over HTTP:
original files" while conversions are pending (decided: the consequence is
shown where Save is pressed). `Toast` takes an optional `action`;
`StatusJob.unit: 'bytes'` shows a download in MB. Every background job's status-bar entry reads label + count · a bar SPLIT horizontally when the job reports per-item progress (top = the current item's `fraction`, 0-100 %; bottom = the whole job, (done + fraction) / total, so 99 % into the first of two tracks reads ~50 %) — a single bar otherwise; two colours in one bar was tried and read as confusing · its `status` ("separating 41 %") at its natural width · the item's name LAST (the only part that truncates; full name on hover). The section is a FIXED width (560 px; the view name on the left gives way instead) and everything BEFORE the bar is fixed (count sized for its largest value, "cancelling…" as a status, not a label), so neither a long name nor a phase change moves the bar. The status deliberately has no fixed slot: it is after the bar, and a slot left a gap before the name. `Job.fraction`/`status` come from `JobHandle.progress(fraction=, status=)` and reset whenever `done` advances; a stem conversion maps decode / separate / encode onto a track's 0-1 by measured shares.
`AnalyzeDialog` (the context menu's **Analyze…**, decided 2026-10-04:
BPM / Grid / Key ticks, remembered as `analyzeWhat`, each disabled with a
reason where the library cannot store it — offered when EITHER grids or
keys are writable; the Replace questions are inside the dialog, never a
second popup, and never remembered: the grid's only when BPM AND Grid are
ticked, since with one tick adjusting the grid is the point. Every count
and the "Analyze N" button come from `/api/tracks/analyze/preview`, i.e.
the backend's own `plan_grid`. The finished job's toast says what was
written and skipped, by reason. The deck's one-click Analyze writes the
key too, and App hands the deck the fresh copy of its track whenever the
view it came from refetches — the deck otherwise held a load-time
snapshot, so neither an analysed key nor an Edit Tags change reached it),
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself
@@ -730,7 +994,11 @@ Two independent apps that talk over HTTP:
`ContextMenu` (supports `▸` submenus, section headings, separators and
checkbox items that toggle without closing — the header row's right-click
column chooser uses those; "Add to" lists
playlists + exports and acts on the whole selection; "Remove ▸" holds
playlists + exports and acts on the whole selection; in an editable
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
moves the selection as ONE block in playlist order so its first track
lands at #N — allowed while sorted/filtered, unlike drag, because it
reorders the FULL entry list; "Remove ▸" holds
From this playlist / From this export / Grids / Hotcues / From collection,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
@@ -842,18 +1110,30 @@ Two independent apps that talk over HTTP:
via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against
defaults so newly-added columns still appear). The prep deck's main-waveform
zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the
shared `['prefs']` query).
shared `['prefs']` query). Continuously-changing prefs (columns, zoom,
`beatSize`) are written through ONE debounced writer, `lib/prefs.ts`
(`usePrefsWriter` / `queuePrefs`): changes merge into one PATCH, sent in
order, and the queue outlives unmounts; `QuitGuard` calls `flushPrefs()`
before quitting. Do not give a new pref its own timer.
## Commands
```bash
./dev.sh # start both servers (see README for one-time setup)
.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md)
# Backend
cd backend && source .venv/bin/activate
uvicorn konduktor.main:app --reload --port 8000
# point at another file: KONDUKTOR_NML=/path/to/collection.nml uvicorn ...
# A Konduktor SERVER (a remote library) from source — configured by env, see
# server/.env.example; the container runs the same command:
KONDUKTOR_PLATFORM=traktor KONDUKTOR_LIBRARY=/path/collection.nml \
KONDUKTOR_CONTENT=/path/music KONDUKTOR_USERNAME=dj KONDUKTOR_PASSWORD=pw \
python -m konduktor.server # listens on :8765
docker build -f server/Dockerfile -t konduktor-server . # from the repo root
# Frontend
cd frontend
npm run dev # dev server (proxies /api -> :8000)
@@ -881,10 +1161,22 @@ 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. And
**`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and
moving back is byte-identical; a folder moves with its subtree and answers
its new path id; into its own descendant / beside a namesake is refused with
nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
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.
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
changes nothing and counts) and `/api/playlists/move` (path id answered,
400 into itself, 404 unknown).
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
@@ -901,7 +1193,10 @@ serialization path.** It enforces:
48 kHz resampling does not move time; MP3 and FLAC through both encoders give
five streams with only the mix enabled, no shift (cross-correlation), the
bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a
shifted, truncated or box-less file; a raising checkpoint cancels.
shifted, truncated or box-less file; a raising checkpoint cancels. The
threaded encode is byte-identical to a single-threaded reference (with each
encoder present), reports progress 0 → 1, and a cancel or a failing encoder
thread leaves no thread running.
- `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real
collection with a generated MP3 (with header) and a real stem file: prep
reads back at the same decoded second while its START moves by the 2257-
@@ -952,7 +1247,9 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip. And
disk until save; and playlist create/fill/rename/delete round-trip, and
`move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with
`Seq` 1..n in both parents. And
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
@@ -970,6 +1267,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
@@ -986,9 +1288,13 @@ serialization path.** It enforces:
changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries
from 1; and the stick hazards — another app's write refused, an unplugged
from 1, a move changing only parent + `sequenceNo` (0..n-1 in both
parents); 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
@@ -1020,12 +1326,24 @@ serialization path.** It enforces:
companion cue is invented), that the existing 8,485 entries render
byte-identically, that the job registry runs/fails/cancels, and that a
cancelled import leaves **no orphaned audio and an untouched collection**.
And the route with chosen `track_ids` + `into_playlist` + `export_id` (a
device drop): only that track, into the playlist and the export, no drive
folder made.
- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the
tempo and first beat are known rather than borrowed from another analyser:
exact integer and non-integer BPMs, the 125 BPM the old detector could not
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
each fooled one band on real music. Holding either half: a held BPM comes
back untouched (never snapped or re-octaved, a wrong one reports drift) with
the phase still found through the hat/bass traps; a held anchor comes back
untouched with the tempo detected, an off-beat one reported as drift. And
`plan_grid`'s every rule. 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
@@ -1033,7 +1351,7 @@ serialization path.** It enforces:
collection — the previous implementation's route returned 500 on every call
for a week while its helper's tests passed.
- `test_grid_batch.py` — **batch analysis** from the context menu, both
`jobs.py` jobs shown in the status bar: Analyze Grid & BPM
`jobs.py` jobs shown in the status bar: Analyze… (BPM / Grid / Key)
(`POST /api/tracks/grid/auto-batch`) and Auto Hotcues…
(`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the
batch-only decisions: locked grids are skipped always, existing grids unless
@@ -1045,6 +1363,20 @@ serialization path.** It enforces:
returns its result; opening another library cancels the run. Each shares its
helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track
button.
Also BPM alone / Grid alone through `_analyse_grid` on a real Traktor copy:
the detector is asked to hold the right half, BPM alone retempos the marker
in place with its beat-1 cue untouched, Grid alone moves it (cue dragged
along) at the same tempo, and a TEMPO-only track gets one marker at it.
And **Analyze** (`POST /api/tracks/analyze` + `/analyze/preview`, the
dialog's BPM / Grid / Key; `grid/auto-batch` is now an alias of it with
BPM+Grid): nothing ticked 400s; Key alone sets keyless tracks, skips keyed
ones unless `replace_key`, never touches a grid; the preview's counts match
the run's (BPM alone: single grids adjusted, flexible skipped, bare in
full); a skipped track is never decoded and grid+key share ONE decode; a
grid that cannot be fitted still gets its key; the deck's Analyze writes
the key too and never fails on it. The decode is `main._decode_for_analysis`
(the seam the fakes replace); `test_key_detect.py` runs the route once with
the REAL decode and detectors on a generated F-minor 124 BPM WAV.
- `test_bulk_remove.py` — the context menu's **Remove ▸** routes
(`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`):
locked grids are kept, clearing hotcues empties the whole bank (loops and the
@@ -1061,7 +1393,11 @@ serialization path.** It enforces:
scan did not find; **a file the collection already points at is never added
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
collection) but still reaches the playlist/export it was headed for; "copy"
points the entry at the copy and "reference" at the original.
points the entry at the copy and "reference" at the original. And a DROP
(`/api/folder/dropped`): folders recursively minus hidden ones, dropped
non-audio counted as skipped, only what was dropped becomes streamable, the
folder's own listing stays whole, the cap, held files as their collection
track, and the preview's per-file external-drive count and `in_destination`.
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -1071,6 +1407,11 @@ serialization path.** It enforces:
as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the
answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library.
- `test_prefs.py` — `userprefs.json` under concurrent writes: 200 bursts of
simultaneous patches (plus a reader) keep every key and every patch; the
last-collection and path-mapping helpers lose nothing either; an unreadable
file is moved aside, not overwritten. Against the old unlocked code it fails
on the first trial.
- `test_exports.py` — export sets against a temp copy of the real collection.
Pins the things that would fail SILENTLY: a live reference picks up a playlist
edited AFTER curation; contents dedupe across playlists and loose tracks; a
@@ -1123,11 +1464,39 @@ serialization path.** It enforces:
reopen), and a running batch has stopped by the time discard returns; on
Rekordbox (temp copy, skipped when absent) the library is clean afterwards and
a later save writes nothing that was thrown away; read-only libraries 409.
- `test_remote_protocol.py` — pure: every `LibraryAdapter` member is an RPC or
excluded with a reason, every command is `MUTATING`, args/results survive
JSON by the protocol's types (tuples, dataclasses, `None`), a misspelt or
missing argument is refused, a prepared analysis crosses intact, the
version rule.
- `test_remote_server.py` — the server's own routes on a temp copy of the
collection with a FAKE clock: config refusals, 401s, one computer at a time
(423 without the token, 409 naming the holder and its batch, takeover kills
the old token, an expired lease frees it, the same client renews), leftover
edits named, save + history on the server, discard, confinement (`..`,
symlinks), uploads never overwrite and delete only their own, Range audio.
- `test_remote_adapter.py` — END TO END: a real server in a thread, the app's
routes opening it. Handshake refusals, fallback, the mirror, Save touching
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
on the cached copy, export (and a re-export copying nothing), an upload
stored in the mapping's stored form, takeover → read-only at once,
reopening names the holder and the edits left, leaving releases. And the
content folder as a drive: listed first, confined, held files ticked off,
auditioned with one download, an add IN PLACE (no upload, the held one not
added twice, both into the playlist, analysed here when the server reports
a lead).
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
the plan's transfer and two-machine space, Replace parks and swaps ON THE
SERVER (saved file untouched until Save, which deletes the parked
original), Discard restores, Cancel deletes only this run's uploads, a
takeover's uploads are reused without the engine.
- `test_layering.py` — `core/` imports nothing platform-specific, and no adapter
imports another platform's library (checked on real imports via AST, so merely
naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately
**share** `pyrekordbox`: the rule is "no adapter reaches for a rival vendor's
library", and a shared dependency is not a breach.
library", and a shared dependency is not a breach. Also: `adapters/remote`
imports no platform adapter, and importing `konduktor.server` pulls in no
librosa / scikit-learn / torch / numba / PyAV.
Also validate the backend interactively at `http://localhost:8000/docs` and the
frontend at `http://localhost:5173`.
@@ -1136,14 +1505,25 @@ frontend at `http://localhost:5173`.
1. **`traktor-nml-utils` MUST come from GitHub, not PyPI.** PyPI's `3.1.0` is
stale and **cannot parse Traktor Pro 4 (NML v20)** files — its strict parser
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins the
GitHub `master` (v4.0.0). Do not "simplify" this to a plain PyPI pin.
dies on the v4 `<GRID>` element inside `CUE_V2`. `requirements.txt` pins a
GitHub commit (v4.0.0). Do not "simplify" this to a plain PyPI pin.
**`pyrekordbox` is now the same situation**: PyPI's latest (0.4.4) has no
`devicelib_plus`, which is the OneLibrary (`exportLibrary.db`) reader, so
`requirements.txt` pins the GitHub master. That upgrade renamed `db6` →
`masterdb` and `tables` → `models` and moved `BLOB` out of `db6.database`;
the Rekordbox adapter uses the new names. `db6` still works as a deprecated
alias and is **removed in 0.6.0**.
`onelibrary` module, which is the OneLibrary (`exportLibrary.db`) reader
(`OneLibrary` class; `devicelib_plus` / `DeviceLibraryPlus` before upstream's
rename), nor `masterdb` (formerly `db6`, now removed upstream; `tables` →
`models`, `BLOB` in `masterdb.database`).
**Both GitHub deps are pinned to a COMMIT, never bare master**: the
`devicelib_plus` → `onelibrary` rename reached CI's fresh install while dev
venvs kept the old commit, and a release shipped that could not export or
read OneLibrary while every local test passed. Move a pin on purpose, with
`./run_tests.sh`.
**PyAV: open files for reading through `core/pyav.open_input`, never
`av.open` directly.** PyAV 18 refuses a file with non-UTF-8 tags unless
given `metadata_errors="ignore"`; PyAV 19 removed that keyword. CI installs
fresh (it got 19) while a dev venv keeps what it had (18), so code passing
the keyword passed every local test and shipped a release whose deck played
every stem track as the mix. `requirements.txt` caps `av<20`: check
`pyav.py` before raising it.
2. **The collection is real, irreplaceable data — protect it.** Every save
writes a timestamped `.bak` first (into a `backups/` folder next to the
collection). When testing writes, point `KONDUKTOR_NML` at a COPY. Warn the
@@ -1153,6 +1533,21 @@ frontend at `http://localhost:5173`.
render is the library's own pipeline (see "Write path"), which reproduces
Traktor's byte-exact layout so a no-op save is byte-identical and only edited
objects diff. `test_save_fidelity.py` enforces this.
4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to
onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp
folder on every launch, and macOS (XProtect / syspolicyd) checks each library
it has not seen before as it is dlopen()ed, keyed per FILE: the window
appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load
them all fresh, 1 s once seen). As a folder in the app they are checked
once; a launch is ~0.5 s. `build_sidecar.*` stages
`src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns
`<resources>/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by
`tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`:
the resource copier follows symlinks, turning PyInstaller's 37 library
aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s
`Versions/Current`) into second copies a library could be loaded twice
from. Windows has no such links and uses `resources`
(`tauri.windows.conf.json`).
## Data model notes
@@ -1160,7 +1555,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
@@ -1353,7 +1756,8 @@ that number and nothing else — everything derives from it:
(`waveform.decode` → `analyse_samples` + `grid_detect`), in a first phase
that may be cancelled through `checkpoint` before the library is touched;
a file with no grid of its own gets Konduktor's (decided: arrive ready to
prep). Then `RekordboxStore.add_track` writes the row the way Rekordbox's
prep), and one with no key of its own a detected key
(`key_detect.with_detected_key`, from the same decode; OneLibrary too). Then `RekordboxStore.add_track` writes the row the way Rekordbox's
own add was MEASURED to (file facts, `DateCreated` from the file's birth
time, this library's device) and the grid/cues replay through
`replace_grid`/`set_cue`/`add_memory_cue` — memory cues and colours cross
@@ -1409,7 +1813,11 @@ that number and nothing else — everything derives from it:
**volume-relative** `DIR`, never a host path — so a USB export is portable by
construction, and the `.nml` cannot be written until the destination is known.
Also settled: loose tracks land in an **"Other" playlist**, playlist folders
are preserved, and the export is a **standalone `collection.nml`** the user
are preserved — at the exported library's TOP LEVEL by default; the
`exportRootFolder` setting (`ExportPayload.root_folder`) nests the whole
tree, Other included, in one folder named after the export, in all four
writers (decided 2026-10-12: the export is a library of its own, so the
wrapper was one more click at the gig), and the export is a **standalone `collection.nml`** the user
swaps into a Traktor install — so it needs the full skeleton, verified from the
real file: `<NML VERSION="20">`, `<HEAD>`, `<COLLECTION ENTRIES>`,
`<SETS ENTRIES="0">`, `<PLAYLISTS>` wrapping a `$ROOT` FOLDER node with a
@@ -1440,7 +1848,7 @@ that number and nothing else — everything derives from it:
deliberately NOT in the fixture, since they carry the machine's name and
UUIDs; those are generated fresh per export.
- **The two Pioneer key blobs are different.** `masterdb`'s key and
`devicelib_plus`'s are not the same string; mixing them up yields a database
`onelibrary`'s are not the same string; mixing them up yields a database
Rekordbox cannot open.
`adapters/onelibrary/export.py` writes a whole drive (`PIONEER/rekordbox/
exportLibrary.db` from the checked-in DDL, plus ANLZ under `PIONEER/USBANLZ/`,
@@ -1585,7 +1993,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.
@@ -1651,6 +2064,16 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with.
- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the
deck, playlists around the tree and onto exports; see `lib/drag.tsx` and
the Sidebar under Architecture.
- ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks,
import by upload, Convert to Stems — all with analysis and separation on the
laptop. One computer at a time, with takeover. See "Remote libraries" under
Architecture. Not yet: verified on a real TrueNAS (the image is published by
CI's `server-image` job), a web UI served by the server (decided: not now).
- ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
+125 -197
View File
@@ -1,213 +1,141 @@
# Konduktor
<p align="center">
<img src="design/konduktor-icon.svg" width="96" alt="Konduktor icon">
</p>
**A fast, modern home for your Traktor collection.**
<h1 align="center">Konduktor</h1>
Konduktor is a lightweight desktop-style app for DJs who run **Native
Instruments Traktor** (Pro 4 / NML v20). It opens your existing
`collection.nml`, gives you a beautiful dark library to explore, and lets you
build playlists and prep tracks — without launching the whole heavyweight
Traktor app just to tidy up your tags or drop a few cue points.
<p align="center">
<b>Prep your tracks and run your DJ libraries in one fast app.</b><br>
Traktor, Rekordbox, or the USB stick in your pocket.
</p>
Your collection stays exactly where it is. Konduktor reads and writes the same
file Traktor uses, so everything you do shows up next time you open Traktor.
<p align="center">
<a href="https://github.com/MrPatben8/konduktor/releases"><b>Download for macOS & Windows</b></a>
</p>
![Konduktor: the prep deck with a track loaded, above a playlist](docs/screenshots/library.png)
Konduktor opens the library you already have, in the format it already uses.
You can tidy tags, build playlists, set grids and cues, and pack a USB stick
for the gig without launching your full DJ software. When you open your DJ
software again, everything you changed is there.
---
## Why you'll like it
## One app for every library
- **Instant, searchable library.** Your whole collection loads into a snappy,
virtualized grid. Search, filter by genre / key / BPM / rating, and sort by
any column — all instant, no waiting.
- **Make it yours.** Show only the columns you care about, drag them into the
order you like, and resize them to fit. Your layout is remembered.
- **Edit tags without the ceremony.** Double-click any field to fix a title or
genre on the spot, click the stars to rate a track, or right-click for a full
tag + cover-art editor. Great for quick one-off fixes.
- **Playlists, the easy way.** Create, rename, and delete playlists, then
drag-and-drop to reorder or add tracks.
- **A real prep deck.** Load any track into the deck at the top and:
- play it with a **frequency-colored waveform** (Traktor-style Spectrum look),
scrolling under a fixed playhead with zoom in/out
- scratch it by dragging the waveform
- see and adjust the **beatgrid** and BPM
- set, jump to, and delete **hotcues** (with a color-coded 8-slot bar)
- build **loops** in fixed beat sizes, tied into the hotcue system
- use keyboard shortcuts: **Space** to play/pause, **1–8** to fire hotcues,
**Shift+1–8** to clear them
- **Your data is safe.** Every save makes a timestamped backup first, and only
ever touches the parts you changed — the rest of the file stays byte-for-byte
identical.
<img src="docs/screenshots/platforms.png" align="right" width="420" alt="Choosing a platform: Rekordbox, Traktor, OneLibrary or Remote">
- **Traktor** collections.
- **Rekordbox** libraries.
- **OneLibrary** USB sticks, the format CDJs read. Plug one in to browse it,
preview tracks off it, import them, or edit the stick directly.
- **Remote** libraries: keep your whole library and music on a home server and
open it from any laptop ([set up a server](docs/REMOTE-SERVER.md)).
- **Any folder or drive**: browse loose audio files, preview them, and add
them to your library.
Your library is never converted into a Konduktor database. Saves write back to
the original file and change only what you edited.
<br clear="right">
## A real prep deck
![The prep deck in beatgrid editing mode](docs/screenshots/deck.png)
- A scrolling waveform, coloured by frequency, with zoom, scratching and an
overview of the whole track.
- Eight hotcue pads with names, types and colours, plus beat loops, beat jump
and tap tempo.
- **Beatgrid editing**, including grids with tempo changes. Nudge, retempo,
halve or double without opening your DJ software.
- Keyboard shortcuts for the whole deck: Space to play, 1–8 for hotcues,
arrow keys to jump or move a loop.
## Stems, built in
![A stem file in the deck: drums, bass, synths and vocals each in their own lane](docs/screenshots/stems.png)
**Play stem files as stems.** Load a stem file and the deck splits into
drums, bass, synths and vocals, each drawn in its own lane. Click a lane's
button to mute it, Alt/Option-click to solo it, or use Q W E R.
**Convert to Stems.** In a Traktor collection, right-click any tracks and
choose Convert to Stems. They come back as standard Traktor stem files with their tags, cover art, cues and
beatgrid intact.
- The separation runs on your own computer, so your music isn't sent to an
online service.
- Replace the originals, or save the stems to a folder and add them as new
tracks.
- Convert a whole playlist in one go.
## Let it do the boring parts
| Auto Hotcues | Analyze |
|:---:|:---:|
| ![Auto Hotcues: choose an event for each pad](docs/screenshots/auto-hotcues.png) | ![Analyze: BPM, grid and key](docs/screenshots/analyze.png) |
| Pick an event for each pad (first beat, build, drop, breakdown, outro). Konduktor finds them in the track and places the cues. Run it on one track or a whole playlist. | Detects tempo, beatgrid and musical key, for one track or hundreds. |
## Export to USB for CDJs, or other platforms
<img src="docs/screenshots/export.png" align="right" width="380" alt="An export set for OneLibrary, Traktor and Rekordbox">
Make an **export** in the sidebar, drag playlists onto it, and press Export.
One stick can carry a Traktor collection, a OneLibrary library for current
CDJs and a Rekordbox Device Library for older players, all sharing **one copy
of the audio**.
- Hotcues, memory cues, loops, grids, keys and cover art are converted for
each platform.
- Playlists stay linked: edit a playlist, re-export, and the stick catches up.
- Re-exports copy only what changed, so updating a stick is quick.
- Konduktor only ever clears a folder that it wrote itself.
<br clear="right">
## Your library is safe
- **Saves are surgical.** A Traktor save changes only the entries you edited.
The rest of the file stays byte-for-byte identical.
- **Backups and history.** Every Traktor save makes a backup first and is kept
in a version history that you can restore from in the app.
- **Nothing is written until you press Save.** Discard changes throws away
everything you did since your last save.
- Tag edits are also written into the audio files themselves, so other apps
see them too.
## And also
- A fast library with search, filters, sorting and columns you can rearrange,
even with thousands of tracks.
- Edit tags inline or in a full tag and cover-art editor.
- Drag and drop tracks onto playlists, exports or the deck, and drag playlists
to reorganise them.
- If you open a Traktor collection on a different computer or drive,
Konduktor finds the missing files for you.
---
## Getting started
## Get Konduktor
Konduktor runs as two small local servers (a Python backend and a web
frontend). Do the one-time setup, then start them — the same steps work on
macOS, Linux, and Windows.
Download the latest build from
[**Releases**](https://github.com/MrPatben8/konduktor/releases):
a `.dmg` for macOS (Apple Silicon) and a `-setup.exe` for Windows.
### 1. Install (once)
> **First launch:** builds aren't notarised yet, so your OS will warn you the
> first time.
> **macOS:** right-click the app, choose **Open**, then **Open** again. If it
> still refuses, run `xattr -cr /Applications/Konduktor.app` once.
> **Windows:** click **More info → Run anyway**.
**Backend** — needs Python 3.11+. Create a virtual environment and install the
dependencies:
> **Using Traktor?** Close it before saving in Konduktor. Traktor rewrites
> `collection.nml` when it quits, which would overwrite your changes.
```bash
cd backend
python3 -m venv .venv # Windows: python -m venv .venv
```
Want to run it from source or build it yourself? See
[docs/BUILDING.md](docs/BUILDING.md).
Activate it, then install:
## License
```bash
source .venv/bin/activate # Windows (PowerShell): .\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
cd ..
```
**Frontend** — needs Node 18+ (same on every platform):
```bash
cd frontend
npm install
cd ..
```
### 2. Run it (development)
Konduktor runs as two local servers (backend on `:8000`, frontend on `:5173`).
**macOS / Linux** — one command starts both:
```bash
./dev.sh
```
**Windows** — start each server in its own terminal:
```powershell
# Terminal 1 — backend
cd backend; .\.venv\Scripts\Activate.ps1; uvicorn konduktor.main:app --reload --port 8000
# Terminal 2 — frontend
cd frontend; npm run dev
```
Either way, open **http://localhost:5173** in your browser (`Ctrl-C` stops a
server). This is the fastest way to try Konduktor or hack on it — the frontend
hot-reloads as you edit. To package a real double-clickable app instead, see
[Build a standalone app](#build-a-standalone-app-production) below.
### 3. Open your collection
On launch, Konduktor offers to:
- **Automatically** open the collection from your latest installed Traktor,
- reopen the **last collection** you used, or
- **browse** for a `collection.nml` yourself.
That's it — you're in.
---
## Build a standalone app (production)
Prefer a real double-clickable app over running the dev servers? Konduktor
packages into a native desktop app (via **Tauri**) that bundles the Python
backend as a sidecar — no terminal, no servers to start by hand.
### Extra prerequisites
On top of the Python 3.11+ and Node 18+ from above:
- **Rust** — install from <https://rustup.rs> (the app shell is Tauri/Rust).
- **PyInstaller** — into the backend venv:
`pip install -r backend/requirements-build.txt`
- **Windows only:** also the MSVC C++ build tools and the WebView2 runtime — see
[BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup.
The build is a two-step recipe on both platforms: **freeze the backend into a
sidecar binary**, then **build the app**. The only difference is which sidecar
script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its
own OS (the app can't be cross-compiled).
### macOS / Linux
```bash
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd ..
# 2) Build the app
cd frontend && npx tauri build
```
The installer lands at
`frontend/src-tauri/target/release/bundle/dmg/Konduktor_<version>_aarch64.dmg`
(with the `.app` beside it).
### Windows
```powershell
# 1) Freeze the backend into a sidecar binary (from the activated backend venv)
cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd ..
# 2) Build the app
cd frontend; npx tauri build
```
The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` and
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
walkthrough and Windows-specific notes.
> **First launch — getting past the OS security prompt.** Builds are
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
> the OS flags them the first time. This is expected — the app isn't damaged.
>
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
> quarantines — clear the quarantine flag once from Terminal:
> ```bash
> xattr -cr /Applications/Konduktor.app
> ```
> - **Windows:** click **More info → Run anyway** past SmartScreen.
>
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
> optimizer and the installer, giving you a runnable app in seconds — handy while
> iterating.
### Rebuilding after changes
Changed **backend** Python? Re-run the sidecar script for your OS
(`./build_sidecar.sh` or `.\build_sidecar.ps1`), then `npx tauri build`.
Frontend-only change? Just `npx tauri build` — it rebuilds the web app for you.
---
## Saving back to Traktor
Playlist edits, tag changes, and prep tweaks all apply live in the app. When
you're happy, hit **Save to Traktor** to write them to `collection.nml`.
> ⚠️ **Close Traktor before saving.** Traktor rewrites `collection.nml` when it
> quits, so if it's open it will overwrite your changes. Konduktor always writes
> a backup first (into a `backups/` folder next to your collection), but closing
> Traktor first is the safe habit.
Want to experiment risk-free? Point Konduktor at a *copy* of your collection and
play around.
---
## Good to know
- Konduktor is built on [`traktor-nml-utils`](https://github.com/MrPatben8/traktor-nml-utils)
and speaks Traktor's real file format — no import/export, no separate database.
- Run it in your browser from source, or package it into a native desktop app
(macOS `.dmg` / Windows `.msi`) that bundles the backend — see
[Build a standalone app](#build-a-standalone-app-production). A mobile version
is on the horizon.
- Under the hood: **FastAPI** (Python) backend + **React / TypeScript / Vite**
frontend. Curious about internals or contributing? See
[CLAUDE.md](CLAUDE.md) for the architecture and conventions.
[AGPL-3.0](LICENSE)
+7 -1
View File
@@ -6,6 +6,8 @@ compare rather than a pass/fail. Every open is read-only — nothing is saved.
python bench_grid_detect.py # the local Rekordbox library
python bench_grid_detect.py path/to/collection.nml path/to/master.db
python bench_grid_detect.py --legacy # score the old librosa beat_track
python bench_grid_detect.py --hold bpm # Grid alone: phase, given the right BPM
python bench_grid_detect.py --hold anchor # BPM alone: tempo, given the right anchor
The reference is each track's own grid, and only single-marker grids are used:
a multi-marker grid is either a real tempo change (which a constant-tempo
@@ -102,6 +104,9 @@ def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("libraries", nargs="*", type=Path)
ap.add_argument("--legacy", action="store_true", help="score the old librosa beat_track detector")
ap.add_argument("--hold", choices=("bpm", "anchor"),
help="score one half alone: hold the REFERENCE's BPM (the Analyze dialog's "
"'Grid' tick — phase is all that is scored) or its anchor ('BPM')")
args = ap.parse_args()
libs = args.libraries or [Path.home() / "Library/Pioneer/rekordbox/master.db"]
@@ -119,7 +124,8 @@ def main() -> int:
for name, audio, r0, rb in refs:
t0 = time.perf_counter()
try:
res = detect(str(audio))
hold = {"bpm": {"bpm": rb}, "anchor": {"anchor": r0}}.get(args.hold, {})
res = detect(str(audio), **hold)
except Exception as ex: # a failure is a data point, not a crash
print(f" FAIL {name[:48]:48} {ex}")
rows.append(None)
+172
View File
@@ -0,0 +1,172 @@
"""Benchmark key detection (`core/key_detect.py`).
NOT part of `run_tests.sh`: it needs real audio, and the answer is a score to
compare rather than a pass/fail.
python bench_key_detect.py --giantsteps DATA/gs # hand-annotated EDM
python bench_key_detect.py ~/Music # files with a key TAG
GiantSteps (604 Beatport previews, keys corrected by hand) is ground truth
and the number to quote; the model never trained on it (see
`train_key_model.py`). A folder's key tags were written by some other
analyser — usually Traktor, sometimes Mixed In Key or a store — so that score
is AGREEMENT with it, not accuracy. Copies of one song (a stem file beside its
source) count once, by title.
Errors are classed the MIREX way, because they are not equally wrong for a
DJ: a FIFTH (one step round the Camelot wheel) or the RELATIVE key (same
number, other letter) still mixes harmonically; PARALLEL (same tonic, other
mode) and OTHER do not. MIREX's weighted score is 1 / 0.5 / 0.3 / 0.2 / 0.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
import warnings
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
warnings.filterwarnings("ignore")
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"}
def relation(det: tuple[int, str], ref: tuple[int, str]) -> str:
"""How a detected (wheel, mode) relates to the reference."""
(dw, dm), (rw, rm) = det, ref
if (dw, dm) == (rw, rm):
return "exact"
if dw == rw:
return "relative"
if dm == rm and (dw - rw) % 12 in (1, 11):
return "fifth"
if dm != rm:
major, minor = (dw, rw) if dm == "major" else (rw, dw)
if (major - minor) % 12 == 3: # C major 8B vs C minor 5A
return "parallel"
return "other"
def parse_any(text: str) -> tuple[int, str] | None:
"""Open Key, Camelot or a named key ("Abm", "F# minor", "Gmin")."""
w, m = musical_key.parse(text)
return (w, m) if w else None
def _tag_key(path: Path) -> tuple[str, str] | None:
import mutagen
try:
f = mutagen.File(path)
except Exception:
return None
if not f or not f.tags:
return None
t = f.tags
def has(name: str) -> bool:
try:
return name in t
except ValueError: # a Vorbis comment refuses an MP4-style atom name
return False
key = title = None
for name in ("TKEY", "----:com.apple.iTunes:initialkey", "initialkey", "INITIALKEY"):
if has(name):
v = t[name]
v = v.text[0] if hasattr(v, "text") else v[0]
key = v.decode() if isinstance(v, bytes) else str(v)
break
for name in ("TIT2", "\xa9nam", "title", "TITLE"):
if has(name):
v = t[name]
title = str(v.text[0] if hasattr(v, "text") else v[0])
break
return (key, title or path.stem) if key else None
def folder_refs(roots: list[Path]) -> list[tuple[Path, tuple[int, str], str]]:
seen, out = set(), []
for root in roots:
for dp, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for name in sorted(files):
p = Path(dp) / name
if p.suffix.lower() not in AUDIO or name.startswith("."):
continue
tagged = _tag_key(p)
if not tagged or not (ref := parse_any(tagged[0])):
continue
title = re.sub(r"\.stem$", "", tagged[1].strip().lower())
if title not in seen:
seen.add(title)
out.append((p, ref, tagged[1]))
return out
def giantsteps_refs(gs: Path) -> list[tuple[Path, tuple[int, str], str]]:
out = []
for f in sorted((gs / "annotations/key").glob("*.key")):
audio = gs / "audio" / f"{f.stem}.mp3"
ref = parse_any(f.read_text()) # "C minor"
if audio.exists() and ref:
out.append((audio, ref, f.stem))
return out
def _detect(path: Path):
warnings.filterwarnings("ignore")
try:
r = key_detect.detect_key(str(path))
except Exception as ex: # an undecodable file is reported, not fatal
return None, str(ex)
return (r.wheel, r.mode, r.name, r.confidence) if r else None, None
def run(refs, label: str, verbose: bool) -> None:
with ProcessPoolExecutor() as ex:
results = list(ex.map(_detect, [p for p, _, _ in refs], chunksize=2))
rels, misses = [], []
for (path, ref, title), (det, err) in zip(refs, results):
if det is None:
print(f" could not analyse {title}: {err or 'silent / too short'}")
continue
rel = relation(det[:2], ref)
rels.append(rel)
if rel != "exact":
misses.append((title, ref, det, rel))
n = len(rels)
if not n:
print(f"{label}: nothing to score")
return
c = Counter(rels)
print(f"\n{label}: {n} tracks")
for k in WEIGHT:
print(f" {k:9s} {c[k]:4d} {100 * c[k] / n:5.1f}%")
print(f" MIREX weighted score {sum(WEIGHT[r] for r in rels) / n:.3f}")
print(f" harmonically mixable (exact + fifth + relative) {100 * (c['exact'] + c['fifth'] + c['relative']) / n:.1f}%")
if verbose:
for title, ref, det, rel in misses:
print(f" {rel:9s} ref {ref[0]}{'A' if ref[1] == 'minor' else 'B'} "
f"got {det[0]}{'A' if det[1] == 'minor' else 'B'} ({det[2]}, p={det[3]:.2f}) {title[:60]}")
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("folders", nargs="*", type=Path, help="folders of audio files carrying a key tag")
ap.add_argument("--giantsteps", type=Path, help="a downloaded giantsteps-key-dataset clone")
ap.add_argument("-v", "--verbose", action="store_true", help="list every miss")
a = ap.parse_args()
if not a.folders and not a.giantsteps:
ap.error("give --giantsteps and/or folders")
if a.giantsteps:
run(giantsteps_refs(a.giantsteps), "GiantSteps key (hand-annotated)", a.verbose)
if a.folders:
run(folder_refs(a.folders), "Key tags (agreement with another analyser)", a.verbose)
sys.exit(0)
+17 -10
View File
@@ -1,6 +1,7 @@
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
# Tauri as binaries\konduktor-sidecar-<target-triple>.exe.
# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\...
# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and
# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which
# tauri.conf.json bundles as a resource folder (`sidecar\` in the app).
# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\
#
# Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.:
# cd backend
@@ -15,13 +16,19 @@ Set-Location $Root
$Py = Join-Path $Root ".venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { $Py = "python" }
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
Write-Host "Built: $Root\dist\konduktor-sidecar.exe"
# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a
# native command's stderr into an error record, which "Stop" makes fatal on the
# first INFO line — so relax it for this call and judge by the exit code.
$ErrorActionPreference = "Continue"
& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" }
$ErrorActionPreference = "Stop"
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" }
Write-Host "Built: $Root\dist\konduktor-sidecar\"
# Stage for Tauri: name with the host target triple + .exe so the shell plugin
# resolves it. (rustc must be on PATH.)
$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim()
# Stage for Tauri, replacing the whole folder so no file from an older build survives.
$Dest = Join-Path $Root "..\frontend\src-tauri\binaries"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force
Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe"
$Staged = Join-Path $Dest "konduktor-sidecar"
if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged }
Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged
Write-Host "Staged: $Staged\"
+19 -23
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the frozen backend sidecar (single-file binary) with PyInstaller and
# stage it for Tauri as binaries/konduktor-sidecar-<target-triple>.
# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/…
# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage
# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which
# tauri.conf.json bundles as a resource folder (`sidecar/` in the app).
# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/
#
# One-time: pip install -r requirements-build.txt (into the backend venv).
set -euo pipefail
@@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
PY="${PY:-.venv/bin/python}"
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
echo "Built: $ROOT/dist/konduktor-sidecar"
echo "Built: $ROOT/dist/konduktor-sidecar/"
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
# fails with "different Team IDs" and the sidecar dies on launch (which makes
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this binary without re-signing it.
# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc
# signs the executable AND its collected libraries (Python, the .so/.dylib
# files) with a matching identity. Re-signing only some of them desyncs the
# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on
# launch (the app then shows "Konduktor couldn't start"). The app bundle is
# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
# which seals this folder as a resource without re-signing it.
# Stage for Tauri: the sidecar must be named with the host target triple so the
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
if command -v rustc >/dev/null 2>&1; then
TRIPLE="$(rustc -vV | sed -n 's/host: //p')"
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE"
echo "Staged: $DEST/konduktor-sidecar-$TRIPLE"
else
echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2
fi
# Stage for Tauri. Replace the whole folder so no file from an older build
# survives; `cp -R` keeps PyInstaller's symlinks as symlinks.
DEST="$ROOT/../frontend/src-tauri/binaries"
mkdir -p "$DEST"
rm -rf "$DEST/konduktor-sidecar"
cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar"
echo "Staged: $DEST/konduktor-sidecar/"
+29 -5
View File
@@ -1,6 +1,14 @@
# PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone
# build). Produces a single-file binary that serves the FastAPI API on a free
# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the
# executable plus `_internal/` — that serves the FastAPI API on a free loopback
# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh)
#
# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390
# native libraries) into a NEW temp folder on every launch, and macOS checks
# every library it has not seen before (XProtect / syspolicyd) as it is
# dlopen()ed, keyed per file — so every launch paid ~10 s before the window
# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once
# seen). Installed as a folder inside the app, they are checked once.
#
# The tricky bits this handles:
# - uvicorn imports its loop/protocol backends dynamically → collect_submodules
@@ -10,7 +18,7 @@
# - python-multipart is imported as `multipart` by starlette → hidden import
# - dulwich (version-history backups) imports git backends dynamically →
# collect_submodules('dulwich')
from PyInstaller.utils.hooks import collect_submodules, collect_all
from PyInstaller.utils.hooks import collect_all, collect_submodules, copy_metadata
hiddenimports = []
datas = []
@@ -31,6 +39,12 @@ for pkg in ("uvloop", "httptools", "websockets", "av"):
# Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"]
# A remote library's password lives in the OS keychain through `keyring`, which
# finds its backends (macOS Keychain, Windows Credential Manager) by entry point
# — so both the modules AND the package metadata that names them must ship.
hiddenimports += collect_submodules("keyring")
datas += copy_metadata("keyring")
# Bundle the canonical version file so konduktor.__version__ can read it at
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
# app version — see konduktor/__init__.py). Path is relative to this spec.
@@ -54,6 +68,8 @@ datas += [
("konduktor/stems/engine.json", "konduktor/stems"),
("konduktor/stems/weights.json", "konduktor/stems"),
]
# The key-detection network's weights (konduktor/core/key_detect.py).
datas += [("konduktor/core/key_model.npz", "konduktor/core")]
a = Analysis(
["sidecar.py"],
@@ -74,9 +90,8 @@ pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
exclude_binaries=True,
name="konduktor-sidecar",
debug=False,
bootloader_ignore_signals=False,
@@ -89,3 +104,12 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=False,
name="konduktor-sidecar",
)
@@ -21,7 +21,7 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(getattr(r, "playlist_id_parent", 0) or 0)
parents[node_id] = "root" if parent in ("0", "", "None") else parent
@@ -223,6 +224,9 @@ class OneLibraryAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
"""Ignored: a drive's paths are relative to wherever it is mounted.
@@ -312,7 +316,7 @@ class OneLibraryAdapter:
`audio_path` is where `place_audio` said to copy it (or the file itself,
already on the stick); Save moves copies into place.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core import audio_tags, grid_detect, key_detect, waveform
from ...core.export import ExportTrack
from ..rekordbox import artwork, timebase
from .export import OneLibraryExporter
@@ -348,21 +352,23 @@ class OneLibraryAdapter:
taken.add(cue.slot)
else:
memory.append(cue.model_copy(update={"role": "memory", "slot": None}))
export_track = ExportTrack(track=item.track, destination=audio,
# A file with no key of its own gets one, as it gets a grid.
track = key_detect.with_detected_key(item.track, samples, waveform.SR)
export_track = ExportTrack(track=track, destination=audio,
cues=TrackCues(grid_markers=markers, cues=memory))
# Decoded once above; the writer must not decode it again.
export_track.waveform = lambda *, lead=0.0, m=measured: m
art = item.art or audio_tags.read_cover(audio)
jpegs = artwork.pioneer_jpegs(art[0]) if art else None
length = item.track.length or (int(measured.duration) if measured else None)
prepared.append((item, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
length = track.length or (int(measured.duration) if measured else None)
prepared.append((item, track, audio, rel, exporter.anlz_files(export_track, rel), jpegs,
markers, hot, length))
added: list[str] = []
for item, audio, rel, anlz, jpegs, markers, hot, length in prepared:
for item, track, audio, rel, anlz, jpegs, markers, hot, length in prepared:
track_id = self._store.add_track(
audio, item.track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else item.track.bpm, length=length)
audio, track, rel=rel, anlz_rel=self._store._anlz_rel(rel), anlz=anlz,
jpegs=jpegs, bpm=markers[0].bpm if markers else track.bpm, length=length)
for cue in hot:
self._store.set_cue(track_id, slot=cue.slot, start_sec=cue.start,
cue_type="loop" if cue.length else "cue",
@@ -392,6 +398,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")
@@ -414,6 +426,10 @@ class OneLibraryAdapter:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
@@ -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
@@ -49,7 +49,7 @@ class OneLibraryDriver:
def _has_onelibrary_schema(path: Path) -> bool:
try:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
except ImportError: # pragma: no cover — dependency missing
return False
@@ -121,7 +121,7 @@ class OneLibraryExporter:
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
root = Path(destination)
@@ -381,7 +381,8 @@ class OneLibraryExporter:
# ---- playlists -----------------------------------------------------------
def _write_playlists(self, con, payload: ExportPayload, by_source: dict) -> None:
"""One folder named after the export, with the tree preserved under it.
"""The tree preserved — at the top level (parent NULL), or with
`payload.root_folder` under one folder named after the export.
`playlist` is a flat table with `playlist_id_parent`, so folders and
playlists are the same row kind told apart by `attribute` (1 = folder).
@@ -397,8 +398,8 @@ class OneLibraryExporter:
)
return next_id[0]
root = add(payload.name, None, folder=True)
folders: dict[tuple[str, ...], int] = {(): root}
root = add(payload.name, None, folder=True) if payload.root_folder else None
folders: dict[tuple[str, ...], int | None] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -427,8 +428,10 @@ class OneLibraryExporter:
)
#: rekordbox's `fileType` codes, as `pyrekordbox.devicelib_plus.FileType` has them.
#: `.stem.m4a` (a Traktor STEM) is an M4A to a Pioneer player.
#: rekordbox's `fileType` codes. `.stem.m4a` (a Traktor STEM) is an M4A to a
#: Pioneer player. `pyrekordbox.onelibrary.FileType` now also lists MP4 = 3 (the
#: `.mp4` container) and ALAC = 6 (an ALAC `.m4a`); neither is measured here, so
#: both still write 4.
_FILE_TYPES = {".mp3": 1, ".m4a": 4, ".mp4": 4, ".aac": 4, ".flac": 5, ".wav": 11,
".aif": 12, ".aiff": 12}
@@ -1,6 +1,6 @@
"""OneLibrary rows -> the generic projection.
The only place a ``devicelib_plus`` ORM object becomes a generic `Track` /
The only place a ``pyrekordbox.onelibrary`` ORM object becomes a generic `Track` /
`TrackCues`. Everything above this file sees generic types exclusively.
Field conventions are read off a real rekordbox 7 export rather than guessed:
+85 -19
View File
@@ -1,7 +1,7 @@
"""The retained native model for a OneLibrary drive.
Owns the drive's ``exportLibrary.db`` and the layout around it, and is the only
place a ``pyrekordbox.devicelib_plus`` row or an ANLZ tag is touched.
place a ``pyrekordbox.onelibrary`` row or an ANLZ tag is touched.
The database is SQLCipher-encrypted SQLite, like Rekordbox's ``master.db``, but
with a **different and universal key**: every OneLibrary drive from every vendor
@@ -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))
@@ -170,10 +170,10 @@ class OneLibraryStore(ReplaceGridCommands):
def _load(self) -> None:
"""Copy the drive's database into app-data and open the copy."""
try:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
except ImportError as ex: # pragma: no cover — dependency missing
raise LibraryNotSupported(
"Reading OneLibrary drives needs pyrekordbox with devicelib_plus"
"Reading OneLibrary drives needs pyrekordbox with its onelibrary module"
) from ex
_clear_stale_work()
work = Path(tempfile.mkdtemp(prefix="drive-", dir=_work_root()))
@@ -186,7 +186,7 @@ class OneLibraryStore(ReplaceGridCommands):
sidecar = self.path.with_name(self.path.name + suffix)
if sidecar.is_file() and sidecar.stat().st_size:
shutil.copyfile(sidecar, working.with_name(working.name + suffix))
db = DeviceLibraryPlus(str(working))
db = OneLibrary(str(working))
except Exception as ex: # noqa: BLE001 — surfaced as a clean 4xx
shutil.rmtree(work, ignore_errors=True)
raise LibraryNotSupported(f"Could not open OneLibrary database: {ex}") from ex
@@ -206,7 +206,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""Release the working copy and delete it.
The drive itself is never held open (see the module docstring); the copy
is, and `DeviceLibraryPlus.close()` only unregisters events, so the
is, and `OneLibrary.close()` only unregisters events, so the
session and engine are closed here explicitly.
"""
db, self._db = self._db, None
@@ -316,7 +316,7 @@ class OneLibraryStore(ReplaceGridCommands):
image_id = getattr(self.content(track_id), "image_id", None)
if not image_id:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
row = self._require_db().query(models.Image).filter_by(image_id=image_id).one_or_none()
small = self.layout.resolve(getattr(row, "path", None)) if row is not None else None
@@ -456,7 +456,7 @@ class OneLibraryStore(ReplaceGridCommands):
"""
if not name:
return None
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
model = getattr(models, model_name)
pk = f"{model.__tablename__}_id"
@@ -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.onelibrary 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
@@ -539,7 +567,7 @@ class OneLibraryStore(ReplaceGridCommands):
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
try:
pid = int(node_id)
@@ -551,14 +579,14 @@ class OneLibraryStore(ReplaceGridCommands):
return row
def _siblings(self, parent_id: int, *, excluding: int | None = None) -> list:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
rows = self._require_db().query(models.Playlist).filter_by(playlist_id_parent=parent_id).all()
rows = [r for r in rows if r.playlist_id != excluding]
return sorted(rows, key=lambda r: (int(r.sequenceNo or 0), int(r.playlist_id)))
def _create_node(self, name: str, parent_id: str | None, attribute: int) -> str:
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
name = (name or "").strip()
noun = "folder" if attribute == ATTRIBUTE_FOLDER else "playlist"
@@ -603,7 +631,7 @@ class OneLibraryStore(ReplaceGridCommands):
def delete_playlist(self, node_id: str) -> None:
"""Delete a playlist, or a folder WITH everything in it, and close the gap
its `sequenceNo` leaves among its siblings."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
row = self._playlist(node_id)
@@ -624,9 +652,48 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children, renumbering
`sequenceNo` from 0 in both parents as create and delete do. The
Device Library's playlist tree follows at Save (`device_library`
mirrors parent and sort from these rows)."""
db = self._require_db()
row = self._playlist(node_id)
dest = 0
if parent_id:
folder = self._playlist(parent_id)
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
raise InvalidCommand("A playlist can only be moved into a folder")
dest = int(folder.playlist_id)
ancestor = folder
while ancestor is not None:
if int(ancestor.playlist_id) == int(row.playlist_id):
raise InvalidCommand("A folder cannot be moved into itself")
up = int(ancestor.playlist_id_parent or 0)
ancestor = self._playlist(str(up)) if up else None
source = int(row.playlist_id_parent or 0)
siblings = self._siblings(dest, excluding=row.playlist_id)
index = max(0, min(int(index), len(siblings)))
order = siblings[:index] + [row] + siblings[index:]
if source == dest and [r.playlist_id for r in order] == [
r.playlist_id for r in self._siblings(dest)
]:
return str(row.playlist_id)
row.playlist_id_parent = dest
for n, r in enumerate(order):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
if source != dest:
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
db.flush()
self._journal.record("playlist", "move", row.name)
return str(row.playlist_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models
from pyrekordbox.onelibrary import models
db = self._require_db()
playlist = self._playlist(node_id)
@@ -1026,7 +1093,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 +1136,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,
@@ -1312,9 +1378,9 @@ class OneLibraryStore(ReplaceGridCommands):
return SaveOutcome(summary=summary, snapshot=None, tag_results=tag_results)
def _reopen_working(self, work: Path) -> None:
from pyrekordbox.devicelib_plus import DeviceLibraryPlus
from pyrekordbox.onelibrary import OneLibrary
self._db, self._work = DeviceLibraryPlus(str(work / self.path.name)), work
self._db, self._work = OneLibrary(str(work / self.path.name)), work
self._content_cache = None
self._by_id = None
@@ -1375,7 +1441,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:
+53 -13
View File
@@ -21,13 +21,14 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import InvalidCommand, Unsupported
from ...core.adapter import InvalidCommand, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import palette, projection, timebase
from ...core import add_analysis
from .store import RekordboxStore
@@ -171,6 +172,7 @@ class RekordboxAdapter:
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
can_move=writable,
)
parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
@@ -202,6 +204,9 @@ class RekordboxAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
# The FILE decides a track's media kind, and the mapping moves files.
@@ -215,6 +220,10 @@ class RekordboxAdapter:
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
return None
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: see `TraktorAdapter.set_write_stored_paths`."""
self._store.set_write_stored_paths(enabled)
def path_prefix_suggestions(self) -> dict:
paths = self._store.all_audio_paths()
primary = common_dir_prefix(paths)
@@ -245,6 +254,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")
@@ -262,6 +277,10 @@ class RekordboxAdapter:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
@@ -382,6 +401,12 @@ class RekordboxAdapter:
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._journal.summary()
def save(self):
self._require_writable("Saving")
return self._store.save()
@@ -416,6 +441,14 @@ class RekordboxAdapter:
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def analysis_lead(self, audio: Path) -> float:
"""The time-base lead `add_tracks` measures a file's waveform with —
rekordbox's clock against the decoded audio, read from the file's
header (`timebase.py`). OPTIONAL on the protocol: a platform that does
not analyse what it adds has none, and whoever prepares an analysis
for this one (a client of a server-held library) asks for it."""
return timebase.offset(Path(audio))
def add_tracks(self, items: list, *, checkpoint=None) -> list[str]:
"""Add tracks that came from somewhere else, with their prep.
@@ -437,7 +470,7 @@ class RekordboxAdapter:
bank or already taken becomes a memory cue at the same position rather
than being dropped.
"""
from ...core import audio_tags, grid_detect, waveform
from ...core import audio_tags
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
@@ -453,22 +486,29 @@ class RekordboxAdapter:
if str(audio) in held:
raise InvalidCommand(f"The library already holds {audio}")
held.add(str(audio))
samples = waveform.decode(audio)
measured = waveform.analyse_samples(samples, lead=timebase.offset(audio))
markers = list(item.cues.grid_markers) if item.cues else []
if not markers and samples is not None:
try:
found = grid_detect.detect_grid(str(audio), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
if item.analysis is not None:
# Measured by whoever added it — a library held by a server is
# never asked to decode audio (see `PreparedAnalysis`).
analysed = item.analysis
if not markers:
markers = list(analysed.markers)
else:
analysed = add_analysis.prepare(audio, lead=self.analysis_lead(audio),
detect=not markers,
detect_key=item.track.key_wheel is None)
markers = markers or list(analysed.markers)
measured = analysed.measured
# A file with no key of its own gets one, as it gets a grid
# (decided: arrive ready to prep). Rekordbox's own add analyses one.
track = add_analysis.with_key(item.track, analysed.key)
art = item.art or audio_tags.read_cover(audio)
prepared.append((item, audio, measured, markers, art[0] if art else None))
prepared.append((item, track, audio, measured, markers, art[0] if art else None))
added: list[str] = []
for item, audio, measured, markers, art in prepared:
for item, track, audio, measured, markers, art in prepared:
track_id = self._store.add_track(
audio, item.track, measured=measured, with_grid=bool(markers), art=art)
audio, track, measured=measured, with_grid=bool(markers), art=art)
self._index.add(projection.to_track(self._store.content(track_id), (),
stem=self._store.is_stem(track_id)))
if markers:
@@ -91,6 +91,7 @@ def capabilities_for(
media_kinds=["audio", "stem"],
removable=True,
addable=True,
key_writable=True,
artwork=False,
artwork_note=None,
),
@@ -198,8 +198,9 @@ class RekordboxDeviceExporter:
@staticmethod
def _playlists(payload: ExportPayload, by_source: dict) -> tuple[list[bytes], list[bytes]]:
"""The tree under one folder named after the export, as the other
targets build it. `sort_order` is a node's position among its siblings."""
"""The tree as the other targets build it — at the top level (parent
0), or with `payload.root_folder` under one folder named after the
export. `sort_order` is a node's position among its siblings."""
tree: list[bytes] = []
entries: list[bytes] = []
next_id = [0]
@@ -220,7 +221,7 @@ class RekordboxDeviceExporter:
index += 1
entries.append(pdb.playlist_entry_row(index, track_id, playlist_id))
root = add(payload.name, 0, folder=True)
root = add(payload.name, 0, folder=True) if payload.root_folder else 0
folders: dict[tuple[str, ...], int] = {(): root}
for playlist in payload.playlists:
parent = root
@@ -125,7 +125,7 @@ class RekordboxExporter:
)
def write(self, payload: ExportPayload, destination: Path) -> WrittenLibrary:
# `masterdb`'s OWN key blob. `devicelib_plus` has a different one — a
# `masterdb`'s OWN key blob. `onelibrary` has a different one — a
# OneLibrary drive uses a universal key shared across vendors, and
# master.db does not. Mixing them up produces a database Rekordbox
# cannot open, and pyrekordbox rejects the wrong one outright.
@@ -383,9 +383,12 @@ class RekordboxExporter:
# ---- playlists ---------------------------------------------------------------
def _write_playlists(self, db, payload: ExportPayload, rows: dict) -> None:
"""The tree, under one folder named after the export."""
root = db.create_playlist_folder(payload.name)
db.flush()
"""The tree — at the top level, or with `payload.root_folder` under one
folder named after the export (None = the top level)."""
root = None
if payload.root_folder:
root = db.create_playlist_folder(payload.name)
db.flush()
folders: dict[tuple[str, ...], object] = {(): root}
for playlist in payload.playlists:
@@ -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:
+135 -8
View File
@@ -46,7 +46,7 @@ from ...core.adapter import (
)
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping
from ...core.pathmap import PathMapping, stored_form
from . import timebase
from .cue_types import beat_loop_size, kind_for, role_and_slot
@@ -117,6 +117,8 @@ class RekordboxStore(ReplaceGridCommands):
def __init__(self, path: Path):
self.path = Path(path)
self._mapping = PathMapping()
# Write an added file in the library's STORED form (`pathmap.stored_form`).
self._write_stored_paths = False
self._grid_cache: dict[str, tuple[list[float], list[float], list[int]] | None] = {}
self._journal = EditJournal()
# Grid edits buffered until save(): ANLZ files are written to disk, so
@@ -375,6 +377,14 @@ class RekordboxStore(ReplaceGridCommands):
def set_path_mapping(self, mapping: PathMapping) -> None:
self._mapping = mapping or PathMapping()
def set_write_stored_paths(self, enabled: bool) -> None:
self._write_stored_paths = bool(enabled)
def _stored(self, audio: Path) -> Path:
if not self._write_stored_paths:
return Path(audio)
return stored_form(Path(audio), [self._mapping])
def is_stem(self, track_id: str) -> bool:
"""Whether the track's FILE is a native-instruments stem file — read
from its contents (only `.m4a`/`.mp4` are opened, ~0.7 ms each), and
@@ -506,6 +516,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
@@ -558,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands):
self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s visible children.
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
parent", so nothing can be moved to the top level with it. The same
writes are made here — `ParentID`, the moved row's `updated_at`, and
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
share the table and the numbering, so `index` is placed relative to
the VISIBLE siblings and the hidden ones keep their order around it."""
import datetime
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
t = self._tables
row = self._playlist(node_id)
dest = self._playlist(parent_id) if parent_id else None
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
raise InvalidCommand("A playlist can only be moved into a folder")
ancestor = dest
while ancestor is not None:
if str(ancestor.ID) == str(row.ID):
raise InvalidCommand("A folder cannot be moved into itself")
up = str(ancestor.ParentID or "root")
ancestor = None if up in ("root", "0", "") else self._playlist(up)
def children(key: str) -> list:
return (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ParentID == key)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
.all()
)
old_key = str(row.ParentID or "root")
new_key = str(dest.ID) if dest is not None else "root"
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
index = max(0, min(int(index), len(visible)))
if index < len(visible):
at = siblings.index(visible[index])
else:
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
order = siblings[:at] + [row] + siblings[at:]
if old_key == new_key and [str(c.ID) for c in order] == [
str(c.ID) for c in children(new_key)
]:
return str(row.ID)
row.ParentID = new_key
with self._db.registry.disabled():
row.updated_at = datetime.datetime.now()
for n, c in enumerate(order, start=1):
if c.Seq != n:
c.Seq = n
if old_key != new_key:
for n, c in enumerate(
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
):
if c.Seq != n:
c.Seq = n
xml = getattr(self._db, "playlist_xml", None)
if xml is not None:
try:
xml.update(row.ID, parent_id=new_key)
except ValueError:
pass # a playlist the XML never listed: nothing to keep in step
self._db.flush()
self._journal.record("playlist", "move", row.Name)
return str(row.ID)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order.
@@ -604,14 +727,15 @@ 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():
raise InvalidCommand(f"No audio file at {audio}")
t = self._tables
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=str(audio)).count():
raise InvalidCommand(f"The library already holds {audio}")
stored = self._stored(audio)
for form in {str(audio), str(stored)}:
if self._db.session.query(t.DjmdContent).filter_by(FolderPath=form).count():
raise InvalidCommand(f"The library already holds {audio}")
facts = _file_facts(audio)
content = self._db.add_content(
str(audio),
@@ -633,11 +757,14 @@ 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
if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted).
content.FolderPath = str(stored)
track_uuid = str(content.UUID)
rel = new_content.anlz_rel(track_uuid)
@@ -0,0 +1,99 @@
"""Remote libraries: a library held by a Konduktor server, opened from here.
NOT a registered driver: a remote is not a file `can_open` could probe, and it
is chosen from the picker's own "Remote" step, by the saved remote's id. What
opening one returns is everything `AppState.open_remote` installs — the
adapter, the services that keep history and export sets on the server, and the
session that keeps this computer's hold on it.
Imports no platform adapter (`test_layering.py`): what platform the server
holds is the server's business, and reaches this side only as capabilities.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ... import exports
from . import config
from .adapter import RemoteAdapter
from .client import AuthFailed, InUse, RemoteClient, SessionLost, Unreachable, VersionMismatch
from .services import RemotePending, RemoteServices, RemoteSetStore
from .session import RemoteSession
__all__ = [
"AuthFailed", "InUse", "Opened", "RemoteAdapter", "SessionLost", "Unreachable",
"VersionMismatch", "handshake", "open_remote",
]
@dataclass
class Opened:
remote: config.Remote
path: Path
adapter: RemoteAdapter
services: RemoteServices
session: RemoteSession
library_id: str
pending: object | None
#: Edits another computer left unsaved: {machine, summary}, or None.
pending_edits: dict | None
def open_remote(remote: config.Remote, *, takeover: bool = False, batch_probe=None,
password: str | None = None, cache=None) -> Opened:
"""Connect, take the session, and mirror the library. Raises `InUse` when
another computer holds it (and `takeover` is not set), `AuthFailed`,
`VersionMismatch` or `Unreachable` — all before anything is installed."""
secret = password if password is not None else config.password(remote.id)
if not secret:
raise AuthFailed("No password is saved for this remote — edit it to enter one")
client = RemoteClient(remote, secret)
try:
client_id = config.client_id()
hello = client.hello(client_id)
machine = config.machine_name()
acquired = client.acquire(client_id, machine, takeover=takeover)
session = RemoteSession(client, batch_probe=batch_probe, identity=(client_id, machine))
adapter = RemoteAdapter(client, session, hello, cache=cache)
session.on_reacquired = adapter.refresh
except Exception:
client.release()
client.close()
raise
# The server's id for the library, namespaced: this computer's export-set
# store for it is the SERVER (`RemoteSetStore`), and nothing this computer
# keeps under the server's own id may be mistaken for it.
library_id = f"remote:{hello['library_id']}"
exports.use_store(library_id, RemoteSetStore(client))
session.start()
return Opened(
remote=remote, path=Path(hello.get("path") or remote.name), adapter=adapter,
services=RemoteServices(client), session=session, library_id=library_id,
pending=RemotePending(client), pending_edits=acquired.get("pending_edits"),
)
def handshake(remote: config.Remote, password: str) -> list[dict]:
"""Try each of the remote's addresses on its own: what a Save of the
remote's settings reports. Each result is {address, url, ok, error, kind},
`kind` one of ok / unreachable / auth / version / other."""
results = []
for label, url in remote.addresses():
single = config.Remote(id=remote.id, name=remote.name, host=url, username=remote.username)
client = RemoteClient(single, password, timeout=8.0)
try:
info = client.hello()
results.append({"address": label, "url": url, "ok": True, "error": None, "kind": "ok",
"name": info.get("name"), "platform": info.get("platform")})
except Unreachable as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "unreachable"})
except AuthFailed as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "auth"})
except VersionMismatch as ex:
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "version"})
except Exception as ex: # noqa: BLE001 — anything else is that address's answer
results.append({"address": label, "url": url, "ok": False, "error": str(ex), "kind": "other"})
finally:
client.close()
return results
@@ -0,0 +1,514 @@
"""`RemoteAdapter`: a library held by a Konduktor server, as a `LibraryAdapter`.
Everything above the adapter layer — routes, export, import, batches, the UI —
works on a remote library unchanged, because this IS the adapter: the server
holds the native model (`konduktor.server`), and every command travels to it
over `remote_protocol`.
* **The projection is mirrored here.** The server's tracks are fetched once
into a local `TrackIndex`, and each command's answer carries the tracks it
changed — so filtering, sorting, facets and stats are as instant as on a
local library, and use the SAME query code (`core/query.py`). Every answer
carries the server's revision; a gap (an answer out of order, a reconnect)
re-fetches the whole projection rather than guessing.
* **`audio_path` downloads.** It must return a readable file on THIS
computer, so it fetches the track into the shared cache (`cache.py`).
Anything that only needs to know WHICH file a track is asks `audio_facts`,
which never downloads.
* **Read-only when the session is not ours** — taken over, or the server out
of reach — through `capabilities()`, so the UI gates itself as it does for
any read-only library. A command the server refuses for that reason (423)
turns the session `taken_over` on the spot, not at the next heartbeat.
"""
from __future__ import annotations
import base64
import threading
from pathlib import Path
from ... import remote_protocol as rp
from ...core.adapter import (
AudioFacts,
FileTagResult,
NotFound,
SaveOutcome,
Unavailable,
Unsupported,
)
from ...core.capabilities import Capabilities
from ...core.query import TrackIndex
from .cache import RemoteAudioCache, StaleFacts
from .cache import shared as shared_cache
from .client import RemoteClient, SessionLost
from .folder import ServerFile, ServerFiles
from .session import RemoteSession
_NOT_HERE = "A remote library's paths are the server's configuration"
class RemoteAdapter:
def __init__(self, client: RemoteClient, session: RemoteSession, hello: dict, *,
cache: RemoteAudioCache | None = None):
self.platform = hello["platform"]
self.path = Path(hello.get("path") or "")
self.hello = hello
self.client = client
self.session = session
self.cache = cache or shared_cache()
self._index = TrackIndex()
self._lock = threading.RLock()
self._rev: int | None = None
self._caps: tuple[int, Capabilities] | None = None
self._facts: dict[str, AudioFacts] = {}
#: Server path of an upload → (the local file it came from, its analysis lead).
self._uploads: dict[str, tuple[Path, float | None]] = {}
#: Content-folder files a listing returned, by their server path.
self._listed: dict[str, ServerFile] = {}
#: `str(Path(p))` → `p` for every server path this side has turned into
#: a `Path` (an upload's target, a listed file): on Windows that
#: conversion rewrites the separators, and the server must get its own
#: spelling back.
self._server_paths: dict[str, str] = {}
self._dirty = bool(hello.get("dirty"))
self._load()
# ---- following the server ---------------------------------------------------
def _load(self) -> None:
envelope = self.client.rpc("tracks")
with self._lock:
self._index.rebuild(list(envelope["result"]))
self._rev = envelope["rev"]
self._facts.clear()
self._caps = None
def _apply(self, envelope: dict) -> None:
"""Fold a command's answer into the mirror — or re-fetch on any gap."""
with self._lock:
rev = envelope.get("rev")
if envelope.get("reset") or self._rev is None or rev != self._rev + 1:
in_order = False
else:
in_order = True
from ...core.model import Track
removed = set(envelope.get("removed") or [])
if removed:
self._index.rebuild([t for t in self._index.tracks if t.id not in removed])
for raw in envelope.get("changed") or []:
track = Track.model_validate(raw)
self._index.add(track)
self._facts.pop(track.id, None)
for track_id in removed:
self._facts.pop(track_id, None)
self._rev = rev
if not in_order:
self._load()
def _call(self, method: str, /, **args):
try:
envelope = self.client.rpc(method, **args)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
if rp.RPC[method].mutating:
self.session.reached()
self._apply(envelope)
return envelope["result"]
def refresh(self) -> None:
"""Re-read everything from the server (after a restore, a reconnect)."""
self._load()
# ---- identity -----------------------------------------------------------------
def capabilities(self) -> Capabilities:
with self._lock:
cached = self._caps
if cached is None or cached[0] != self._rev:
try:
caps = self._call("capabilities")
except Unavailable:
# Out of reach: the last answer, read-only (below) — the UI
# must still render, and gate every edit.
if cached is None:
raise
caps = cached[1]
else:
with self._lock:
self._caps = (self._rev, caps)
else:
caps = cached[1]
if self.session.writable:
return caps
return caps.model_copy(update={"writable": False, "readonly_cause": self.session.readonly_cause})
def reload(self) -> None:
# The server is what holds (and drops) the edits — `AppState.discard`
# asks it to discard first; this is the mirror following.
self._load()
# ---- read projection (the mirror) -------------------------------------------
@property
def tracks(self):
return self._index.tracks
def track(self, track_id: str):
return self._index.get(track_id)
def query_tracks(self, **kw):
return self._index.query_tracks(**kw)
def facets(self):
return self._index.facets()
def stats(self, playlist_count: int):
return self._index.stats(playlist_count)
# ---- read projection (the server) -------------------------------------------
def playlist_tree(self):
return self._call("playlist_tree")
def playlist_count(self) -> int:
return self._call("playlist_count")
def playlist_entries(self, node_id: str):
return self._call("playlist_entries", node_id=node_id)
def playlist_tracks(self, node_id: str):
entries = self.playlist_entries(node_id)
if entries is None:
return None
return [t for k in entries if (t := self._index.get(k)) is not None]
def track_cues(self, track_id: str):
return self._call("track_cues", track_id=track_id)
@property
def dirty(self) -> bool:
try:
self._dirty = self._call("dirty")
except Unavailable:
pass # out of reach: what it was
return self._dirty
# ---- commands -------------------------------------------------------------------
def create_playlist(self, name, parent_id=None):
return self._call("create_playlist", name=name, parent_id=parent_id)
def create_folder(self, name, parent_id=None):
return self._call("create_folder", name=name, parent_id=parent_id)
def rename_playlist(self, node_id, name):
return self._call("rename_playlist", node_id=node_id, name=name)
def delete_playlist(self, node_id):
return self._call("delete_playlist", node_id=node_id)
def move_playlist(self, node_id, parent_id, index):
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
def set_playlist_entries(self, node_id, track_ids):
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
def remove_tracks(self, track_ids):
return self._call("remove_tracks", track_ids=list(track_ids))
def set_track_metadata(self, track_id, fields):
return self._call("set_track_metadata", track_id=track_id, fields=fields)
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
def set_cue_type(self, track_id, slot, cue_type):
return self._call("set_cue_type", track_id=track_id, slot=slot, cue_type=cue_type)
def set_cue_color(self, track_id, slot, color):
return self._call("set_cue_color", track_id=track_id, slot=slot, color=color)
def delete_cue(self, track_id, slot):
return self._call("delete_cue", track_id=track_id, slot=slot)
def place_cues(self, track_id, cues, *, overwrite=False):
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
def add_grid_marker(self, track_id, start_sec, bpm=None):
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
def move_grid_marker(self, track_id, index, start_sec):
return self._call("move_grid_marker", track_id=track_id, index=index, start_sec=start_sec)
def set_grid_marker_bpm(self, track_id, index, bpm):
return self._call("set_grid_marker_bpm", track_id=track_id, index=index, bpm=bpm)
def delete_grid_marker(self, track_id, index):
return self._call("delete_grid_marker", track_id=track_id, index=index)
def replace_grid(self, track_id, markers):
return self._call("replace_grid", track_id=track_id, markers=_pairs(markers))
def set_analysed_grid(self, track_id, markers):
return self._call("set_analysed_grid", track_id=track_id, markers=_pairs(markers))
def delete_grid(self, track_id):
return self._call("delete_grid", track_id=track_id)
def set_grid_lock(self, track_id, locked):
return self._call("set_grid_lock", track_id=track_id, locked=locked)
# ---- adding tracks ------------------------------------------------------------------
def upload_audio(self, source: Path, folder: str, name: str, *, progress=None) -> Path:
"""Send `source` into `folder` on the server; the path it landed at (a
taken name gets `-2`…, as a local copy does). What a local import's
file copy becomes when the library's destination is the server's."""
try:
landed = self.client.upload(Path(source), folder, name, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
self._server_paths[str(Path(landed["path"]))] = landed["path"]
return Path(landed["path"])
def free_space(self, path: str) -> int:
"""Free space on the SERVER's disk at `path` (an import's destination)."""
return self.client.fs_space(path)
def delete_upload(self, path) -> None:
"""Undo `upload_audio` (a cancelled or failed import)."""
key = self._server_key(path)
self._uploads.pop(key, None)
self.client.delete_upload(key)
def _server_key(self, path) -> str:
text = str(path)
return self._server_paths.get(text, text)
def add_tracks(self, items, *, checkpoint=None):
"""Add uploaded files. Where the platform analyses what it adds (the
server said so with an analysis lead), the analysis is done HERE, on
the copy this computer uploaded — the server never decodes audio."""
from ...core import add_analysis
wire = []
total = len(items)
keys = [self._server_key(item.audio_path) for item in items]
# Files already in the content folder (added in place): the server says
# whether the platform analyses, and only then is the file fetched.
in_place = [k for k, item in zip(keys, items)
if item.analysis is None and k not in self._uploads and k in self._listed]
leads = self.client.folder_leads(in_place) if in_place else {}
for n, (item, key) in enumerate(zip(items, keys), start=1):
source, lead = self._uploads.get(key, (None, None))
analysis = item.analysis
if analysis is None and source is None and leads.get(key) is not None:
lead = leads[key]
if checkpoint is not None:
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
source = self.folder_audio(key)
if analysis is None and lead is not None and source is not None:
if checkpoint is not None:
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
has_grid = bool(item.cues and item.cues.grid_markers)
analysis = add_analysis.prepare(source, lead=lead, detect=not has_grid,
detect_key=item.track.key_wheel is None)
art = rp.WireArt(data=base64.b64encode(item.art[0]).decode("ascii"), mime=item.art[1]) \
if item.art else None
wire.append(rp.WireNewTrack(track=item.track, audio_path=key, cues=item.cues, art=art,
analysis=rp.pack_analysis(analysis)))
if checkpoint is not None:
checkpoint(f"Adding {total} track{'' if total == 1 else 's'} on the server",
step=total, of=total)
try:
envelope = self.client.rpc("add_tracks", items=wire, timeout=None)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply(envelope)
for key in keys:
self._uploads.pop(key, None)
return envelope["result"]
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
raise Unsupported("A remote library's stem files are swapped in on the server")
# ---- Convert to Stems (the library side lives on the server) ---------------------
# `stems/remote_convert.py` drives these: the server plans and swaps, this
# computer separates. See the server's stem routes for why.
def stems_plan(self, body: dict) -> dict:
return self.client.stems_plan(body)
def stage_stem(self, track_id: str, target: str, local: Path, *, bit_rate: int,
duration: float, progress=None) -> dict:
import hashlib
digest = hashlib.sha256()
with open(local, "rb") as f:
while chunk := f.read(1 << 20):
digest.update(chunk)
try:
return self.client.stems_stage(track_id, target, local, sha256=digest.hexdigest(),
bit_rate=bit_rate, duration=duration, progress=progress)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
def abandon_stems(self, targets: list[str]) -> None:
self.client.stems_abandon(targets)
def publish_stems(self, items: list[dict], options: dict) -> dict:
try:
result = self.client.stems_publish(items, options)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._load() # ids changed (repoint) or entries were added
return result
# ---- metadata / art ------------------------------------------------------------------
def set_cover_art(self, track_id, data, mime):
try:
envelope = self.client.put_art(track_id, data, mime)
except SessionLost as ex:
self.session.lost(ex.holder)
raise
self._apply({**envelope, "removed": [], "reset": False})
def cover_art(self, track_id):
return self.client.art(track_id)
# ---- audio ------------------------------------------------------------------------------
def audio_facts(self, track_ids):
wanted = list(dict.fromkeys(track_ids))
with self._lock:
missing = [t for t in wanted if t not in self._facts]
if missing:
found = {}
for start in range(0, len(missing), 2000):
found.update(self._call("audio_facts", track_ids=missing[start:start + 2000]))
with self._lock:
self._facts.update(found)
with self._lock:
return {t: self._facts[t] for t in wanted if t in self._facts}
def audio_path(self, track_id, *, progress=None):
"""A local copy of the track's audio, downloaded if this computer has
none of this version. None when the server has no file for it."""
for attempt in range(2):
facts = self.audio_facts([track_id]).get(track_id)
if facts is None:
return None
cached = self.cache.get(facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
facts, lambda partial: self.client.download(track_id, partial, progress=progress))
except StaleFacts:
with self._lock:
self._facts.pop(track_id, None)
if attempt:
raise
return None
def cached_audio(self, track_id) -> Path | None:
"""The local copy if there already is one — never downloads."""
facts = self.audio_facts([track_id]).get(track_id)
return self.cache.get(facts) if facts else None
# ---- the content folder, browsed --------------------------------------------------
def folder_listing(self, path: str | None) -> ServerFiles:
"""The audio directly inside a content folder (None: the folder itself),
as the server lists it — and remembered, so a file can then be played
or added by its path."""
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
with self._lock:
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
self._listed.update(listing.files)
self._server_paths.update({str(Path(k)): k for k in listing.files})
return listing
def listed_files(self, paths) -> ServerFiles | None:
"""The listed files among `paths` as one source (they may come from
several folders); None when none of them was listed."""
with self._lock:
found = [self._listed[p] for p in paths if p in self._listed]
return ServerFiles(self, found[0].folder, found) if found else None
def folder_audio(self, path: str, *, progress=None) -> Path:
"""A local copy of a listed file, downloaded into the shared cache —
keyed by the same facts as a library track's, so a file that is both
downloads once."""
for attempt in range(2):
with self._lock:
found = self._listed.get(path)
if found is None:
raise NotFound("File not found — browse to its folder first")
cached = self.cache.get(found.facts)
if cached is not None:
return cached
try:
return self.cache.fetch(
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
except StaleFacts:
if attempt:
raise
self.folder_listing(found.folder) # changed on the server: re-read it
raise NotFound(path)
# ---- paths: the server's business ------------------------------------------------
def set_path_mapping(self, mapping):
raise Unsupported(_NOT_HERE)
def set_session_mappings(self, mappings):
raise Unsupported(_NOT_HERE)
def unresolved_path_groups(self):
return []
def path_prefix_suggestions(self):
raise Unsupported(_NOT_HERE)
def remap_preview(self, mapping):
raise Unsupported(_NOT_HERE)
def remap_locations(self, mapping):
raise Unsupported(_NOT_HERE)
# ---- save ----------------------------------------------------------------------------
def save(self):
try:
result = self.client.save()
except SessionLost as ex:
self.session.lost(ex.holder)
raise
outcome = SaveOutcome(
summary=result.get("summary") or "",
snapshot=None,
tag_results=[FileTagResult(**r) for r in result.get("tag_results") or []],
)
# Versioned on the server; `RemoteServices.commit_save` hands it on.
outcome.commit = result.get("commit")
self._load()
return outcome
def snapshot(self) -> bytes:
raise Unsupported("A remote library's version history is kept on the server")
def close(self) -> None:
self.session.stop()
self.client.release()
self.client.close()
def _pairs(markers) -> list[tuple[float, float]]:
out = []
for m in markers:
if hasattr(m, "start"):
out.append((float(m.start), float(m.bpm)))
else:
start, bpm = m
out.append((float(start), float(bpm)))
return out
+194
View File
@@ -0,0 +1,194 @@
"""This computer's copies of a remote library's audio.
Everything that needs a track's audio as a FILE runs here, not on the server —
the deck's decode, grid and cue analysis, stem separation and extraction, an
export's copy onto a stick. One cache serves them all, so a track analysed and
then exported downloads once.
* **Keyed by what the server says the file IS** — its path there, size and
mtime (`AudioFacts`) — never by when it was fetched: an edited file (Save
writes tags into it) is a new entry, and the same file fetched again after
an eviction, or by another computer exporting the same set, is recognised.
* **A partial, renamed into place**, so a cut connection never leaves a
truncated file under a real entry's name, and a download whose size does
not match the facts is refused rather than kept.
* **Least recently used, under a cap** (`remoteCacheBytes` in prefs). The
entry just written and anything touched in the last few minutes are never
the ones evicted: they are being played or copied right now.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import threading
import time
from pathlib import Path
from ... import paths, prefs
from ...core.adapter import AudioFacts, Unavailable
DEFAULT_CAP = 10 * 1024 ** 3
_RECENT = 300.0 # seconds: an entry touched this recently is in use
_PART = ".part"
class StaleFacts(Unavailable):
"""The server's file changed between asking about it and downloading it."""
def cache_root() -> Path:
return paths.app_data_dir() / "remote-cache"
def cap_bytes() -> int:
try:
value = int(prefs.load_prefs().get("remoteCacheBytes") or DEFAULT_CAP)
except (TypeError, ValueError):
value = DEFAULT_CAP
return max(value, 256 * 1024 ** 2)
class RemoteAudioCache:
def __init__(self, root: Path | None = None, *, cap=None, clock=time.time):
self.root = Path(root) if root is not None else cache_root()
self._cap = cap if cap is not None else cap_bytes
self._clock = clock
self._locks: dict[str, threading.Lock] = {}
self._guard = threading.Lock()
#: Recent download speeds (bytes/s), newest last — for time estimates.
self._speeds: list[float] = []
# ---- naming ----------------------------------------------------------------
@staticmethod
def key(facts: AudioFacts) -> str:
text = f"{facts.key}|{facts.size}|{facts.mtime_ns}"
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:32]
def path_for(self, facts: AudioFacts) -> Path:
# The original's suffix, so a MIME type and a decoder's guess still work.
suffix = Path(facts.key.replace("\\", "/")).suffix.lower()
return self.root / f"{self.key(facts)}{suffix}"
def _lock_for(self, key: str) -> threading.Lock:
with self._guard:
return self._locks.setdefault(key, threading.Lock())
# ---- use -------------------------------------------------------------------
def get(self, facts: AudioFacts) -> Path | None:
path = self.path_for(facts)
if path.is_file():
self._touch(path)
return path
return None
def fetch(self, facts: AudioFacts, download) -> Path:
"""The cached copy, downloading it first if needed. `download(partial)`
writes the file and returns the server's `{size, mtime_ns}` for it."""
path = self.path_for(facts)
with self._lock_for(path.name):
if path.is_file():
self._touch(path)
return path
self.root.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}{_PART}")
started = time.monotonic()
try:
meta = download(partial) or {}
got = partial.stat().st_size
if got != facts.size or (meta.get("size") and meta["size"] != facts.size):
raise StaleFacts(f"{Path(facts.key).name} changed on the server while downloading")
os.replace(partial, path)
finally:
partial.unlink(missing_ok=True)
elapsed = max(time.monotonic() - started, 1e-3)
if facts.size > 1 << 20:
self._speeds = (self._speeds + [facts.size / elapsed])[-8:]
self._touch(path)
self.prune(keep={path})
return path
def speed(self) -> float | None:
"""A recent download speed in bytes/s, or None before the first."""
if not self._speeds:
return None
ordered = sorted(self._speeds)
return ordered[len(ordered) // 2]
def _touch(self, path: Path) -> None:
now = self._clock()
try:
os.utime(path, (now, now))
except OSError:
pass
# ---- housekeeping ------------------------------------------------------------
def _entries(self) -> list[tuple[float, int, Path]]:
out = []
if not self.root.is_dir():
return out
for p in self.root.iterdir():
if p.name.endswith(_PART) or not p.is_file():
continue
try:
st = p.stat()
except OSError:
continue
out.append((st.st_mtime, st.st_size, p))
return out
def prune(self, keep: set[Path] | None = None) -> int:
"""Evict least-recently-used entries until under the cap. Returns bytes freed."""
cap = self._cap() if callable(self._cap) else self._cap
entries = sorted(self._entries())
total = sum(size for _, size, _ in entries)
freed = 0
now = self._clock()
for used, size, p in entries:
if total <= cap:
break
if (keep and p in keep) or now - used < _RECENT:
continue
try:
p.unlink()
except OSError:
continue # held open (Windows): next time
total -= size
freed += size
return freed
def usage(self) -> dict:
entries = self._entries()
cap = self._cap() if callable(self._cap) else self._cap
return {"bytes": sum(s for _, s, _ in entries), "files": len(entries), "cap": cap,
"free": _free(self.root)}
def clear(self) -> int:
freed = 0
for _, size, p in self._entries():
try:
p.unlink()
freed += size
except OSError:
pass
return freed
def _free(folder: Path) -> int:
probe = folder
while not probe.exists() and probe != probe.parent:
probe = probe.parent
try:
return shutil.disk_usage(probe).free
except OSError:
return 0
_shared: RemoteAudioCache | None = None
def shared() -> RemoteAudioCache:
global _shared
if _shared is None:
_shared = RemoteAudioCache()
return _shared
+325
View File
@@ -0,0 +1,325 @@
"""Talking to a Konduktor server: addresses, sign-in, and the error vocabulary.
Every request tries the address that last worked, then the others in the
remote's order (primary, then fallback) — so a laptop that leaves the house
moves from the LAN address to the VPN one without being asked, and back again.
Only a CONNECT failure moves on: the request never reached that server, so
sending it to the other one cannot apply it twice. A request that reached a
server and then failed is that server's answer.
The server's refusals come back as the adapter's own error classes (the same
status codes `main.py` maps them from), so a route on this computer reports a
remote library's refusal exactly as it would a local one's.
"""
from __future__ import annotations
import logging
import threading
from pathlib import Path
import httpx
from ... import remote_protocol as rp
from ...core.adapter import (
AdapterError,
InvalidCommand,
LibraryNotSupported,
NotFound,
Unavailable,
Unsupported,
)
from .config import Remote
log = logging.getLogger(__name__)
_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
class Unreachable(Unavailable):
"""No address of the remote answered."""
class AuthFailed(LibraryNotSupported):
"""The server refused the username or password."""
class VersionMismatch(LibraryNotSupported):
def __init__(self, update: str, server_version: str):
side = "Konduktor on this computer" if update == "app" else "the Konduktor server"
super().__init__(
f"This server speaks a different version of Konduktor's protocol "
f"(server {server_version}): update {side}."
)
self.update = update
class InUse(AdapterError):
"""Another computer holds the session: `holder` = {machine, since, batch}."""
def __init__(self, holder: dict):
super().__init__(f"In use by {holder.get('machine') or 'another computer'}")
self.holder = holder
class SessionLost(Unavailable):
"""This computer no longer holds the session (another one took over)."""
def __init__(self, holder: dict | None):
who = (holder or {}).get("machine")
super().__init__(
f"{who} has taken over this library — it is read-only here" if who
else "This computer no longer holds the library's session"
)
self.holder = holder
def _detail(response: httpx.Response):
try:
return response.json().get("detail")
except Exception: # noqa: BLE001
return response.text[:300]
class RemoteClient:
def __init__(self, remote: Remote, password: str, *, timeout: float = 30.0):
self.remote = remote
self._addresses = remote.addresses()
self._active: int | None = None
self.token: str | None = None
self._lock = threading.Lock()
self._http = httpx.Client(
auth=(remote.username, password),
timeout=httpx.Timeout(timeout, connect=4.0),
follow_redirects=False,
)
def close(self) -> None:
self._http.close()
@property
def via(self) -> str | None:
"""Which address is in use: "primary" / "fallback" (None until one answers)."""
return None if self._active is None else self._addresses[self._active][0]
# ---- transport ----------------------------------------------------------------
def _order(self) -> list[int]:
everything = list(range(len(self._addresses)))
if self._active is None:
return everything
return [self._active] + [i for i in everything if i != self._active]
def request(self, method: str, path: str, *, retry: bool = True, session: bool = True,
**kw) -> httpx.Response:
headers = dict(kw.pop("headers", None) or {})
if session and self.token:
headers[rp.SESSION_HEADER] = self.token
order = self._order() if retry else ([self._active] if self._active is not None else [0])
last: Exception | None = None
for i in order:
base = self._addresses[i][1]
try:
response = self._http.request(method, base + path, headers=headers, **kw)
except _CONNECT_ERRORS as ex:
last = ex
continue
except httpx.TimeoutException as ex:
self._active = i
raise Unreachable(f"The server at {base} stopped answering") from ex
except httpx.TransportError as ex:
last = ex
continue
self._active = i
return self.check(response)
names = " or ".join(b for _, b in (self._addresses[i] for i in order))
raise Unreachable(f"Cannot reach the server at {names}") from last
def stream(self, method: str, path: str, **kw):
"""A streaming request on the address in use (a download)."""
headers = dict(kw.pop("headers", None) or {})
if self.token:
headers[rp.SESSION_HEADER] = self.token
# Pick the address first with a cheap call, so the stream itself is not
# the request that discovers the primary is gone.
if self._active is None:
self.request("GET", "/v1/hello", session=False)
base = self._addresses[self._active][1]
return self._http.stream(method, base + path, headers=headers, **kw)
@staticmethod
def check(response: httpx.Response) -> httpx.Response:
status = response.status_code
if status < 400:
return response
detail = _detail(response)
if status == 401:
raise AuthFailed("The server refused the username or password")
if status == 423:
raise SessionLost((detail or {}).get("holder") if isinstance(detail, dict) else None)
if status == 409 and isinstance(detail, dict) and detail.get("code") == "in_use":
raise InUse(detail)
text = detail if isinstance(detail, str) else (detail or {}).get("message", str(detail))
cls = {404: NotFound, 400: InvalidCommand, 422: Unsupported, 503: Unavailable}.get(status)
if cls is not None:
raise cls(text)
raise AdapterError(f"The server answered {status}: {text}")
# ---- handshake + session ----------------------------------------------------------
def hello(self, client_id: str | None = None) -> dict:
info = self.request("GET", "/v1/hello", params={"client_id": client_id} if client_id else None,
session=False).json()
server_version = tuple(info.get("api_version") or (0, 0))
update = rp.compatible(rp.API_VERSION, (int(server_version[0]), int(server_version[1])))
if update:
raise VersionMismatch(update, info.get("app_version") or ".".join(map(str, server_version)))
return info
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> dict:
body = self.request("POST", "/v1/session/acquire", session=False,
json={"client_id": client_id, "machine": machine, "takeover": takeover}).json()
self.token = body["token"]
return body
def heartbeat(self, batch: str | None) -> dict:
return self.request("POST", "/v1/session/heartbeat", json={"batch": batch}).json()
def release(self, *, timeout: float | None = None) -> None:
if not self.token:
return
try:
kw = {"timeout": timeout} if timeout is not None else {}
self.request("POST", "/v1/session/release", retry=False, **kw)
except AdapterError:
pass
self.token = None
# ---- the protocol -------------------------------------------------------------------
def rpc(self, method: str, /, *, timeout=..., **args) -> dict:
"""Call one protocol method; the envelope `{result, rev, changed, removed, reset}`
with `result` already deserialised."""
kw = {} if timeout is ... else {"timeout": timeout}
body = self.request("POST", f"/v1/rpc/{method}", json={"args": rp.dump_args(method, args)}, **kw).json()
body["result"] = rp.load_result(method, body.get("result"))
return body
# ---- bytes -----------------------------------------------------------------------------
def download(self, track_id: str, target: Path, *, progress=None) -> dict:
"""Stream a track's audio into `target`; its server-side size and mtime."""
with self.stream("GET", "/v1/audio", params={"track_id": track_id}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def upload(self, source: Path, folder: str, name: str, *, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request("POST", "/v1/upload", params={"dir": folder, "name": name},
content=body(), retry=False, timeout=None).json()
def delete_upload(self, path: str) -> None:
self.request("DELETE", "/v1/upload", params={"path": path})
def art(self, track_id: str) -> tuple[bytes, str] | None:
try:
r = self.request("GET", "/v1/art", params={"track_id": track_id})
except NotFound:
return None
return r.content, r.headers.get("content-type", "image/jpeg").split(";")[0]
def put_art(self, track_id: str, data: bytes, mime: str) -> dict:
return self.request("PUT", "/v1/art", params={"track_id": track_id, "mime": mime},
content=data).json()
def fs_list(self, path: str | None) -> dict:
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
def folder_tracks(self, path: str | None) -> dict:
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
timeout=None).json()
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
"""Stream a listed content-folder file into `target` (as `download`)."""
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
if response.status_code >= 400:
response.read()
self.check(response)
with open(target, "wb") as out:
for chunk in response.iter_bytes(1 << 20):
out.write(chunk)
if progress is not None:
progress(len(chunk))
return {
"size": int(response.headers.get("X-Konduktor-Size") or 0),
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
}
def fs_space(self, path: str | None) -> int:
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
# ---- Convert to Stems ----------------------------------------------------------------
def stems_plan(self, body: dict) -> dict:
return self.request("POST", "/v1/stems/plan", json=body, timeout=None).json()
def stems_stage(self, track_id: str, target: str, source: Path, *, sha256: str,
bit_rate: int, duration: float, progress=None) -> dict:
def body():
with open(source, "rb") as f:
while chunk := f.read(1 << 20):
if progress is not None:
progress(len(chunk))
yield chunk
return self.request(
"PUT", "/v1/stems/stage",
params={"track_id": track_id, "target": target, "sha256": sha256,
"bit_rate": bit_rate, "duration": duration},
content=body(), retry=False, timeout=None,
).json()
def stems_abandon(self, targets: list[str]) -> None:
self.request("POST", "/v1/stems/abandon", json={"targets": targets})
def stems_publish(self, items: list[dict], options: dict) -> dict:
return self.request("POST", "/v1/stems/publish", json={"items": items, "options": options},
timeout=None).json()
def stems_pending(self) -> dict:
return self.request("GET", "/v1/stems/pending").json()
# ---- save / history / export sets -------------------------------------------------
def save(self) -> dict:
return self.request("POST", "/v1/save", timeout=None).json()
def discard(self) -> dict:
return self.request("POST", "/v1/discard", timeout=None).json()
def history(self) -> list[dict]:
return self.request("GET", "/v1/history").json()
def restore(self, commit_id: str) -> dict:
return self.request("POST", f"/v1/history/{commit_id}/restore", timeout=None).json()
def clear_history(self) -> None:
self.request("DELETE", "/v1/history")
def export_sets(self) -> dict:
return self.request("GET", "/v1/export-sets").json()
def put_export_sets(self, doc: dict) -> None:
self.request("PUT", "/v1/export-sets", json=doc)
+199
View File
@@ -0,0 +1,199 @@
"""Saved remotes: the servers this computer knows how to reach.
A remote is where a Konduktor server is (an address, an optional port, and a
fallback address — typically the LAN address first and a VPN one second) and
who to sign in as. Everything but the password is a plain preference
(`userprefs.json`, key `remotes`); the password lives in the OS keychain
(macOS Keychain, Windows Credential Manager) through `keyring`, never in a JSON
file beside the app's other data.
This computer also has a stable `client_id`, which is how a server tells "the
same laptop back from sleep" (renew its session silently) from "another
computer" (offer a takeover).
"""
from __future__ import annotations
import socket
import uuid
from dataclasses import asdict, dataclass
from ... import prefs
DEFAULT_PORT = 8765
_PREFS_KEY = "remotes"
_CLIENT_KEY = "remoteClientId"
_KEYRING_SERVICE = "Konduktor"
@dataclass
class Remote:
id: str
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str = ""
def addresses(self) -> list[tuple[str, str]]:
"""`(label, base url)`, primary first — the order every connect tries.
Each address keeps its OWN port. The fallback once borrowed the
primary's, so a reverse-proxied fallback (`konduktor.example.net`,
served on 443) was tried at `:8765` because the LAN address named it.
"""
out = [("primary", _base(self.host, self.port))]
if self.fallback_host:
out.append(("fallback", _base(self.fallback_host, self.fallback_port)))
return out
def public(self) -> dict:
return asdict(self)
def _base(host: str, port: int | None) -> str:
"""An address as typed → a base URL. A full URL (`https://…`, the way to
reach a server behind the user's own reverse proxy) is taken exactly as
given, port and all; anything else is plain HTTP on its port, else 8765."""
host = host.strip()
if host.startswith("http://") or host.startswith("https://"):
return host.rstrip("/")
bare, inline = split_host(host)
if inline is not None:
host, port = bare, port or inline
if ":" in host and not host.startswith("["):
host = f"[{host}]" # an IPv6 literal
return f"http://{host}:{port or DEFAULT_PORT}"
def split_host(text: str) -> tuple[str, int | None]:
"""`"nas.local:9000"` → `("nas.local", 9000)`; a bare host keeps no port."""
text = (text or "").strip()
if text.startswith("http://") or text.startswith("https://"):
return text, None
if text.count(":") == 1:
host, _, port = text.partition(":")
if port.isdigit():
return host, int(port)
return text, None
# ---- the list ------------------------------------------------------------------
def remotes() -> list[Remote]:
raw = prefs.load_prefs().get(_PREFS_KEY) or []
out = []
for item in raw if isinstance(raw, list) else []:
try:
out.append(Remote(**{k: item.get(k) for k in Remote.__dataclass_fields__ if k in item}))
except TypeError:
continue
return out
def get(remote_id: str) -> Remote | None:
return next((r for r in remotes() if r.id == remote_id), None)
def save(remote: Remote) -> Remote:
items = [r for r in remotes() if r.id != remote.id] + [remote]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
return remote
def delete(remote_id: str) -> bool:
before = remotes()
items = [r for r in before if r.id != remote_id]
prefs.update_prefs({_PREFS_KEY: [r.public() for r in items]})
forget_password(remote_id)
return len(items) != len(before)
def new_id() -> str:
return uuid.uuid4().hex[:12]
# ---- this computer ---------------------------------------------------------------
def client_id() -> str:
current = prefs.load_prefs().get(_CLIENT_KEY)
if isinstance(current, str) and current:
return current
fresh = uuid.uuid4().hex
prefs.update_prefs({_CLIENT_KEY: fresh})
return fresh
def machine_name() -> str:
"""What another computer is told holds the library ("Ben's MacBook")."""
try:
import subprocess
import sys
if sys.platform == "darwin":
name = subprocess.run(["scutil", "--get", "ComputerName"], capture_output=True,
text=True, timeout=2).stdout.strip()
if name:
return name
except Exception: # noqa: BLE001
pass
name = socket.gethostname()
return name[:-6] if name.endswith(".local") else name
# ---- the password ------------------------------------------------------------------
# A seam for tests (and any machine without a keychain): `use_password_store`.
class _Keyring:
def get(self, account: str) -> str | None:
import keyring
return keyring.get_password(_KEYRING_SERVICE, account)
def set(self, account: str, password: str) -> None:
import keyring
keyring.set_password(_KEYRING_SERVICE, account, password)
def delete(self, account: str) -> None:
import keyring
from keyring.errors import PasswordDeleteError
try:
keyring.delete_password(_KEYRING_SERVICE, account)
except PasswordDeleteError:
pass
_store = _Keyring()
def use_password_store(store) -> None:
"""Replace the keychain (`get`/`set`/`delete` by account) — tests only."""
global _store
_store = store if store is not None else _Keyring()
def _account(remote_id: str) -> str:
return f"remote:{remote_id}"
def password(remote_id: str) -> str | None:
try:
return _store.get(_account(remote_id))
except Exception: # noqa: BLE001 — a locked keychain reads as "no password"
return None
def set_password(remote_id: str, value: str) -> None:
_store.set(_account(remote_id), value)
def forget_password(remote_id: str) -> None:
try:
_store.delete(_account(remote_id))
except Exception: # noqa: BLE001
pass
+102
View File
@@ -0,0 +1,102 @@
"""The server's content folder, browsed from this computer like a drive.
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
remote library the music lives in the server's content folder, which this
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
facts, and which files the library already holds) and this module holds the
answer as a read-only SOURCE, the shape the table, the deck and the importer
already read.
Adding one of these files never uploads anything: it is already where the
library can reach it, so it is added IN PLACE (`on_library_host`), and the
importer skips both the copy and the copy-or-reference question.
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
until the importer needs one, because a server path is not a path here (on a
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from ...core.adapter import AudioFacts
from ...core.model import PlaylistNode, Track, TrackCues
@dataclass
class ServerFile:
folder: str
track: Track
facts: AudioFacts
#: The library's id for this file, when it already points at it.
held: str | None = None
class ServerFiles:
"""Files in the content folder, as the read half of a source."""
#: The importer's cue that these are already on the machine holding the
#: library: added where they are, neither copied nor uploaded.
on_library_host = True
def __init__(self, adapter, path: str, files: list[ServerFile]):
self.adapter = adapter
self.path = path
self._files = {f.track.id: f for f in files}
@classmethod
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
folder = body["path"]
facts = body.get("files") or {}
held = body.get("held") or {}
files = []
for raw in body.get("tracks") or []:
track = Track.model_validate(raw)
fact = facts.get(track.id)
if fact is None:
continue
files.append(ServerFile(
folder=folder, track=track,
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
held=held.get(track.id),
))
return cls(adapter, folder, files)
@property
def files(self) -> dict[str, ServerFile]:
return self._files
@property
def tracks(self) -> list[Track]:
return [f.track for f in self._files.values()]
def track(self, track_id: str) -> Track | None:
found = self._files.get(track_id)
return found.track if found else None
def held(self, track_id: str) -> str | None:
found = self._files.get(track_id)
return found.held if found else None
def size(self, track_id: str) -> int:
found = self._files.get(track_id)
return found.facts.size if found else 0
def track_cues(self, track_id: str) -> TrackCues | None:
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
return {t: self._files[t].facts for t in track_ids if t in self._files}
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
"""A local copy (downloaded into the shared cache, like a library track)."""
if track_id not in self._files:
return None
return self.adapter.folder_audio(track_id, progress=progress)
def playlist_tree(self) -> list[PlaylistNode]:
return []
def playlist_tracks(self, node_id: str) -> list[Track] | None:
return None
@@ -0,0 +1,85 @@
"""A remote library's app-level bookkeeping — kept on the server, beside it.
Version history, export sets and the stems ledger belong with the library, not
with whichever computer opened it: they are what every computer that opens it
should see. So for a remote library these are calls to the server, and this
computer's app-data holds none of them (`services.py` is the local half).
"""
from __future__ import annotations
from ...core.adapter import NotFound
from ...history import HistoryEntry
from .client import RemoteClient
class RemoteServices:
remote = True
def __init__(self, client: RemoteClient):
self.client = client
def baseline(self) -> None:
pass # the server records its own "as I found it" version when it opens
def commit_save(self, adapter, outcome) -> str | None:
# The server versioned the save itself; its commit rides on the outcome.
return getattr(outcome, "commit", None)
def history(self) -> list[HistoryEntry]:
return [HistoryEntry(**e) for e in self.client.history()]
def restore(self, commit_id: str) -> bool:
try:
self.client.restore(commit_id)
except NotFound:
return False
return True
def clear_history(self) -> None:
self.client.clear_history()
def discard(self) -> None:
self.client.discard()
class RemoteSetStore:
"""`exports.use_store`'s store for a remote library: its sets, on the server."""
def __init__(self, client: RemoteClient):
self.client = client
def read(self) -> dict:
return self.client.export_sets()
def write(self, doc: dict) -> None:
self.client.put_export_sets(doc)
class RemotePending:
"""`AppState.pending` for a remote library: the SERVER keeps the ledger of
converted tracks awaiting Save (and commits, restores and recovers it
itself), so on this computer there is nothing to commit or restore — only
the server's summary to report, and its "blocking" to honour."""
items: list = []
def __init__(self, client: RemoteClient):
self.client = client
def summary(self) -> dict:
try:
return self.client.stems_pending()
except Exception: # noqa: BLE001 — out of reach: nothing known to be pending
return {"tracks": 0, "parked": 0, "bytes": 0}
def blocking(self) -> bool:
return bool(self.summary().get("tracks"))
def swapped(self) -> list:
return []
def restore(self) -> int:
return 0
def commit(self) -> dict:
return {}
@@ -0,0 +1,159 @@
"""This computer's hold on a remote library's session.
The server lets ONE computer edit at a time (`server/session.py`); this keeps
this computer's hold alive with a heartbeat every `HEARTBEAT_SECONDS`, and is
the one place that knows how this computer stands:
connected — holding the session; edits go through
reconnecting — a heartbeat failed to reach the server; edits still try
(each request walks the addresses again)
offline — several in a row failed; read-only until one gets through
taken_over — another computer took the session; read-only, for good
Coming back from `reconnecting` or `offline` needs no new sign-in: the server
renews a lapsed lease for the computer that held it, as long as nobody else
has taken it meanwhile — and says so (423) if somebody has.
The heartbeat names the batch running here, so a computer asking to take over
is told what it would cancel. Being taken over cancels it (`on_change`).
"""
from __future__ import annotations
import logging
import threading
from ...core.adapter import Unavailable
from ...remote_protocol import HEARTBEAT_SECONDS
from .client import RemoteClient, SessionLost
log = logging.getLogger(__name__)
#: Missed heartbeats in a row before `reconnecting` becomes `offline`.
OFFLINE_AFTER = 3
class RemoteSession:
def __init__(self, client: RemoteClient, *, batch_probe=None, interval: float = HEARTBEAT_SECONDS,
identity: tuple[str, str] | None = None):
self.client = client
self.interval = interval
self._batch_probe = batch_probe or (lambda: None)
#: (client_id, machine) — to take the session back when the server has
#: forgotten it (a restart) and nobody else holds it.
self.identity = identity
self.state = "connected"
self.machine: str | None = None # who took it over
#: The last thing worth telling the user that is not a state ("the
#: server restarted"), with a counter so the UI shows each once.
self.notice: str | None = None
self.notices = 0
#: Called after the session was taken back: the library must be re-read.
self.on_reacquired = None
self._failures = 0
self._listeners: list = []
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
# ---- facts ---------------------------------------------------------------------
@property
def writable(self) -> bool:
return self.state in ("connected", "reconnecting")
@property
def readonly_cause(self) -> str | None:
return {"taken_over": "taken_over", "offline": "offline"}.get(self.state)
def describe(self) -> dict:
return {"state": self.state, "via": self.client.via if self.state != "offline" else None,
"machine": self.machine, "notice": self.notice, "notices": self.notices}
def on_change(self, listener) -> None:
"""`listener(state)` after every change of state (from the heartbeat thread)."""
self._listeners.append(listener)
# ---- running -------------------------------------------------------------------
def start(self) -> None:
if self._thread is None:
self._thread = threading.Thread(target=self._run, name="konduktor-remote-heartbeat",
daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
def _run(self) -> None:
while not self._stop.wait(self.interval):
if self.state == "taken_over":
return
self.beat()
def beat(self) -> None:
try:
self.client.heartbeat(self._batch_probe())
except SessionLost as ex:
self.lost(ex.holder)
return
except Unavailable:
self._failures += 1
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
return
except Exception: # noqa: BLE001 — a bad answer is a missed beat, not a crash
log.exception("heartbeat failed")
self._failures += 1
self._set("offline" if self._failures >= OFFLINE_AFTER else "reconnecting")
return
self._failures = 0
self._set("connected")
def _take_back(self) -> bool:
"""The server no longer knows this computer's token and nobody holds the
session — it restarted (unsaved edits went with it, an accepted loss).
Take the session back without asking, unless the library now holds
someone ELSE's unsaved edits: those deserve the Save / Discard question
that reopening asks, so then this stays read-only."""
if self.identity is None:
return False
try:
got = self.client.acquire(*self.identity)
except Exception: # noqa: BLE001 — someone got there first, or no server
return False
if got.get("pending_edits"):
self.client.release()
return False
if self.on_reacquired is not None:
try:
self.on_reacquired()
except Exception: # noqa: BLE001
log.exception("re-reading the library after a reconnect failed")
self.notice = "The server restarted — any edits not yet saved there were lost"
self.notices += 1
self._failures = 0
self._set("connected")
return True
def lost(self, holder: dict | None) -> None:
"""Another computer holds the session — from a heartbeat, or a command
the server refused with 423. Nobody holding it means the server forgot
this computer's token (a restart): take it back if that is safe."""
if holder is None and self.state != "taken_over" and self._take_back():
return
self.machine = (holder or {}).get("machine")
self._set("taken_over")
def reached(self) -> None:
"""A request got through: whatever the heartbeat last saw, the server is there."""
if self.state in ("reconnecting", "offline"):
self._failures = 0
self._set("connected")
def _set(self, state: str) -> None:
with self._lock:
if state == self.state:
return
self.state = state
for listener in list(self._listeners):
try:
listener(state)
except Exception: # noqa: BLE001
log.exception("remote session listener failed")
+27 -1
View File
@@ -15,7 +15,7 @@ from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from ...core.adapter import InvalidCommand, NotFound, Unsupported
from ...core.adapter import InvalidCommand, NotFound, Unsupported, local_audio_facts
from ...core.capabilities import Capabilities
from ...core.model import PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping
@@ -131,6 +131,10 @@ class TraktorAdapter:
with _translate():
self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
with _translate():
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents. The adapter resolves each id to its
native entry kind, so callers never see Traktor's STEM/TRACK split."""
@@ -146,6 +150,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)
@@ -377,12 +387,22 @@ class TraktorAdapter:
def audio_path(self, track_id: str):
return self._store.audio_path(track_id)
def audio_facts(self, track_ids: list[str]):
return local_audio_facts(self, track_ids)
def set_path_mapping(self, mapping: PathMapping) -> None:
self._store.set_path_mapping(mapping)
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
self._store.set_session_mappings(mappings)
def set_write_stored_paths(self, enabled: bool) -> None:
"""OPTIONAL: write a file added through the path mapping in the
library's STORED form (see `pathmap.stored_form`). A Konduktor server
holding a collection made on another computer turns this on, so a
track uploaded there is stored as that computer would have stored it."""
self._store.set_write_stored_paths(enabled)
def unresolved_path_groups(self) -> list[PathGroup]:
return self._store.unresolved_path_groups()
@@ -405,6 +425,12 @@ class TraktorAdapter:
def dirty(self) -> bool:
return self._store.dirty
def edit_summary(self) -> str:
"""OPTIONAL: this session's unsaved edits in one line ("edited 3
tracks; added 6 hotcues") — what a server tells the next computer to
open the library about the edits it is inheriting."""
return self._store._edit_summary()
def save(self):
outcome = self._store.save()
self._rebuild() # save() re-parses, so every object identity changed
@@ -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"],
@@ -73,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
"need a manual Import Cover Art to show up."
),
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
playlists=PlaylistCapabilities(
folders=True, smart="read_only", reorder=True,
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
# itself adds a track twice when asked.
duplicates=True,
),
save=SaveCapabilities(
app_name="Traktor",
library_label="collection.nml",
+5 -9
View File
@@ -106,14 +106,10 @@ class TraktorExporter:
return WrittenLibrary(library=library)
def _write_playlists(self, adapter, payload: ExportPayload, moved: dict) -> None:
"""Recreate the tree under one folder named after the export.
Nested under the export's own name for the same reason import nests a
drive's playlists under the drive's name: a collection swapped onto
another machine should say where its playlists came from.
"""
root = adapter.create_folder(payload.name)
folders: dict[tuple[str, ...], str] = {(): root}
"""Recreate the tree — at the top level, or with `payload.root_folder`
under one folder named after the export (None = the top level)."""
root = adapter.create_folder(payload.name) if payload.root_folder else None
folders: dict[tuple[str, ...], str | None] = {(): root}
for playlist in payload.playlists:
parent = self._folder_for(adapter, folders, tuple(playlist.folders), root)
@@ -128,7 +124,7 @@ class TraktorExporter:
adapter.set_playlist_entries(node_id, loose)
@staticmethod
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str) -> str:
def _folder_for(adapter, folders: dict, path: tuple[str, ...], root: str | None) -> str | None:
"""Create (once) the folder chain a playlist sits under, and return it."""
for depth in range(1, len(path) + 1):
branch = path[:depth]
@@ -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),
+166 -6
View File
@@ -35,6 +35,7 @@ from traktor_nml_utils.models.collection import (
Entrytype,
GridType,
Infotype,
MusicalKeytype,
Locationtype,
Nodetype,
Playlisttype,
@@ -48,13 +49,14 @@ from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import FileTagResult, InvalidCommand, SaveOutcome, StemSwapResult
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup
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.
@@ -77,6 +79,9 @@ class TraktorStore:
self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping()
# Write a file added through a mapping in the library's STORED form
# (`pathmap.stored_form`) — a Konduktor server sets this.
self._write_stored_paths = False
# Mappings the user confirmed in the open-time missing-files check.
# Session-only: never saved, re-derived on every open.
self._session_mappings: list[PathMapping] = []
@@ -99,6 +104,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(
@@ -154,11 +160,13 @@ class TraktorStore:
can_reorder=True,
can_rename=True,
can_delete=True,
can_move=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, kind="smart"
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
can_move=True,
)
path = parent_path + [name]
return PlaylistNode(
@@ -169,6 +177,7 @@ class TraktorStore:
can_contain_children=True,
can_rename=True,
can_delete=True,
can_move=True,
)
@staticmethod
@@ -342,6 +351,79 @@ class TraktorStore:
self._note("playlist-delete", node.name)
self.dirty = True
def _find_node(self, node_id: str) -> Nodetype:
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
smart playlist's `sl:` path (its folder path plus its own name)."""
if node_id.startswith("fld:"):
return self._find_folder(node_id)
if node_id.startswith("sl:"):
*folders, name = node_id[len("sl:"):].split("/")
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
match = next(
(c for c in self._children(parent)
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
None,
)
if match is None:
raise PlaylistError(f"Smart playlist not found: {node_id}")
return match
node = self._find_playlist_node(node_id)
if node is None:
raise PlaylistError(f"Playlist not found: {node_id}")
return node
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children (counted without
it) and return its id afterwards — a folder's and a smart playlist's id
is their path of names, so moving one changes it (and its subtree's).
A folder or smart playlist landing beside a namesake of its own kind is
refused, as rename refuses it: the two paths would be one, and one of
them unaddressable. Playlists are UUIDs, so their names may repeat."""
with self._lock:
node = self._find_node(node_id)
if node is self._root():
raise PlaylistError("Cannot move the root folder")
dest = self._find_folder(parent_id)
if dest is node or any(n is dest for n in self._iter_nodes(node)):
raise PlaylistError("A folder cannot be moved into itself")
is_folder = node.playlist is None and node.smartplaylist is None and (
node.type or "FOLDER") == "FOLDER"
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
if is_folder or is_smart:
kind = "folder" if is_folder else "smart playlist"
for c in self._children(dest):
same_kind = (
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
and c.smartplaylist is None
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
if c is not node and same_kind and c.name == node.name:
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
source = self._find_parent_of(node)
if source is None:
raise PlaylistError("Cannot move a top-level node")
siblings = [c for c in self._children(dest) if c is not node]
index = max(0, min(int(index), len(siblings)))
if source is dest and self._children(dest).index(node) == index:
return self._node_id(node, parent_id) # already there
source.subnodes.node.remove(node)
source.subnodes.count = len(source.subnodes.node)
if dest.subnodes is None:
dest.subnodes = Subnodestype(node=[], count=0)
dest.subnodes.node.insert(index, node)
dest.subnodes.count = len(dest.subnodes.node)
self._note("playlist-move", node.name)
self.dirty = True
return self._node_id(node, parent_id)
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
if node.playlist is not None:
return node.playlist.uuid
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
with self._lock:
node = self._find_playlist_node(playlist_uuid)
@@ -399,6 +481,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.
@@ -428,7 +573,7 @@ class TraktorStore:
# Read before the lock: it opens the file.
stems = nml_stems_for(audio_path)
with self._lock:
volume, dir_, file = os_path_to_location(Path(audio_path))
volume, dir_, file = os_path_to_location(self._stored(Path(audio_path)))
key = f"{volume}{dir_}{file}"
if key in self._entry_by_key:
raise PlaylistError(
@@ -443,7 +588,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 +614,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,
)
@@ -988,6 +1139,15 @@ class TraktorStore:
with self._lock:
self._path_mapping = mapping
def set_write_stored_paths(self, enabled: bool) -> None:
self._write_stored_paths = bool(enabled)
def _stored(self, os_path: Path) -> Path:
"""Where a NEW entry points, as the collection stores paths."""
if not self._write_stored_paths:
return Path(os_path)
return stored_form(Path(os_path), [self._path_mapping, *self._session_mappings])
def set_session_mappings(self, mappings: list[PathMapping]) -> None:
"""Set the mappings confirmed for this session (applied at resolve time)."""
with self._lock:
@@ -1283,7 +1443,7 @@ class TraktorStore:
if swap.mode not in ("repoint", "add"):
raise PlaylistError(f"Unknown stem swap mode: {swap.mode}")
seen_ids.add(swap.track_id)
loc = os_path_to_location(Path(swap.stem_path))
loc = os_path_to_location(self._stored(Path(swap.stem_path)))
new_key = "".join(x or "" for x in loc)
if new_key in self._entry_by_key or new_key in new_keys:
raise PlaylistError(
+82 -23
View File
@@ -28,11 +28,12 @@ import os
import threading
from pathlib import Path
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
from . import adapters, library_id, prefs # noqa: F401 — registers adapters
from .core import registry
from .core.adapter import LibraryAdapter
from .core.pathmap import PathMapping
from .relocation import RelocationCheck
from .services import LibraryServices, LocalServices
class AppState:
@@ -61,6 +62,18 @@ class AppState:
# and what the last open's crash recovery did about any left over.
self.pending = None
self.recovery: dict | None = None
# Where this library's history (and, for a remote, its export sets and
# ledger) are kept — see `services.py`.
self.services: LibraryServices | None = None
# The open remote's connection (`adapters/remote/session.py`), or None
# for a library on this computer.
self.remote = None
# …and the saved remote it was opened through (`adapters/remote/config.py`).
self.remote_config = None
# Called with the adapter at the end of every open (and so after a
# restore, which reopens): how a Konduktor SERVER re-applies the path
# mapping its configuration names, which lives in no prefs file.
self.open_hooks: list = []
@property
def loaded(self) -> bool:
@@ -120,16 +133,7 @@ class AppState:
# write-ahead log beside a file another process replaces is how a SQLite
# library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact.
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
self._release_previous()
# Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path))
@@ -161,9 +165,55 @@ class AppState:
# Started after the saved mapping is applied, so a volume that mapping
# already fixes is not asked about.
self.relocation = RelocationCheck(adapter)
# Version history: record an "as I found it" baseline (deduped, so
# re-opening an unchanged library is a no-op). Best-effort.
history.ensure_baseline(path)
self.services = LocalServices(path)
self.services.baseline()
for hook in self.open_hooks:
hook(adapter)
def _release_previous(self) -> None:
previous = self.adapter
# Leaving a library discards its unsaved edits (the UI has confirmed), so
# a stem conversion's parked originals go back under their own names.
if self.pending is not None and self.pending.items:
self.pending.restore()
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
if self.remote is not None and self.library_id:
# A remote library's export sets were the server's; stop asking it.
from . import exports
exports.use_store(self.library_id, None)
self.adapter = None
self.remote = None
self.remote_config = None
def open_remote(self, opened) -> None:
"""Make an already-connected remote library THE library.
`opened` is what `adapters.remote.open_remote` returns: the adapter, its
services and session, and the server's identity for the library. The
connection (handshake, version check, session) is made BEFORE this, so
a refusal leaves the current library intact, as a failed parse does.
"""
with self.mutation:
self._release_previous()
self.path = opened.path
self.adapter = opened.adapter
self.services = opened.services
self.remote = opened.session
self.remote_config = opened.remote
# The server's id for the library: export sets are keyed by it, and
# they live on the server too, so every computer sees the same ones.
self.library_id = opened.library_id
# The server keeps its own ledger of converted tracks; nothing of a
# remote library's lives in this computer's.
self.pending = opened.pending
self.recovery = None
# A remote library's files are not on this computer's drives.
self.relocation = None
def save(self):
"""Write the library, then record the saved bytes in version history.
@@ -178,15 +228,7 @@ class AppState:
def _save(self):
outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
# capabilities rather than this module knowing which platforms those are.
versioned = self.adapter.capabilities().save.history
commit = None
if versioned and outcome.snapshot is not None:
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
commit = self.services.commit_save(self.adapter, outcome)
# The swap is now on disk: what it replaced can go. After the library
# write, so a failed save deletes nothing; here rather than in the save
# route, because import and path remap save too.
@@ -209,8 +251,25 @@ class AppState:
with self.mutation:
if self.pending is not None and self.pending.items:
self.pending.restore()
if self.services is not None and self.services.remote:
# The server holds the edits; it is what drops them.
self.services.discard()
self.adapter.reload()
def restore_version(self, commit_id: str) -> bool:
"""Write a past version back as a new save and re-read the library.
False when the version is unknown."""
assert self.adapter is not None and self.services is not None
with self.mutation:
if not self.services.restore(commit_id):
return False
if self.services.remote:
# The server reopened its own library; follow it.
self.adapter.reload()
else:
self._open(self.path) # rebuild read + edit models from the restored file
return True
STATE = AppState()
+78
View File
@@ -65,6 +65,60 @@ class SaveOutcome:
tag_results: list = field(default_factory=list)
@dataclass(frozen=True)
class AudioFacts:
"""One track's audio file as its library's host sees it — WITHOUT reading it.
`key` is the file's path on the machine that holds it (a string, because on
a remote library that is not this machine), `size` and `mtime_ns` its stat.
Together they name one version of one file: what an export's manifest
records, what the analysis cache keys on, and how a downloaded copy is
recognised. Callers that only need a file's IDENTITY ask for these rather
than `audio_path`, which on a remote library means downloading it.
"""
key: str
size: int
mtime_ns: int
def local_audio_facts(adapter, track_ids) -> dict[str, AudioFacts]:
"""`audio_facts` for a library whose files are on this machine: stat each
`audio_path`. A track whose file is missing is left out."""
out: dict[str, AudioFacts] = {}
for track_id in track_ids:
try:
path = adapter.audio_path(track_id)
if path is None:
continue
st = Path(path).stat()
except (OSError, AdapterError):
continue
if not Path(path).is_file():
continue
out[track_id] = AudioFacts(key=str(path), size=st.st_size, mtime_ns=st.st_mtime_ns)
return out
@dataclass
class PreparedAnalysis:
"""What adding a track would otherwise decode the file to learn.
A platform that must ANALYSE what it adds (Rekordbox: the waveform and grid
live in its ANLZ files) decodes each file in `add_tracks`. When the library
lives on a server that never decodes audio, the client does that work on
its own copy and the result travels with the track. `measured` is a
`core.waveform.Analysis` measured with the file's own time-base lead,
`markers` the detected grid (empty: none found) and `key` the detected
`core.key_detect.KeyResult` (None: not asked for, or none found). Absent,
the adapter decodes as before.
"""
measured: object
markers: list = field(default_factory=list)
key: object | None = None
@dataclass
class NewTrack:
"""A track to ADD to a library, described generically.
@@ -93,6 +147,9 @@ class NewTrack:
# For a platform that keeps its own copy of the art (Rekordbox); one that
# reads the file's tags (Traktor) ignores it.
art: tuple[bytes, str] | None = None
# Precomputed analysis for a platform that would otherwise decode the file
# (see `PreparedAnalysis`); ignored by one that does not analyse.
analysis: PreparedAnalysis | None = None
@dataclass(frozen=True)
@@ -153,6 +210,11 @@ class Unsupported(AdapterError):
"""The platform cannot represent this edit at all."""
class Unavailable(AdapterError):
"""The library's host cannot be reached, or no longer lets this computer
write (a library held by a server, taken over by another computer)."""
@runtime_checkable
class LibraryAdapter(Protocol):
"""One open library. Stateful; exactly one is loaded at a time."""
@@ -172,6 +234,7 @@ class LibraryAdapter(Protocol):
def facets(self) -> Facets: ...
def stats(self, playlist_count: int) -> Stats: ...
def playlist_tree(self) -> list[PlaylistNode]: ...
def playlist_count(self) -> int: ...
def playlist_entries(self, node_id: str) -> list[str] | None: ...
def playlist_tracks(self, node_id: str) -> list[Track] | None: ...
def track_cues(self, track_id: str) -> TrackCues | None: ...
@@ -184,6 +247,12 @@ class LibraryAdapter(Protocol):
def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
def rename_playlist(self, node_id: str, name: str) -> None: ...
def delete_playlist(self, node_id: str) -> None: ...
# Move a node (playlist, folder or smart playlist) to `index` among
# `parent_id`'s children (None = the top level), counted with the moved
# node left out. Returns the node's id AFTER the move: an id is opaque, and
# on a platform that addresses a folder by its path it changes. A folder
# cannot go into itself or a descendant (InvalidCommand).
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
# ---- commands: adding tracks ----------------------------------------
@@ -223,6 +292,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: ...
@@ -256,7 +329,12 @@ class LibraryAdapter(Protocol):
def set_grid_lock(self, track_id: str, locked: bool) -> TrackCues: ...
# ---- audio / paths ---------------------------------------------------
# A READABLE file on this machine — which, for a library held by a server,
# means downloading it. Anything that only needs to know WHICH file a track
# is (an export plan, "is this already in the library?") asks `audio_facts`
# instead, which never reads the file and never downloads.
def audio_path(self, track_id: str) -> Path | None: ...
def audio_facts(self, track_ids: list[str]) -> dict[str, AudioFacts]: ...
def set_path_mapping(self, mapping: PathMapping) -> None: ...
# The open-time missing-files check (`core/relocate.py`): the stored volumes
# in which NO track resolves, and the mappings the user confirmed for them —
+52
View File
@@ -0,0 +1,52 @@
"""The analysis a platform that ANALYSES what it adds needs for one new track.
Rekordbox draws a new track's waveform and grid from its ANLZ files, so adding a
track means decoding it once: the waveform measured on the platform's own clock
(`lead`, read from the file's header by that platform) plus a detected grid and
key when the track brings none. One definition, used both by the adapter (a library on
this computer) and by the client of a library held by a server — which never
decodes audio, so the client measures its own copy and sends the result
(`PreparedAnalysis`) with the track.
"""
from __future__ import annotations
import logging
from pathlib import Path
from .adapter import PreparedAnalysis
from .model import GridMarker
def prepare(path: Path, *, lead: float, detect: bool = True,
detect_key: bool = False) -> PreparedAnalysis:
"""Decode `path` once: its waveform at `lead`, and (with `detect`) a grid,
(with `detect_key`) a key."""
from . import grid_detect, waveform
samples = waveform.decode(Path(path))
measured = waveform.analyse_samples(samples, lead=lead)
markers: list[GridMarker] = []
if detect and samples is not None:
try:
found = grid_detect.detect_grid(str(path), y=samples, sr=waveform.SR)
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
key = None
if detect_key and samples is not None:
from . import key_detect
try:
key = key_detect.detect_key_samples(samples, waveform.SR)
except Exception: # noqa: BLE001 - a missing key is not worth failing an add over
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
return PreparedAnalysis(measured=measured, markers=markers, key=key)
def with_key(track, key):
"""`track` (a generic `Track`) with the detected `key` if it has none of its
own. A key the track already carries (its tags, its source library) is
never second-guessed."""
if key is None or getattr(track, "key_wheel", None) is not None:
return track
return track.model_copy(update={"key": key.name, "key_wheel": key.wheel, "key_mode": key.mode})
+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:
+28 -1
View File
@@ -25,7 +25,12 @@ from pydantic import BaseModel
# `browsing` is an editable library opened only to READ alongside the loaded one
# (a OneLibrary stick in the sidebar's Devices): the way to edit it is to open it
# as THE library, which one SaveBar and one dirty state can then follow.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library", "browsing"]
# `taken_over` is a library held by a server that another computer has taken
# over; `offline` one whose server cannot be reached. Both are temporary, and
# both mean "nothing you do here can be saved" until the session is back.
ReadonlyCause = Literal[
"platform_incomplete", "cloud_synced", "not_in_library", "browsing", "taken_over", "offline",
]
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
@@ -78,18 +83,39 @@ 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.
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
artwork: bool = False
artwork_note: str | None = None
# Whose filesystem an import destination is on. "host": this computer's,
# browsed with the ordinary file browser. "library": the machine that holds
# the library (a server), whose folders are listed through the library —
# added audio is UPLOADED there.
audio_destination: Literal["host", "library"] = "host"
# Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all.
reference: bool = True
class PlaylistCapabilities(BaseModel):
folders: bool = False
smart: Literal["none", "read_only"] = "none"
reorder: bool = False
# A playlist can hold the same track more than once. Where it cannot, a
# drop of tracks already there skips them rather than asking.
duplicates: bool = False
class PathCapabilities(BaseModel):
# Path mapping, path rewriting and the open-time missing-files check apply.
# False for a library held by a server: its mapping is the server's own
# configuration, and this computer's drives are not where its files are.
remappable: bool = True
class SaveCapabilities(BaseModel):
@@ -126,4 +152,5 @@ class Capabilities(BaseModel):
grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities()
playlists: PlaylistCapabilities = PlaylistCapabilities()
paths: PathCapabilities = PathCapabilities()
save: SaveCapabilities
+7 -1
View File
@@ -94,8 +94,14 @@ class ExportPayload:
tracks: list[ExportTrack] = field(default_factory=list)
playlists: list[ExportPlaylist] = field(default_factory=list)
#: The export's name, used for the folder its playlists are nested under.
#: The export's name, used for the folder its playlists are nested under
#: when `root_folder` is set.
name: str = "Export"
#: Nest the whole playlist tree (and "Other") in one folder named `name`.
#: Off — the default, a Konduktor setting — the playlists sit at the
#: library's top level: an export is a library of its own, so a folder
#: saying where it came from is one more click at the gig.
root_folder: bool = False
#: Called by a writer before each slow step (e.g. decoding a track for its
#: waveform) with a message for the status bar, and — for a per-track loop —
#: `step` of `of`, which drives the progress bar. RAISES when the user has
+107 -6
View File
@@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
them — so a click on a drive root never walks the whole drive. A folder
DROPPED onto the window is the exception (`FolderScanner.dropped`): the user
asked for everything in it, so it recurses, capped at `MAX_DROPPED`.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
@@ -26,6 +28,7 @@ from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass, field
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
@@ -150,6 +153,11 @@ class FolderSource:
def audio_path(self, track_id: str) -> Path | None:
return Path(track_id) if track_id in self._by_id else None
def audio_facts(self, track_ids: list[str]):
from .adapter import local_audio_facts
return local_audio_facts(self, track_ids)
def playlist_tree(self) -> list[PlaylistNode]:
return []
@@ -160,17 +168,88 @@ class FolderSource:
return capabilities_for(self.path)
# A drop of a whole drive must not read tags for hours: past this many audio
# files the rest are left out and the answer says so.
MAX_DROPPED = 20_000
@dataclass
class Dropped:
"""What a drop onto the window resolved to."""
tracks: list[Track] = field(default_factory=list)
# Dropped FILES that are not audio this library can hold (or are gone).
# Non-audio inside a dropped folder is not counted: an album folder's
# cover and cue sheet are not something the user asked to add.
skipped: int = 0
# More than MAX_DROPPED audio files: the rest were left out.
truncated: bool = False
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
found by a scan — or dropped onto the window by the user — so the audio
route cannot be used to read an arbitrary path off the disk, only audio the
user has browsed to or handed over.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
# Files dropped one by one: their folder was never scanned (and is not
# cached as if it had been — a partial listing would hide its other
# files from the sidebar), so each is held on its own.
self._files: dict[str, Track] = {}
def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped:
"""Resolve paths dropped onto the window: folders RECURSIVELY (hidden
and OS-housekeeping folders left out, as the tree leaves them out),
files as themselves. Every audio file found becomes addable and
playable through the folder routes, exactly as if it had been browsed."""
wanted = {f.lower() for f in formats}
out = Dropped()
seen: set[str] = set()
def take(tracks: list[Track]) -> bool:
for t in tracks:
if t.id in seen:
continue
if len(out.tracks) >= limit:
out.truncated = True
return False
seen.add(t.id)
out.tracks.append(t)
return True
for raw in paths:
path = Path(raw).expanduser()
if path.is_dir():
for folder in _walk(path):
if not audio_files(folder, formats):
continue
if not take(self.scan(folder, formats).tracks):
return out
elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path):
track = self._file_track(path)
if not take([track]):
return out
else:
out.skipped += 1
return out
def _file_track(self, path: Path) -> Track:
key = str(path)
with self._lock:
hit = self._cache.get(str(path.parent))
known = hit[2].track(key) if hit is not None else None
if known is not None:
return known
track = read_track(path)
with self._lock:
self._files[key] = track
return track
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
@@ -193,10 +272,32 @@ class FolderScanner:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
loose = self._files.get(track_id)
if hit is not None and hit[2].track(track_id) is not None:
return hit[2]
if loose is not None:
return FolderSource(Path(folder), [loose])
return None
def clear(self) -> None:
with self._lock:
self._cache.clear()
self._files.clear()
def _walk(root: Path):
"""`root` and every visible folder under it, depth first, sorted by name."""
yield root
try:
with os.scandir(root) as it:
subs = []
for entry in it:
try:
if entry.is_dir(follow_symlinks=False) and not is_hidden(entry):
subs.append(Path(entry.path))
except OSError:
continue
except OSError:
return
for sub in sorted(subs, key=lambda p: p.name.lower()):
yield from _walk(sub)
+52 -13
View File
@@ -213,24 +213,71 @@ def detect_grid(
*,
y: np.ndarray | None = None,
sr: int = _SR,
bpm: float | None = None,
anchor: float | None = None,
) -> GridResult:
"""Detect a track's constant tempo and first beat.
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
Either half can be held fixed — the Analyze dialog's BPM and Grid ticks:
- ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no
round-BPM snap — and only where its beats fall is found. For a BPM the
user trusts (typed, or a store's) and a grid that sits off the beat.
- ``anchor`` given ("BPM" alone): the tempo is detected and the anchor
returned as given, so the grid's downbeat stays where the user put it.
``drift_ms`` is then measured against THAT anchor: large means the kept
anchor does not sit on the detected beat.
"""
if bpm is not None and anchor is not None:
raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect")
if bpm is not None and not (20.0 <= bpm <= 400.0):
raise ValueError(f"Not a usable BPM: {bpm}")
if y is None:
import librosa
y, sr = librosa.load(audio_path, sr=sr, mono=True)
from . import waveform
y, sr = waveform.load(audio_path, sr=sr)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / sr
if duration < 1.5:
raise ValueError("Track is too short to detect a tempo")
lo, hi = bpm_range
low = _onset(_band_env(y, sr, 30.0, 150.0))
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
if bpm is not None:
period = 60.0 / bpm
if not np.isfinite(attack).all() or attack.max() <= 0:
raise ValueError("No onsets found")
phase = _phase(low, attack, period)
return GridResult(
bpm=float(bpm),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1),
)
found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration)
period = 60.0 / found_bpm
if anchor is not None:
return GridResult(
bpm=round(found_bpm, 4),
anchor=float(anchor),
duration=duration,
drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1),
)
return GridResult(
bpm=round(found_bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]:
"""(bpm, phase, drift) — the tempo search, octave rule and round snap."""
lo, hi = bpm_range
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
o_tempo = low + mid + 0.5 * full
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
@@ -260,15 +307,7 @@ def detect_grid(
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
phase = _phase(low, attack, 60.0 / bpm)
drift = _drift(attack, bpm, phase)
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
period = 60.0 / bpm
return GridResult(
bpm=round(bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
return _snap_round(low, attack, bpm, phase, drift, duration)
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
+63
View File
@@ -0,0 +1,63 @@
"""What an analysis does to one track's grid, given the BPM / Grid ticks.
One pure function, so the batch, the dialog's counts and the tests cannot come
to mean different things. Decided with the user (2026-10-04, see
`.claude/discussions/discuss-key-analysis-2026-10-04.md`):
- BPM + Grid: a full analysis. A track that already has a grid is replaced
only when the user ticked "Replace" — a grid may hold hand edits.
- BPM alone: re-detect the tempo, KEEP the anchor (the first marker).
- Grid alone: KEEP the BPM, find only where the beats fall.
- With one tick, adjusting the existing grid is the point, so "Replace" does
not apply; a track with nothing to keep (no grid / no BPM) is analysed in
full rather than skipped — one tick never leaves a track worse off.
- A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its
tempo changes are exactly what one constant tempo would flatten.
- A locked grid is skipped whatever is ticked.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Sequence
Action = Literal["none", "full", "bpm", "phase", "skip"]
SkipReason = Literal["locked", "existing", "flexible"]
@dataclass(frozen=True)
class GridStep:
action: Action
reason: SkipReason | None = None
hold_bpm: float | None = None # "phase": the tempo kept
hold_anchor: float | None = None # "bpm": the anchor kept (seconds)
def plan_grid(
*,
bpm: bool,
grid: bool,
markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order
track_bpm: float | None,
locked: bool,
replace_existing: bool,
) -> GridStep:
if not (bpm or grid):
return GridStep("none")
if locked:
return GridStep("skip", "locked")
ordered = sorted(markers, key=lambda m: m.start)
if bpm and grid:
if ordered and not replace_existing:
return GridStep("skip", "existing")
return GridStep("full")
if len(ordered) > 1:
return GridStep("skip", "flexible")
if bpm: # BPM alone
if not ordered:
return GridStep("full")
return GridStep("bpm", hold_anchor=float(ordered[0].start))
# Grid alone
held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None)
if not held or held <= 0:
return GridStep("full")
return GridStep("phase", hold_bpm=held)
+184
View File
@@ -0,0 +1,184 @@
"""Musical key detection: a small convolutional network, run in numpy.
Why a network and not key profiles. The classic method — fold the spectrum
into a 12-bin chroma vector and correlate it with a major / minor template —
was benchmarked first on GiantSteps (604 Beatport previews, keys corrected by
hand), over Krumhansl, Temperley, Sha'ath (KeyFinder) and Faraldo's EDM
templates and every combination of octave range, compression and harmonic
filtering tried: the best got 49.5% exactly right. A template sees only how
much of each pitch class there is; a network also sees WHERE in pitch it is
(the bass line, the pad, the lead) and learns from data what states a key.
The model follows Korzeniowski & Widmer, "End-to-end musical key estimation
using a convolutional neural network" (EUSIPCO 2017): five 5x5 convolutions,
then a per-frame dense layer over the whole pitch axis — a key is NOT
pitch-invariant, so nothing pools over frequency — then 24 logits averaged
over the track. ~76 k weights per network; `key_model.npz` holds an ensemble
of three (logits averaged), trained by `backend/train_key_model.py` on the
SEPARATE GiantSteps MTG dataset. torch is used only to train: the backend
never imports it.
Measured (`bench_key_detect.py`, 2026-10-04): GiantSteps 69.4% exact, 83.4%
harmonically mixable (exact, a fifth, or the relative key), MIREX 0.758 —
about the published figure for this design. Against the key tags of 47 local
files (Traktor's analysis, not ground truth) it agrees on 62%, 77% mixable.
`confidence` tracks correctness (82% exact above 0.7, ~40% below 0.4) but even
a low one is ten times better than chance, so a key is always returned for
music; only silence and clips under 5 s get None.
Cost on a 6.7-minute track: CQT 0.1 s, the three networks 0.5 s — beside the
decode, which the grid analysis shares.
"""
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
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
FMIN_NOTE = "C1"
OCTAVES = 7 # C1..C8: the input window plus room to pitch-shift it
# The network's input: C2..C7 (65 Hz - 2.1 kHz), where bass lines, pads and
# leads state the key. The octave either side is only there so training can
# shift the window by up to six semitones.
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 = musical_key.SPELLING
@dataclass(frozen=True)
class KeyResult:
pitch_class: int # tonic, 0 = C
mode: Literal["major", "minor"]
wheel: int # Camelot position 1-12, the generic model's key
confidence: float # the network's probability for this key, 0-1
@property
def name(self) -> str:
return PITCH_NAMES[self.pitch_class] + ("m" if self.mode == "minor" else "")
def camelot_wheel(pitch_class: int, mode: str) -> int:
"""Camelot position: C major = 8B, A minor = 8A; one step = a fifth."""
return musical_key.wheel_of(pitch_class, mode)
def features(y: np.ndarray, sr: int = SR) -> np.ndarray:
"""Log-magnitude constant-Q spectrogram, (OCTAVES * 36, frames), float32.
Normalised to the track's own loudest bin, so a quiet master and a loud
one give the same picture. Training calls this same function."""
import librosa
if sr != SR:
y = librosa.resample(y, orig_sr=sr, target_sr=SR)
C = np.abs(librosa.cqt(
y, sr=SR, hop_length=HOP, fmin=librosa.note_to_hz(FMIN_NOTE),
n_bins=OCTAVES * BINS_PER_OCTAVE, bins_per_octave=BINS_PER_OCTAVE, tuning=0.0,
))
peak = float(C.max()) or 1.0
return np.log1p(1000.0 * C / peak).astype(np.float32)
@lru_cache(maxsize=1)
def _members() -> list[dict[str, np.ndarray]]:
"""The ensemble: `key_model.npz` holds N networks as `m<i>.<param>`, plus
`pool` (frequency bins averaged before the dense layer; 1 = none)."""
with np.load(_MODEL) as z:
flat = {k: z[k] for k in z.files}
pool = int(flat.pop("pool"))
members: dict[int, dict[str, np.ndarray]] = {}
for k, v in flat.items():
i, name = k.split(".", 1)
members.setdefault(int(i[1:]), {})[name] = v.astype(np.float32)
for m in members.values():
m["pool"] = np.array(pool)
return [members[i] for i in sorted(members)]
def _elu(x: np.ndarray) -> np.ndarray:
return np.where(x > 0, x, np.expm1(np.minimum(x, 0)))
def _conv5(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
"""'same' 5x5 convolution (cross-correlation, as torch's Conv2d).
x: (cin, F, T), w: (cout, cin, 5, 5) -> (cout, F, T)."""
cin, f, t = x.shape
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
out = np.empty((w.shape[0], f, t), np.float32)
for t0 in range(0, t, _TIME_CHUNK):
t1 = min(t, t0 + _TIME_CHUNK)
view = np.lib.stride_tricks.sliding_window_view(xp[:, :, t0:t1 + 4], (5, 5), axis=(1, 2))
out[:, :, t0:t1] = np.tensordot(w, view, axes=([1, 2, 3], [0, 3, 4]))
return out + b[:, None, None]
def _network(x: np.ndarray, w: dict[str, np.ndarray]) -> np.ndarray:
"""One member's 24 logits, averaged over time. x: (1, F, T)."""
n = sum(1 for k in w if k.startswith("conv") and k.endswith(".weight"))
for i in range(n):
x = _elu(_conv5(x, w[f"conv{i}.weight"], w[f"conv{i}.bias"]))
pool = int(w["pool"]) # average within a semitone
if pool > 1:
f = x.shape[1] // pool * pool
x = x[:, :f].reshape(x.shape[0], f // pool, pool, -1).mean(axis=2)
dw = w["dense.weight"][..., 0] # (hid, ch, F)
h = _elu(np.tensordot(dw, x, axes=([1, 2], [0, 1])) + w["dense.bias"][:, None])
out = w["out.weight"][:, :, 0, 0] @ h + w["out.bias"][:, None] # (24, T)
return out.mean(axis=1)
def logits(spec: np.ndarray) -> np.ndarray:
"""The ensemble's 24 logits — major C..B, then minor C..B — for a
`features()` spectrogram: each member's, averaged."""
x = spec[WINDOW[0]:WINDOW[1]][None]
return np.mean([_network(x, w) for w in _members()], axis=0)
def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
"""The key of decoded mono audio, or None for silence / too short to say."""
if y.size < sr * 5 or not np.any(y):
return None
z = logits(features(y, sr)).astype(np.float64)
p = np.exp(z - z.max())
p /= p.sum()
k = int(np.argmax(p))
pc, mode = k % 12, ("minor" if k >= 12 else "major")
return KeyResult(pc, mode, camelot_wheel(pc, mode), float(p[k]))
def with_detected_key(track, y: np.ndarray | None, sr: int):
"""`track` (a generic `Track`) with a detected key if it has none of its
own — for a file being ADDED, which is decoded anyway. A key the track
already carries (its tags, its source library) is never second-guessed,
and a detection failure leaves the track as it was: a missing key is not
worth failing an add over."""
if getattr(track, "key_wheel", None) is not None or y is None:
return track
try:
found = detect_key_samples(y, sr)
except Exception: # noqa: BLE001
import logging
logging.getLogger(__name__).warning("key detection failed", exc_info=True)
return track
if found is None:
return track
return track.model_copy(update={"key": found.name, "key_wheel": found.wheel, "key_mode": found.mode})
def detect_key(audio_path: str) -> KeyResult | None:
from . import waveform
y, sr = waveform.load(audio_path, sr=SR)
return detect_key_samples(y, sr)
Binary file not shown.
+7 -1
View File
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
can_rename: bool = False
can_delete: bool = False
can_contain_children: bool = False # a valid parent for a new playlist
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
# its siblings or moved into another folder.
can_move: bool = False
PlaylistNode.model_rebuild()
@@ -194,6 +197,9 @@ class LibraryInfo(BaseModel):
path: str
display_name: str # short label for the status bar
version: str | None = None
# Set when the library is held by a server: {id, name, via} of the saved
# remote it was opened through. None for a library on this computer.
remote: dict | None = None
class PlatformOption(BaseModel):
@@ -208,7 +214,7 @@ class PlatformOption(BaseModel):
platform: str
name: str
library_label: str
selects: Literal["file", "directory"] = "file"
selects: Literal["file", "directory", "remote"] = "file"
installed: bool = False
#: How many libraries this platform has right now; `installed` is `found > 0`.
found: int = 0
+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
+22
View File
@@ -54,6 +54,10 @@ class PathMapping:
return True
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
def inverted(self) -> "PathMapping":
"""The mapping back: a path HERE → the form the library stores."""
return PathMapping(self.to_prefix, self.from_prefix)
def apply(self, os_path: Path) -> Path:
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
path unchanged when it doesn't match (non-matching tracks untouched)."""
@@ -81,3 +85,21 @@ def common_dir_prefix(paths: list[str]) -> str:
else:
break
return "/".join(common)
def stored_form(os_path: Path, mappings) -> Path:
"""`os_path` as the library STORES its paths, when it sits under where one
of `mappings` points (the first that does).
A library opened through a mapping (a server holding a collection made on
another computer) stores every path in the other computer's form. A file
added through that mapping is written in the same form, so the library
keeps ONE convention — and still opens, mapping and all, where it was made.
"""
for mapping in mappings:
if mapping is None or mapping.empty:
continue
back = mapping.inverted()
if back.matches(os_path):
return back.apply(os_path)
return os_path
+33
View File
@@ -0,0 +1,33 @@
"""Opening a file for reading with PyAV, on every PyAV version the app ships.
A file whose tags are not valid UTF-8 must still open: it is still audio.
PyAV 18 decodes tags strictly by default and raises UnicodeDecodeError at open
unless given `metadata_errors="ignore"`; PyAV 19 REMOVED that keyword (passing
it is a TypeError) and opens such a file as it is, the bad bytes as surrogates.
Measured on both with a generated M4A and MP3 whose title is invalid UTF-8.
The keyword once went straight into `av.open`, which worked on the dev venv's
18.1 while CI's fresh install took 19.0.1: every stem file then failed to open
in the released app, and the deck played stem tracks as the mix. Every read
goes through `open_input`, so the difference lives in one place.
"""
from __future__ import annotations
from functools import cache
from pathlib import Path
@cache
def _takes_metadata_errors() -> bool:
import av
return int(av.__version__.split(".")[0]) < 19
def open_input(path: Path | str):
"""`av.open(path)` for reading, tolerant of tags that are not UTF-8."""
import av
if _takes_metadata_errors():
return av.open(str(path), metadata_errors="ignore")
return av.open(str(path))
+2
View File
@@ -105,6 +105,8 @@ class TrackIndex:
if (t.artist and ql in t.artist.lower())
or (t.title and ql in t.title.lower())
or (t.album and ql in t.album.lower())
or (t.comment and ql in t.comment.lower())
or (t.comment2 and ql in t.comment2.lower())
]
if genre:
items = [t for t in items if t.genre == genre]
+125 -28
View File
@@ -37,15 +37,17 @@ from __future__ import annotations
import fractions
import json
import queue
import struct
import sys
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import numpy as np
from . import mp4_edit, tag_copy
from . import mp4_edit, pyav, tag_copy
SR = 44100
FRAME = 1024 # AAC-LC frame size, for both encoders
@@ -132,7 +134,7 @@ def decode(path: Path | str) -> Source:
"""Decode the first audio stream to stereo float32 at 44.1 kHz."""
import av
with av.open(str(path), metadata_errors="ignore") as container:
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
codec = stream.codec_context.name
bit_rate = stream.bit_rate or container.bit_rate or None
@@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source:
return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate)
#: Encoded frames each stream's thread may run ahead of the muxer.
_ENCODE_QUEUE = 64
#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio).
_ENCODE_TICK = 256
def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
checkpoint: Callable[[], None] | None) -> None:
"""Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the
muxer never buffers a whole stream (which it would if they came one after
another)."""
checkpoint: Callable[[], None] | None,
progress: Callable[[float], None] | None = None) -> None:
"""Encode the AAC streams on one thread EACH and mux them on this one, IN
LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer
never buffers a whole stream (which it would if they came one after another).
The encoders are independent and PyAV releases the GIL inside FFmpeg, so
this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's
real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded
one, the file is byte-identical. Every codec is opened and the header written
HERE before any worker starts: the first `mux()` would otherwise open (and
read) codec contexts a worker may be opening or encoding with. After that
this thread never touches a codec, and a worker never touches the container.
`checkpoint()` and `progress(fraction)` are called from this thread only.
"""
import av
n = tracks[0].shape[1]
tb = fractions.Fraction(1, SR)
offsets = range(0, n, FRAME)
stop = threading.Event()
threads: list[threading.Thread] = []
container = av.open(fp, "w", format="ipod")
try:
streams = []
@@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str,
if k:
s.disposition = 0 # present, not enabled: a plain player plays the mix
streams.append(s)
for i, offset in enumerate(range(0, n, FRAME)):
if checkpoint is not None and i % 512 == 0:
checkpoint()
for s, x in zip(streams, tracks):
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
for packet in s.encode(frame):
container.mux(packet)
for s in streams:
for packet in s.encode(None):
s.codec_context.open(strict=False)
container.start_encoding()
queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks]
def put(q: queue.Queue, item) -> bool:
while not stop.is_set():
try:
q.put(item, timeout=0.1)
return True
except queue.Full:
pass
return False # the muxer gave up: stop encoding
def work(s, x: np.ndarray, q: queue.Queue) -> None:
try:
for offset in offsets:
frame = av.AudioFrame.from_ndarray(
np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32),
format="fltp", layout="stereo",
)
frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb
if not put(q, s.encode(frame)):
return
put(q, s.encode(None))
except BaseException as ex: # noqa: BLE001 — re-raised by the muxer
put(q, ex)
def mux(q: queue.Queue) -> None:
packets = q.get()
if isinstance(packets, BaseException):
raise packets
for packet in packets:
container.mux(packet)
threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}")
for k, (s, x, q) in enumerate(zip(streams, tracks, queues))]
for t in threads:
t.start()
for i in range(len(offsets)):
if i % _ENCODE_TICK == 0:
if checkpoint is not None:
checkpoint()
if progress is not None:
progress(i / len(offsets))
for q in queues:
mux(q)
for q in queues:
mux(q) # each stream's flush
if progress is not None:
progress(1.0)
finally:
# A cancel or a failure: the workers stop at their next frame, and must
# have stopped before the container (and their codecs) are freed.
stop.set()
for t in threads:
t.join()
container.close()
@@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]]
def build(source_path: Path | str, target: Path | str, separate: Separate, *,
encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written:
encoder: str | None = None, checkpoint: Callable[[], None] | None = None,
on_encode: Callable[[float], None] | None = None) -> Written:
"""Convert `source_path` into a stem file at `target`.
`separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems
in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch
writes a `*.konduktor-partial` and renames it once the batch commits — since
nothing here infers a format from the suffix. `checkpoint()` is called between
phases and during the encode, and may raise to cancel.
phases and during the encode, and may raise to cancel. `on_encode(fraction)`
reports the encode's progress, 0 to 1 (verifying after it takes ~1 s).
"""
target = Path(target)
tick = checkpoint or (lambda: None)
@@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *,
bit_rate = choose_bitrate(source)
with open(target, "wb") as fp:
_encode(fp, [source.pcm, *stems], bit_rate=bit_rate,
encoder=encoder or default_encoder(), checkpoint=checkpoint)
encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode)
add_stem_box(target)
tags = tag_copy.copy_tags(source_path, target)
verify(target, source)
@@ -356,17 +423,14 @@ def stem_layout(path: Path | str) -> list[dict] | None:
MP3 entries in the real collection carry that element."""
import json
import av
path = Path(path)
try:
raw = read_stem_box(path)
if raw is None:
return None
return None # not a stem file: nothing to count, no decoder needed
stems = json.loads(raw).get("stems") or []
with av.open(str(path), metadata_errors="ignore") as c:
streams = len(c.streams.audio)
except (OSError, ValueError, av.FFmpegError):
streams = _audio_stream_count(path)
except (OSError, ValueError):
return None
if not stems or streams < 1 + len(stems):
return None
@@ -374,6 +438,39 @@ def stem_layout(path: Path | str) -> list[dict] | None:
for i, s in enumerate(stems)]
def _audio_stream_count(path: Path) -> int:
"""How many audio streams an MP4 holds. Through PyAV where it is installed;
otherwise (the Konduktor SERVER ships without it — it never decodes) by
counting the `trak`s whose handler is `soun`, which is what PyAV counts."""
try:
import av
except ImportError:
av = None
if av is not None:
try:
with pyav.open_input(path) as c:
return len(c.streams.audio)
except av.FFmpegError as ex:
raise ValueError(str(ex))
size = path.stat().st_size
count = 0
with open(path, "rb") as f:
moov = _find(f, 0, size, b"moov")
if moov is None:
return 0
for kind, body, end in mp4_edit._boxes(f, moov[1], moov[2]):
if kind != b"trak":
continue
mdia = _find(f, body, end, b"mdia")
hdlr = _find(f, mdia[1], mdia[2], b"hdlr") if mdia else None
if hdlr is None:
continue
f.seek(hdlr[1] + 8) # version/flags (4) + pre_defined (4), then the type
if f.read(4) == b"soun":
count += 1
return count
def _traktor_json(v) -> str:
if isinstance(v, bool):
return "true" if v else "false"
@@ -423,7 +520,7 @@ def extract_stream(path: Path | str, stream: int, fp) -> None:
"""
import av
with av.open(str(path), metadata_errors="ignore") as inp:
with pyav.open_input(path) as inp:
if not 0 <= stream < len(inp.streams.audio):
raise StemFileError(f"The file has no audio stream {stream}")
ist = inp.streams.audio[stream]
+2 -2
View File
@@ -273,8 +273,8 @@ def analyse(
if not markers:
raise ValueError("Set a beatgrid first")
if y is None:
import librosa
y, _ = librosa.load(audio_path, sr=_SR, mono=True)
from . import waveform
y, _ = waveform.load(audio_path, sr=_SR)
y = np.asarray(y, dtype=np.float32)
duration = len(y) / _SR
beats, bar0 = grid_beats(markers, duration)
+20 -10
View File
@@ -84,8 +84,8 @@ class Analysis:
return self.columns.duration
def _decode_pyav(path: Path) -> np.ndarray:
"""Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel.
def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray:
"""Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel.
The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY
OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured
@@ -94,9 +94,11 @@ def _decode_pyav(path: Path) -> np.ndarray:
"""
import av
with av.open(str(path)) as container:
from . import pyav
with pyav.open_input(path) as container:
stream = container.streams.audio[0]
resampler = av.AudioResampler(format="flt", layout="mono", rate=SR)
resampler = av.AudioResampler(format="flt", layout="mono", rate=sr)
chunks = []
for frame in container.decode(stream):
for out in resampler.resample(frame):
@@ -120,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]:
return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])]
def _decode(path: Path) -> np.ndarray | None:
def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]:
"""Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it
does. EVERY analysis decode goes through here, never `librosa.load` itself:
librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows
a `.stem.m4a` failed with "Format not recognised"."""
try:
return _decode_pyav(path)
return _decode_pyav(Path(path), sr), sr
except Exception as ex: # PyAV missing, or a file FFmpeg cannot open
log.debug("PyAV could not decode %s (%s); trying librosa", path, ex)
try:
import librosa
import librosa
y, _ = librosa.load(str(path), sr=SR, mono=True)
return y
y, _ = librosa.load(str(path), sr=sr, mono=True)
return y, sr
def _decode(path: Path) -> np.ndarray | None:
try:
return load(path)[0]
except Exception as ex: # any decoder failure: no waveform, not a failed export
log.warning("could not decode %s for a waveform: %s", path, ex)
return None
+22 -16
View File
@@ -341,11 +341,15 @@ def plan(adapter, export_set) -> ExportPlan:
resolved = exports.resolve(adapter, export_set)
tracks = [t for t in (adapter.track(i) for i in resolved.track_ids) if t is not None]
# The source is the adapter's `audio_path`, never `Track.filepath`: that is
# a DISPLAY path, which on Traktor omits the volume and ignores the active
# The source is the adapter's file, never `Track.filepath`: that is a
# DISPLAY path, which on Traktor omits the volume and ignores the active
# path mapping — so every track off the boot volume (or on a remapped
# Windows drive) read as missing and the export was "empty".
sources = {t.id: adapter.audio_path(t.id) for t in tracks}
# Windows drive) read as missing and the export was "empty". Its FACTS,
# not `audio_path`: planning must not read a file, and on a library held
# by a server reading one means downloading it. `run` fetches each file
# only when it copies it.
facts = adapter.audio_facts([t.id for t in tracks])
sources = {tid: Path(f.key) for tid, f in facts.items()}
# Mirror relative to the deepest shared folder, so the export carries the
# user's structure without carrying their home directory.
@@ -355,16 +359,10 @@ def plan(adapter, export_set) -> ExportPlan:
previous = _previous_copies(destination)
claimed: set[Path] = set()
for track in tracks:
source = sources[track.id]
exists = False
size = mtime_ns = 0
try:
exists = bool(source and source.is_file())
if exists:
st = source.stat()
size, mtime_ns = st.st_size, st.st_mtime_ns
except OSError:
exists = False
source = sources.get(track.id)
fact = facts.get(track.id)
exists = fact is not None
size, mtime_ns = (fact.size, fact.mtime_ns) if fact else (0, 0)
planned = PlannedTrack(
track_id=track.id,
title=track.title or (source.name if source else track.id),
@@ -435,9 +433,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
# ---- running -----------------------------------------------------------------
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
def run(adapter, export_set, built: ExportPlan, handle: JobHandle, *,
root_folder: bool = False) -> dict:
"""Copy what changed, then write every target's library over the audio.
`root_folder` nests the playlists in a folder named after the export (the
"Put exported playlists in a folder" setting); otherwise they sit at the top.
Rolls back EVERYTHING this run wrote on cancel or on any failure —
including the libraries of targets that had already been written when a
later one failed. What it KEPT from the previous export stays, and the
@@ -519,7 +521,10 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
done += n
handle.progress(done=done)
copy_file(planned.source_path, partial, handle, advance)
# The file to READ: on this machine that is the source itself;
# on a library held by a server, a downloaded copy of it.
local = adapter.audio_path(planned.track_id) or planned.source_path
copy_file(local, partial, handle, advance)
os.replace(partial, target)
payload_tracks.append(
ExportTrack(
@@ -544,6 +549,7 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
payload = ExportPayload(
name=export_set.name,
root_folder=root_folder,
tracks=payload_tracks,
playlists=built.playlists,
checkpoint=checkpoint,
+34 -3
View File
@@ -123,8 +123,39 @@ def _store_path(library_id: str) -> Path:
return paths.app_data_dir() / "exports" / f"{library_id}.json"
# A library whose sets are kept somewhere other than this computer's app-data —
# a library held by a server keeps them beside itself, so every computer that
# opens it sees the same sets. Each store reads and writes the WHOLE document
# (`{"library_id", "sets"}`); everything else here is unchanged by where it is.
_STORES: dict[str, object] = {}
def use_store(library_id: str, store) -> None:
"""Keep `library_id`'s sets in `store` (`read() -> dict`, `write(dict)`);
None returns them to this computer's app-data."""
if store is None:
_STORES.pop(library_id, None)
else:
_STORES[library_id] = store
def _read_doc(library_id: str) -> dict:
store = _STORES.get(library_id)
if store is not None:
return store.read()
return paths.read_json(_store_path(library_id), {})
def _write_doc(library_id: str, doc: dict) -> None:
store = _STORES.get(library_id)
if store is not None:
store.write(doc)
else:
paths.write_json(_store_path(library_id), doc)
def _load(library_id: str) -> dict[str, ExportSet]:
data = paths.read_json(_store_path(library_id), {})
data = _read_doc(library_id)
raw = data.get("sets") if isinstance(data, dict) else None
out: dict[str, ExportSet] = {}
if isinstance(raw, dict):
@@ -158,8 +189,8 @@ def _targets(values: dict) -> list[str]:
def _save(library_id: str, sets: dict[str, ExportSet]) -> None:
paths.write_json(
_store_path(library_id),
_write_doc(
library_id,
{"library_id": library_id, "sets": {k: v.as_dict() for k, v in sets.items()}},
)
+80 -11
View File
@@ -112,18 +112,19 @@ def _key(path: Path) -> str:
def _existing_files(dest) -> dict[str, str]:
"""Every audio file the destination points at → its track id.
Resolved through the adapter's own `audio_path`, which is the only answer
Resolved through the adapter's own `audio_facts`, which is the only answer
that includes the volume and the active path mapping; the projected
`filepath` is a display string and is not good enough to match on.
`filepath` is a display string and is not good enough to match on. Facts,
not `audio_path`: on a library held by a server that would download every
file it has.
"""
out: dict[str, str] = {}
for track in dest.tracks:
try:
path = dest.audio_path(track.id)
except Exception: # noqa: BLE001
path = None
if path is not None:
out.setdefault(_key(path), track.id)
try:
facts = dest.audio_facts([t.id for t in dest.tracks])
except Exception: # noqa: BLE001
return out
for track_id, fact in facts.items():
out.setdefault(_key(Path(fact.key)), track_id)
return out
@@ -190,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
return plan
def plan_on_host(source, track_ids) -> ImportPlan:
"""A plan for files that are already on the machine holding the library — a
remote library's content folder, browsed from this computer
(`source.on_library_host`). Nothing is checked on THIS disk, where those
paths mean nothing: the source says each file's size and which ones the
library already holds. Added in place (`run(reference=True)`), so there is
no destination and nothing to copy.
"""
plan = ImportPlan(destination=None)
for track_id in dict.fromkeys(track_ids):
track = source.track(track_id)
if track is None:
continue
name = track_id.replace("\\", "/").rsplit("/", 1)[-1]
plan.tracks.append(PlannedTrack(
track_id=track_id,
title=track.title or name,
source_path=Path(track_id),
size=source.size(track_id),
existing_id=source.held(track_id),
))
return plan
def _playlist_name(source, node_id: str) -> str | None:
for nid, name in _all_playlists(source):
if nid == node_id:
@@ -216,7 +241,16 @@ def _all_playlists(source) -> list[tuple[str, str]]:
return out
def free_bytes(path: Path) -> int | None:
def free_bytes(path: Path, dest=None) -> int | None:
"""Free space where the audio will land. On the DESTINATION's machine: a
library held by a server reports its own disk (`free_space`), since the
path names a folder there, not here."""
remote_free = getattr(dest, "free_space", None) if dest is not None and uploads_audio(dest) else None
if remote_free is not None:
try:
return remote_free(str(path))
except Exception: # noqa: BLE001 — unknown is not "full"
return None
try:
target = path if path.exists() else path.parent
return shutil.disk_usage(target).free
@@ -224,6 +258,15 @@ def free_bytes(path: Path) -> int | None:
return None
def uploads_audio(dest) -> bool:
"""Whether added audio is SENT to the machine holding the library (a
server) rather than copied on this one — `tracks.audio_destination`."""
try:
return dest.capabilities().tracks.audio_destination == "library" and hasattr(dest, "upload_audio")
except Exception: # noqa: BLE001
return False
def _unique_target(folder: Path, name: str, taken: set[str]) -> Path:
"""A free filename in `folder`, suffixing on collision.
@@ -298,7 +341,13 @@ def run(
"""
destination = plan.destination
places = places_audio(dest)
if not reference and not places:
# A library held by a server: each file is UPLOADED into `destination`,
# a folder on the server, instead of copied here. Nothing can be left in
# place — the server cannot see this computer's files.
uploads = not places and uploads_audio(dest)
if uploads and reference and not getattr(source, "on_library_host", False):
raise ValueError("A remote library cannot reference files on this computer")
if not reference and not places and not uploads:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -312,6 +361,8 @@ def run(
# from it leaves the half-written file behind — which then makes the next
# attempt suffix around a file that is not really there.
created: list[Path] = []
# Files sent to the server, which a failure asks it to delete again.
uploaded: list[Path] = []
taken: set[str] = set()
moved = 0
@@ -333,6 +384,19 @@ def run(
elif reference:
copied.append((planned, planned.source_path))
continue
elif uploads:
handle.progress(message=f"Uploading {planned.title}")
def sent(n: int) -> None:
handle.raise_if_cancelled() # mid-file: the server drops the partial
bump(n)
# The server never overwrites: a taken name comes back `-2`…
target = dest.upload_audio(planned.source_path, str(destination),
planned.source_path.name, progress=sent)
uploaded.append(target)
copied.append((planned, target))
continue
else:
target = _unique_target(destination, planned.source_path.name, taken)
handle.progress(message=f"Copying {planned.title}")
@@ -409,6 +473,11 @@ def run(
target.unlink(missing_ok=True)
except OSError:
log.debug("could not clean up %s", target, exc_info=True)
for target in uploaded:
try:
dest.delete_upload(target) # refused once the library names it
except Exception: # noqa: BLE001
log.debug("could not clean up upload %s", target, exc_info=True)
raise
+662 -88
View File
File diff suppressed because it is too large. Load diff
+68 -31
View File
@@ -3,10 +3,19 @@
A self-contained JSON file in the app's per-OS user-writable data dir (see
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
on every platform. Best-effort: any I/O error degrades to "no prefs".
**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI
runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on
launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could
catch the file empty, take it for "no prefs" and write back only its own key —
wiping everything else (measured: 249 of 300 trials of three concurrent patches).
A file that exists but will not parse is moved aside before it is replaced, so
it is never silently overwritten.
"""
from __future__ import annotations
import json
import threading
from pathlib import Path
from . import paths
@@ -16,6 +25,9 @@ from . import paths
_PREFS_PATH = paths.app_data_dir() / "userprefs.json"
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
# Reentrant: the helpers below read and write inside one critical section.
_LOCK = threading.RLock()
def _migrate_legacy() -> None:
"""One-time: if the new file is absent but a legacy package-relative one
@@ -27,29 +39,52 @@ def _migrate_legacy() -> None:
pass
def load_prefs() -> dict:
def _read(*, for_write: bool) -> dict:
"""The stored prefs, or {} if there are none or they cannot be read.
With ``for_write``, a file that exists but is not a JSON object is renamed
to ``userprefs.json.corrupt`` first, since the caller is about to replace it.
"""
try:
_migrate_legacy()
data = json.loads(_PREFS_PATH.read_text())
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
text = _PREFS_PATH.read_text()
except OSError:
return {}
try:
data = json.loads(text)
if isinstance(data, dict):
return data
except ValueError:
pass
if for_write:
try:
_PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt"))
except OSError:
pass
return {}
def load_prefs() -> dict:
with _LOCK:
return _read(for_write=False)
def save_prefs(prefs: dict) -> None:
try:
_PREFS_PATH.write_text(json.dumps(prefs, indent=2))
except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
with _LOCK:
try:
paths.write_json(_PREFS_PATH, prefs)
except OSError:
pass # non-fatal — prefs are a convenience, not a requirement
def update_prefs(patch: dict) -> dict:
"""Shallow-merge `patch` into the stored prefs and persist. Returns the
full updated prefs dict."""
prefs = load_prefs()
prefs.update(patch)
save_prefs(prefs)
return prefs
with _LOCK:
prefs = _read(for_write=True)
prefs.update(patch)
save_prefs(prefs)
return prefs
def get_path_mapping(collection_path: str) -> dict | None:
@@ -69,16 +104,17 @@ def set_path_mapping(
collection_path: str, from_prefix: str | None, to_prefix: str | None
) -> None:
"""Persist (or, when either prefix is blank, clear) a collection's mapping."""
prefs = load_prefs()
mappings = prefs.get("path_mappings")
if not isinstance(mappings, dict):
mappings = {}
if from_prefix and to_prefix:
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
else:
mappings.pop(collection_path, None)
prefs["path_mappings"] = mappings
save_prefs(prefs)
with _LOCK:
prefs = _read(for_write=True)
mappings = prefs.get("path_mappings")
if not isinstance(mappings, dict):
mappings = {}
if from_prefix and to_prefix:
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
else:
mappings.pop(collection_path, None)
prefs["path_mappings"] = mappings
save_prefs(prefs)
def get_last_collection(platform: str | None = None) -> str | None:
@@ -105,12 +141,13 @@ def get_last_collection(platform: str | None = None) -> str | None:
def set_last_collection(path: str, platform: str | None = None) -> None:
"""Record a library as the last opened, globally and for its platform."""
prefs = load_prefs()
prefs["last_collection"] = path
if platform:
by_platform = prefs.get("last_collection_by_platform")
if not isinstance(by_platform, dict):
by_platform = {}
by_platform[platform] = path
prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
with _LOCK:
prefs = _read(for_write=True)
prefs["last_collection"] = path
if platform:
by_platform = prefs.get("last_collection_by_platform")
if not isinstance(by_platform, dict):
by_platform = {}
by_platform[platform] = path
prefs["last_collection_by_platform"] = by_platform
save_prefs(prefs)
+272
View File
@@ -0,0 +1,272 @@
"""The wire contract between a Konduktor SERVER and the app that opens it.
A library held by a server (`konduktor.server`, a container on the user's NAS)
is opened on a laptop through `adapters/remote`'s `RemoteAdapter`, which speaks
THIS protocol to the server. Both sides import this module, so the method list,
which commands need the session, and the version they speak cannot drift apart.
The protocol is the `LibraryAdapter` protocol itself, not the UI's `/api`
routes: commands in, projections out. Every member of `LibraryAdapter` is
either in `RPC` or in `EXCLUDED` with the reason it does not travel —
`test_remote_protocol.py` fails the moment a new protocol member is neither, so
a command added later cannot silently be missing from remote libraries.
Arguments and results are (de)serialised with pydantic `TypeAdapter`s built
from the protocol's own type hints; the model classes are pydantic already and
the dataclasses convert. Bytes never travel as JSON — art, audio and uploads
have routes of their own.
"""
from __future__ import annotations
import base64
import inspect
import io
import typing
from dataclasses import dataclass
from functools import lru_cache
from typing import Any
from pydantic import BaseModel, TypeAdapter
from .core.adapter import LibraryAdapter
from .core.model import AutoHotcue, Track, TrackCues
#: (major, minor). A client speaks to a server of the SAME major whose minor is
#: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread.
#: 1.1 — `move_playlist` (sidebar drag and drop).
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
API_VERSION: tuple[int, int] = (1, 2)
#: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
#: address; short enough that moving to another computer after closing a lid
#: rarely needs a takeover (decided 2026-10-02).
LEASE_SECONDS = 120.0
HEARTBEAT_SECONDS = 15.0
#: The header that carries the session token on every command.
SESSION_HEADER = "X-Konduktor-Session"
def compatible(client: tuple[int, int], server: tuple[int, int]) -> str | None:
"""None when `client` can talk to `server`; otherwise which side to update."""
if client[0] != server[0]:
return "app" if server[0] > client[0] else "server"
if server[1] < client[1]:
return "server"
return None
@dataclass(frozen=True)
class Method:
name: str
#: Changes the library — needs the session token, bumps the revision.
mutating: bool
#: A property on the protocol rather than a method (`tracks`, `dirty`).
prop: bool = False
#: Parameter types where the protocol's hint is too loose to validate.
overrides: tuple[tuple[str, Any], ...] = ()
_READ = (
"capabilities", "track", "query_tracks", "facets", "stats", "playlist_tree",
"playlist_count", "playlist_entries", "playlist_tracks", "track_cues", "audio_facts",
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
)
RPC: dict[str, Method] = {
**{n: Method(n, False) for n in _READ},
"tracks": Method("tracks", False, prop=True),
"dirty": Method("dirty", False, prop=True),
**{n: Method(n, True) for n in _MUTATING},
}
RPC["place_cues"] = Method("place_cues", True, overrides=(("cues", list[AutoHotcue]),))
#: Protocol members that do not travel as RPC, and why.
EXCLUDED: dict[str, str] = {
"reload": "POST /v1/discard — a discard on the server is what drops its edits",
"save": "POST /v1/save — the server saves, versions and backs up beside the library",
"snapshot": "version history lives on the server",
"audio_path": "GET /v1/audio — a server path names no file on this computer",
"cover_art": "GET /v1/art — bytes",
"set_cover_art": "PUT /v1/art — bytes",
"apply_stem_swaps": "the server applies stem swaps itself (POST /v1/stems/publish)",
"set_path_mapping": "the server's path mapping is its own configuration",
"set_session_mappings": "the missing-files check searches THIS computer's drives",
"unresolved_path_groups": "the missing-files check searches THIS computer's drives",
"path_prefix_suggestions": "paths.remappable is false for a remote library",
"remap_preview": "paths.remappable is false for a remote library",
"remap_locations": "paths.remappable is false for a remote library",
}
def protocol_members() -> set[str]:
"""Every method and property `LibraryAdapter` declares (not its attributes)."""
out = set()
for name, value in vars(LibraryAdapter).items():
if name.startswith("_"):
continue
if inspect.isfunction(value) or isinstance(value, property):
out.add(name)
return out
def _callable(name: str):
member = getattr(LibraryAdapter, name)
return member.fget if isinstance(member, property) else member
@lru_cache(maxsize=None)
def _hints(name: str) -> dict[str, Any]:
hints = typing.get_type_hints(_callable(name))
method = RPC[name]
hints.update(dict(method.overrides))
return hints
@lru_cache(maxsize=None)
def _params(name: str) -> tuple[tuple[str, Any, Any], ...]:
"""(name, type, default) for each parameter the RPC takes."""
if name == "query_tracks":
# `**kw` on the protocol: the index's own signature is the real one.
from .core.query import TrackIndex
sig = inspect.signature(TrackIndex.query_tracks)
hints = typing.get_type_hints(TrackIndex.query_tracks)
else:
sig = inspect.signature(_callable(name))
hints = _hints(name)
out = []
for p in sig.parameters.values():
if p.name == "self" or p.kind in (p.VAR_KEYWORD, p.VAR_POSITIONAL):
continue
if name == "add_tracks" and p.name == "checkpoint":
continue # a callable; the server reports progress instead
hint = hints.get(p.name, Any)
if name == "add_tracks" and p.name == "items":
hint = list[WireNewTrack]
out.append((p.name, hint, p.default))
return tuple(out)
@lru_cache(maxsize=None)
def _adapter(hint) -> TypeAdapter:
return TypeAdapter(hint)
def dump_args(name: str, args: dict) -> dict:
"""Arguments → JSON-able, by the protocol's own types."""
out = {}
for pname, hint, _default in _params(name):
if pname in args:
out[pname] = _adapter(hint).dump_python(args[pname], mode="json")
return out
def load_args(name: str, raw: dict) -> dict:
"""JSON → validated arguments. Unknown names are refused rather than
ignored: a misspelt argument silently taking its default is a wrong edit."""
params = {p: (h, d) for p, h, d in _params(name)}
unknown = set(raw) - set(params)
if unknown:
raise ValueError(f"{name}: unknown argument(s) {sorted(unknown)}")
out = {}
for pname, (hint, default) in params.items():
if pname in raw:
out[pname] = _adapter(hint).validate_python(raw[pname])
elif default is inspect.Parameter.empty:
raise ValueError(f"{name}: missing argument {pname!r}")
return out
def _result_hint(name: str):
if name == "add_tracks":
return list[str]
return _hints(name).get("return", Any)
def dump_result(name: str, value) -> Any:
return _adapter(_result_hint(name)).dump_python(value, mode="json")
def load_result(name: str, raw) -> Any:
return _adapter(_result_hint(name)).validate_python(raw)
# ---- adding tracks -------------------------------------------------------------
class WireArt(BaseModel):
data: str # base64
mime: str
class WireNewTrack(BaseModel):
"""`NewTrack` as it crosses the wire. `audio_path` is a path ON THE SERVER —
the client uploaded the file first (`POST /v1/upload`), exactly as a local
import copies it first. The analysis is the client's (the server never
decodes audio)."""
track: Track
audio_path: str
cues: TrackCues | None = None
art: WireArt | None = None
analysis: str | None = None # base64 `.npz`, see `pack_analysis`
def pack_analysis(prepared) -> str | None:
"""A `PreparedAnalysis` → base64 `.npz` (float32: what the writers use)."""
if prepared is None or prepared.measured is None:
return None
import numpy as np
m = prepared.measured
buf = io.BytesIO()
markers = np.array([[g.start, g.bpm] for g in prepared.markers], dtype=np.float64).reshape(-1, 2)
np.savez(
buf,
rms=np.asarray(m.columns.rms, dtype=np.float32),
brightness=np.asarray(m.columns.brightness, dtype=np.float32),
columns_duration=np.float64(m.columns.duration),
bands=np.asarray(m.frames.bands, dtype=np.float32),
frames_duration=np.float64(m.frames.duration),
markers=markers,
**({} if prepared.key is None else {
"key": np.array([prepared.key.pitch_class, prepared.key.wheel,
prepared.key.mode == "minor", prepared.key.confidence], dtype=np.float64)}),
)
return base64.b64encode(buf.getvalue()).decode("ascii")
def unpack_analysis(text: str | None):
"""The inverse of `pack_analysis` → `PreparedAnalysis` (or None)."""
if not text:
return None
import numpy as np
from .core import waveform
from .core.adapter import PreparedAnalysis
from .core.model import GridMarker
with np.load(io.BytesIO(base64.b64decode(text))) as z:
measured = waveform.Analysis(
columns=waveform.Columns(rms=z["rms"], brightness=z["brightness"],
duration=float(z["columns_duration"])),
frames=waveform.Frames(bands=z["bands"], duration=float(z["frames_duration"])),
)
markers = [GridMarker(start=float(s), bpm=float(b)) for s, b in z["markers"]]
key = None
if "key" in z:
from .core.key_detect import KeyResult
pitch, wheel, minor, confidence = z["key"]
key = KeyResult(pitch_class=int(pitch), mode="minor" if minor else "major",
wheel=int(wheel), confidence=float(confidence))
return PreparedAnalysis(measured=measured, markers=markers, key=key)
+106 -2
View File
@@ -21,6 +21,20 @@ class SetEntries(BaseModel):
track_ids: list[str] # ordered; full desired contents of the playlist
class AddEntries(BaseModel):
track_ids: list[str]
# Tracks the playlist already holds: "skip" them, "add" them again (only
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip"
class MovePlaylist(BaseModel):
node_id: str
parent_id: str | None = None # None = the top level
index: int # among the new parent's children, not counting the node
class EditTrack(BaseModel):
track_id: str
fields: dict[str, str | int | None]
@@ -133,6 +147,40 @@ class AutoGridRequest(BaseModel):
track_id: str
class AnalyzeRequest(BaseModel):
"""The Analyze dialog's choices. BPM and Grid are independent halves of a
beatgrid (`core/grid_plan`); `replace_grid` only guards a FULL re-analysis
(both ticked), since with one tick adjusting the grid is the point.
`replace_key` lets detection overwrite a key the track already has."""
track_ids: list[str]
bpm: bool = True
grid: bool = True
key: bool = False
replace_grid: bool = False
replace_key: bool = False
class AnalyzePreview(BaseModel):
"""What an Analyze run WOULD do, for the dialog. Counted from the
projection, so on a platform whose marker counts are lazy (Rekordbox,
OneLibrary: 1 for any track with a BPM) a flexible grid is only found when
the run reads the real grid — it is then skipped and reported."""
total: int
tracks_to_analyze: int = 0 # tracks with anything to do (grid and key overlap)
# Grid: what `plan_grid` decides per track — full / bpm / phase / skipped.
grid_full: int = 0
grid_bpm: int = 0
grid_phase: int = 0
grid_locked: int = 0
grid_existing: int = 0 # skipped: has a grid, Replace not ticked
grid_flexible: int = 0
with_grid: int = 0 # unlocked tracks that have a grid (the Replace tick's count)
# Key.
key_set: int = 0
key_existing: int = 0 # skipped: has a key, Replace not ticked
with_key: int = 0 # tracks that have a key (the Replace tick's count)
class AutoGridBatchRequest(BaseModel):
track_ids: list[str]
# False skips tracks that already have a grid. Locked grids are skipped
@@ -187,6 +235,8 @@ class EditState(BaseModel):
stem_job: str | None = None
# What this open's crash recovery did about an interrupted conversion.
stem_recovery: dict | None = None
# A remote library's connection: {state, via, machine}. None when local.
remote: dict | None = None
# ---- collection selection ----
@@ -200,12 +250,34 @@ class CollectionStatus(BaseModel):
# 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
# Opening a remote library: the unsaved edits another computer left there,
# {machine, summary} — the user chooses to save or discard them.
pending_edits: dict | None = None
class OpenCollection(BaseModel):
path: str
class RemoteIn(BaseModel):
"""A remote's settings as the picker's form sends them. `password` may be
omitted on an edit, which keeps the saved one."""
name: str
host: str
port: int | None = None
fallback_host: str | None = None
fallback_port: int | None = None
username: str
password: str | None = None
class OpenRemote(BaseModel):
remote_id: str
# Take the session from the computer holding it (the user confirmed).
takeover: bool = False
class CollectionCandidate(BaseModel):
path: str
label: str # folder name, e.g. "Traktor 4.5.0"
@@ -435,6 +507,11 @@ class ImportRequest(BaseModel):
# Playlists land in a folder named after the drive. Null keeps them at the
# root; the default is filled in from the source's label.
folder_name: str | None = None
# Device tracks dropped on a collection playlist / an export (drag and
# drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does.
into_playlist: str | None = None
export_id: str | None = None
class Drive(BaseModel):
@@ -444,11 +521,15 @@ class Drive(BaseModel):
candidate `/api/sources` reports, attached to the drive it lives on so the
sidebar can show one row per drive rather than a device list and a drive
list that disagree about what is plugged in.
`server` is a remote library's content folder (path `server:`), listed
first while a remote library is open — the one place its music can be
browsed by folder from this computer.
"""
name: str
path: str
kind: Literal["local", "external"]
kind: Literal["local", "external", "server"]
library: SourceCandidate | None = None
@@ -456,14 +537,37 @@ class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks."""
path: str
# A file the collection holds is listed AS the collection's track (its id,
# key, rating, cues…); any other file as its own tags, id = its path.
tracks: list[Track]
# Ids (= absolute paths) of the files the collection already points at.
# Collection ids of the rows that are collection tracks.
in_collection: list[str]
# Those rows' collection id → the file's folder id, which adding takes.
files: dict[str, str] = {}
# On an external drive: a track referenced in place goes missing when the
# drive is unplugged, which the add dialog has to say.
removable: bool
class DroppedPaths(BaseModel):
"""Files and folders dropped onto the window from Finder / Explorer."""
paths: list[str]
class DroppedFiles(BaseModel):
"""What a drop resolved to: the audio in it, as a folder lists its files."""
tracks: list[Track]
# As FolderTracks: rows the collection holds are its tracks, and this maps
# their collection id back to the file's folder id, which adding takes.
files: dict[str, str] = {}
# Dropped files that are not audio the library can hold, or are gone.
skipped: int = 0
# Too many files: only the first MAX_DROPPED are here.
truncated: bool = False
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
+2
View File
@@ -0,0 +1,2 @@
"""Konduktor's server: one library, held on the machine where its audio lives,
opened from the desktop app as a "Remote" library. See `app.py`."""
+37
View File
@@ -0,0 +1,37 @@
"""`python -m konduktor.server` — what the container runs.
Configuration is the environment (see `config.py`); a bad setting stops here
with one clear line instead of serving a library that half-works.
"""
from __future__ import annotations
import logging
import sys
import uvicorn
from .config import ConfigError, from_env
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
try:
config = from_env()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
from .app import Server, create_app
server = Server(config)
try:
server.open()
except ConfigError as ex:
print(f"konduktor-server: {ex}", file=sys.stderr)
return 2
uvicorn.run(create_app(server), host=config.host, port=config.port,
log_level="info", proxy_headers=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+729
View File
@@ -0,0 +1,729 @@
"""The Konduktor SERVER: one library, held where its audio lives.
Runs in a container on the user's NAS (`server/Dockerfile`) and is opened from
the desktop app as a "Remote" library. It is deliberately NOT `main.py` behind a
password: the UI's routes would become a public contract, and half of them are
about THIS computer (its drives, its stem engine, its sticks). What it serves is
the `LibraryAdapter` protocol itself (`remote_protocol.py`), plus the few things
that are bytes — audio, art, uploads — and the app-level bookkeeping that lives
beside the library: save + backups + version history, export sets, the stems
ledger.
Lightweight by decision: the server never DECODES audio. Analysis, waveforms and
stem separation all run on the computer that opened the library; what arrives
here are the results, as ordinary commands. Its work is file IO, the native
model, tags, and header reads.
One computer at a time (`session.py`): every command carries the session token,
and anything that changes the library without it is answered 423 with who holds
it.
"""
from __future__ import annotations
import logging
import mimetypes
import os
import secrets
import shutil
import threading
from pathlib import Path
from fastapi import Body, Depends, FastAPI, Header, HTTPException, Query, Request, Response
from fastapi.responses import FileResponse, JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from .. import __version__, exports
from .. import remote_protocol as rp
from ..app_state import AppState
from ..core import registry
from ..core.adapter import (
AdapterError,
InvalidCommand,
LibraryNotSupported,
NewTrack,
NotFound,
Unsupported,
)
from ..core.folder import FolderScanner
from ..core.places import is_os_housekeeping
from .config import ConfigError, ServerConfig
from .session import InUse, Lost, SessionLock
log = logging.getLogger("konduktor.server")
#: Upload partials, published by a rename that never overwrites.
PARTIAL_SUFFIX = ".konduktor-upload"
_CHUNK = 1 << 20
class Server:
"""The open library, its session, and the revision counter clients follow."""
def __init__(self, config: ServerConfig, *, state: AppState | None = None,
lock: SessionLock | None = None):
self.config = config
self.state = state if state is not None else _default_state()
self.lock = lock or SessionLock()
self.rev = 0
self._rev_lock = threading.Lock()
#: The content folder's audio as browsed from a client's Files tree —
#: tags read once per folder state, and the gatekeeper for streaming
#: one of those files (only a file a listing found is served).
self.folders = FolderScanner()
# ---- opening ---------------------------------------------------------------
def open(self) -> None:
cfg = self.config
try:
driver = registry.driver_for(cfg.library)
except LibraryNotSupported as ex:
raise ConfigError(f"KONDUKTOR_LIBRARY: {ex}")
if driver.platform != cfg.platform:
raise ConfigError(
f"KONDUKTOR_PLATFORM is {cfg.platform!r} but {cfg.library} is a "
f"{driver.display_name} library"
)
self.state.open_hooks.append(self._configure)
self.state.open(cfg.library)
def _configure(self, adapter) -> None:
"""After every (re)open: the configured path mapping, and no missing-files
search of a container's empty drives."""
maps = self.config.path_maps
if maps:
adapter.set_path_mapping(maps[0])
adapter.set_session_mappings(list(maps[1:]))
# A file uploaded here is stored as the library stores every other
# path — so it still opens, mapping and all, where it was made.
write_stored = getattr(adapter, "set_write_stored_paths", None)
if write_stored is not None:
write_stored(True)
self.state.relocation = None
@property
def adapter(self):
if self.state.adapter is None:
raise HTTPException(503, "The library is not open")
return self.state.adapter
def bump(self) -> int:
with self._rev_lock:
self.rev += 1
return self.rev
# ---- facts -------------------------------------------------------------------
def capabilities(self):
"""The adapter's own, plus what being held by a server changes."""
caps = self.adapter.capabilities().model_copy(deep=True)
caps.tracks.audio_destination = "library"
caps.tracks.reference = False
caps.paths.remappable = False
# Nothing runs a DJ app against a library on a NAS while it is being
# saved: the "close Traktor first" warning would only confuse.
caps.save.overwrite_risk = "none"
return caps
def name(self) -> str:
return self.config.name or self.config.library.stem
def pending_edits(self, client_id: str | None = None) -> dict | None:
"""The unsaved edits someone else left, for the computer arriving."""
adapter = self.adapter
if not adapter.dirty:
return None
editor = self.lock.last_editor or {}
if client_id and editor.get("client_id") == client_id:
return None
summary = getattr(adapter, "edit_summary", None)
return {
"machine": editor.get("machine"),
"summary": (summary() if summary else "") or "unsaved changes",
}
def confine(self, raw: str | None) -> Path:
"""A path inside the content folder, or 400. Resolved first, so neither
`..` nor a symlink can lead out of it."""
root = self.config.content
candidate = Path(raw) if raw else root
if not candidate.is_absolute():
candidate = root / candidate
resolved = candidate.resolve()
if resolved != root and not resolved.is_relative_to(root):
raise HTTPException(400, f"{raw} is outside the library's content folder")
return resolved
def _default_state() -> AppState:
# The process-wide STATE: a server holds one library, and the stem end step
# reaches for `app_state.STATE.mutation` like the desktop app's does.
from ..app_state import STATE
return STATE
def create_app(server: Server) -> FastAPI:
cfg = server.config
security = HTTPBasic(realm="Konduktor")
def auth(creds: HTTPBasicCredentials = Depends(security)) -> None:
user_ok = secrets.compare_digest(creds.username.encode(), cfg.username.encode())
pass_ok = secrets.compare_digest(creds.password.encode(), cfg.password.encode())
if not (user_ok and pass_ok):
raise HTTPException(401, "Wrong username or password",
headers={"WWW-Authenticate": 'Basic realm="Konduktor"'})
app = FastAPI(title="Konduktor server", version=__version__, dependencies=[Depends(auth)])
app.state.server = server
@app.exception_handler(AdapterError)
def _adapter_error(_request, exc: AdapterError):
status = {NotFound: 404, InvalidCommand: 400, Unsupported: 422,
LibraryNotSupported: 400}.get(type(exc), 400)
return JSONResponse(status_code=status, content={"detail": str(exc)})
def session(token: str | None = Header(None, alias=rp.SESSION_HEADER)):
try:
return server.lock.check(token)
except Lost as ex:
raise HTTPException(423, {
"code": "taken_over", "message": str(ex), "holder": server.lock.describe(),
})
# ---- handshake + session -----------------------------------------------------
@app.get("/v1/hello")
def hello(client_id: str | None = None) -> dict:
state = server.state
caps = server.capabilities()
return {
"api_version": list(rp.API_VERSION),
"app_version": __version__,
"platform": caps.platform,
"app_name": caps.save.app_name,
"library_label": caps.save.library_label,
"name": server.name(),
"path": str(state.path),
"library_id": state.library_id,
"holder": server.lock.describe(),
"dirty": server.adapter.dirty,
"pending_edits": server.pending_edits(client_id),
"rev": server.rev,
}
@app.post("/v1/session/acquire")
def acquire(body: dict = Body(...)) -> dict:
client_id = str(body.get("client_id") or "")
machine = str(body.get("machine") or "another computer")
if not client_id:
raise HTTPException(400, "client_id is required")
try:
holder = server.lock.acquire(client_id, machine, takeover=bool(body.get("takeover")))
except InUse as ex:
h = ex.holder
raise HTTPException(409, {"code": "in_use", "machine": h.machine,
"since": h.since, "batch": h.batch})
return {
"token": holder.token,
"lease": server.lock.lease,
"heartbeat": rp.HEARTBEAT_SECONDS,
"pending_edits": server.pending_edits(client_id),
"rev": server.rev,
}
@app.post("/v1/session/heartbeat")
def heartbeat(body: dict = Body(default={}),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
try:
server.lock.heartbeat(token, body.get("batch"))
except Lost as ex:
raise HTTPException(423, {"code": "taken_over", "message": str(ex),
"holder": server.lock.describe()})
return {"rev": server.rev, "dirty": server.adapter.dirty}
@app.post("/v1/session/release")
def release(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
server.lock.release(token)
return {"status": "released"}
# ---- the protocol ------------------------------------------------------------
@app.post("/v1/rpc/{name}")
def rpc(name: str, body: dict = Body(default={}),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
method = rp.RPC.get(name)
if method is None:
raise HTTPException(404, f"No such method: {name}")
holder = session(token) if method.mutating else None
try:
args = rp.load_args(name, body.get("args") or {})
except ValueError as ex:
raise HTTPException(400, str(ex))
adapter = server.adapter
changed: list = []
removed: list[str] = []
reset = False
if name == "capabilities":
value = server.capabilities()
elif name == "add_tracks":
with server.state.mutation:
value = adapter.add_tracks([_new_track(server, w) for w in args["items"]])
changed = [t for i in value if (t := adapter.track(i)) is not None]
elif method.prop:
value = getattr(adapter, name)
else:
value = getattr(adapter, name)(**args)
if method.mutating:
if name == "remove_tracks":
removed = list(args["track_ids"])
elif "track_id" in args:
track = adapter.track(args["track_id"])
if track is None:
removed = [args["track_id"]]
else:
changed = [track]
server.lock.touch(holder)
rev = server.bump()
else:
rev = server.rev
return {
"result": rp.dump_result(name, value),
"rev": rev,
"changed": [t.model_dump(mode="json") for t in changed],
"removed": removed,
"reset": reset,
}
# ---- bytes -------------------------------------------------------------------
@app.get("/v1/audio")
def audio(track_id: str):
path = server.adapter.audio_path(track_id)
if path is None or not Path(path).is_file():
raise HTTPException(404, "The audio file is missing")
st = Path(path).stat()
media = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
return FileResponse(path, media_type=media, headers={
"X-Konduktor-Size": str(st.st_size),
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
})
@app.get("/v1/art")
def art(track_id: str):
found = server.adapter.cover_art(track_id)
if not found:
raise HTTPException(404, "No cover art")
data, mime = found
return Response(content=data, media_type=mime)
@app.put("/v1/art")
async def put_art(request: Request, track_id: str, mime: str,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
holder = session(token)
data = await request.body()
server.adapter.set_cover_art(track_id, data, mime)
server.lock.touch(holder)
track = server.adapter.track(track_id)
return {"rev": server.bump(), "changed": [track.model_dump(mode="json")] if track else []}
@app.post("/v1/upload")
async def upload(request: Request, dir: str, name: str,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""Receive one audio file into `dir` (created if needed) under the content
folder. Never overwrites: a name already taken gets `-2`, `-3`, … as a
local import's copy does. The partial is renamed in only when complete,
so a cut connection leaves no half file under a real name."""
holder = session(token)
folder = server.confine(dir)
clean = _safe_name(name)
folder.mkdir(parents=True, exist_ok=True)
partial = folder / f".{clean}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}"
try:
with open(partial, "wb") as out:
async for chunk in request.stream():
out.write(chunk)
target = _publish(partial, folder / clean)
finally:
partial.unlink(missing_ok=True)
holder.uploads.add(str(target))
st = target.stat()
# A platform that analyses what it adds measures on its own clock, read
# from the file's header — which only the server can read. The client
# measures with this (`PreparedAnalysis`); None: nothing to measure.
lead = getattr(server.adapter, "analysis_lead", None)
return {"path": str(target), "size": st.st_size, "mtime_ns": st.st_mtime_ns,
"analysis_lead": lead(target) if lead else None}
@app.delete("/v1/upload")
def delete_upload(path: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""Remove a file THIS session uploaded and the library does not name —
how a cancelled or failed import cleans up after itself."""
holder = session(token)
target = server.confine(path)
if str(target) not in holder.uploads:
raise HTTPException(403, "Only a file this session uploaded can be removed")
adapter = server.adapter
named = {f.key for f in adapter.audio_facts([t.id for t in adapter.tracks]).values()}
if str(target) in named:
raise HTTPException(409, "The library names that file")
target.unlink(missing_ok=True)
holder.uploads.discard(str(target))
return {"status": "deleted"}
# ---- the content folder ------------------------------------------------------
@app.get("/v1/fs/list")
def fs_list(path: str | None = None) -> dict:
folder = server.confine(path)
if not folder.is_dir():
raise HTTPException(404, f"Not a folder: {folder}")
entries = []
try:
children = sorted(folder.iterdir(), key=lambda p: p.name.lower())
except OSError as ex:
raise HTTPException(400, f"Cannot list {folder}: {ex}")
for child in children:
if child.name.startswith(".") or is_os_housekeeping(child.name):
continue
try:
is_dir = child.is_dir()
except OSError:
continue
entries.append({"name": child.name, "path": str(child), "is_dir": is_dir})
root = server.config.content
return {
"path": str(folder),
"parent": None if folder == root else str(folder.parent),
"root": str(root),
"entries": entries,
}
@app.get("/v1/folder/tracks")
def folder_tracks(path: str | None = None) -> dict:
"""The audio directly inside a content folder, projected as tracks — the
client's Files tree for the server, like `/api/folder/tracks` for a
drive of its own. Tags only (no decoding). `held` maps each file the
library already points at to the library's id for it, so the client
can tick it off and add it to a playlist without adding it twice."""
from .. import importer
folder = server.confine(path)
if not folder.is_dir():
raise HTTPException(404, f"Not a folder: {folder}")
adapter = server.adapter
source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats)
library = importer._existing_files(adapter)
files, held = {}, {}
for track in source.tracks:
try:
st = Path(track.id).stat()
except OSError:
continue
files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
known = library.get(importer._key(Path(track.id)))
if known is not None:
held[track.id] = known
return {
"path": str(folder),
"tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files],
"files": files,
"held": held,
}
def listed_file(path: str) -> Path:
# Confined (a symlink in a listing cannot lead out of the content
# folder), and only a file a listing found: this is not a way to read
# any path on the server.
server.confine(path)
source = server.folders.source_for_file(path)
if source is None:
raise HTTPException(404, "File not found — list its folder first")
target = Path(path)
if not target.is_file():
raise HTTPException(404, "The audio file is missing")
return target
@app.get("/v1/folder/audio")
def folder_audio(path: str):
target = listed_file(path)
st = target.stat()
media = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
return FileResponse(target, media_type=media, headers={
"X-Konduktor-Size": str(st.st_size),
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
})
@app.post("/v1/folder/leads")
def folder_leads(body: dict = Body(...)) -> dict:
"""The analysis lead of each listed file, as an upload reports it: what
a client adding these files IN PLACE measures with. None for every file
when the platform does not analyse what it adds."""
lead = getattr(server.adapter, "analysis_lead", None)
out = {}
for path in body.get("paths") or []:
target = listed_file(str(path))
out[str(path)] = lead(target) if lead else None
return {"leads": out}
@app.get("/v1/fs/space")
def fs_space(path: str | None = None) -> dict:
folder = server.confine(path)
probe = folder
while not probe.exists() and probe != server.config.content:
probe = probe.parent
return {"free": shutil.disk_usage(probe).free}
# ---- save / discard / history ------------------------------------------------
@app.post("/v1/save")
def save(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
adapter = server.adapter
if not adapter.dirty:
return {"saved": False, "commit": None, "summary": "",
"tag_results": [], "playlists": adapter.playlist_count(), "rev": server.rev}
outcome, commit = server.state.save()
server.lock.clear_editor()
return {
"saved": True,
"commit": commit,
"summary": outcome.summary,
"tag_results": [r.__dict__ for r in outcome.tag_results],
"playlists": adapter.playlist_count(),
"rev": server.bump(),
}
@app.post("/v1/discard")
def discard(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
server.state.discard()
server._configure(server.adapter)
server.lock.clear_editor()
return {"rev": server.bump()}
@app.get("/v1/history")
def history() -> list[dict]:
return [e.__dict__ for e in server.state.services.history()]
@app.post("/v1/history/{commit_id}/restore")
def restore(commit_id: str, token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
if not server.state.restore_version(commit_id):
raise HTTPException(404, f"Version not found: {commit_id}")
server.lock.clear_editor()
return {"rev": server.bump()}
@app.delete("/v1/history")
def clear_history(token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
server.state.services.clear_history()
return {"status": "cleared"}
# ---- export sets -------------------------------------------------------------
@app.get("/v1/export-sets")
def get_export_sets() -> dict:
return exports._read_doc(server.state.library_id)
@app.put("/v1/export-sets")
def put_export_sets(doc: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
session(token)
if not isinstance(doc.get("sets"), dict):
raise HTTPException(400, "Expected {'sets': {...}}")
exports._write_doc(server.state.library_id,
{"library_id": server.state.library_id, "sets": doc["sets"]})
return {"status": "saved"}
# ---- Convert to Stems: the library side ---------------------------------------
# The SEPARATION runs on the computer that opened the library (the server
# never decodes audio); what lives here is everything about the FILES and the
# library: where each stem file goes, what is skipped and why, the verified
# files it uploads (kept as leftovers until the batch's end step, so a
# takeover mid-batch loses nothing — the next run reuses them), and the end
# step itself, under the library's mutation lock, with the server's ledger.
def stem_options(body: dict):
from ..stems import convert
destination = body.get("destination")
if body.get("mode") == "destination":
if not destination:
raise HTTPException(400, "Choose a destination folder")
destination = server.confine(destination)
return convert.Options(
mode=body.get("mode") or "replace", destination=Path(destination) if destination else None,
collection=body.get("collection") or "repoint", playlist_id=body.get("playlist_id"),
new_playlist=body.get("new_playlist"),
)
@app.post("/v1/stems/plan")
def stems_plan(body: dict = Body(...)) -> dict:
from ..stems import convert
adapter = server.adapter
caps = adapter.capabilities()
if not caps.tracks.stem_convertible:
raise HTTPException(422, "This library cannot hold stem files")
try:
planned = convert.plan(adapter, list(body.get("track_ids") or []), stem_options(body),
server.state.pending)
except convert.ConvertError as ex:
raise HTTPException(400, str(ex))
out = planned.as_dict()
out["items"] = [{
"track_id": p.track_id, "title": p.title, "source": str(p.source), "target": str(p.target),
"seconds": p.seconds, "source_size": p.source.stat().st_size if p.source.exists() else 0,
"reuse": p.reuse["written"] if p.reuse else None,
} for p in planned.items]
return out
def stem_item(track_id: str, target: str) -> tuple[Path, Path]:
"""The source and target a stem upload / publish names, checked against
the library rather than trusted: a target outside the content folder, or
one not named after its own track's file, is refused."""
from ..core import stem_file as sf
source = server.adapter.audio_path(track_id)
if source is None or not Path(source).is_file():
raise HTTPException(404, "The track's audio file is missing")
dest = server.confine(target)
if dest.name != sf.stem_target_name(Path(source).name):
raise HTTPException(400, f"{dest.name} is not the stem file of {Path(source).name}")
return Path(source), dest
@app.put("/v1/stems/stage")
async def stems_stage(request: Request, track_id: str, target: str, sha256: str,
bit_rate: int, duration: float,
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
import hashlib
from ..stems.pending import partial_name, source_facts
session(token)
source, dest = stem_item(track_id, target)
if dest.exists():
raise HTTPException(409, f"A stem file already exists: {dest.name}")
dest.parent.mkdir(parents=True, exist_ok=True)
partial = partial_name(dest)
incoming = dest.with_name(f".{dest.name}.{secrets.token_hex(4)}{PARTIAL_SUFFIX}")
digest = hashlib.sha256()
size = 0
try:
with open(incoming, "wb") as out:
async for chunk in request.stream():
out.write(chunk)
digest.update(chunk)
size += len(chunk)
if digest.hexdigest() != sha256.lower():
raise HTTPException(400, "The stem file arrived damaged (checksum mismatch)")
os.replace(incoming, partial)
finally:
incoming.unlink(missing_ok=True)
pending = server.state.pending
with pending._lock:
pending.leftovers = [lo for lo in pending.leftovers if lo["partial"] != str(partial)]
pending.leftovers.append({
"source": str(source), "facts": source_facts(source), "partial": str(partial),
"written": {"bit_rate": bit_rate, "duration": duration, "size": size},
})
pending._write()
return {"partial": str(partial), "size": size}
@app.post("/v1/stems/abandon")
def stems_abandon(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""A cancelled batch: delete the files it uploaded (a cancel deletes
only new files, as on this computer)."""
from ..stems.pending import partial_name
session(token)
pending = server.state.pending
wanted = {str(partial_name(server.confine(t))) for t in body.get("targets") or []}
for lo in [lo for lo in pending.leftovers if lo["partial"] in wanted]:
pending.forget_leftover(lo, delete=True)
return {"status": "abandoned"}
@app.post("/v1/stems/publish")
def stems_publish(body: dict = Body(...),
token: str | None = Header(None, alias=rp.SESSION_HEADER)) -> dict:
"""The batch's END STEP, here where the files are: publish each staged
stem file, park originals (Replace), swap every entry at once."""
from ..core import stem_file as sf
from ..stems import convert
from ..stems.pending import partial_name
holder = session(token)
opts = stem_options(body.get("options") or {})
pending = server.state.pending
result = {"converted": [], "renamed": {}, "added": {}, "failed": [], "clamped": {}}
with server.state.mutation:
finished = []
for entry in body.get("items") or []:
source, dest = stem_item(entry["track_id"], entry["target"])
partial = partial_name(dest)
lo = next((x for x in pending.leftovers if x["partial"] == str(partial)), None)
track = server.adapter.track(entry["track_id"])
title = convert._title(track)
if lo is None or not partial.is_file():
result["failed"].append({"track_id": entry["track_id"], "title": title,
"reason": "the converted file never reached the server"})
continue
written = lo["written"]
pitem = pending.add({"track_id": entry["track_id"], "mode": opts.collection,
"source": str(source), "stem": str(dest), "state": "converted",
"facts": lo.get("facts"), "written": written})
pending.forget_leftover(lo, delete=False)
planned = convert.Planned(entry["track_id"], title, source, dest, float(written["duration"]))
finished.append((planned, pitem, sf.Written(path=partial, bit_rate=int(written["bit_rate"]),
duration=float(written["duration"]),
size=int(written["size"]), tags={})))
convert._end_step(server.adapter, finished, opts, pending, result)
server.lock.touch(holder)
result["rev"] = server.bump()
return result
@app.get("/v1/stems/pending")
def stems_pending() -> dict:
pending = server.state.pending
return pending.summary() if pending is not None else {"tracks": 0, "parked": 0, "bytes": 0}
return app
def _safe_name(name: str) -> str:
clean = os.path.basename((name or "").replace("\\", "/")).strip()
if not clean or clean in (".", "..") or clean.startswith("."):
raise HTTPException(400, f"Not a usable file name: {name!r}")
return clean
def _publish(partial: Path, wanted: Path) -> Path:
"""Rename `partial` to `wanted`, or `wanted-2`… — never over an existing file
(a hard link fails rather than replaces)."""
stem, suffix = wanted.stem, wanted.suffix
# `.stem.m4a` keeps its double suffix together.
if stem.endswith(".stem"):
stem, suffix = stem[: -len(".stem")], ".stem" + suffix
n = 1
while True:
target = wanted if n == 1 else wanted.with_name(f"{stem}-{n}{suffix}")
try:
os.link(partial, target)
return target
except FileExistsError:
n += 1
def _new_track(server: Server, wire: rp.WireNewTrack) -> NewTrack:
import base64
path = server.confine(wire.audio_path)
art = (base64.b64decode(wire.art.data), wire.art.mime) if wire.art else None
return NewTrack(track=wire.track, audio_path=path, cues=wire.cues, art=art,
analysis=rp.unpack_analysis(wire.analysis))
# ---- entry points ------------------------------------------------------------------
def create_from_env() -> FastAPI:
"""`uvicorn --factory konduktor.server.app:create_from_env`."""
from .config import from_env
server = Server(from_env())
server.open()
log.info("Serving %s (%s) to remote clients", server.config.library, server.config.platform)
return create_app(server)
+101
View File
@@ -0,0 +1,101 @@
"""The server's configuration: the container's environment (its `.env`).
Everything is read once at start and checked before the library is opened, and
a bad setting stops the container with ONE clear line rather than a library
that half-works: a missing content folder would otherwise show up as every
track "missing", and an empty password as an open door.
KONDUKTOR_PLATFORM traktor | rekordbox — checked against the library file
KONDUKTOR_LIBRARY the library file (collection.nml / master.db)
KONDUKTOR_CONTENT the folder holding the audio; uploads and the folder
browser are confined to it
KONDUKTOR_USERNAME the one account
KONDUKTOR_PASSWORD
KONDUKTOR_PATH_MAP optional: "stored => here", e.g.
"/Users/ben/Music => /music"; several separated by ";".
Applied for the session only — the library keeps its
stored paths, so it still opens on the computer it
was made on.
KONDUKTOR_NAME optional: what the library is called on screen
KONDUKTOR_DATA_DIR where history, export sets and the ledger live
(read by `paths.app_data_dir`)
KONDUKTOR_HOST / KONDUKTOR_PORT where to listen (0.0.0.0:8765)
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from ..core.pathmap import PathMapping
PLATFORMS = ("traktor", "rekordbox")
class ConfigError(Exception):
pass
@dataclass(frozen=True)
class ServerConfig:
platform: str
library: Path
content: Path
username: str
password: str
path_maps: tuple[PathMapping, ...] = field(default_factory=tuple)
name: str = ""
host: str = "0.0.0.0"
port: int = 8765
def parse_path_maps(text: str | None) -> tuple[PathMapping, ...]:
"""`"a => b; c => d"` → mappings. Raises `ConfigError` on a malformed one."""
out = []
for part in (text or "").split(";"):
part = part.strip()
if not part:
continue
if "=>" not in part:
raise ConfigError(f"KONDUKTOR_PATH_MAP: expected 'stored => here', got {part!r}")
src, dst = (s.strip() for s in part.split("=>", 1))
mapping = PathMapping.make(src, dst)
if mapping.empty:
raise ConfigError(f"KONDUKTOR_PATH_MAP: both sides are needed in {part!r}")
out.append(mapping)
return tuple(out)
def from_env(env=None) -> ServerConfig:
env = os.environ if env is None else env
def need(key: str) -> str:
value = (env.get(key) or "").strip()
if not value:
raise ConfigError(f"{key} is not set")
return value
platform = need("KONDUKTOR_PLATFORM").lower()
if platform not in PLATFORMS:
raise ConfigError(f"KONDUKTOR_PLATFORM must be one of {', '.join(PLATFORMS)}, not {platform!r}")
library = Path(need("KONDUKTOR_LIBRARY"))
if not library.exists():
raise ConfigError(f"KONDUKTOR_LIBRARY: {library} does not exist")
content = Path(need("KONDUKTOR_CONTENT"))
if not content.is_dir():
raise ConfigError(f"KONDUKTOR_CONTENT: {content} is not a folder")
username = need("KONDUKTOR_USERNAME")
password = env.get("KONDUKTOR_PASSWORD") or ""
if not password:
raise ConfigError("KONDUKTOR_PASSWORD is not set")
try:
port = int(env.get("KONDUKTOR_PORT") or 8765)
except ValueError:
raise ConfigError("KONDUKTOR_PORT must be a number")
return ServerConfig(
platform=platform, library=library, content=content.resolve(),
username=username, password=password,
path_maps=parse_path_maps(env.get("KONDUKTOR_PATH_MAP")),
name=(env.get("KONDUKTOR_NAME") or "").strip(),
host=(env.get("KONDUKTOR_HOST") or "0.0.0.0").strip(), port=port,
)
+133
View File
@@ -0,0 +1,133 @@
"""One computer at a time: the server's session lock.
A library held by a server is edited by ONE computer at a time (decided: a
shared or merged session was rejected). That computer holds the session; every
command carries its token, and anything else is told who holds it.
* **A lease, renewed by heartbeat.** The holder's app sends one every
`HEARTBEAT_SECONDS`; `LEASE_SECONDS` without one and the session is free.
A crashed laptop or a closed lid therefore never locks the library for
good, and a Wi-Fi blip does not lose it.
* **Takeover** is how a second computer gets in before the lease runs out:
it is told who holds the session (and what batch is running there) and may
take it. The old token is refused from then on, which is how the displaced
computer finds out.
* **The same computer coming back** — after sleep, after a reconnect through
its fallback address — renews its expired lease silently, as long as
nobody else has taken the session meanwhile.
Unsaved edits are NOT the session's: they live in the one native model the
server holds, so whoever holds the session next inherits them (and is asked to
save or discard them — `last_editor` says whose they were).
"""
from __future__ import annotations
import secrets
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from ..remote_protocol import LEASE_SECONDS
@dataclass
class Holder:
token: str
client_id: str
machine: str
since: str # ISO 8601, UTC
last_seen: float # on the lock's clock
batch: str | None = None # the kind of batch job running there, if any
uploads: set[str] = field(default_factory=set)
class InUse(Exception):
"""Another computer holds the session."""
def __init__(self, holder: Holder):
super().__init__(f"In use by {holder.machine}")
self.holder = holder
class Lost(Exception):
"""This token no longer holds the session."""
def __init__(self, holder: Holder | None):
super().__init__("Another computer has taken over this library" if holder
else "This computer no longer holds the session")
self.holder = holder
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
class SessionLock:
def __init__(self, *, lease: float = LEASE_SECONDS, clock=time.monotonic):
self.lease = lease
self._clock = clock
self._lock = threading.Lock()
self._holder: Holder | None = None
#: The machine whose commands made the unsaved edits (see `touch`).
self.last_editor: dict | None = None
# ---- reading --------------------------------------------------------------
def _live(self, holder: Holder | None) -> bool:
return holder is not None and self._clock() - holder.last_seen < self.lease
def holder(self) -> Holder | None:
"""Who holds the session right now (None: free, or the lease ran out)."""
with self._lock:
return self._holder if self._live(self._holder) else None
def describe(self) -> dict | None:
h = self.holder()
return None if h is None else {"machine": h.machine, "since": h.since, "batch": h.batch}
# ---- changing -------------------------------------------------------------
def acquire(self, client_id: str, machine: str, *, takeover: bool = False) -> Holder:
"""Hold the session. Raises `InUse` when another computer holds it and
`takeover` is not set. The same client re-acquiring keeps its uploads."""
with self._lock:
current = self._holder
live = self._live(current)
if live and current.client_id != client_id and not takeover:
raise InUse(current)
uploads = current.uploads if current is not None and current.client_id == client_id else set()
self._holder = Holder(
token=secrets.token_urlsafe(24), client_id=client_id, machine=machine,
since=_now_iso(), last_seen=self._clock(), uploads=uploads,
)
return self._holder
def check(self, token: str | None) -> Holder:
"""The holder this token names, renewing its lease. Raises `Lost`.
A token whose lease ran out is still honoured when nobody else has
taken the session since — the same computer back from sleep."""
with self._lock:
current = self._holder
if current is None or not token or not secrets.compare_digest(current.token, token):
raise Lost(current if self._live(current) else None)
current.last_seen = self._clock()
return current
def heartbeat(self, token: str | None, batch: str | None) -> Holder:
holder = self.check(token)
holder.batch = batch
return holder
def release(self, token: str | None) -> None:
with self._lock:
current = self._holder
if current is not None and token and secrets.compare_digest(current.token, token):
self._holder = None
def touch(self, holder: Holder) -> None:
"""Record that `holder` made an edit — whose the unsaved ones are."""
self.last_editor = {"client_id": holder.client_id, "machine": holder.machine}
def clear_editor(self) -> None:
"""After a save or discard, nobody's edits are pending."""
self.last_editor = None
+70
View File
@@ -0,0 +1,70 @@
"""The app-level bookkeeping around ONE open library, wherever it is kept.
Version history belongs to the app, not the adapter (see `app_state.py`), and
until a library could live on a server it could only mean one thing: a git repo
in this computer's app-data, keyed by the library's local path. A library held
by a server is versioned THERE, beside the file it describes — so the open
library carries the services that know where its history lives, and the routes
ask them rather than the history module directly.
`LocalServices` is the whole of what used to be inline: nothing about a library
on this computer changes. The remote implementation lives with the remote
adapter (`adapters/remote/services.py`).
"""
from __future__ import annotations
from pathlib import Path
from typing import Protocol
from . import __version__, history
from .core import registry
class LibraryServices(Protocol):
#: Whether this library is held by a server (its history lives there).
remote: bool
def baseline(self) -> None: ...
def commit_save(self, adapter, outcome) -> str | None: ...
def history(self) -> list[history.HistoryEntry]: ...
def restore(self, commit_id: str) -> bool: ...
def clear_history(self) -> None: ...
class LocalServices:
"""History in this computer's app-data, keyed by the library's path."""
remote = False
def __init__(self, path: Path):
self.path = path
def baseline(self) -> None:
# An "as I found it" version (deduped, so re-opening an unchanged
# library is a no-op). Best-effort.
history.ensure_baseline(self.path)
def commit_save(self, adapter, outcome) -> str | None:
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
# capabilities rather than this module knowing which platforms those are.
if adapter.capabilities().save.history and outcome.snapshot is not None:
return history.commit(self.path, outcome.snapshot, outcome.summary, __version__)
return None
def history(self) -> list[history.HistoryEntry]:
return history.list_history(self.path)
def restore(self, commit_id: str) -> bool:
"""Write a past version back as a NEW forward save. False if unknown.
The caller reopens the library afterwards."""
data = history.read_version(self.path, commit_id)
if data is None:
return False
# The adapter's driver owns writing its own format back, even for a restore.
registry.driver_for(self.path).restore(self.path, data)
history.commit(self.path, data, f"Restored version {commit_id[:8]}", __version__)
return True
def clear_history(self) -> None:
history.clear_history(self.path)
+29 -14
View File
@@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 *
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
#: Shares of ONE track's conversion time, for the status bar's within-track
#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode +
#: verify ~4 s for a 4-minute track).
_DECODE_SHARE = 0.03
_SEPARATE_SHARE = 0.90
#: Shares of ONE track's conversion time (decode, separate; encoding + verifying
#: take the rest), for the status bar's within-track progress, by AAC encoder.
#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate
#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute
#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s).
_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)}
def track_shares(encoder: str) -> tuple[float, float]:
return _SHARES.get(encoder, _SHARES["aac"])
def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]:
"""`on_encode` for `stem_file.build`: the encode runs from `start` to `end`
of the track, and the ~1 s of tags + verification after it reads as such."""
def report(f: float) -> None:
frac = start + f * (end - start)
handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %")
return report
class ConvertError(Exception):
@@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
work = work_root() / f"batch-{id(handle):x}"
finished: list[tuple[Planned, dict, sf.Written]] = []
needs_engine = any(p.reuse is None for p in items)
encoder = sf.default_encoder()
if needs_engine and not mgr.ready():
raise ConvertError("The stem engine is not installed")
@@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
item.target.parent.mkdir(parents=True, exist_ok=True)
# Of a TRACK's time, separation is nearly all (~90 % on MPS);
# decoding before it and encoding + verifying after share the rest.
# Of a TRACK's time, separation is nearly all; decoding before it
# and encoding + verifying after share the rest.
decode_share, separate_share = track_shares(encoder)
def on_progress(f: float) -> None:
frac = _DECODE_SHARE + f * (_SEPARATE_SHARE)
frac = decode_share + f * separate_share
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm):
handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %")
stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
done_at = _DECODE_SHARE + _SEPARATE_SHARE
handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %")
return stems
handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %")
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
handle.progress(status="decoding 0 %")
try:
written = sf.build(item.source, partial, separate, checkpoint=checkpoint)
written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint,
on_encode=encode_reporter(handle, decode_share + separate_share))
except (_Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
pending.drop([pitem])
+215
View File
@@ -0,0 +1,215 @@
"""Convert to Stems on a library held by a Konduktor server.
The same batch as `convert.py`, split where the machines split:
* **The server plans** — where each stem file goes, what is skipped and why,
whether its disk has room — because the files and the library are there.
* **This computer separates.** The server never decodes audio, so each source
is downloaded into the shared cache (`adapters/remote/cache.py`), separated
and encoded here with the local engine, verified, and UPLOADED. The server
keeps each upload as a verified leftover until the end step, so a batch
interrupted by a takeover loses no separation: the next run reuses it.
* **The server swaps.** One end step there — publish, park the original
(Replace), swap every entry at once — under its own mutation lock, with its
own ledger, which its Save commits and its Discard restores.
Cancel deletes what this run uploaded, as a local cancel deletes what it wrote.
"""
from __future__ import annotations
import contextlib
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from ..core import stem_file as sf
from ..core.adapter import AdapterError
from ..importer import SPACE_HEADROOM
from . import convert
from . import engine_manager as em
from .engine_process import EngineCancelled, EngineProcess, keep_awake
#: Before this computer has measured a download, a conservative LAN speed.
DEFAULT_SPEED = 20 * 1024 ** 2 # bytes / s
def options_body(opts: convert.Options) -> dict:
return {
"mode": opts.mode,
"destination": str(opts.destination) if opts.destination else None,
"collection": opts.collection,
"playlist_id": opts.playlist_id,
"new_playlist": opts.new_playlist,
}
@dataclass
class RemotePlan:
server: dict
items: list[dict] = field(default_factory=list)
blocked: str | None = None
#: Bytes to download (sources this computer has no copy of) and upload.
download: int = 0
upload: int = 0
speed: float | None = None
space: list[dict] = field(default_factory=list)
def as_dict(self) -> dict:
out = dict(self.server)
out.pop("items", None)
out["blocked"] = self.blocked
out["space"] = self.space
out["transfer"] = {"download": self.download, "upload": self.upload,
"speed": self.speed or DEFAULT_SPEED, "measured": self.speed is not None}
return out
def plan(adapter, track_ids: list[str], opts: convert.Options) -> RemotePlan:
"""The server's plan, plus what only this computer can answer: how much it
must download and upload, and whether its cache and work folder have room."""
from ..importer import free_bytes
try:
server = adapter.stems_plan({"track_ids": list(track_ids), **options_body(opts)})
except AdapterError as ex:
raise convert.ConvertError(str(ex))
items = list(server.get("items") or [])
result = RemotePlan(server=server, items=items, blocked=server.get("blocked"))
to_separate = [i for i in items if i.get("reuse") is None]
# Server volumes, named as the server's.
result.space = [{**e, "volume": f"the server ({e.get('volume')})"} for e in server.get("space") or []]
result.download = sum(int(i.get("source_size") or 0) for i in to_separate
if adapter.cached_audio(i["track_id"]) is None)
result.upload = int(server.get("bytes") or 0)
result.speed = adapter.cache.speed()
if to_separate:
biggest = max(float(i.get("seconds") or 0) for i in to_separate) * convert._WORK_BYTES_PER_SECOND
work = convert.work_root()
work_free = free_bytes(work)
cache_usage = adapter.cache.usage()
# Downloads land in the cache and the stem file is written in the work
# folder before it is uploaded — both on THIS computer's disk.
need_here = biggest + max((int(i.get("source_size") or 0) for i in to_separate), default=0)
result.space.append({"volume": "this computer", "folder": str(work), "bytes": int(need_here),
"free": work_free})
if result.blocked is None and work_free is not None and need_here + SPACE_HEADROOM > work_free:
result.blocked = (f"Not enough space on this computer: about {need_here / 1e9:.1f} GB is needed "
f"while a track is downloaded and converted, {work_free / 1e9:.1f} GB is free")
if result.blocked is None and cache_usage["free"] and result.download > cache_usage["free"]:
result.blocked = "Not enough space on this computer for the downloads"
return result
def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_current,
manager: em.EngineManager | None = None) -> dict:
mgr = manager or em.default_manager()
result = {"converted": [], "renamed": {}, "added": {}, "skipped": list(planned.server.get("skipped") or []),
"failed": [], "clamped": {}, "cancelled": False}
items = planned.items
handle.progress(done=0, total=len(items), unit="tracks", message="Starting the stem engine…")
work = convert.work_root() / f"remote-batch-{id(handle):x}"
work.mkdir(parents=True, exist_ok=True)
staged: list[dict] = []
uploaded: list[str] = [] # targets THIS run uploaded (a cancel deletes them)
if any(i.get("reuse") is None for i in items) and not mgr.ready():
raise convert.ConvertError("The stem engine is not installed")
def checkpoint() -> None:
if handle.cancelled:
raise convert._Cancel()
with contextlib.ExitStack() as stack:
engine: EngineProcess | None = None
try:
for n, item in enumerate(items):
checkpoint()
handle.progress(done=n, message=item["title"], fraction=0.0, status="")
if item.get("reuse") is not None:
staged.append(item) # already on the server, verified
continue
size = max(int(item.get("source_size") or 0), 1)
got = 0
def downloaded(k: int) -> None:
nonlocal got
got += k
checkpoint()
f = min(got / size, 1.0) * 0.05
handle.progress(fraction=f, status=f"downloading {f * 100:.0f} %")
local = adapter.audio_path(item["track_id"], progress=downloaded)
if local is None:
result["failed"].append({"track_id": item["track_id"], "title": item["title"],
"reason": "the file is missing on the server"})
continue
if engine is None:
handle.progress(status="starting…")
engine = stack.enter_context(EngineProcess(mgr.executable(), mgr.weights_dir(), device=opts.device))
stack.enter_context(keep_awake(engine.proc.pid))
def on_progress(f: float) -> None:
frac = 0.05 + f * 0.80
handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %")
def separate(pcm):
handle.progress(fraction=0.05, status="separating 5 %")
return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled)
partial = work / f"{n}.stem.m4a"
try:
written = sf.build(local, partial, separate, checkpoint=checkpoint,
on_encode=convert.encode_reporter(handle, 0.85, 0.9))
except (convert._Cancel, EngineCancelled):
partial.unlink(missing_ok=True)
raise
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
partial.unlink(missing_ok=True)
result["failed"].append({"track_id": item["track_id"], "title": item["title"],
"reason": str(ex) or type(ex).__name__})
if isinstance(ex, em.EngineError) and engine.proc.poll() is not None:
engine = None
continue
sent = 0
def uploading(k: int) -> None:
nonlocal sent
sent += k
checkpoint()
f = 0.9 + min(sent / max(written.size, 1), 1.0) * 0.1
handle.progress(fraction=f, status=f"uploading {f * 100:.0f} %")
try:
adapter.stage_stem(item["track_id"], item["target"], partial, bit_rate=written.bit_rate,
duration=written.duration, progress=uploading)
finally:
partial.unlink(missing_ok=True)
uploaded.append(item["target"])
staged.append(item)
except (convert._Cancel, EngineCancelled):
# Cancel = delete what this run uploaded; nothing else was touched.
# (If another computer took over, this is refused — and the uploads
# stay as verified leftovers the next run reuses, as decided.)
with contextlib.suppress(AdapterError):
if uploaded:
adapter.abandon_stems(uploaded)
result["cancelled"] = True
return result
finally:
shutil.rmtree(work, ignore_errors=True)
if not staged:
return result
if not still_current():
with contextlib.suppress(AdapterError):
adapter.abandon_stems(uploaded)
raise convert.ConvertError("The library changed while converting; nothing was swapped in")
handle.progress(done=len(items), message="Swapping the converted tracks in on the server…", status="")
swapped = adapter.publish_stems([{"track_id": i["track_id"], "target": i["target"]} for i in staged],
options_body(opts))
for key in ("converted", "renamed", "added", "clamped"):
if key in swapped:
result[key] = swapped[key]
result["failed"] += swapped.get("failed") or []
if swapped.get("playlist_missing"):
result["playlist_missing"] = True
return result
+1 -1
View File
@@ -1,4 +1,4 @@
# Build-only dependencies (not needed to run the backend in dev).
# Freezes the backend into a standalone sidecar binary for the desktop build.
# Freezes the backend into a standalone sidecar folder (onedir) for the desktop build.
# See konduktor-sidecar.spec and build_sidecar.sh.
pyinstaller>=6.16 # 6.16+ supports Python 3.14
+18
View File
@@ -0,0 +1,18 @@
# The Konduktor SERVER (a container on the user's NAS — see server/Dockerfile).
#
# Deliberately NOT requirements.txt: the server never DECODES audio (analysis,
# waveforms and stem separation run on the computer that opened the library),
# so librosa, scikit-learn and PyAV stay out of the image. What it does is file
# IO, the native model, tags and header reads. `test_layering.py` checks that
# importing `konduktor.server` pulls none of them in.
fastapi>=0.115
uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # tags written into the audio files at Save
numpy>=2.0 # a prepared analysis arrives as arrays (Rekordbox's ANLZ writer)
Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library
platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+18 -10
View File
@@ -4,7 +4,7 @@ fastapi>=0.115
uvicorn[standard]>=0.34
pydantic>=2.11
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
av>=18.1 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS
av>=18.1,<20 # PyAV: FFmpeg's decoders in the wheel — waveforms for export, AAC on every OS. Before allowing a new major, check core/pyav.py (19 broke av.open)
Pillow>=11 # cover art -> the 80/240 px JPEGs a Pioneer export carries
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
# Version-history backups: a self-contained git impl (no system git needed;
@@ -18,19 +18,27 @@ librosa>=0.11
scikit-learn>=1.5
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
#
# Both GitHub dependencies are PINNED TO A COMMIT. Unpinned, a fresh install
# (CI's release build) takes whatever master is that day while a dev venv keeps
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
#
# FROM GITHUB, NOT PyPI — the same situation as traktor-nml-utils above, and for
# the same kind of reason. PyPI's latest (0.4.4) has no `devicelib_plus`, which
# is the OneLibrary (`exportLibrary.db`) reader the OneLibrary adapter is built
# on; it exists only on master. Do not "simplify" this back to a version pin.
#
# The upgrade also renames `db6` to `masterdb`. `db6` still works as a
# deprecated alias and is removed in 0.6.0, so the Rekordbox adapter keeps
# running as-is — but that rename is the thing to fix before taking 0.6.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git
# the same kind of reason. PyPI's latest (0.4.4) has no `onelibrary` module
# (`exportLibrary.db`, which the OneLibrary adapter is built on; it was called
# `devicelib_plus` before the rename) and no `masterdb` (formerly `db6`, now
# removed). Do not "simplify" this back to a version pin.
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
# The stem engine and its weights are downloaded over HTTPS by the sidecar; a
# frozen Python on macOS has no system CA bundle of its own.
certifi>=2024.7
# Remote libraries (a Konduktor server on the user's NAS): the HTTP client the
# remote adapter speaks to it with, and the OS keychain (macOS Keychain /
# Windows Credential Manager) its password is kept in — never userprefs.json.
httpx>=0.27
keyring>=25
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+40 -3
View File
@@ -28,13 +28,50 @@ def _watch_parent_and_exit() -> None:
shut down, so the backend can never be orphaned (the Rust-side kill-on-exit
only covers the graceful path). When run standalone from a terminal, stdin is
a TTY and this blocks harmlessly forever.
NOT on Windows: there a read left pending on the stdin pipe stalls loading
scipy's OpenBLAS DLL in any other thread, forever — so the first analysis
hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain
Python, through the CRT and through kernel32.ReadFile alike. Windows waits
on the parent PROCESS instead, which also covers a crash.
"""
try:
while sys.stdin.buffer.read(1):
if sys.platform == "win32":
_wait_for_parent_process()
else:
try:
while sys.stdin.buffer.read(1):
pass
except Exception:
pass
_release_remote()
os._exit(0)
def _wait_for_parent_process() -> None:
"""Block until the process that started us exits (Windows only)."""
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
synchronize, infinite = 0x00100000, 0xFFFFFFFF
handle = kernel32.OpenProcess(synchronize, False, os.getppid())
if handle: # None: the parent is already gone
kernel32.WaitForSingleObject(handle, infinite)
def _release_remote() -> None:
"""Hand back a remote library's session on the way out, so the next
computer opens it at once instead of waiting out the lease (or being asked
to take over a laptop that has already quit). Best-effort and brief."""
try:
from konduktor.app_state import STATE
if STATE.remote is not None:
STATE.remote.stop()
STATE.remote.client.release(timeout=2.0)
except Exception:
pass
os._exit(0)
def _free_port() -> int:
+10 -4
View File
@@ -177,9 +177,9 @@ check("bpm x100, rating, file type, bitmask as rekordbox writes them",
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists}
check("the tree: a folder named after the export > House > Peak, plus Other for loose tracks",
tree["GIG"]["folder"] and tree["House"]["parent"] == tree["GIG"]["id"]
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == tree["GIG"]["id"])
check("the tree: House > Peak, plus Other for loose tracks, at the top level (parent 0)",
"GIG" not in tree and tree["House"]["folder"] and tree["House"]["parent"] == 0
and tree["Peak"]["parent"] == tree["House"]["id"] and tree["Other"]["parent"] == 0)
peak = [e for e in lib.entries if e[2] == tree["Peak"]["id"]]
check("playlist entries in order, 1-based", peak == [(1, 1, tree["Peak"]["id"]), (2, 2, tree["Peak"]["id"])], peak)
check("every track has an analysis path, and the files exist",
@@ -188,6 +188,13 @@ check("artwork rows name the a<n>.jpg files, which exist",
all((root / p.lstrip("/")).is_file() for p in lib.artwork.values()) and len(lib.artwork) == 3)
check("every file written is reported, so a re-export can clear it",
all(p.exists() for p in written.all_paths))
import dataclasses # noqa: E402
rooted_tree = {p["name"]: p for p in P.read(
dev.write(dataclasses.replace(payload, root_folder=True), root).library.read_bytes()).playlists}
check("with the root-folder setting: a folder named after the export holds House and Other",
rooted_tree["GIG"]["folder"] and rooted_tree["GIG"]["parent"] == 0
and rooted_tree["House"]["parent"] == rooted_tree["GIG"]["id"]
and rooted_tree["Other"]["parent"] == rooted_tree["GIG"]["id"])
print("== alongside OneLibrary: one set of analysis files and artwork ==")
both = Path(tempfile.mkdtemp())
@@ -195,7 +202,6 @@ for t in tracks:
dst = both / t.destination.relative_to(root)
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes(t.destination.read_bytes())
import dataclasses # noqa: E402
moved = [dataclasses.replace(t, destination=both / t.destination.relative_to(root)) for t in tracks]
both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlists)
ol_written = core_export.for_platform("onelibrary").write(both_payload, both)
+24 -11
View File
@@ -137,19 +137,20 @@ def walk(nodes, path=()):
walk(back.playlist_tree())
check("one folder named after the export", ("GIG",) in tree and tree[("GIG",)].kind == "folder")
check("nested folders are preserved", ("GIG", "House") in tree)
check("and nest further", ("GIG", "House", "Slow") in tree)
# By default the tree sits at the top level: an export is a library of its own.
check("no folder named after the export by default", ("GIG",) not in tree)
check("nested folders are preserved", ("House",) in tree and tree[("House",)].kind == "folder")
check("and nest further", ("House", "Slow") in tree)
check("playlists land in their folder",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
("House", "Peak Time") in tree and ("House", "Slow", "Warmup") in tree)
check("with the right counts",
tree[("GIG", "House", "Peak Time")].count == 2
and tree[("GIG", "House", "Slow", "Warmup")].count == 1)
tree[("House", "Peak Time")].count == 2
and tree[("House", "Slow", "Warmup")].count == 1)
# A track added individually would otherwise be reachable only by search.
check("loose tracks get an 'Other' playlist", ("GIG", "Other") in tree)
check("loose tracks get an 'Other' playlist, at the top level", ("Other",) in tree)
check("holding exactly the ones no playlist claimed",
tree[("GIG", "Other")].count == 1, tree[("GIG", "Other")].count)
other_ids = back.playlist_entries(tree[("GIG", "Other")].id)
tree[("Other",)].count == 1, tree[("Other",)].count)
other_ids = back.playlist_entries(tree[("Other",)].id)
check("and it is the right track",
back.track(other_ids[0]).title == plain.title)
@@ -182,7 +183,19 @@ again = exporter.write(payload, dest).library
check("the entry count did not double",
f'<COLLECTION ENTRIES="{len(chosen)}">' in again.read_text(encoding="utf-8"))
check("and the tree did not duplicate",
len(TraktorDriver().open(again).playlist_tree()) == 1)
len(TraktorDriver().open(again).playlist_tree()) == len(back.playlist_tree()))
print("== with the root-folder setting: everything under one folder named after the export ==")
payload.root_folder = True
rooted = TraktorDriver().open(exporter.write(payload, dest).library)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"] and tree[("GIG",)].kind == "folder")
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree and ("GIG", "House", "Slow", "Warmup") in tree)
check("and so does 'Other'", ("GIG", "Other") in tree and tree[("GIG", "Other")].count == 1)
payload.root_folder = False
# ==============================================================================
# Running an export: the copy, the safety rules, and the rollback.
@@ -207,7 +220,7 @@ for i, track in enumerate(src.tracks[:4]):
seed_items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
exporter_obj = core_export.for_platform("traktor")
exporter_obj.write(
_Payload(name="Source", tracks=seed_items,
_Payload(name="Source", tracks=seed_items, root_folder=True,
playlists=[ExportPlaylist(name="Peak Time",
track_ids=[src.tracks[0].id, src.tracks[1].id])]),
lib_root,
+17 -3
View File
@@ -173,9 +173,23 @@ for platform, reopen in (
tree.clear()
walk(back.playlist_tree())
check("a folder named after the export", ("GIG",) in tree)
check("nested folders are preserved", ("GIG", "House") in tree)
check("no folder named after the export by default", ("GIG",) not in tree)
check("nested folders are preserved, at the top level", ("House",) in tree)
check("with the playlist inside",
("House", "Peak Time") in tree
and tree[("House", "Peak Time")].count == len(chosen))
print(f"-- {platform}: with the root-folder setting")
rooted_root = Path(tempfile.mkdtemp()) / "GIG"
rooted_payload = build(rooted_root)
rooted_payload.root_folder = True
exporter.write(rooted_payload, rooted_root)
rooted = reopen(rooted_root)
tree.clear()
walk(rooted.playlist_tree())
check("one top-level node: a folder named after the export",
[n.name for n in rooted.playlist_tree()] == ["GIG"])
check("the tree nests inside it",
("GIG", "House", "Peak Time") in tree
and tree[("GIG", "House", "Peak Time")].count == len(chosen))
@@ -490,7 +504,7 @@ print("\n== content.contentLink is what rekordbox writes ==")
# row's song-list preview plain blue and put a "?" beside CUE — exactly what
# every row of Konduktor's exports showed while it was NULL.
import sqlcipher3.dbapi2 as _sq # noqa: E402
from pyrekordbox.devicelib_plus.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.onelibrary.database import BLOB as _BLOB # noqa: E402
from pyrekordbox.utils import deobfuscate as _deob # noqa: E402
_con = _sq.connect(str(art_written.library))
+81 -1
View File
@@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("it is in the playlist", a.playlist_entries(playlist) == [added])
check("it was saved, not left pending", not a.dirty)
body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"]))
check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"]))
row = next((t for t in body["tracks"] if t["id"] == added), None)
check("…its row IS the collection track (its id and data), mapped back to the file",
row is not None and body["files"] == {added: str(one)}
and row["import_date"] == a.track(added).import_date, str(body["files"]))
print("== a held file is never added twice, but still reaches its target ==")
library = STATE.library_id
@@ -193,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== a drop onto the window: folders all the way down, files as themselves ==")
drop = Path(tempfile.mkdtemp()) / "Dropped"
d_a = flac(drop / "Album" / "a.flac", title="Dropped A")
d_b = flac(drop / "Album" / "CD2" / "b.flac")
(drop / "Album" / "cover.jpg").write_bytes(b"not audio")
flac(drop / "Album" / ".cache" / "h.flac")
single = flac(drop / "Loose" / "single.flac", title="Single")
sibling = flac(drop / "Loose" / "sibling.flac")
(drop / "Loose" / "readme.txt").write_text("not audio")
r = c.post("/api/folder/dropped", json={"paths": [
str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"),
str(drop / "gone.flac"), str(single), str(d_a),
]})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("the folder's audio, subfolders included, then the file — each once",
ids == [str(d_a), str(d_b), str(single)], str(ids))
check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids)
check("a dropped non-audio file and a missing one are counted as skipped",
body["skipped"] == 2, str(body["skipped"]))
check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2)
check("tags are read", body["tracks"][0]["title"] == "Dropped A")
check("not truncated", body["truncated"] is False)
check("a dropped file streams",
c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200)
check("so does one found inside a dropped folder",
c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200)
check("but not its undropped sibling",
c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404)
listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]]
check("browsing that folder afterwards still lists ALL of it",
listed == [str(sibling), str(single)], str(listed))
r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]})
check("a non-audio file is never made streamable",
r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={
"track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404)
capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1)
check("past the cap the rest are left out, and it says so",
len(capped.tracks) == 1 and capped.truncated)
body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json()
check("a dropped file the collection holds IS its collection track",
[t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)},
str(body))
req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")}
p = c.post("/api/folder/add/preview", json=req).json()
check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p))
req["destination"] = str(Path(tempfile.mkdtemp()))
p = c.post("/api/folder/add/preview", json=req).json()
check("…and not elsewhere", p.get("in_destination") == 0, str(p))
real_drives = main.places.drives
main.places.drives = lambda: [
{"name": "Computer", "path": drop.anchor, "kind": "local"},
{"name": "Stick", "path": str(drop / "Album"), "kind": "external"},
]
try:
req = {"track_ids": [str(d_a), str(single)], "mode": "reference"}
p = c.post("/api/folder/add/preview", json=req).json()
check("the external-drive warning counts files per drive, not by the first",
p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"],
str(p))
p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)],
"mode": "reference"}).json()
check("…whichever file comes first", p["removable_count"] == 1, str(p))
finally:
main.places.drives = real_drives
n = len(a.tracks)
job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)],
"mode": "reference"}).json())
check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2,
str(job))
print("== Rekordbox: the same route adds to a master.db ==")
from konduktor.adapters.rekordbox import discovery as rb_discovery
+158
View File
@@ -57,6 +57,9 @@ with tempfile.TemporaryDirectory() as d:
return SimpleNamespace(anchor=0.123, bpm=127.5)
main.grid_detect.detect_grid = fake_detect
# The batch decodes once for grid AND key; the detector above is fake, so
# the decode is too (audio_path points at this .py file).
main._decode_for_analysis = lambda path: (detected.append(str(path)) or np.zeros(22050 * 8, np.float32), 22050)
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
@@ -239,6 +242,161 @@ with tempfile.TemporaryDirectory() as d:
jid = main.JOBS.submit("unit-probe", lambda h: h.progress(done=1, total=2, unit="bytes")).id
check("a job's unit reaches the client", wait(c, jid).get("unit") == "bytes")
print("== Analyze: BPM / Grid / Key through the routes ==")
with tempfile.TemporaryDirectory() as d:
from konduktor.core.key_detect import KeyResult
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
os.environ["KONDUKTOR_NML"] = str(work)
decodes: list[str] = []
main._decode_for_analysis = lambda path: (decodes.append(str(path)) or np.ones(22050 * 8, np.float32), 22050)
main.grid_detect.detect_grid = lambda path, *a, **k: SimpleNamespace(
anchor=k.get("anchor") or 0.5, bpm=k.get("bpm") or 133.0)
main.key_detect.detect_key_samples = lambda y, sr: KeyResult(5, "minor", 4, 0.9) # F minor, 4A
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
a.audio_path = lambda tid: Path(__file__)
keyed = [t.id for t in a.tracks if t.key_wheel is not None][:3]
unkeyed = [t.id for t in a.tracks if t.key_wheel is None][:3]
single = [t.id for t in a.tracks if t.grid_marker_count == 1 and not t.grid_locked][:3]
# Every flexible grid in the real collection is locked: make one.
flexible = single.pop()
a.add_grid_marker(flexible, a.track_cues(flexible).grid_markers[0].start + 60.0, 126.0)
bare = [t.id for t in a.tracks if t.grid_marker_count == 0][:2]
def run(**body):
r = c.post("/api/tracks/analyze", json=body)
assert r.status_code == 200, r.text
return wait(c, r.json()["id"])["result"]
r = c.post("/api/tracks/analyze", json={"track_ids": keyed, "bpm": False, "grid": False, "key": False})
check("nothing ticked is refused", r.status_code == 400, r.text)
# Key alone: an existing key is skipped unless Replace; the grid untouched.
before_grid = {t: a.track_cues(t).grid_markers for t in keyed}
before_keys = {t: a.track(t).key for t in keyed}
res = run(track_ids=keyed + unkeyed, bpm=False, grid=False, key=True)
check("Key alone sets the keyless tracks' keys", res["key"]["set"] == len(unkeyed)
and all(a.track(t).key_wheel == 4 for t in unkeyed), str(res["key"]))
check("…and skips tracks that have one", res["key"]["existing"] == len(keyed)
and {t: a.track(t).key for t in keyed} == before_keys)
check("…leaving every grid alone", {t: a.track_cues(t).grid_markers for t in keyed} == before_grid)
res = run(track_ids=keyed, bpm=False, grid=False, key=True, replace_key=True)
check("Replace keys overwrites them", res["key"]["set"] == len(keyed)
and all(a.track(t).key_wheel == 4 for t in keyed), str(res["key"]))
# The preview counts what the run does.
ids = single + [flexible] + bare
pv = c.post("/api/tracks/analyze/preview", json={"track_ids": ids, "bpm": True, "grid": False}).json()
check("preview: BPM alone adjusts single grids, skips flexible, analyses bare in full",
(pv["grid_bpm"], pv["grid_flexible"], pv["grid_full"]) == (len(single), 1, len(bare)), str(pv))
pv = c.post("/api/tracks/analyze/preview", json={"track_ids": ids, "bpm": True, "grid": True}).json()
check("preview: BPM+Grid without Replace skips every gridded track",
(pv["grid_existing"], pv["grid_full"], pv["with_grid"]) == (len(single) + 1, len(bare), len(single) + 1),
str(pv))
pv = c.post("/api/tracks/analyze/preview",
json={"track_ids": ids, "bpm": True, "grid": True, "key": True, "replace_key": True}).json()
check("preview: tracks_to_analyze counts a track once for grid AND key",
pv["tracks_to_analyze"] == len(ids), str(pv))
# BPM alone, through the run.
anchors = {t: a.track_cues(t).grid_markers[0].start for t in single}
flex_before = a.track_cues(flexible).grid_markers
decodes.clear()
res = run(track_ids=ids, bpm=True, grid=False, key=False)
check("BPM alone: the run's counts match the preview",
(res["grid"]["bpm"], res["grid"]["flexible"], res["grid"]["full"]) == (len(single), 1, len(bare)),
str(res["grid"]))
check("…single grids keep their anchor, take the new tempo",
all(abs(a.track_cues(t).grid_markers[0].start - anchors[t]) < 1e-6
and a.track_cues(t).grid_markers[0].bpm == 133.0 for t in single))
check("…a flexible grid is untouched", a.track_cues(flexible).grid_markers == flex_before)
check("…and is never decoded (nothing to do)", len(decodes) == len(single) + len(bare), str(len(decodes)))
# Grid + Key together: ONE decode per track.
decodes.clear()
res = run(track_ids=bare, bpm=True, grid=True, key=True, replace_grid=True, replace_key=True)
check("BPM+Grid+Key decodes each track once", len(decodes) == len(bare), str(decodes))
check("…and writes both", res["grid"]["full"] == len(bare) and res["key"]["set"] == len(bare), str(res))
# A grid that cannot be fitted still gets its key.
def no_pulse(*a, **k):
raise ValueError("No onsets found")
main.grid_detect.detect_grid = no_pulse
res = run(track_ids=unkeyed[:1], bpm=True, grid=True, key=True, replace_grid=True, replace_key=True)
check("a failed grid is reported and the key still written",
res["key"]["set"] == 1 and any(f["reason"].startswith("Grid:") for f in res["failed"]), str(res))
# The deck's Analyze sets the key too.
main.grid_detect.detect_grid = lambda path, *a, **k: SimpleNamespace(anchor=0.5, bpm=133.0)
main.key_detect.detect_key_samples = lambda y, sr: KeyResult(9, "minor", 8, 0.9) # A minor, 8A
r = c.post("/api/tracks/grid/auto", json={"track_id": bare[0]})
check("the deck's Analyze writes the grid AND the key",
r.status_code == 200 and a.track(bare[0]).key_wheel == 8, r.text[:200])
main.key_detect.detect_key_samples = lambda y, sr: (_ for _ in ()).throw(RuntimeError("boom"))
r = c.post("/api/tracks/grid/auto", json={"track_id": bare[1]})
check("…and a failing key never fails the grid", r.status_code == 200, r.text[:200])
check("nothing reached disk", work.read_bytes() == REAL.read_bytes())
print("== BPM alone / Grid alone write through the hand-edit commands ==")
with tempfile.TemporaryDirectory() as d:
from konduktor.adapters.traktor.adapter import TraktorAdapter
from konduktor.core.grid_plan import GridStep
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
a = TraktorAdapter(work)
a.audio_path = lambda tid: Path(__file__)
asked: list[dict] = []
def fake_detect(path, *args, **k):
asked.append({key: k.get(key) for key in ("bpm", "anchor")})
return SimpleNamespace(anchor=k.get("anchor") or 0.777, bpm=k.get("bpm") or 131.0)
main.grid_detect.detect_grid = fake_detect
def single_with_companion():
for t in a.tracks:
cues = a.track_cues(t.id)
if t.grid_locked or not cues or len(cues.grid_markers) != 1:
continue
m = cues.grid_markers[0]
comp = [c for c in cues.cues if c.slot is not None and abs(c.start - m.start) < 0.002]
if comp:
yield t.id, m, comp[0]
picks = single_with_companion()
tid, m, comp = next(picks)
out = main._analyse_grid(a, tid, GridStep("bpm", hold_anchor=m.start))
g = out.grid_markers
check("BPM alone asks the detector to hold the anchor", asked[-1] == {"bpm": None, "anchor": m.start}, str(asked[-1]))
check("…and retempos the marker in place",
len(g) == 1 and abs(g[0].bpm - 131.0) < 1e-6 and abs(g[0].start - m.start) < 1e-6, str(g))
check("…leaving its beat-1 cue where it was",
any(c.slot == comp.slot and abs(c.start - comp.start) < 1e-6 for c in out.cues))
check("the track's BPM follows", abs(a.track(tid).bpm - 131.0) < 0.01, str(a.track(tid).bpm))
tid, m, comp = next(picks)
out = main._analyse_grid(a, tid, GridStep("phase", hold_bpm=m.bpm))
g = out.grid_markers
check("Grid alone asks the detector to hold the BPM", asked[-1] == {"bpm": m.bpm, "anchor": None}, str(asked[-1]))
check("…and moves the marker, keeping its tempo",
len(g) == 1 and abs(g[0].start - 0.777) < 0.002 and abs(g[0].bpm - m.bpm) < 1e-6, str(g))
check("…dragging its beat-1 cue along",
any(c.slot == comp.slot and abs(c.start - 0.777) < 0.002 for c in out.cues))
bare = next(t for t in a.tracks if t.grid_marker_count == 0 and not t.grid_locked)
out = main._analyse_grid(a, bare.id, GridStep("phase", hold_bpm=128.0))
check("Grid alone with a BPM but no grid creates one marker at that BPM",
[(round(x.start, 3), x.bpm) for x in out.grid_markers] == [(0.777, 128.0)], str(out.grid_markers))
try:
main._analyse_grid(a, bare.id, GridStep("skip", "locked"))
check("a skip step is never written", False)
except ValueError:
check("a skip step is never written", True)
print()
print("FAILED" if failed else "RESULT: ALL PASSED")
raise SystemExit(1 if failed else 0)
+65
View File
@@ -136,6 +136,38 @@ print("== a wandering tempo is reported, not hidden ==")
r = detect(track(124, tempo_b=124.15))
check("drift is reported when one grid cannot fit", r.drift_ms is not None and r.drift_ms >= 12, f"{r.drift_ms}")
print("== Grid alone: the BPM is held, only the phase is found ==")
r = detect(track(124, first=0.3), bpm=124.0)
check("the given BPM comes back untouched", r.bpm == 124.0, f"got {r.bpm}")
check("the anchor is found on the first kick (±3 ms)", abs(r.anchor - 0.3) <= 0.003, f"got {r.anchor}")
r = detect(track(123.37, first=0.2), bpm=123.37)
check("a non-round held BPM is not snapped to 123", r.bpm == 123.37, f"got {r.bpm}")
check("…and its grid is on the beat at the end (±5 ms)", abs(beat_error_ms(r, 123.37, 0.2, 175)) <= 5)
r = detect(track(124, first=0.4, hat=1.5, bass=1.2), bpm=124.0)
check("the phase traps still hold with a held BPM",
abs(beat_error_ms(r, 124, 0.4, 60)) <= 3, f"{beat_error_ms(r, 124, 0.4, 60):+.1f} ms")
r = detect(track(87, first=0.3), bpm=174.0)
check("a held double-time BPM is kept (the octave is the user's call)",
r.bpm == 174.0 and abs(beat_error_ms(r, 87, 0.3, 60)) <= 3, f"{r.bpm} {beat_error_ms(r, 87, 0.3, 60):+.1f}")
r = detect(track(124, first=0.3), bpm=124.2)
check("a WRONG held BPM is kept, and its drift reported", r.bpm == 124.2 and r.drift_ms >= 20, f"{r.drift_ms}")
print("== BPM alone: the tempo is found, the anchor is held ==")
r = detect(track(125, first=0.3), anchor=0.3 + 2 * 60 / 125) # a downbeat two beats in
check("the tempo is detected", r.bpm == 125.0, f"got {r.bpm}")
check("the given anchor comes back untouched", r.anchor == 0.3 + 2 * 60 / 125, f"got {r.anchor}")
check("an anchor on the beat reports little drift", r.drift_ms <= 5, f"{r.drift_ms}")
r = detect(track(125, first=0.3), anchor=0.33)
check("an anchor 30 ms off the beat is kept, and the drift says so",
r.anchor == 0.33 and 25 <= r.drift_ms <= 35, f"{r.anchor} {r.drift_ms}")
print("== holding both is refused ==")
try:
detect(track(124), bpm=124.0, anchor=0.3)
check("bpm + anchor raises ValueError", False)
except ValueError:
check("bpm + anchor raises ValueError", True)
print("== nothing to fit ==")
for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short", np.zeros(SR, dtype=np.float32))):
try:
@@ -144,6 +176,39 @@ for label, y in (("silence", np.zeros(SR * 20, dtype=np.float32)), ("too short",
except ValueError:
check(f"{label} raises ValueError", True)
print("== the BPM / Grid plan (core/grid_plan) ==")
from types import SimpleNamespace as M # noqa: E402
from konduktor.core.grid_plan import plan_grid # noqa: E402
one = [M(start=0.5, bpm=124.0)]
two = [M(start=60.0, bpm=126.0), M(start=0.5, bpm=124.0)] # unsorted on purpose
def plan(bpm, grid, markers=(), track_bpm=None, locked=False, replace=False):
return plan_grid(bpm=bpm, grid=grid, markers=list(markers), track_bpm=track_bpm,
locked=locked, replace_existing=replace)
check("nothing ticked does nothing", plan(False, False, one).action == "none")
check("locked is skipped whatever is ticked",
all(plan(b, g, one, locked=True).reason == "locked" for b, g in ((1, 1), (1, 0), (0, 1))))
check("BPM+Grid on an ungridded track: full", plan(True, True).action == "full")
check("BPM+Grid on a gridded track, no Replace: skipped as existing",
plan(True, True, one).reason == "existing")
check("BPM+Grid with Replace replaces even a flexible grid", plan(True, True, two, replace=True).action == "full")
s_ = plan(True, False, one)
check("BPM alone keeps the anchor", s_.action == "bpm" and s_.hold_anchor == 0.5)
check("BPM alone ignores Replace (adjusting IS the point)", plan(True, False, one, replace=False).action == "bpm")
check("BPM alone, no grid: analysed in full", plan(True, False, track_bpm=124).action == "full")
s_ = plan(False, True, one, track_bpm=999)
check("Grid alone keeps the MARKER's BPM", s_.action == "phase" and s_.hold_bpm == 124.0)
s_ = plan(False, True, track_bpm=128.0)
check("Grid alone, no grid but a BPM: keeps that BPM", s_.action == "phase" and s_.hold_bpm == 128.0)
check("Grid alone, no BPM at all: analysed in full", plan(False, True).action == "full")
check("one tick on a flexible grid: skipped, never flattened",
plan(True, False, two).reason == "flexible" and plan(False, True, two).reason == "flexible")
print()
print("FAILED" if failed else "OK")
raise SystemExit(1 if failed else 0)
+37
View File
@@ -447,6 +447,43 @@ check("re-importing flags the tracks as already present",
check("but does not refuse them — the user chose to add everything",
len(plan8.importable) == 2)
print("== import route: chosen tracks into a playlist and an export (drag and drop) ==")
# Device tracks dropped on a collection playlist open Import with that playlist
# as the target: only the chosen tracks, no drive folder, all into the playlist.
nml9, music9, _ = fresh_collection()
drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus"
shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited"))
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
with TestClient(main.app) as c:
check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200)
check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200)
picked = c.get("/api/source/tracks", params={"limit": 10}).json()
picked = picked["items"][:1]
target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"]
eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"],
"destination": str(music9.parent / "gig")}).json()["id"]
r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]],
"into_playlist": target, "export_id": eset})
check("the import starts", r.status_code == 200, r.text[:200])
job = r.json()
for _ in range(200):
job = c.get(f"/api/jobs/{job['id']}").json()
if job["state"] != "running":
break
time.sleep(0.05)
check("…and finishes", job["state"] == "done", str(job)[:300])
entries = c.get(f"/api/playlists/{target}/tracks").json()
check("the one chosen track lands in the target playlist",
len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries]))
names = [n["name"] for n in c.get("/api/playlists").json()]
check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names))
ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset)
check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"]))
c.delete("/api/source")
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+168
View File
@@ -0,0 +1,168 @@
"""Tests for key detection (`core/key_detect.py`) on synthetic audio.
Needs no audio files: every track is generated, so its key is KNOWN. These
pin what `bench_key_detect.py` (real music) cannot: that all 24 keys come out
— a wrong label order or wheel mapping would get exactly some of them wrong —
that loudness and sample rate do not change the answer, that silence gives no
key rather than a made-up one, and that the numpy network computes what was
trained (the convolution against a direct reference implementation).
The progressions are cadences that state their key unambiguously (I-IV-V-I;
i-iv-V-i with the raised leading tone). A pop I-V-vi-IV is deliberately NOT
used: it spends a quarter of its time on the relative minor, and a model
trained on dance music — 85% minor — fairly calls some of those minor.
"""
import warnings
import numpy as np
warnings.filterwarnings("ignore")
from konduktor.core import key_detect # noqa: E402
SR = 22050
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def tone(midi: int, dur: float, amp: float, harmonics: int = 6, sr: int = SR) -> np.ndarray:
t = np.arange(int(dur * sr)) / sr
f = 440.0 * 2 ** ((midi - 69) / 12)
x = sum(np.sin(2 * np.pi * f * h * t) / h for h in range(1, harmonics + 1) if f * h < sr / 2)
env = np.minimum(1, t / 0.01) * np.minimum(1, (dur - t) / 0.05)
return amp * x * env
MAJOR = [(0, "M"), (5, "M"), (7, "M"), (0, "M")] # I IV V I
MINOR = [(0, "m"), (5, "m"), (7, "M"), (0, "m")] # i iv V i
def song(tonic: int, mode: str, bars: int = 16, bpm: float = 124.0, sr: int = SR) -> np.ndarray:
beat = 60.0 / bpm
prog = MAJOR if mode == "major" else MINOR
out = []
for b in range(bars):
root, q = prog[b % len(prog)]
r = 48 + (tonic + root) % 12
chord = sum(tone(r + 12 + i, 4 * beat, 0.12, sr=sr) for i in (0, 4 if q == "M" else 3, 7))
bass = np.concatenate([tone(r - 12, beat, 0.3, 3, sr=sr) for _ in range(4)])
n = min(len(chord), len(bass))
out.append(chord[:n] + bass[:n])
y = np.concatenate(out)
return (y / np.abs(y).max() * 0.8).astype(np.float32)
def name(pc: int, mode: str) -> str:
return key_detect.PITCH_NAMES[pc] + ("m" if mode == "minor" else "")
print("all 24 keys")
for mode in ("major", "minor"):
for pc in range(12):
r = key_detect.detect_key_samples(song(pc, mode), SR)
check(f"{name(pc, mode):4s} -> {r.name if r else None}",
r is not None and (r.pitch_class, r.mode) == (pc, mode))
if r:
check(f"{name(pc, mode):4s} wheel {r.wheel}", r.wheel == key_detect.camelot_wheel(pc, mode))
print("the Camelot mapping")
check("C major = 8B", key_detect.camelot_wheel(0, "major") == 8)
check("A minor = 8A", key_detect.camelot_wheel(9, "minor") == 8)
check("G major = 9B (a fifth up = one step)", key_detect.camelot_wheel(7, "major") == 9)
check("F minor = 4A", key_detect.camelot_wheel(5, "minor") == 4)
print("invariance")
y = song(2, "minor")
base = key_detect.detect_key_samples(y, SR)
quiet = key_detect.detect_key_samples(y * 0.05, SR)
check("a quiet master gives the same key", quiet and quiet.name == base.name)
check("...and the same confidence", quiet and abs(quiet.confidence - base.confidence) < 0.02,
f"{base.confidence:.3f} vs {quiet and quiet.confidence:.3f}")
hi = key_detect.detect_key_samples(song(2, "minor", sr=44100), 44100)
check("44.1 kHz input gives the same key", hi and hi.name == base.name)
check("confidence is a probability", 0.0 < base.confidence <= 1.0)
print("nothing to say")
check("silence -> None", key_detect.detect_key_samples(np.zeros(SR * 30, np.float32), SR) is None)
check("under 5 s -> None", key_detect.detect_key_samples(song(0, "major")[: SR * 3], SR) is None)
print("the numpy network")
rng = np.random.default_rng(1)
x = rng.standard_normal((3, 20, 300)).astype(np.float32) # > one time chunk, odd sizes
w = rng.standard_normal((4, 3, 5, 5)).astype(np.float32)
b = rng.standard_normal(4).astype(np.float32)
got = key_detect._conv5(x, w, b)
xp = np.pad(x, ((0, 0), (2, 2), (2, 2)))
ref = np.zeros_like(got)
for o in range(4):
for i in range(3):
for di in range(5):
for dj in range(5):
ref[o] += w[o, i, di, dj] * xp[i, di:di + 20, dj:dj + 300]
ref[o] += b[o]
check("5x5 'same' conv == direct cross-correlation", np.allclose(got, ref, atol=1e-3),
f"max diff {np.abs(got - ref).max():.2e}")
members = key_detect._members()
check("the shipped model is an ensemble of >= 1 network", len(members) >= 1)
spec = key_detect.features(y, SR)
check("24 logits", key_detect.logits(spec).shape == (24,))
print("end to end: the Analyze route with the REAL decode and detectors")
# Every other route test fakes the detectors. A route can still be broken
# around working helpers (Auto Hotcues' once 500'd for a week), so one real
# run: a generated F minor track at 124 BPM, written to a WAV, analysed for
# BPM + Grid + Key through `/api/tracks/analyze` on a temp copy of the collection.
import os # noqa: E402
import shutil # noqa: E402
import tempfile # noqa: E402
import time # noqa: E402
from pathlib import Path # noqa: E402
import soundfile # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
with tempfile.TemporaryDirectory() as d:
os.environ["KONDUKTOR_DATA_DIR"] = str(Path(d) / "appdata")
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
os.environ["KONDUKTOR_NML"] = str(work)
music = song(5, "minor", bars=24, bpm=124.0)
kick = np.zeros_like(music)
beat = int(round(SR * 60 / 124.0))
t = np.arange(int(0.12 * SR)) / SR
hit = (np.sin(2 * np.pi * 55 * t) * np.exp(-t / 0.05)).astype(np.float32)
for i in range(0, len(kick) - len(hit), beat):
kick[i:i + len(hit)] += hit
wav = Path(d) / "f-minor.wav"
soundfile.write(wav, 0.6 * music + 0.4 * kick, SR)
from fastapi.testclient import TestClient
import konduktor.main as main
with TestClient(main.app) as c:
a = main.require_adapter()
tid = next(t.id for t in a.tracks if t.grid_marker_count == 0 and t.key_wheel is None)
a.audio_path = lambda track_id: wav
r = c.post("/api/tracks/analyze", json={"track_ids": [tid], "bpm": True, "grid": True, "key": True})
job = r.json()
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
res = job.get("result") or {}
check("the run finishes without failures", job["state"] == "done" and not res.get("failed"), str(job)[:300])
track = a.track(tid)
check("the key is F minor (4A), written in the collection's Open Key (9m)",
(track.key_wheel, track.key_mode, track.key) == (4, "minor", "9m"),
f"{track.key} {track.key_wheel} {track.key_mode}")
g = a.track_cues(tid).grid_markers
check("the grid is 124 BPM", len(g) == 1 and abs(g[0].bpm - 124.0) < 0.05, str(g))
print("\nFAILED" if failed else "\nall key-detection tests passed")
raise SystemExit(1 if failed else 0)
+35
View File
@@ -95,5 +95,40 @@ for platform, module in NATIVE.items():
]
check(f"the {platform} adapter does import {module} somewhere", bool(own), "nowhere")
print("== remote libraries ==")
# The remote adapter speaks a PROTOCOL; which platform the server holds is the
# server's business. Importing a platform's adapter (or its library) here would
# make a remote library quietly platform-shaped again.
remote_pkg = CORE.parent / "adapters" / "remote"
strays = []
for src in sorted(remote_pkg.rglob("*.py")):
tree = ast.parse(src.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
mod = node.module or ""
if node.level and any(mod == p or mod.startswith(p + ".") for p in NATIVE):
strays.append(f"{src.name}: ..{mod}")
if not node.level and any(mod.startswith(m) for m in set(NATIVE.values())):
strays.append(f"{src.name}: {mod}")
elif isinstance(node, ast.Import):
for a in node.names:
if any(a.name.startswith(m) for m in set(NATIVE.values())):
strays.append(f"{src.name}: {a.name}")
check("the remote adapter imports no platform adapter or library", not strays, "; ".join(strays))
# The server is lightweight by decision: it never decodes audio, so importing
# it must not pull in the analysis stack (and its image ships without it).
import subprocess
probe = subprocess.run(
[sys.executable, "-c",
"import sys, konduktor.server.app; "
"print(','.join(m for m in ('librosa', 'sklearn', 'torch', 'numba', 'av') if m in sys.modules))"],
capture_output=True, text=True, cwd=str(CORE.parents[1]),
)
heavy = probe.stdout.strip()
check("the server imports no audio-analysis library", probe.returncode == 0 and not heavy,
heavy or probe.stderr[-300:])
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+94 -1
View File
@@ -60,7 +60,7 @@ def dump(db: Path) -> dict:
"""Every row of every table; keyed by primary key, or by the whole row for
the link tables, which have none."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db))
@@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close()
print("== moving playlists (sidebar drag and drop) ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
folder = a.create_folder("Gigs")
probe = a.create_playlist("Probe")
a.save()
before = dump(db_of(drive))
check("every node offers can_move", all(n.can_move for n in a.playlist_tree()))
demos = next(n for n in a.playlist_tree() if n.name == "demos")
a.move_playlist(demos.id, folder, 0)
a.move_playlist(probe, None, 1)
tree = a.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id])
check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe],
str([n.name for n in tree]))
check("a folder cannot be moved into itself",
_raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand))
check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand))
a.save()
after = dump(db_of(drive))
changes = diff(before, after)
check("only playlist rows change, by UPDATE",
{(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes))
check("only parent and sequenceNo columns change",
{c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"},
str([f for *_, f in changes]))
for parent in (0, int(folder)):
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent)
check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs))
a.close()
reopened = OneLibraryAdapter(drive)
check("the move round-trips through a reopen",
[c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id])
reopened.move_playlist(probe, None, 1)
check("moving a node onto its own place is not an edit", reopened.dirty is False)
reopened.close()
# ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==")
drive = fresh_drive()
@@ -349,6 +387,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)
+3 -1
View File
@@ -65,7 +65,7 @@ def fingerprint(root: Path) -> str:
def rows(root: Path, sql: str):
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.devicelib_plus.database import BLOB
from pyrekordbox.onelibrary.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(root / "PIONEER" / "rekordbox" / "exportLibrary.db"))
@@ -237,6 +237,8 @@ target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ONE, target)
[pending] = a.add_tracks([NewTrack(track=Track(id="x", title="Kick"), audio_path=target)])
check("an unsaved add plays from its incoming copy", a.track(pending).filepath == str(target))
check("a file with no key of its own arrives with one detected", a.track(pending).key_wheel is not None,
str(a.track(pending).key))
a.reload()
check("Discard deletes the copy and leaves the stick as it was",
not target.exists() and fingerprint(drive) == before and a.track(pending) is None)
+37
View File
@@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete",
check("unknown folder is 404",
client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
print("== drag and drop: add with duplicates, move ==")
target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"]
first, rest = track_ids[:2], track_ids[2:4]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json()
check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json()
check("'ask' with a duplicate changes nothing and counts it",
r["status"] == "duplicates" and r["duplicates"] == 1
and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json()
check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1], "duplicates": "add"}).json()
check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0})
check("moving a folder answers its (path) id", r.json()["id"] == box)
check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0})
check("a folder into itself is a 400", r.status_code == 400)
r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0})
check("an unknown node is a 404", r.status_code == 404)
client.delete(f"/api/playlists/{box}")
client.post("/api/save")
check("COLLECTION still byte-identical after drops and moves",
collection_span(WORK.read_bytes()) == collection_before)
print("== original untouched ==")
check(
"original collection.nml never modified",
+8 -2
View File
@@ -36,13 +36,19 @@ def check(label, cond, detail=""):
failed = True
opts = platforms()
everything = platforms()
# A remote library is offered LAST, after every platform on this computer: it is
# a way to reach a library (held by a Konduktor server), not a driver here.
opts = [p for p in everything if p.platform != "remote"]
by_name = {p.platform: p for p in opts}
print("== /api/platforms reports the facts the platform step needs ==")
check("every registered driver is offered", len(opts) == len(registry.drivers()),
f"{len(opts)} of {len(registry.drivers())}")
check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name))
check("Remote is offered once, after them, as a remote",
[p.platform for p in everything].count("remote") == 1 and everything[-1].platform == "remote"
and everything[-1].selects == "remote")
check("selects is per-platform, not assumed",
by_name["traktor"].selects == "file"
and by_name["rekordbox"].selects == "file"
@@ -61,7 +67,7 @@ check("ordered fixed-location first, then by name",
[p.platform for p in opts] == [p.platform for p in
sorted(opts, key=lambda o: (o.removable, o.name.lower()))],
[p.platform for p in opts])
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts])
check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in everything])
print("== /api/library/options is scoped to ONE platform ==")
for plat in ("traktor", "rekordbox", "onelibrary"):
+104
View File
@@ -0,0 +1,104 @@
"""userprefs.json under concurrent writes.
The UI sends several `PATCH /api/prefs` at once on launch (column layout, deck
zoom, loop size), and FastAPI runs them on a thread pool. Before the lock and
the atomic write, a reader could catch the file truncated mid-write, take it for
"no prefs" and write back only its own key — the column layout, and with it
every other pref, vanished between sessions (249 of 300 trials of the burst
below lost the other keys). Nothing failed; the app just forgot.
Prefs are redirected to a temp file — a test must never rewrite the user's own.
"""
import tempfile
import threading
from pathlib import Path
from konduktor import prefs
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
BASE = {"columns": {"order": ["a", "b"]}, "autoCueTemplate": [1, 2, 3], "beatSize": 4}
PATCHES = [
{"columns": {"order": ["b", "a"]}},
{"mainZoomSec": 16},
{"beatSize": 8},
{"stemDevice": "cpu"},
]
# The launch burst, many times over: every patch lands and nothing else is lost.
TRIALS = 200
bad = []
for i in range(TRIALS):
prefs.save_prefs(BASE)
go = threading.Barrier(len(PATCHES) + 1)
def write(p):
go.wait()
prefs.update_prefs(p)
def read():
go.wait()
for _ in range(20):
if "autoCueTemplate" not in prefs.load_prefs():
bad.append(f"trial {i}: a reader saw no prefs")
return
threads = [threading.Thread(target=write, args=(p,)) for p in PATCHES]
threads.append(threading.Thread(target=read))
for t in threads:
t.start()
for t in threads:
t.join()
got = prefs.load_prefs()
want = {**BASE, **{k: v for p in PATCHES for k, v in p.items()}}
if got != want:
bad.append(f"trial {i}: {got}")
check(f"{TRIALS} concurrent bursts keep every key and every patch", not bad,
bad[0] if bad else "")
# The path-specific helpers share the lock: a burst of them loses nothing either.
prefs.save_prefs({"autoCueTemplate": [1]})
threads = [threading.Thread(target=prefs.set_last_collection, args=(f"/lib/{p}", p))
for p in ("traktor", "rekordbox", "onelibrary")]
threads += [threading.Thread(target=prefs.set_path_mapping, args=(f"/c{n}", "X:", "/Volumes/X"))
for n in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
got = prefs.load_prefs()
check("concurrent last-collection writes keep every platform",
set(got.get("last_collection_by_platform", {})) == {"traktor", "rekordbox", "onelibrary"},
str(got))
check("concurrent path mappings keep every collection",
set(got.get("path_mappings", {})) == {"/c0", "/c1", "/c2"}, str(got))
check("and the unrelated key survives", got.get("autoCueTemplate") == [1])
# A file that will not parse is moved aside, never silently overwritten.
prefs._PREFS_PATH.write_text('{"columns": {"order": ["a"')
check("an unreadable file reads as no prefs", prefs.load_prefs() == {})
check("reading leaves it in place", prefs._PREFS_PATH.read_text().startswith('{"columns"'))
prefs.update_prefs({"beatSize": 2})
corrupt = prefs._PREFS_PATH.with_name("userprefs.json.corrupt")
check("writing over it keeps the old bytes beside it",
corrupt.exists() and corrupt.read_text() == '{"columns": {"order": ["a"')
check("and the new file holds the patch", prefs.load_prefs() == {"beatSize": 2})
check("no temp file is left behind",
not [p for p in Path(_TMP.name).iterdir() if ".tmp" in p.name])
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup()
raise SystemExit(1 if failed else 0)
+101
View File
@@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
failed = False
@@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d:
folder_reopened.close()
after_folder.close()
# ---- E2: moving nodes in the tree (sidebar drag and drop) -----------
print("== E2: move_playlist reorders and reparents, touching only playlist rows ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
adapter = RekordboxAdapter(work)
folder_id = adapter.create_folder("Konduktor Move Folder")
a_id = adapter.create_playlist("Konduktor Move A")
b_id = adapter.create_playlist("Konduktor Move B")
adapter.save()
adapter.close()
before = dump(work)
adapter = RekordboxAdapter(work)
check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree()))
adapter.move_playlist(b_id, folder_id, 0)
adapter.move_playlist(a_id, None, 0)
tree = adapter.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id,
[n.name for n in tree[:3]])
try:
adapter.move_playlist(folder_id, folder_id, 0)
check("a folder cannot be moved into itself", False)
except InvalidCommand:
check("a folder cannot be moved into itself", True)
adapter.save()
changes = diff(before, dump(work))
check("only djmdPlaylist rows and the counter change",
{t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes))
rows = dump(work)["djmdPlaylist"]
for parent in ("root", folder_id):
seqs = sorted(int(r["Seq"]) for r in rows.values()
if str(r["ParentID"]) == parent and not r["rb_local_deleted"])
check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs)
adapter.close()
reopened = RekordboxAdapter(work)
tree = reopened.playlist_tree()
check("the moves round-trip through a reopen",
tree[0].id == a_id
and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
reopened.move_playlist(b_id, None, len(tree))
check("a playlist moved out of a folder lands last at the top level",
reopened.playlist_tree()[-1].id == b_id)
reopened.close()
again = final = RekordboxAdapter(work)
# ---- F: a cue write touches the cue row AND its mirror ---------------
print("== F: a hot cue write is localized, and keeps the mirror in step ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
@@ -684,6 +730,13 @@ with tempfile.TemporaryDirectory() as d:
plain_row["DeviceID"] == next(iter(before["djmdContent"].values()))["DeviceID"])
check("the release year is kept", plain_row["ReleaseYear"] == 2021)
check("the key is rendered, not copied", prepped_row["KeyID"] is not None)
from konduktor.adapters.rekordbox.projection import parse_key as _pk
key_rows = dump(work)["djmdKey"]
check("a source's own key is kept, not re-detected",
_pk(key_rows[str(prepped_row["KeyID"])]["ScaleName"]) == (10, "minor"),
str(key_rows.get(str(prepped_row["KeyID"]))))
check("a file with no key of its own gets one detected",
plain_row["KeyID"] is not None and str(plain_row["KeyID"]) in key_rows, str(plain_row["KeyID"]))
files: dict[str, list] = {}
for r in after["contentFile"].values():
files.setdefault(str(r["ContentID"]), []).append(r)
@@ -736,5 +789,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)
+427
View File
@@ -0,0 +1,427 @@
"""A remote library, end to end: a real server, the app's own routes.
A Konduktor server (`konduktor.server`) runs in a thread on a temp copy of the
real collection, its audio mapped onto generated MP3s; the app (`main.py`)
opens it through the picker's routes, exactly as the desktop app would. Pins:
* a remote is saved only after a handshake — a wrong password is refused with
nothing saved, and an unreachable PRIMARY falls back to the fallback;
* the remote is offered as a platform, and opens as THE library: projection,
capabilities (destination on the library, no reference, no remapping);
* edits go to the server and come back in the mirror; Save writes on the
server and touches only the edited ENTRY (the fidelity guarantee survives
the trip); a no-op save writes nothing; history lists the server's
versions; discard drops edits there;
* audio is downloaded once into the cache, by what the server says the file
is; analysis (Analyze grid) runs here on that copy and lands on the server;
* another computer taking over makes this one read-only — at the next
command, not the next heartbeat — and reopening says who holds it, offers
the takeover and names the edits left behind;
* export sets are kept by the server, and an export from the remote library
copies the audio, then re-exports copying nothing;
* importing a file UPLOADS it into a folder on the server and adds it there;
* opening a local library releases the server's session.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import threading
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remote-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
import uvicorn
from fastapi.testclient import TestClient
from konduktor import history
from konduktor import remote_protocol as rp
from konduktor.adapters.remote import config as remote_config
from konduktor.adapters.remote.client import RemoteClient
from konduktor.adapters.traktor.adapter import TraktorAdapter
from konduktor.app_state import AppState
from konduktor.core.pathmap import PathMapping
from konduktor.server.app import Server, create_app
from konduktor.server.config import ServerConfig
from konduktor.server.session import SessionLock
from stem_test_support import make_mp3
class MemoryKeychain:
def __init__(self):
self.items = {}
def get(self, account):
return self.items.get(account)
def set(self, account, password):
self.items[account] = password
def delete(self, account):
self.items.pop(account, None)
remote_config.use_password_store(MemoryKeychain())
def serve(app):
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=0, log_level="warning"))
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
for _ in range(200):
if server.started:
break
time.sleep(0.05)
return server, server.servers[0].sockets[0].getsockname()[1]
def entry_span(data: bytes, file_name: str):
marker = f'FILE="{file_name}"'.encode()
i = data.find(marker)
return data.rfind(b"<ENTRY ", 0, i), data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
with tempfile.TemporaryDirectory() as d:
root = Path(d)
work = root / "library" / "collection.nml"
work.parent.mkdir()
shutil.copy2(REAL, work)
content = (root / "music").resolve()
content.mkdir()
# Map one folder of the collection onto generated audio on the "server".
probe = TraktorAdapter(work)
by_dir: dict[Path, list[str]] = {}
for t in probe.tracks:
p = probe.audio_path(t.id)
if p is not None and p.suffix.lower() == ".mp3":
by_dir.setdefault(p.parent, []).append(t.id)
folder, ids = max(by_dir.items(), key=lambda kv: len(kv[1]))
ids = ids[:3]
mapped = content / "Mapped"
for n, tid in enumerate(ids):
make_mp3(mapped / probe.audio_path(tid).name, seconds=4, seed=n + 1)
probe_paths = {tid: probe.audio_path(tid) for tid in ids}
del probe
t = [1000.0]
cfg = ServerConfig(platform="traktor", library=work, content=content, username="dj",
password="secret", name="NAS",
path_maps=(PathMapping.make(str(folder), str(mapped)),))
srv = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
srv.open()
uv, port = serve(create_app(srv))
server_adapter = srv.state.adapter
import konduktor.main as main
c = TestClient(main.app)
print("== saving a remote ==")
form = {"name": "NAS", "host": "127.0.0.1:1", "fallback_host": f"127.0.0.1:{port}",
"username": "dj", "password": "wrong"}
r = c.post("/api/remotes", json=form)
check("a wrong password is refused, nothing saved",
r.status_code == 400 and "password" in r.json()["detail"]["message"].lower()
and c.get("/api/remotes").json() == [], r.text[:200])
form["password"] = "secret"
r = c.post("/api/remotes", json=form)
body = r.json()
check("the right one saves, reporting each address",
r.status_code == 200 and [x["kind"] for x in body["results"]] == ["unreachable", "ok"], r.text[:300])
remote_id = body["remote"]["id"]
check("the password is in the keychain, not prefs",
"secret" not in Path(os.environ["KONDUKTOR_DATA_DIR"], "userprefs.json").read_text())
plats = c.get("/api/platforms").json()
check("Remote is offered as a platform, last", plats[-1]["platform"] == "remote"
and plats[-1]["found"] == 1 and plats[-1]["selects"] == "remote")
print("== opening it ==")
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
status = r.json()
check("it opens as THE library", r.status_code == 200 and status["loaded"]
and status["tracks"] == len(server_adapter.tracks), r.text[:300])
check("…named as saved, reached through the fallback",
status["library"]["display_name"] == "NAS" and status["library"]["remote"]["via"] == "fallback")
caps = c.get("/api/capabilities").json()
check("its capabilities: the destination is the server's, nothing referenced, nothing remapped",
caps["writable"] and caps["tracks"]["audio_destination"] == "library"
and not caps["tracks"]["reference"] and not caps["paths"]["remappable"])
page = c.get("/api/tracks", params={"limit": 20000}).json()
check("the table reads from the mirror", page["total"] == len(server_adapter.tracks))
check("the server shows this computer holding the session",
srv.lock.describe()["machine"] == remote_config.machine_name())
print("== edits and saves ==")
target = ids[0]
file_name = probe_paths[target].name
original = work.read_bytes()
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
check("an edit applies on the server", r.status_code == 200
and server_adapter.track(target).genre == "Remote Edit")
check("…and in the mirror", main.require_adapter().track(target).genre == "Remote Edit")
r = c.post("/api/tracks/cue", json={"track_id": target, "slot": 4, "start": 1.0, "type": "cue"})
check("a hotcue goes to the server", r.status_code == 200
and any(cu["slot"] == 4 for cu in server_adapter.track_cues(target).model_dump()["cues"]), r.text[:200])
check("the state says unsaved", c.get("/api/state").json()["dirty"] is True)
versions = len(history.list_history(work))
r = c.post("/api/save").json()
saved = work.read_bytes()
check("save writes on the server", r["saved"] and saved != original)
s0, e0 = entry_span(original, file_name)
s1, e1 = entry_span(saved, file_name)
check("…changing nothing outside the edited ENTRY",
original[:s0] == saved[:s1] and original[e0:] == saved[e1:])
check("…and is versioned there", len(history.list_history(work)) == versions + 1
and len(c.get("/api/history").json()) == versions + 1)
r = c.post("/api/save").json()
check("a no-op save writes nothing", r["saved"] is False and work.read_bytes() == saved)
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Throw away"}})
r = c.post("/api/discard")
check("discard drops the edit on the server", r.status_code == 200 and not server_adapter.dirty
and server_adapter.track(target).genre == "Remote Edit"
and main.require_adapter().track(target).genre == "Remote Edit", r.text[:200])
print("== version history, on the server ==")
listed = c.get("/api/history").json()
oldest = listed[-1]["id"]
r = c.post(f"/api/history/{oldest}/restore")
check("restoring a version writes it back ON THE SERVER", r.status_code == 200
and work.read_bytes() == original, r.text[:200])
check("…as a new version", len(c.get("/api/history").json()) == len(listed) + 1)
server_adapter = srv.state.adapter # a restore reopens the library there
check("…and the mirror follows", main.require_adapter().track(target).genre
== server_adapter.track(target).genre)
# Back to the edited state, for what follows.
c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Remote Edit"}})
c.post("/api/save")
print("== audio, on this computer ==")
adapter = main.require_adapter()
downloads = []
real_download = adapter.client.download
adapter.client.download = lambda *a, **k: (downloads.append(a[0]), real_download(*a, **k))[1]
r = c.get("/api/tracks/audio", params={"track_id": target})
served = (mapped / file_name).read_bytes()
check("the deck's audio is the server's file", r.status_code == 200 and r.content == served)
c.get("/api/tracks/audio", params={"track_id": target})
check("…downloaded once, then served from the cache", downloads == [target], downloads)
cached = adapter.cached_audio(target)
check("the cache keys it by what the server says the file is",
cached is not None and cached.read_bytes() == served and cached.suffix == ".mp3")
r = c.post("/api/tracks/grid/auto", json={"track_id": target})
grid = server_adapter.track_cues(target).grid_markers
check("Analyze runs here and the grid lands on the server",
r.status_code == 200 and grid and abs(grid[0].bpm - 120) < 1.5, r.text[:200])
check("…with no second download", downloads == [target], downloads)
c.post("/api/save")
print("== export, from the server's library ==")
dest = root / "stick"
r = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"], "destination": str(dest)})
set_id = r.json().get("id")
c.post(f"/api/exports/{set_id}/add", json={"track_ids": ids})
doc = c.get("/api/exports").json()
check("an export set is created", set_id and any(s["id"] == set_id for s in doc), r.text[:300])
import httpx
kept = httpx.get(f"http://127.0.0.1:{port}/v1/export-sets", auth=("dj", "secret")).json()
check("…and kept by the server", set_id in kept["sets"], kept)
def run_export():
job = c.post(f"/api/exports/{set_id}/run").json()
for _ in range(600):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
return j
downloads.clear()
job = run_export()
copies = sorted(p for p in (dest / "Contents").rglob("*.mp3"))
check("the export copies every track's audio onto the stick",
job["state"] == "done" and len(copies) == len(ids), job.get("error"))
check("…downloading only what the cache lacked", sorted(downloads) == sorted(ids[1:]), downloads)
inodes = {p: p.stat().st_ino for p in copies}
downloads.clear()
job = run_export()
check("a re-export copies nothing", job["state"] == "done"
and all(p.stat().st_ino == i for p, i in inodes.items()) and downloads == [], downloads)
print("== importing: an upload into the server ==")
incoming = make_mp3(root / "laptop" / "Brand New.mp3", seconds=3, seed=9)
# The folder-add path: a folder of loose files on THIS computer.
c.get("/api/folder/tracks", params={"path": str(incoming.parent)}) # the scan the add reads
add = {"track_ids": [str(incoming)], "mode": "copy", "destination": str(mapped / "Incoming")}
r = c.post("/api/folder/add/preview", json=add)
check("(preview) adding a local file to the remote library, space read from the server",
r.status_code == 200 and r.json()["free_bytes"], r.text[:300])
job = c.post("/api/folder/add", json=add).json()
for _ in range(400):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
time.sleep(0.05)
landed = mapped / "Incoming" / "Brand New.mp3"
check("the file is uploaded into the chosen folder ON THE SERVER",
j["state"] == "done" and landed.read_bytes() == incoming.read_bytes(), j.get("error"))
added = [tr for tr in server_adapter.tracks if (tr.filepath or "").endswith("Brand New.mp3")]
check("…and added to the server's library", len(added) == 1)
from konduktor.adapters.traktor.locations import os_path_to_location
stored = "".join(os_path_to_location(folder / "Incoming" / "Brand New.mp3"))
check("…stored as the collection stores every other path (the mapping, inverted)",
added and added[0].id == stored, added[0].id if added else None)
check("…and still resolving to the uploaded file", added and server_adapter.audio_path(added[0].id) == landed)
check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3")
for tr in main.require_adapter().tracks))
print("== the content folder, browsed like a drive ==")
loose = make_mp3(content / "Crate" / "Loose One.mp3", seconds=3, seed=11)
drives = c.get("/api/fs/drives").json()
check("the server is listed first among the drives, under the remote's name",
drives and drives[0] == {"name": "NAS", "path": "server:", "kind": "server", "library": None},
drives[:1])
tops = c.get("/api/fs/folders", params={"path": "server:"}).json()
check("its Files tree starts at the content folder",
{e["name"] for e in tops} >= {"Crate", "Mapped"}
and all(e["path"].startswith("server:") for e in tops), tops)
r = c.get("/api/folder/tracks", params={"path": f"server:{content}/Mapped"})
listed = r.json()
check("a folder's files the library holds are listed AS its tracks, ticked off",
r.status_code == 200 and sorted(tr["id"] for tr in listed["tracks"]) == sorted(ids)
and sorted(listed["in_collection"]) == sorted(ids) and not listed["removable"]
and all(v.startswith("server:") for v in listed["files"].values()), r.text[:300])
check("…with the collection's data, not the file's tags",
next(tr for tr in listed["tracks"] if tr["id"] == target)["genre"] == "Remote Edit")
r = c.get("/api/folder/tracks", params={"path": "server:/etc"})
check("…and nothing outside the content folder is listed", r.status_code == 400, r.text[:200])
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
loose_id = f"server:{loose}"
check("a file the library does not hold is listed unticked",
[tr["id"] for tr in crate["tracks"]] == [loose_id] and crate["in_collection"] == [])
caps = c.get("/api/folder/capabilities", params={"path": f"server:{content}/Crate"}).json()
check("…read-only, like any browsed folder", not caps["writable"]
and caps["readonly_cause"] == "not_in_library")
folder_downloads = []
real_folder_download = adapter.client.folder_download
adapter.client.folder_download = lambda *a, **k: (folder_downloads.append(a[0]),
real_folder_download(*a, **k))[1]
r = c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
check("the deck can audition it", r.status_code == 200 and r.content == loose.read_bytes())
c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
check("…downloaded once", folder_downloads == [str(loose)], folder_downloads)
r = c.get("/api/folder/tracks/audio", params={"track_id": f"server:{content}/Crate/nope.mp3"})
check("a file no listing returned is not served", r.status_code == 404)
srv_unlisted = httpx.get(f"http://127.0.0.1:{port}/v1/folder/audio",
params={"path": str(work)}, auth=("dj", "secret"))
check("…nor, asked of the server directly, anything outside the content folder",
srv_unlisted.status_code == 400, srv_unlisted.text[:200])
pl = c.post("/api/playlists", json={"name": "From the server"}).json()["id"]
held_track = listed["in_collection"][0]
held_id = listed["files"][held_track] # adding speaks in folder ids
add = {"track_ids": [loose_id, held_id], "mode": "reference", "playlist_id": pl}
r = c.post("/api/folder/add/preview", json=add)
pv = r.json()
check("(preview) one new, one already held, nothing to copy",
r.status_code == 200 and pv["importable"] == 1 and len(pv["existing"]) == 1
and pv["total_bytes"] == 0 and pv["enough_space"] is None, r.text[:300])
mixed = c.post("/api/folder/add/preview", json={**add, "track_ids": [loose_id, str(incoming)]})
check("files here and on the server are not mixed in one add", mixed.status_code == 400)
# Pretend the platform analyses what it adds (as Rekordbox does): the file
# is then fetched and analysed HERE, and the server receives the result.
received = []
real_add = server_adapter.add_tracks
server_adapter.add_tracks = lambda items, **k: (received.extend(items), real_add(items, **k))[1]
server_adapter.analysis_lead = lambda path: 0.0
before = sorted(p.name for p in content.rglob("*") if p.is_file())
job = c.post("/api/folder/add", json=add).json()
for _ in range(400):
j = c.get(f"/api/jobs/{job['id']}").json()
if j["state"] != "running":
break
time.sleep(0.05)
del server_adapter.analysis_lead
server_adapter.add_tracks = real_add
added = [tr for tr in server_adapter.tracks if server_adapter.audio_path(tr.id) == loose]
check("the file is added to the library WHERE IT IS", j["state"] == "done" and len(added) == 1,
j.get("error"))
check("…nothing uploaded or copied", sorted(p.name for p in content.rglob("*") if p.is_file()) == before)
check("…analysed here on the cached copy, the result sent along",
len(received) == 1 and received[0].analysis is not None and folder_downloads == [str(loose)],
f"{len(received)} {folder_downloads}")
entries = server_adapter.playlist_entries(pl) or []
check("…both land in the playlist, the held one not added twice",
added and entries == [added[0].id, held_track]
and len(server_adapter.tracks) == len(main.require_adapter().tracks), entries)
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
check("…and the folder now shows it ticked off, as the collection track",
crate["in_collection"] == [added[0].id] and crate["files"] == {added[0].id: loose_id}
if added else False, crate)
check("the save is versioned on the server", not server_adapter.dirty)
print("== another computer takes over ==")
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret")
other.acquire("other-client", "Studio iMac", takeover=True)
other.rpc("set_track_metadata", track_id=ids[1], fields={"comment": "from the studio"})
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"genre": "Too late"}})
check("this computer's next command is refused, naming who took it",
r.status_code == 503 and "Studio iMac" in r.json()["detail"], r.text[:200])
st = c.get("/api/state").json()
check("…and it is read-only now, at once", st["remote"]["state"] == "taken_over"
and st["remote"]["machine"] == "Studio iMac")
caps = c.get("/api/capabilities").json()
check("…through its capabilities", not caps["writable"] and caps["readonly_cause"] == "taken_over")
check("the server still has the genre this computer saved", server_adapter.track(target).genre == "Remote Edit")
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
check("reopening says who holds it", r.status_code == 409
and r.json()["detail"]["machine"] == "Studio iMac", r.text[:200])
r = c.post("/api/library/open-remote", json={"remote_id": remote_id, "takeover": True})
pending = r.json().get("pending_edits")
check("taking it back names the edits the other computer left",
r.status_code == 200 and pending and pending["machine"] == "Studio iMac", r.text[:300])
check("…which the mirror shows", main.require_adapter().track(ids[1]).comment == "from the studio")
other.close()
print("== the server forgets the session (a restart) ==")
c.post("/api/save") # nobody's edits pending, as after a real restart
srv.lock = SessionLock(clock=lambda: t[0])
main.STATE.remote.beat()
d = c.get("/api/state").json()["remote"]
h = srv.lock.holder()
check("the session is taken back without asking, and the user told",
d["state"] == "connected" and d["notices"] == 1 and d["notice"]
and h is not None and h.machine == remote_config.machine_name(), d)
r = c.patch("/api/tracks", json={"track_id": target, "fields": {"comment": "after restart"}})
check("…and edits go through again", r.status_code == 200
and server_adapter.track(target).comment == "after restart", r.text[:200])
print("== leaving ==")
local = root / "local.nml"
shutil.copy2(REAL, local)
r = c.post("/api/library/open", json={"path": str(local)})
check("opening a local library releases the server's session",
r.status_code == 200 and srv.lock.holder() is None, r.text[:200])
uv.should_exit = True
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+151
View File
@@ -0,0 +1,151 @@
"""The wire contract between a Konduktor server and the app (`remote_protocol.py`).
Pure: no library, no network. Pins what would go wrong SILENTLY:
* every member of `LibraryAdapter` is either an RPC or excluded with a reason
— a command added to the protocol later cannot be quietly missing from
remote libraries (the remote adapter would raise AttributeError mid-edit);
* every command is MUTATING — one that was not would skip the session check,
letting a displaced computer keep editing;
* arguments and results survive JSON by the protocol's own types (tuples,
dataclasses, pydantic models, `None`), and a misspelt argument is refused;
* a prepared analysis (waveform, grid, key) crosses intact;
* the version rule: same major, server minor ≥ client's.
"""
from __future__ import annotations
import json
import sys
import warnings
warnings.filterwarnings("ignore")
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
import numpy as np
from konduktor import remote_protocol as rp
from konduktor.core import waveform
from konduktor.core.adapter import AudioFacts, PreparedAnalysis
from konduktor.core.model import AutoHotcue, GridMarker, Track, TrackCues
print("== coverage ==")
members = rp.protocol_members()
missing = members - set(rp.RPC) - set(rp.EXCLUDED)
check("every protocol member is an RPC or excluded", not missing, sorted(missing))
stray = (set(rp.RPC) | set(rp.EXCLUDED)) - members
check("…and nothing is listed that the protocol lacks", not stray, sorted(stray))
check("no member is both", not (set(rp.RPC) & set(rp.EXCLUDED)))
check("every exclusion says why", all(len(r) > 10 for r in rp.EXCLUDED.values()))
VERBS = ("set_", "create_", "delete_", "rename_", "add_", "remove_", "move_", "replace_", "place_", "apply_")
commands = {m for m in members if m.startswith(VERBS)}
unguarded = {m for m in commands if m in rp.RPC and not rp.RPC[m].mutating}
check("every command that travels needs the session", not unguarded, sorted(unguarded))
reads = {"tracks", "track", "track_cues", "query_tracks", "capabilities", "audio_facts", "dirty"}
check("reads do not", all(not rp.RPC[m].mutating for m in reads))
for name in rp.RPC:
try:
rp._params(name)
rp._adapter(rp._result_hint(name))
except Exception as ex: # noqa: BLE001
check(f"{name}: types resolve", False, repr(ex))
print("== round trips ==")
def through_json(name, args):
wire = json.loads(json.dumps({"args": rp.dump_args(name, args)}))
return rp.load_args(name, wire["args"])
got = through_json("set_cue", {"track_id": "a", "slot": 2, "start_sec": 1.5, "cue_type": "loop",
"length_sec": 4.0, "name": None})
check("set_cue's arguments survive", got == {"track_id": "a", "slot": 2, "start_sec": 1.5,
"cue_type": "loop", "length_sec": 4.0, "name": None}, got)
got = through_json("replace_grid", {"track_id": "a", "markers": [(0.1, 128.0), (60.0, 130.0)]})
check("a grid's (start, bpm) tuples survive", got["markers"] == [(0.1, 128.0), (60.0, 130.0)], got)
cue = AutoHotcue(slot=1, start=12.0, name="Drop")
got = through_json("place_cues", {"track_id": "a", "cues": [cue], "overwrite": True})
check("place_cues gets AutoHotcue objects back", isinstance(got["cues"][0], AutoHotcue)
and got["cues"][0].start == 12.0 and got["overwrite"] is True, got)
got = through_json("query_tracks", {"q": "acid", "bpm_min": 120.0, "limit": 5})
check("query_tracks' keywords survive", got == {"q": "acid", "bpm_min": 120.0, "limit": 5}, got)
try:
rp.load_args("track", {"track_id": "a", "trak_id": "b"})
check("a misspelt argument is refused", False)
except ValueError:
check("a misspelt argument is refused", True)
try:
rp.load_args("set_cue", {"track_id": "a"})
check("a missing argument is refused", False)
except ValueError:
check("a missing argument is refused", True)
facts = {"t1": AudioFacts(key="/music/a.mp3", size=10, mtime_ns=123)}
back = rp.load_result("audio_facts", json.loads(json.dumps(rp.dump_result("audio_facts", facts))))
check("audio facts survive as dataclasses", back == facts, back)
cues = TrackCues(track_id="t1", grid_markers=[GridMarker(start=0.1, bpm=128)])
back = rp.load_result("track_cues", json.loads(json.dumps(rp.dump_result("track_cues", cues))))
check("TrackCues survive", back == cues)
check("None survives", rp.load_result("track", rp.dump_result("track", None)) is None)
t = Track(id="x", title="T")
check("a Track survives", rp.load_result("track", rp.dump_result("track", t)) == t)
print("== a prepared analysis ==")
rng = np.random.default_rng(1)
measured = waveform.Analysis(
columns=waveform.Columns(rms=rng.random(400).astype(np.float32),
brightness=rng.random(400).astype(np.float32), duration=181.5),
frames=waveform.Frames(bands=rng.random((27225, 3)).astype(np.float32), duration=181.5),
)
packed = rp.pack_analysis(PreparedAnalysis(measured=measured, markers=[GridMarker(start=0.25, bpm=124.0)]))
back = rp.unpack_analysis(packed)
check("columns, frames and durations cross intact",
np.array_equal(back.measured.columns.rms, measured.columns.rms)
and np.array_equal(back.measured.frames.bands, measured.frames.bands)
and back.measured.duration == 181.5)
check("…and the detected grid", [(m.start, m.bpm) for m in back.markers] == [(0.25, 124.0)])
check("…with no key when none was detected", back.key is None)
from konduktor.core.key_detect import KeyResult
key = KeyResult(pitch_class=9, mode="minor", wheel=8, confidence=0.83)
back = rp.unpack_analysis(rp.pack_analysis(PreparedAnalysis(measured=measured, key=key)))
check("…and the detected key", back.key == key, back.key)
check("no analysis is None", rp.pack_analysis(None) is None and rp.unpack_analysis(None) is None)
print("== remote addresses ==")
from konduktor.adapters.remote.config import Remote
r = Remote(id="r", name="NAS", host="192.168.1.20", port=8765, fallback_host="konduktor.example.net")
check("each address is built from its own parts",
r.addresses() == [("primary", "http://192.168.1.20:8765"), ("fallback", "http://konduktor.example.net:8765")],
r.addresses())
r = Remote(id="r", name="NAS", host="192.168.1.20", port=9000, fallback_host="konduktor.example.net")
check("…so a bare fallback gets the default port, not the primary's 9000",
r.addresses()[1] == ("fallback", "http://konduktor.example.net:8765"), r.addresses())
r = Remote(id="r", name="NAS", host="192.168.1.20", port=9000, fallback_host="https://konduktor.example.net/")
check("a full URL is used exactly as typed (a reverse proxy's port)",
r.addresses()[1] == ("fallback", "https://konduktor.example.net"), r.addresses())
r = Remote(id="r", name="NAS", host="http://nas.lan:8080")
check("…a URL with its own port keeps it", r.addresses() == [("primary", "http://nas.lan:8080")])
check("host:port typed inline is split", Remote(id="r", name="N", host="nas.local:9001").addresses()[0][1]
== "http://nas.local:9001")
print("== versions ==")
check("same version talks", rp.compatible((1, 0), (1, 0)) is None)
check("a newer server minor talks", rp.compatible((1, 0), (1, 3)) is None)
check("an older server minor: update the server", rp.compatible((1, 2), (1, 1)) == "server")
check("a newer server major: update the app", rp.compatible((1, 0), (2, 0)) == "app")
check("an older server major: update the server", rp.compatible((2, 0), (1, 9)) == "server")
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+259
View File
@@ -0,0 +1,259 @@
"""The Konduktor SERVER (`konduktor.server`), through its own routes.
A library held on the user's NAS and opened from the desktop app as a "Remote".
Run against a temp copy of the real collection, with a FAKE clock for the
session lease. Pins the things that would fail quietly or dangerously:
* every route needs the one account — a wrong password is a 401, not a
read-only view;
* ONE computer at a time: a command without the session token is refused
(423), a second computer is told who holds it (409) and may take over,
after which the first one's token is dead; a lease that ran out frees the
session, and the SAME computer coming back renews it silently;
* the edits a computer leaves behind are offered to the next one, named;
* Save writes and versions ON THE SERVER; Discard drops the edits;
* the folder browser and uploads cannot leave the content folder (`..`, a
symlink), an upload never overwrites, and a session can only delete what
it uploaded;
* audio streams with Range; a track added from an upload plays.
* the configuration refuses a missing password, a wrong platform and a
malformed path map with one clear line.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-server-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
from fastapi.testclient import TestClient
from konduktor import history
from konduktor import remote_protocol as rp
from konduktor.app_state import AppState
from konduktor.server.app import Server, create_app
from konduktor.server.config import ConfigError, ServerConfig, from_env, parse_path_maps
from konduktor.server.session import SessionLock
from stem_test_support import make_mp3
print("== configuration ==")
with tempfile.TemporaryDirectory() as d:
lib = Path(d) / "collection.nml"
lib.write_text("x")
content = Path(d) / "music"
content.mkdir()
base = {"KONDUKTOR_PLATFORM": "traktor", "KONDUKTOR_LIBRARY": str(lib),
"KONDUKTOR_CONTENT": str(content), "KONDUKTOR_USERNAME": "dj",
"KONDUKTOR_PASSWORD": "pw"}
def refused(env, needle):
try:
from_env(env)
except ConfigError as ex:
return needle in str(ex)
return False
check("a complete environment parses", from_env(base).content == content.resolve())
check("an empty password is refused", refused({**base, "KONDUKTOR_PASSWORD": ""}, "PASSWORD"))
check("an unknown platform is refused", refused({**base, "KONDUKTOR_PLATFORM": "serato"}, "PLATFORM"))
check("a missing content folder is refused",
refused({**base, "KONDUKTOR_CONTENT": str(Path(d) / "nope")}, "CONTENT"))
check("a malformed path map is refused", refused({**base, "KONDUKTOR_PATH_MAP": "/a -> /b"}, "PATH_MAP"))
maps = parse_path_maps("/Users/ben/Music => /music ; X: => /ssd")
check("several path maps parse, in order",
[(m.from_prefix, m.to_prefix) for m in maps] == [("/Users/ben/Music", "/music"), ("X:", "/ssd")])
print("== the server ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "library" / "collection.nml"
work.parent.mkdir()
shutil.copy2(REAL, work)
original = work.read_bytes()
content = (Path(d) / "music").resolve()
content.mkdir()
outside = Path(d) / "outside"
outside.mkdir()
(content / "Sneaky").symlink_to(outside)
(content / "Crates").mkdir()
cfg = ServerConfig(platform="traktor", library=work, content=content,
username="dj", password="secret", name="NAS")
t = [1000.0]
server = Server(cfg, state=AppState(), lock=SessionLock(clock=lambda: t[0]))
wrong = ServerConfig(**{**cfg.__dict__, "platform": "rekordbox"})
try:
Server(wrong, state=AppState()).open()
check("a platform that does not match the library file is refused", False)
except ConfigError as ex:
check("a platform that does not match the library file is refused", "Traktor" in str(ex), str(ex))
server.open()
app = create_app(server)
c = TestClient(app)
c.auth = ("dj", "secret")
anon = TestClient(app)
check("no credentials → 401", anon.get("/v1/hello").status_code == 401)
check("a wrong password → 401",
TestClient(app).get("/v1/hello", auth=("dj", "nope")).status_code == 401)
hello = c.get("/v1/hello").json()
check("hello names the API version, platform and library",
hello["api_version"] == list(rp.API_VERSION) and hello["platform"] == "traktor"
and hello["name"] == "NAS" and hello["library_id"], hello)
check("…nobody holds it yet, nothing is unsaved",
hello["holder"] is None and hello["dirty"] is False and hello["pending_edits"] is None)
def call(name, token=None, **args):
headers = {rp.SESSION_HEADER: token} if token else {}
return c.post(f"/v1/rpc/{name}", json={"args": rp.dump_args(name, args)}, headers=headers)
adapter = server.state.adapter
r = call("tracks")
check("the projection reads without a session",
r.status_code == 200 and len(r.json()["result"]) == len(adapter.tracks))
caps = call("capabilities").json()["result"]
check("capabilities say: destination on the library, no reference, no remapping",
caps["tracks"]["audio_destination"] == "library" and caps["tracks"]["reference"] is False
and caps["paths"]["remappable"] is False, caps["tracks"])
check("an unknown argument is refused, not ignored",
c.post("/v1/rpc/track", json={"args": {"track_id": "x", "trak": 1}}).status_code == 400)
track = next(t for t in adapter.tracks if t.genre)
r = call("set_track_metadata", track_id=track.id, fields={"genre": "Remote"})
check("a command without the session → 423", r.status_code == 423, r.text[:120])
print("== one computer at a time ==")
a = c.post("/v1/session/acquire", json={"client_id": "A", "machine": "Laptop"}).json()
r = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio"})
check("a second computer is told who holds it",
r.status_code == 409 and r.json()["detail"]["machine"] == "Laptop", r.text[:160])
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Remote"})
body = r.json()
check("the holder's command applies and returns the changed track",
r.status_code == 200 and body["changed"][0]["genre"] == "Remote" and body["rev"] == 1, r.text[:200])
pending = c.get("/v1/hello", params={"client_id": "B"}).json()["pending_edits"]
check("another computer is told whose unsaved edits these are",
pending and pending["machine"] == "Laptop" and "track" in pending["summary"], pending)
check("…but the computer that made them is not",
c.get("/v1/hello", params={"client_id": "A"}).json()["pending_edits"] is None)
b = c.post("/v1/session/acquire", json={"client_id": "B", "machine": "Studio", "takeover": True}).json()
check("a takeover hands over the edits too", b["pending_edits"]["machine"] == "Laptop", b)
r = call("set_track_metadata", a["token"], track_id=track.id, fields={"genre": "Late"})
check("the displaced computer's token is dead (423, naming the new holder)",
r.status_code == 423 and r.json()["detail"]["holder"]["machine"] == "Studio", r.text[:160])
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: a["token"]})
check("…and its heartbeat says so", hb.status_code == 423)
c.post("/v1/session/heartbeat", json={"batch": "grid-analysis"}, headers={rp.SESSION_HEADER: b["token"]})
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
check("the holder's running batch is named to whoever asks",
r.status_code == 409 and r.json()["detail"]["batch"] == "grid-analysis", r.text[:160])
t[0] += rp.LEASE_SECONDS + 1
r = c.post("/v1/session/acquire", json={"client_id": "C", "machine": "Phone"})
check("an expired lease frees the session without a takeover", r.status_code == 200, r.text[:160])
cc = r.json()
t[0] += rp.LEASE_SECONDS * 3
hb = c.post("/v1/session/heartbeat", json={}, headers={rp.SESSION_HEADER: cc["token"]})
check("the same computer coming back renews its lease silently", hb.status_code == 200, hb.text[:160])
tok = cc["token"]
print("== save / discard / history ==")
versions = len(history.list_history(work))
r = c.post("/v1/save", headers={rp.SESSION_HEADER: tok}).json()
check("save writes the library on the server", r["saved"] and work.read_bytes() != original, r)
check("…and versions it there", len(history.list_history(work)) == versions + 1)
check("…and nobody's edits are pending afterwards",
c.get("/v1/hello", params={"client_id": "Z"}).json()["pending_edits"] is None)
saved = work.read_bytes()
call("set_track_metadata", tok, track_id=track.id, fields={"genre": "Throw away"})
check("(setup) a second edit is unsaved", c.get("/v1/hello").json()["dirty"])
c.post("/v1/discard", headers={rp.SESSION_HEADER: tok})
check("discard drops it", not c.get("/v1/hello").json()["dirty"]
and call("track", track_id=track.id).json()["result"]["genre"] == "Remote")
check("…and leaves the file as saved", work.read_bytes() == saved)
listed = c.get("/v1/history").json()
check("history lists the server's versions", len(listed) == versions + 1)
print("== the content folder ==")
r = c.get("/v1/fs/list")
names = [e["name"] for e in r.json()["entries"]]
check("the browser starts at the content folder", r.json()["path"] == str(content) and "Crates" in names)
check("`..` cannot leave it", c.get("/v1/fs/list", params={"path": str(content / "..")}).status_code == 400)
check("nor can a symlink", c.get("/v1/fs/list", params={"path": str(content / "Sneaky")}).status_code == 400)
check("free space is reported", c.get("/v1/fs/space", params={"path": str(content / "New")}).json()["free"] > 0)
print("== uploads ==")
mp3 = make_mp3(Path(d) / "src" / "Kick Tune.mp3")
data = mp3.read_bytes()
up = lambda name, folder: c.post("/v1/upload", params={"dir": folder, "name": name},
content=data, headers={rp.SESSION_HEADER: tok})
r1 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
r2 = up("Kick Tune.mp3", str(content / "Crates" / "New"))
p1, p2 = Path(r1.json()["path"]), Path(r2.json()["path"])
check("an upload lands in the chosen folder (created)", p1 == content / "Crates" / "New" / "Kick Tune.mp3"
and p1.read_bytes() == data, r1.text[:200])
check("a second upload of the same name never overwrites", p2.name == "Kick Tune-2.mp3")
check("no partial is left behind", not list((content / "Crates" / "New").glob(".*")))
check("an upload outside the content folder is refused", up("x.mp3", str(outside)).status_code == 400)
check("a name that hides or climbs is refused", up("../x.mp3", str(content)).status_code == 400
or up(".x.mp3", str(content)).status_code == 400)
check("without the session, refused", c.post("/v1/upload", params={"dir": str(content), "name": "y.mp3"},
content=data).status_code == 423)
r = c.delete("/v1/upload", params={"path": str(p2)}, headers={rp.SESSION_HEADER: tok})
check("a session deletes what it uploaded", r.status_code == 200 and not p2.exists(), r.text[:160])
keep = content / "Crates" / "mine.mp3"
keep.write_bytes(b"user's")
r = c.delete("/v1/upload", params={"path": str(keep)}, headers={rp.SESSION_HEADER: tok})
check("…and nothing else", r.status_code == 403 and keep.exists())
print("== adding an uploaded track, and its audio ==")
from konduktor.core.model import Track
wire = rp.WireNewTrack(track=Track(id="", title="Kick Tune", artist="Tester"), audio_path=str(p1))
r = c.post("/v1/rpc/add_tracks", json={"args": {"items": [wire.model_dump(mode="json")]}},
headers={rp.SESSION_HEADER: tok})
ids = r.json()["result"] if r.status_code == 200 else []
check("an uploaded file is added by the ordinary add_tracks",
len(ids) == 1 and r.json()["changed"][0]["title"] == "Kick Tune", r.text[:300])
if ids:
whole = c.get("/v1/audio", params={"track_id": ids[0]})
check("its audio streams", whole.status_code == 200 and whole.content == data
and int(whole.headers["X-Konduktor-Size"]) == len(data))
part = c.get("/v1/audio", params={"track_id": ids[0]}, headers={"Range": "bytes=10-19"})
check("…with Range", part.status_code == 206 and part.content == data[10:20])
facts = call("audio_facts", track_ids=ids).json()["result"]
check("its facts name the server's file", facts[ids[0]]["key"] == str(p1))
r = c.delete("/v1/upload", params={"path": str(p1)}, headers={rp.SESSION_HEADER: tok})
check("an upload the library now names is not deleted", r.status_code == 409 and p1.exists())
print("== export sets ==")
doc = {"sets": {"s1": {"name": "Gig", "targets": ["traktor"], "destination": "/Volumes/STICK",
"playlist_ids": [], "track_ids": []}}}
check("export sets need the session to change",
c.put("/v1/export-sets", json=doc).status_code == 423)
c.put("/v1/export-sets", json=doc, headers={rp.SESSION_HEADER: tok})
got = c.get("/v1/export-sets").json()
check("…and are kept by the server, keyed by its library id",
got["sets"]["s1"]["name"] == "Gig" and got["library_id"] == hello["library_id"], got)
c.post("/v1/session/release", headers={rp.SESSION_HEADER: tok})
check("release frees the session", c.get("/v1/hello").json()["holder"] is None)
check("the original collection beside the tests was never touched", REAL.exists())
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+235
View File
@@ -0,0 +1,235 @@
"""Convert to Stems on a REMOTE library, with a FAKE engine.
A Konduktor server runs in a thread on a temp copy of the real collection whose
playlisted tracks point at generated MP3s on "the server"; the app converts
through its own routes. The server never decodes audio, so this pins the split:
* the server plans (targets, skips) and this computer reports what it must
download and upload, and the room it needs here;
* a Replace batch separates HERE, uploads, and the SERVER publishes, parks
the original and swaps the entry — its saved collection untouched until
Save, which deletes the parked original there; Discard puts it back;
* Cancel deletes what the run uploaded, and nothing else;
* another computer taking over mid-batch loses no separation: the uploaded,
verified stem file stays on the server and the next run reuses it without
the engine.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import threading
import time
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-remotestems-appdata-")
os.environ.pop("KONDUKTOR_NML", None)
import uvicorn # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor.adapters.remote import config as remote_config # noqa: E402
from konduktor.adapters.remote.client import RemoteClient # noqa: E402
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
from konduktor.adapters.traktor.store import TraktorStore # noqa: E402
from konduktor.app_state import AppState # noqa: E402
from konduktor.core import stem_file as sf # noqa: E402
from konduktor.server.app import Server, create_app # noqa: E402
from konduktor.server.config import ServerConfig # noqa: E402
from konduktor.stems import convert as convert_mod # noqa: E402
from konduktor.stems import engine_manager as em # noqa: E402
from konduktor.stems import remote_convert # noqa: E402
from konduktor.stems.pending import parked_name, partial_name # noqa: E402
from stem_test_support import install_fake_engine, make_mp3 # noqa: E402
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
class MemoryKeychain(dict):
def get(self, account): # noqa: D401
return dict.get(self, account)
def set(self, account, password):
self[account] = password
def delete(self, account):
self.pop(account, None)
remote_config.use_password_store(MemoryKeychain())
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-remotestems-"))
em._DEFAULT = install_fake_engine(ROOT / "engine")
# ---- a server library: playlisted tracks pointed at generated MP3s -------------------
music = (ROOT / "server" / "Music").resolve()
music.mkdir(parents=True)
work = ROOT / "server" / "collection.nml"
shutil.copy2(REAL, work)
st = TraktorStore(work)
in_pl = {k for n in st._iter_nodes(st._root()) if n.playlist for k in st._entry_keys_of(n.playlist)}
entries = [e for e in st._nml.collection.entry if e.location and st._key_of(e) in in_pl and e.stems is None][:5]
ids = []
for n, e in enumerate(entries):
path = make_mp3(music / f"Track {n}.mp3", seed=n + 1)
old = st._key_of(e)
e.location.volume, e.location.dir, e.location.file = os_path_to_location(path)
new = st._key_of(e)
for node in st._iter_nodes(st._root()):
for pe in (node.playlist.entry if node.playlist else None) or []:
if pe.primarykey and pe.primarykey.key == old:
pe.primarykey.key = new
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
e.cue_v2 = []
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
st.replace_grid(new, [(0.5, 120.0)])
ids.append(new)
st.save()
del st
cfg = ServerConfig(platform="traktor", library=work, content=music, username="dj", password="pw", name="NAS")
srv = Server(cfg, state=AppState())
srv.open()
uv = uvicorn.Server(uvicorn.Config(create_app(srv), host="127.0.0.1", port=0, log_level="warning"))
threading.Thread(target=uv.run, daemon=True).start()
while not uv.started:
time.sleep(0.05)
port = uv.servers[0].sockets[0].getsockname()[1]
def wait(c, jid, timeout=120):
end = time.time() + timeout
while time.time() < end:
j = c.get(f"/api/jobs/{jid}").json()
if j["state"] != "running":
return j
time.sleep(0.05)
raise AssertionError("job did not finish")
with TestClient(main.app) as c:
remote_id = c.post("/api/remotes", json={"name": "NAS", "host": f"127.0.0.1:{port}",
"username": "dj", "password": "pw"}).json()["remote"]["id"]
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
assert r.status_code == 200, r.text
server_adapter = srv.state.adapter
print("== the plan: the server's, plus this computer's ==")
p = c.post("/api/tracks/stems/preview", json={"track_ids": ids[:1], "mode": "replace"}).json()
check("one track to convert, its target beside it on the server",
len(p["convert"]) == 1 and p["convert"][0]["target"] == str(music / "Track 0.stem.m4a"), p)
check("…and what must cross the network", p["transfer"]["download"] > 0 and p["transfer"]["upload"] > 0,
p.get("transfer"))
check("…and the room needed on BOTH machines",
any(s["volume"] == "this computer" for s in p["space"])
and any(s["volume"].startswith("the server") for s in p["space"]), p["space"])
print("== a Replace batch ==")
saved_bytes = work.read_bytes()
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids[:1], "mode": "replace"})
job = wait(c, r.json()["id"])
res = job.get("result") or {}
target = music / "Track 0.stem.m4a"
check("the job converts the track", job["state"] == "done" and len(res.get("converted", [])) == 1,
job.get("error") or res)
check("the stem file is on the server, the original parked beside it",
target.is_file() and sf.is_stem_file(target) and parked_name(music / "Track 0.mp3").is_file())
new_id = res.get("renamed", {}).get(ids[0])
check("the server's entry now names the stem file", new_id and server_adapter.track(new_id) is not None)
check("…and the mirror here follows", main.require_adapter().track(new_id) is not None)
check("the SAVED collection is untouched until Save", work.read_bytes() == saved_bytes)
st_ = c.get("/api/state").json()
check("the state reports the conversion awaiting Save (from the server's ledger)",
st_["pending_stems"] and st_["pending_stems"]["tracks"] == 1, st_.get("pending_stems"))
check("…and blocks what would save or drop it", c.post("/api/reload").status_code == 409)
c.post("/api/save")
check("Save deletes the parked original on the server",
not parked_name(music / "Track 0.mp3").exists() and target.is_file())
check("…and the ledger is clear", not (c.get("/api/state").json()["pending_stems"] or {}).get("tracks"))
print("== playing a remote stem file ==")
layout = c.get("/api/tracks/stems", params={"track_id": new_id})
stems = layout.json().get("stems") if layout.status_code == 200 else None
check("the deck is offered the stem file's four stems",
isinstance(stems, list) and len(stems) == 4, layout.text[:200])
one = c.get("/api/tracks/audio", params={"track_id": new_id, "stem": 1})
check("…and each streams, extracted HERE from the downloaded file",
one.status_code == 200 and len(one.content) > 1000, one.status_code)
print("== Discard puts it back ==")
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[1]], "mode": "replace"})
job = wait(c, r.json()["id"])
check("(setup) a second conversion", job["state"] == "done" and (music / "Track 1.stem.m4a").is_file(),
job.get("error"))
c.post("/api/discard")
check("Discard restores the original and removes the stem file, on the server",
(music / "Track 1.mp3").is_file() and not (music / "Track 1.stem.m4a").exists()
and not parked_name(music / "Track 1.mp3").exists())
print("== Cancel deletes what the run uploaded ==")
adapter = main.require_adapter()
opts = convert_mod.Options(mode="replace")
planned = remote_convert.plan(adapter, [ids[2], ids[3]], opts)
class Handle:
cancelled = False
def progress(self, **kw):
pass
h = Handle()
real_stage = adapter.stage_stem
def stage_then_cancel(*a, **k):
out = real_stage(*a, **k)
h.cancelled = True
return out
adapter.stage_stem = stage_then_cancel
out = remote_convert.run(h, adapter, planned, opts, still_current=lambda: True)
adapter.stage_stem = real_stage
check("a cancel after one upload stops the batch", out["cancelled"])
check("…and the uploaded stem file is deleted on the server",
not partial_name(music / "Track 2.stem.m4a").exists() and not srv.state.pending.leftovers,
srv.state.pending.leftovers)
check("…nothing else changed", (music / "Track 2.mp3").is_file() and not server_adapter.dirty)
print("== a takeover mid-batch loses no separation ==")
planned = remote_convert.plan(adapter, [ids[4]], opts)
item = planned.items[0]
local = adapter.audio_path(ids[4])
staged = ROOT / "staged.stem.m4a"
written = sf.build(local, staged, lambda pcm: [pcm * g for g in (0.5, 0.25, -0.2, 0.1)])
adapter.stage_stem(ids[4], item["target"], staged, bit_rate=written.bit_rate, duration=written.duration)
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "pw")
other.acquire("other", "Studio iMac", takeover=True)
other.release()
check("the uploaded file stays on the server as a verified leftover",
partial_name(music / "Track 4.stem.m4a").is_file() and len(srv.state.pending.leftovers) == 1)
r = c.post("/api/library/open-remote", json={"remote_id": remote_id})
p = c.post("/api/tracks/stems/preview", json={"track_ids": [ids[4]], "mode": "replace"}).json()
check("the next plan reuses it", p["convert"] and p["convert"][0]["reuse"] and p["seconds"] == 0, p)
em._DEFAULT = em.EngineManager(ROOT / "no-engine") # an engine call would now fail
r = c.post("/api/tracks/stems/convert", json={"track_ids": [ids[4]], "mode": "replace"})
job = wait(c, r.json()["id"]) if r.status_code == 200 else {"state": "refused", "error": r.text}
check("…and converts without the engine", job["state"] == "done"
and len((job.get("result") or {}).get("converted", [])) == 1, job.get("error") or job.get("result"))
c.post("/api/save")
check("…to a stem file on the server", sf.is_stem_file(music / "Track 4.stem.m4a"))
uv.should_exit = True
print()
print("RESULT:", "FAILURES" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+251
View File
@@ -940,5 +940,256 @@ 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)
# ---- O: moving playlists in the tree ----------------------------------
# Drag and drop in the sidebar. Moving a node relocates its whole block, so
# the guarantee is: the COLLECTION is untouched, the tree reads back as moved,
# and moving it back reproduces the original bytes exactly.
print("\n== O. move_playlist ==")
def _collection_span(data: bytes) -> bytes:
return data[data.find(b"<COLLECTION"):data.find(b"</COLLECTION>")]
def _find(nodes, name):
for n in nodes:
if n.name == name:
return n
hit = _find(n.children, name)
if hit is not None:
return hit
return None
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
before = work.read_bytes()
store = TraktorStore(work)
roots = store.tree()
folders = [n for n in roots if n.kind == "folder" and n.children]
loose = [n for n in roots if n.kind == "playlist"]
if len(folders) < 2 or len(loose) < 2:
print(" [SKIP] the reference collection has too few top-level nodes")
else:
src, dst = folders[0], folders[1]
pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0]
home = _find(roots, pl.name)
home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None)
home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id))
check("O: every node offers can_move", all(n.can_move for n in roots))
# A playlist into another folder, at a position.
new_id = store.move_playlist(pl.id, dst.id, 1)
tree = store.tree()
moved_into = next(n for n in tree if n.id == dst.id)
check("O: a playlist keeps its id when moved", new_id == pl.id, new_id)
check("O: …and lands at the index asked for",
len(moved_into.children) > 1 and moved_into.children[1].id == pl.id,
[c.name for c in moved_into.children[:3]])
store.save()
moved = work.read_bytes()
check("O: the COLLECTION is untouched by a move",
_collection_span(moved) == _collection_span(before))
reread = TraktorStore(work).tree()
check("O: the move round-trips through a save",
any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children))
# …and back again: byte-identical to the original.
store.move_playlist(pl.id, home_parent, home_index)
store.save()
check("O: moving it back restores the original bytes", work.read_bytes() == before,
f"{diff_count(before, work.read_bytes())} lines differ")
# A folder moves with its subtree, and its id (a path) changes with it.
new_folder = store.move_playlist(src.id, dst.id, 0)
check("O: a moved folder answers its new path id",
new_folder == f"{dst.id}/{src.name}", new_folder)
inner = next(n for n in store.tree() if n.id == dst.id).children[0]
check("O: …and its subtree moved with it",
inner.id == new_folder and len(inner.children) == len(src.children))
child_ids = [c.id for c in inner.children]
check("O: …children keep addressable ids",
all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/"))
or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3])
# Into itself: refused, nothing changed.
snapshot = store._render()
try:
store.move_playlist(dst.id, new_folder, 0)
check("O: a folder cannot be moved into its own descendant", False)
except PlaylistError:
check("O: a folder cannot be moved into its own descendant",
store._render() == snapshot)
# A namesake folder in the target: refused (two paths would be one).
store.create_folder(src.name, None)
snapshot = store._render()
try:
store.move_playlist(new_folder, None, 0)
check("O: a folder cannot land beside a namesake", False)
except PlaylistError:
check("O: a folder cannot land beside a namesake", store._render() == snapshot)
# A smart playlist moves too, by its path id.
smart = next((c for c in inner.children if c.kind == "smart"), None)
if smart is not None:
sid = store.move_playlist(smart.id, None, 0)
check("O: a smart playlist moves and answers its new id",
sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid)
# A no-op move leaves the store clean.
fresh = TraktorStore(work)
first = fresh.tree()[0]
fresh.move_playlist(first.id, None, 0)
check("O: moving a node onto its own place is not an edit", not fresh.dirty)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+60
View File
@@ -262,11 +262,71 @@ def stop_in_encode():
raise Stop()
def encoder_threads():
import threading
return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")]
try:
sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode)
check("a checkpoint that raises stops the build", False, "it finished")
except Stop:
check("a checkpoint that raises stops the build", True)
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("== 6. the encode runs on one thread per stream ==")
def encode_single_threaded(fp, tracks, *, bit_rate, encoder):
"""The encode as it was before it was threaded: the reference for the bytes."""
tb = fractions.Fraction(1, SR)
c = av.open(fp, "w", format="ipod")
try:
streams = []
for k in range(len(tracks)):
s = c.add_stream(encoder, rate=SR, layout="stereo")
s.bit_rate = bit_rate
if k:
s.disposition = 0
streams.append(s)
for offset in range(0, tracks[0].shape[1], sf.FRAME):
for s, x in zip(streams, tracks):
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]),
format="fltp", layout="stereo")
f.sample_rate, f.pts, f.time_base = SR, offset, tb
for p in s.encode(f):
c.mux(p)
for s in streams:
for p in s.encode(None):
c.mux(p)
finally:
c.close()
source = sf.decode(MP3)
# A length that is not a whole number of frames, and stems that differ from the mix.
five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))]
for enc in encoders:
ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a"
with open(ref, "wb") as fp:
encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc)
seen = []
with open(par, "wb") as fp:
sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append)
check(f"{enc}: the threaded encode is byte-identical to the single-threaded one",
ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes")
check(f"{enc}: progress runs 0 -> 1, never backwards",
len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen))
try:
with open(tmp / "broken.m4a", "wb") as fp:
# A mono array in a stereo stream: that stream's thread fails on its first frame.
sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None)
check("a failing encoder thread fails the encode", False, "it finished")
except Exception as ex: # noqa: BLE001
check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex))
check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads()))
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+21
View File
@@ -73,6 +73,27 @@ check("a stem file lists its four stems with names and colours, in stream order"
check("a plain MP3 has none", sf.stem_layout(plain) is None)
check("a missing file has none (no exception)", sf.stem_layout(ROOT / "nope.stem.m4a") is None)
print("== a stem file whose tags are not UTF-8 ==")
# PyAV 18 will not open such a file unless told to ignore the bad bytes, and
# PyAV 19 rejects the keyword that tells it (core/pyav.py). A release built on
# 19 while dev ran 18 played every stem track as the mix: the route 500'd.
from mutagen.mp4 import MP4 # noqa: E402
bad = ROOT / "BadTag.stem.m4a"
shutil.copy2(stem, bad)
m = MP4(bad)
m["\xa9nam"] = ["XéX"]
m.save()
raw = bad.read_bytes()
assert raw.count("XéX".encode()) == 1
bad.write_bytes(raw.replace("XéX".encode(), b"X\xe9\xe9X")) # same length: no box sizes change
check(f"it still lists its stems (PyAV {av.__version__})", sf.stem_layout(bad) == layout, str(sf.stem_layout(bad)))
with open(ROOT / "bad-stem-1.m4a", "wb") as fp:
sf.extract_stream(bad, 1, fp)
check("…a stem still extracts, bit-identical to the stream in place",
np.array_equal(decode(ROOT / "bad-stem-1.m4a"), decode(stem, 1)))
check("…and it still decodes for conversion", sf.decode(bad).pcm.shape[1] > 0)
print("== a temp collection pointing at them ==")
work = ROOT / "collection.nml"
shutil.copy2(REAL, work)
+3 -3
View File
@@ -33,7 +33,7 @@ import numpy as np # noqa: E402
from konduktor.adapters.traktor import timebase # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
from konduktor.core import mp3_gapless # noqa: E402
from konduktor.core import mp3_gapless, pyav # noqa: E402
from konduktor.core.adapter import NewTrack # noqa: E402
from konduktor.core.model import Track # noqa: E402
@@ -197,7 +197,7 @@ else:
pad8 = re.search(r'<CUE_V2 [^>]*START="([^"]*)"[^>]*HOTCUE="7"', e)
if not pad8 or not (KIT / name).is_file():
continue
with av.open(str(KIT / name), metadata_errors="ignore") as c:
with pyav.open_input(KIT / name) as c:
st = c.streams.audio[0]
sr = st.rate
y = np.concatenate([f.to_ndarray()[0] for f in c.decode(st)]).astype(np.float64)
@@ -258,7 +258,7 @@ else:
name = c.Content.FileNameL if c.Content else ""
if not name.startswith("K4-") or c.Kind != 9 or not (KIT / name).is_file():
continue # pad H: the ones placed by hand
with av.open(str(KIT / name), metadata_errors="ignore") as con:
with pyav.open_input(KIT / name) as con:
st = con.streams.audio[0]
sr = st.rate
y = np.concatenate([f.to_ndarray()[0] for f in con.decode(st)]).astype(np.float64)
+16
View File
@@ -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")
@@ -105,6 +106,21 @@ with tempfile.TemporaryDirectory() as d:
adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"})
check("metadata edit is visible in the projection",
adapter.track(tid).genre == "Konduktor Test Genre")
# search reaches both comments, case-insensitively
adapter.set_track_metadata(tid, {"comment": "Konduktor Search One",
"comment2": "Konduktor Search Two"})
for q in ("search one", "SEARCH TWO"):
hits = adapter.query_tracks(q=q, limit=20000).items
check(f"search {q!r} finds the track by its comment",
[x.id for x in hits] == [tid], f"{len(hits)} hits")
# 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(
+209
View File
@@ -0,0 +1,209 @@
"""Train the key-detection network shipped as `konduktor/core/key_model.npz`.
NOT part of the app or of `run_tests.sh`: a dev tool, run when the model
changes. Two steps in two environments, because the backend never imports
torch and torch is only installed in the stem engine's venv:
# 0. the data (Beatport EDM previews, hand-annotated keys — ~2.9 GB):
git clone https://github.com/GiantSteps/giantsteps-mtg-key-dataset DATA/mtg
git clone https://github.com/GiantSteps/giantsteps-key-dataset DATA/gs
(cd DATA/mtg && bash audio_dl.sh); (cd DATA/gs && bash audio_dl.sh)
# 1. features, with the app's own `key_detect.features` (backend venv)
python train_key_model.py features DATA
# 2. train + export (engine venv: torch)
../engine/.venv/bin/python train_key_model.py train DATA
The protocol is the literature's (Korzeniowski & Widmer 2017): TRAIN on
GiantSteps MTG (1,159 tracks with one confident key), TEST on the separate
GiantSteps key dataset (604) — `bench_key_detect.py` scores it. Choices made
on a held-out 20% of MTG, three seeds each (2026-10-04):
- the per-frame dense layer over the full pitch axis beat averaging each
semitone's three bins before it (68.1% vs 66.9% on GiantSteps, val equal);
- a fixed 30-epoch cosine schedule, keeping the LAST epoch: validation on
~230 tracks is too noisy to pick an epoch from;
- weight decay made no difference and is off.
The shipped file is an ENSEMBLE of three seeds trained on all of MTG, their
logits averaged — each costs ~0.2 s per six-minute track.
Augmentation: the input window (C2..C7) is shifted by up to six semitones
inside the 7-octave spectrogram, and the label rotated with it, so every
tonic is seen in every position; plus random 128-frame (~24 s) crops.
"""
from __future__ import annotations
import argparse
import hashlib
import re
import sys
from pathlib import Path
PC = {"C": 0, "C#": 1, "Db": 1, "D": 2, "D#": 3, "Eb": 3, "E": 4, "F": 5, "F#": 6,
"Gb": 6, "G": 7, "G#": 8, "Ab": 8, "A": 9, "A#": 10, "Bb": 10, "B": 11}
LO, HI, MAX_SHIFT = 36, 216, 6 # must match key_detect.WINDOW
CROP, BATCH, EPOCHS, LR = 128, 16, 30, 1e-3
SEEDS = (11, 12, 13)
OUT = Path(__file__).parent / "konduktor" / "core" / "key_model.npz"
def label(name: str, mode: str) -> int:
"""Class index: major C..B = 0..11, minor C..B = 12..23 (key_detect's order)."""
return PC[name] + (12 if mode == "minor" else 0)
def mtg_labels(data: Path) -> dict[str, int]:
"""MTG ids with ONE key annotated at the dataset's top confidence (2)."""
out = {}
for line in (data / "mtg/annotations/annotations.txt").read_text().splitlines()[1:]:
parts = line.split("\t")
if len(parts) < 3:
continue
m = re.fullmatch(r"([A-G][#b]?) (major|minor)", parts[1].strip())
if m and parts[2].strip() == "2":
out[f"{parts[0]}.LOFI"] = label(*m.groups())
return out
def gs_labels(data: Path) -> dict[str, int]:
out = {}
for f in (data / "gs/annotations/key").glob("*.key"):
name, mode = f.read_text().split()
out[f.stem] = label(name, mode)
return out
# ---- step 1: features (backend venv) ---------------------------------------
def _feature_job(args):
import warnings
warnings.filterwarnings("ignore")
import librosa
import numpy as np
from konduktor.core import key_detect
src, dst, md5 = args
if dst.exists():
return "cached"
if not src.exists():
return "missing"
if hashlib.md5(src.read_bytes()).hexdigest() != md5:
return "bad md5"
y, sr = librosa.load(str(src), sr=key_detect.SR, mono=True)
np.save(dst, key_detect.features(y, sr))
return "ok"
def features(data: Path) -> None:
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
for which in ("mtg", "gs"):
out = data / "features" / which
out.mkdir(parents=True, exist_ok=True)
jobs = [
(data / which / "audio" / f"{m.stem}.mp3", out / f"{m.stem}.npy", m.read_text().split()[0])
for m in sorted((data / which / "md5").iterdir())
]
with ProcessPoolExecutor() as ex:
print(which, dict(Counter(ex.map(_feature_job, jobs, chunksize=4))), flush=True)
# ---- step 2: train + export (engine venv) ----------------------------------
def _net(torch):
nn, F = torch.nn, torch.nn.functional
class Net(nn.Module):
"""Five 5x5 convs (8 ch, ELU), a dense layer per frame over the whole
pitch axis (48, ELU, dropout), 24 logits averaged over time.
`key_detect._network` is this, in numpy."""
def __init__(self, ch=8, layers=5, hid=48):
super().__init__()
self.convs = nn.ModuleList(
[nn.Conv2d(1 if i == 0 else ch, ch, 5, padding=2) for i in range(layers)])
self.dense = nn.Conv2d(ch, hid, (HI - LO, 1))
self.out = nn.Conv2d(hid, 24, 1)
self.drop = nn.Dropout(0.3)
def forward(self, x): # (B, 1, F, T)
for c in self.convs:
x = F.elu(c(x))
x = self.drop(F.elu(self.dense(x)))
return self.out(x).mean((2, 3))
return Net
def train(data: Path, seeds=SEEDS, out: Path = OUT) -> None:
import random
import numpy as np
import torch
import torch.nn.functional as F
Net = _net(torch)
labels = mtg_labels(data)
X, Y = [], []
for stem, y in sorted(labels.items()):
f = data / "features/mtg" / f"{stem}.npy"
if f.exists():
X.append(np.load(f))
Y.append(y)
print(f"training on {len(X)} tracks", flush=True)
dev = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
arrays: dict[str, np.ndarray] = {"pool": np.array(1)}
for m, seed in enumerate(seeds):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
net = Net().to(dev)
opt = torch.optim.Adam(net.parameters(), LR)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, EPOCHS)
order = list(range(len(X)))
for ep in range(EPOCHS):
net.train()
random.shuffle(order)
total = 0.0
for i in range(0, len(order), BATCH):
xb, yb = [], []
for j in order[i:i + BATCH]:
s = random.randint(-MAX_SHIFT, MAX_SHIFT)
x = X[j][LO + 3 * s:HI + 3 * s]
if x.shape[1] > CROP:
o = random.randint(0, x.shape[1] - CROP)
x = x[:, o:o + CROP]
else:
x = np.pad(x, ((0, 0), (0, CROP - x.shape[1])))
xb.append(x)
# The window moved UP s semitones, so the music moved DOWN.
yb.append((Y[j] % 12 - s) % 12 + Y[j] // 12 * 12)
xt = torch.from_numpy(np.stack(xb))[:, None].to(dev)
loss = F.cross_entropy(net(xt), torch.tensor(yb).to(dev))
opt.zero_grad()
loss.backward()
opt.step()
total += loss.item()
sched.step()
print(f" seed {seed} epoch {ep + 1}/{EPOCHS} loss {total / (len(order) / BATCH):.3f}", flush=True)
for k, v in net.state_dict().items():
arrays[f"m{m}." + k.replace("convs.", "conv")] = v.detach().cpu().numpy().astype(np.float32)
np.savez_compressed(out, **arrays)
print(f"wrote {out} ({out.stat().st_size // 1024} KB, {len(seeds)} members)")
if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("step", choices=("features", "train"))
ap.add_argument("data", type=Path)
a = ap.parse_args()
if a.step == "features":
sys.path.insert(0, str(Path(__file__).parent))
features(a.data)
else:
train(a.data)
+69
View File
@@ -0,0 +1,69 @@
# Build the Konduktor desktop app on Windows: freeze + stage the backend sidecar,
# then build the Tauri installers. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv with requirements-build.txt, and
# `npm install`).
#
# .\build.ps1 # sidecar + app (release installers)
# .\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar
# .\build.ps1 --debug # anything else is passed on to `tauri build`
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\build.ps1)
param([switch]$SkipSidecar)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$TauriArgs = $args
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
if (-not (Test-Path (Join-Path $Root "frontend\node_modules"))) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
$Staged = Join-Path $Root "frontend\src-tauri\binaries\konduktor-sidecar\konduktor-sidecar.exe"
# rustup puts cargo in %USERPROFILE%\.cargo\bin and adds it to PATH only for
# terminals opened AFTER the install - so find it there before giving up, rather
# than failing ten minutes in, after the sidecar build.
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$CargoBin = Join-Path $env:USERPROFILE ".cargo\bin"
if (-not (Test-Path (Join-Path $CargoBin "cargo.exe"))) { throw "No Rust toolchain (cargo) - install it from https://rustup.rs, see BUILDING-WINDOWS.md." }
$env:PATH = "$CargoBin;$env:PATH"
}
$Started = Get-Date
# build_sidecar.ps1 changes directory itself, and a location change outlives the
# script it was made in - so put ours back whatever happens.
Push-Location $Root
try {
if ($SkipSidecar) {
if (-not (Test-Path $Staged)) { throw "No staged sidecar to reuse - run without -SkipSidecar first." }
Write-Host "==> Reusing the staged sidecar (-SkipSidecar)"
}
else {
Write-Host "==> 1/2 Freezing the backend sidecar"
& (Join-Path $Root "backend\build_sidecar.ps1")
}
Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend")
# npx is a .cmd and cargo reports progress on stderr: relax "Stop" for the
# call (as build_sidecar.ps1 does for PyInstaller) and judge by exit code.
$ErrorActionPreference = "Continue"
& npx tauri build @TauriArgs
$code = $LASTEXITCODE
$ErrorActionPreference = "Stop"
if ($code -ne 0) { throw "tauri build failed ($code)" }
}
finally {
Pop-Location
}
# List what this run produced (release or --debug profile).
$Bundles = Join-Path $Root "frontend\src-tauri\target\*\bundle"
$Built = Get-ChildItem -Path "$Bundles\nsis\*-setup.exe", "$Bundles\msi\*.msi" -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -ge $Started }
Write-Host ""
if ($Built) {
Write-Host "Installers:"
$Built | ForEach-Object { Write-Host " $($_.FullName)" }
}
else {
Write-Host "Done (no installer bundled - see frontend\src-tauri\target\)."
}
+42
View File
@@ -0,0 +1,42 @@
# Start both Konduktor servers (backend + frontend) together - the Windows
# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in
# BUILDING-WINDOWS.md (the backend venv and `npm install`).
#
# .\dev.ps1
# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$Py = Join-Path $Root "backend\.venv\Scripts\python.exe"
if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." }
# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a
# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting.
$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js"
if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." }
# Backend (FastAPI on :8000)
$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru `
-ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`""
# Frontend (Vite on :5173, proxies /api -> :8000)
$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru `
-WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`""
Write-Host ""
Write-Host " Konduktor is starting..."
Write-Host " -> App: http://localhost:5173"
Write-Host " -> API docs: http://localhost:8000/docs"
Write-Host " (Ctrl-C to stop both)"
Write-Host ""
try {
# If either one dies, stop the other rather than leave half a dev setup.
while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 }
}
finally {
# Kill the whole tree: uvicorn --reload runs the server in a child process,
# which would otherwise keep :8000 bound after the reloader has gone.
foreach ($p in $Backend, $Frontend) {
if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null }
}
}
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more