Build analyze backend

This commit is contained in:
patben8 committed 2026-10-04 16:33:37 +02:00
1 parent 72a52d3291
commit 36a6df4d3b
10 files changed
+418 -49

No files matched your search

@@ -312,7 +312,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 +348,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",
@@ -443,7 +443,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, grid_detect, key_detect, waveform
self._require_writable("Adding tracks")
held = set(self._store.all_audio_paths())
@@ -468,13 +468,16 @@ class RekordboxAdapter:
markers = [GridMarker(start=found.anchor, bpm=found.bpm)]
except ValueError:
pass # no pulse to fit (a one-shot, silence): no grid
# 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 = key_detect.with_detected_key(item.track, samples, waveform.SR)
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:
+20
View File
@@ -157,6 +157,26 @@ def detect_key_samples(y: np.ndarray, sr: int) -> KeyResult | None:
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:
import librosa
+180 -37
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import logging
import os
from pathlib import Path
from types import SimpleNamespace
from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
@@ -17,8 +18,8 @@ from fastapi.responses import FileResponse, JSONResponse
from . import __version__, exporter, exports, history, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect, structure
from .core.grid_plan import GridStep
from .core import grid_detect, key_detect, structure
from .core.grid_plan import GridStep, plan_grid
from . import importer
from .core import export as core_export
from .core import places, registry
@@ -40,6 +41,8 @@ from .schemas import (
RelocationApply,
RelocationCandidate,
RelocationVolume,
AnalyzePreview,
AnalyzeRequest,
AutoGridBatchRequest,
AutoGridRequest,
AutoCueOutcome,
@@ -1230,18 +1233,36 @@ def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotc
@app.post("/api/tracks/grid/auto", response_model=TrackCues)
def auto_grid(body: AutoGridRequest) -> TrackCues:
"""Detect tempo + first beat and build a beatgrid (see `core/grid_detect`).
"""The deck's one-click Analyze: BPM + grid (see `core/grid_detect`) and,
where the library can store one, the KEY — from one decode.
One constant-tempo marker, written the way the platform's own analyser would
(on Traktor that also sets hotcue 1 to the first beat). Octave (half/double)
ambiguity in halftime genres is left for the ×2 / ÷2 controls."""
ambiguity in halftime genres is left for the ×2 / ÷2 controls. The key
always follows the analysis (a click on Analyze is a request for it), and
a key that cannot be found never fails the grid."""
a = require_adapter()
if a.track(body.track_id) is None:
raise HTTPException(404, "Track not found")
path = a.audio_path(body.track_id)
if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
try:
return _analyse_grid(a, body.track_id)
y, sr = _decode_for_analysis(path)
except Exception as ex: # noqa: BLE001
raise HTTPException(400, f"Could not decode: {ex}")
try:
cues = _analyse_grid(a, body.track_id, y=y, sr=sr)
except _AnalysisError as ex:
raise HTTPException(400, str(ex))
if a.capabilities().tracks.key_writable:
try:
found = key_detect.detect_key_samples(y, sr)
if found is not None:
a.set_key(body.track_id, found.wheel, found.mode)
except Exception: # noqa: BLE001 — the grid is written; a key is a bonus
log.warning("key detection failed for %s", body.track_id, exc_info=True)
return cues
class _AnalysisError(Exception):
@@ -1330,9 +1351,150 @@ def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *,
@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus)
def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
"""Analyse many tracks' grids as a JOB; poll `/api/jobs/{id}`.
# ---- Analyze (the context menu's "Analyze…": BPM / Grid / Key) -------------
def _require_analysable(a, body: AnalyzeRequest) -> None:
caps = a.capabilities()
if not (body.bpm or body.grid or body.key):
raise HTTPException(400, "Nothing to analyse: tick BPM, Grid or Key")
if (body.bpm or body.grid) and not caps.grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited")
if body.key and not caps.tracks.key_writable:
raise HTTPException(422, "This library's keys cannot be written")
def _grid_step(a, track, body: AnalyzeRequest, *, exact: bool) -> GridStep:
"""`plan_grid` for one track. `exact` reads the real markers (a lazy
platform's projected count is only "has a grid"); the preview does not,
so it cannot see a flexible grid there — the run does."""
if not (body.bpm or body.grid):
return GridStep("none")
if track.grid_marker_count and exact:
markers = list((a.track_cues(track.id) or TrackCues()).grid_markers)
else:
markers = [SimpleNamespace(start=0.0, bpm=track.bpm or 0.0)] * (track.grid_marker_count or 0)
return plan_grid(bpm=body.bpm, grid=body.grid, markers=markers, track_bpm=track.bpm,
locked=bool(track.grid_locked), replace_existing=body.replace_grid)
def _wants_key(track, body: AnalyzeRequest) -> bool:
return body.key and (track.key_wheel is None or body.replace_key)
@app.post("/api/tracks/analyze/preview", response_model=AnalyzePreview)
def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
"""Counts for the Analyze dialog, from the same `plan_grid` the run uses."""
a = require_adapter()
out = AnalyzePreview(total=0)
for tid in dict.fromkeys(body.track_ids):
track = a.track(tid)
if track is None:
continue
out.total += 1
if track.grid_marker_count and not track.grid_locked:
out.with_grid += 1
step = _grid_step(a, track, body, exact=False)
if step.action in ("full", "bpm", "phase"):
setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1)
elif step.action == "skip":
setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1)
if track.key_wheel is not None:
out.with_key += 1
if body.key:
if _wants_key(track, body):
out.key_set += 1
else:
out.key_existing += 1
return out
def _decode_for_analysis(path: Path):
"""Mono samples at the rate BOTH detectors work at (they share one decode)."""
import librosa
assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate"
return librosa.load(str(path), sr=key_detect.SR, mono=True)
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
"""Analyse one track as `body` asks, folding the outcome into `result`.
The file is decoded ONCE and shared by grid and key. A failing half is
reported and does not stop the other: a track whose grid cannot be fitted
(a one-shot) can still have a key, and the reverse."""
track = a.track(track_id)
title = (track.title or track_id) if track else track_id
if track is None:
result["failed"].append({"title": title, "reason": "Track not found"})
return
step = _grid_step(a, track, body, exact=True)
if step.action == "skip":
result["grid"][step.reason] += 1
want_key = _wants_key(track, body)
if body.key and not want_key:
result["key"]["existing"] += 1
if step.action not in ("full", "bpm", "phase") and not want_key:
return
path = a.audio_path(track_id)
if path is None or not path.exists():
result["failed"].append({"title": title, "reason": "Audio file not found (is the drive mounted?)"})
return
try:
y, sr = _decode_for_analysis(path)
except Exception as ex: # noqa: BLE001 — an undecodable file is one failure
result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"})
return
wrote = False
if step.action in ("full", "bpm", "phase"):
try:
_analyse_grid(a, track_id, step, y=y, sr=sr)
result["grid"][step.action] += 1
wrote = True
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": f"Grid: {ex}"})
if want_key:
try:
found = key_detect.detect_key_samples(y, sr)
if found is None:
result["key"]["none"] += 1
else:
a.set_key(track_id, found.wheel, found.mode)
result["key"]["set"] += 1
wrote = True
except (AdapterError, ValueError) as ex:
result["failed"].append({"title": title, "reason": f"Key: {ex}"})
if wrote:
result["analysed"].append(track_id)
def _analyze_job(a, body: AnalyzeRequest):
ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict:
result = {
"analysed": [], "failed": [],
"grid": {"full": 0, "bpm": 0, "phase": 0, "locked": 0, "existing": 0, "flexible": 0},
"key": {"set": 0, "existing": 0, "none": 0},
}
handle.progress(done=0, total=len(ids))
for i, track_id in enumerate(ids):
if handle.cancelled:
break # keep what is done; return it rather than raise
track = a.track(track_id)
handle.progress(message=(track.title or track_id) if track else track_id)
_analyse_one(a, track_id, body, result)
handle.progress(done=i + 1)
# The names the context menu's toast read before the dialog existed.
result["locked"], result["existing"] = result["grid"]["locked"], result["grid"]["existing"]
return result
return run
@app.post("/api/tracks/analyze", response_model=JobStatus)
def analyze_batch(body: AnalyzeRequest) -> JobStatus:
"""Analyse many tracks' BPM / grid / key as a JOB; poll `/api/jobs/{id}`.
Each track is written as it finishes, into the in-memory model like any
other edit — so a cancel keeps what is done (it is all unsaved until Save),
@@ -1340,39 +1502,20 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
reported and skipped, never fatal: one unmounted drive must not stop 400
other tracks."""
a = require_adapter()
if not a.capabilities().grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited")
_require_analysable(a, body)
_require_no_batch()
ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict:
result = {"analysed": [], "locked": 0, "existing": 0, "failed": []}
handle.progress(done=0, total=len(ids))
for i, track_id in enumerate(ids):
if handle.cancelled:
break # keep what is done; return it rather than raise
track = a.track(track_id)
title = (track.title or track_id) if track else track_id
handle.progress(message=title)
if track is None:
result["failed"].append({"title": title, "reason": "Track not found"})
elif track.grid_locked:
result["locked"] += 1
elif track.grid_marker_count > 0 and not body.replace_existing:
result["existing"] += 1
else:
try:
_analyse_grid(a, track_id)
result["analysed"].append(track_id)
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": str(ex)})
handle.progress(done=i + 1)
return result
job = _submit_batch(GRID_JOB, run)
job = _submit_batch(GRID_JOB, _analyze_job(a, body))
return JobStatus(**job.as_dict())
@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus)
def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
"""The pre-dialog route: BPM + Grid, no key. Kept as an alias of
`/api/tracks/analyze` so the two cannot drift."""
return analyze_batch(AnalyzeRequest(track_ids=body.track_ids, bpm=True, grid=True,
key=False, replace_grid=body.replace_existing))
@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus)
def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
"""Place one Auto Hotcues template on many tracks, as a JOB.
+33
View File
@@ -133,6 +133,39 @@ 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
# 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
+97
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,100 @@ 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))
# 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
+51
View File
@@ -113,5 +113,56 @@ 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)
+2
View File
@@ -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)
+7
View File
@@ -684,6 +684,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)