mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented stem conversion API
This commit is contained in:
1 parent
e805635383
commit
c560876c02
11 files changed
+1158
-41
No files matched your search
@@ -57,6 +57,10 @@ class AppState:
|
||||
# the middle of another would commit a half-applied state; reentrant so
|
||||
# one of them may call another.
|
||||
self.mutation = threading.RLock()
|
||||
# Converted-to-stem tracks awaiting Save or Discard (see stems/pending.py),
|
||||
# and what the last open's crash recovery did about any left over.
|
||||
self.pending = None
|
||||
self.recovery: dict | None = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -117,6 +121,10 @@ class AppState:
|
||||
# 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()
|
||||
@@ -128,9 +136,6 @@ class AppState:
|
||||
if saved:
|
||||
adapter.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.adapter = path, adapter
|
||||
# Started after the saved mapping is applied, so a volume that mapping
|
||||
# already fixes is not asked about.
|
||||
self.relocation = RelocationCheck(adapter)
|
||||
caps = adapter.capabilities()
|
||||
# No sidecar beside a removable library: writing to a user's USB stick to
|
||||
# satisfy Konduktor's own bookkeeping is not a trade worth making. Those
|
||||
@@ -144,6 +149,18 @@ class AppState:
|
||||
label=Path(str(path)).name,
|
||||
sidecar=not getattr(driver, "removable", False),
|
||||
)
|
||||
# A crash may have left converted tracks mid-lifecycle: settle them from
|
||||
# what the SAVED library says, BEFORE the missing-files check — a parked
|
||||
# original is exactly what that check would report as missing.
|
||||
from .stems.pending import Pending
|
||||
|
||||
self.pending = Pending(self.library_id)
|
||||
self.recovery = None
|
||||
if self.pending.items:
|
||||
self.recovery = self.pending.recover(lambda item: adapter.track(item["new_id"]) is not None)
|
||||
# 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)
|
||||
@@ -170,6 +187,15 @@ class AppState:
|
||||
commit = history.commit(
|
||||
self.path, outcome.snapshot, outcome.summary, __version__
|
||||
)
|
||||
# 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.
|
||||
if self.pending is not None and self.pending.swapped():
|
||||
renames = self.pending.commit()
|
||||
if renames and self.library_id:
|
||||
from . import exports
|
||||
|
||||
exports.retarget(self.library_id, renames)
|
||||
return outcome, commit
|
||||
|
||||
def discard(self) -> None:
|
||||
@@ -181,6 +207,8 @@ class AppState:
|
||||
"""
|
||||
assert self.adapter is not None
|
||||
with self.mutation:
|
||||
if self.pending is not None and self.pending.items:
|
||||
self.pending.restore()
|
||||
self.adapter.reload()
|
||||
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ from .schemas import (
|
||||
TrackPage,
|
||||
StemEngineInstall,
|
||||
StemSideLoad,
|
||||
StemConvert,
|
||||
)
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -217,6 +218,7 @@ def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
|
||||
"""Set (or, with blank prefixes, clear) the current collection's remapping.
|
||||
Persists to userprefs AND updates the live store so playback/analysis
|
||||
re-resolve immediately — no reopen needed. Never touches the .nml."""
|
||||
_require_no_pending_stems("Changing the path mapping")
|
||||
a = require_adapter()
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
prefs.set_path_mapping(
|
||||
@@ -252,6 +254,7 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
|
||||
playlist references that join to them) to the `to` prefix, then save (a
|
||||
version-history commit is written). Destructive and OS-specific — the UI
|
||||
warns accordingly."""
|
||||
_require_no_pending_stems("Rewriting paths")
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
if mapping.empty:
|
||||
raise HTTPException(400, "Both a `from` and `to` prefix are required")
|
||||
@@ -312,6 +315,7 @@ def answer_relocation(body: RelocationApply) -> RelocationApplied:
|
||||
"""Answer the check: apply the chosen mappings for THIS SESSION only (no
|
||||
mappings = "Not now"). Nothing is written to the library or to prefs, and a
|
||||
reopen asks again."""
|
||||
_require_no_pending_stems("Relocating files")
|
||||
require_adapter()
|
||||
check = STATE.relocation
|
||||
if check is None:
|
||||
@@ -730,7 +734,12 @@ def capabilities() -> Capabilities:
|
||||
|
||||
@app.get("/api/state", response_model=EditState)
|
||||
def state() -> EditState:
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info())
|
||||
stem_job = JOBS.active(STEM_JOB)
|
||||
pending = STATE.pending.summary() if STATE.pending is not None else None
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info(),
|
||||
pending_stems=pending if pending and pending["tracks"] else None,
|
||||
stem_job=stem_job[0].id if stem_job else None,
|
||||
stem_recovery=STATE.recovery)
|
||||
|
||||
|
||||
# ---- stem engine (download / side-load / remove) --------------------------
|
||||
@@ -796,6 +805,75 @@ def install_stem_engine(body: StemEngineInstall) -> JobStatus:
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
def _require_no_pending_stems(what: str) -> None:
|
||||
"""Refuse an operation that would SAVE or DROP a stem conversion's swap as a
|
||||
side effect — import and remap save pending edits, reload and restore drop
|
||||
them — while converted tracks await Save/Discard or a conversion runs."""
|
||||
if JOBS.active(STEM_JOB):
|
||||
raise HTTPException(409, f"{what} is not possible while tracks are being converted to stems")
|
||||
if STATE.pending is not None and STATE.pending.blocking():
|
||||
raise HTTPException(409, f"{what} is not possible until the converted tracks are saved or discarded")
|
||||
|
||||
|
||||
def _stem_options(body):
|
||||
from .stems import convert
|
||||
|
||||
return convert.Options(
|
||||
mode=body.mode, destination=Path(body.destination).expanduser() if body.destination else None,
|
||||
collection=body.collection, playlist_id=body.playlist_id, new_playlist=body.new_playlist,
|
||||
device=prefs.load_prefs().get("stemDevice", "auto"),
|
||||
)
|
||||
|
||||
|
||||
def _stem_plan(body):
|
||||
from .stems import convert
|
||||
|
||||
adapter = require_adapter()
|
||||
caps = adapter.capabilities()
|
||||
if not (caps.writable and caps.tracks.stem_convertible):
|
||||
raise HTTPException(422, "This library cannot hold stem files")
|
||||
try:
|
||||
return adapter, convert.plan(adapter, body.track_ids, _stem_options(body), STATE.pending)
|
||||
except convert.ConvertError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
|
||||
|
||||
@app.post("/api/tracks/stems/preview")
|
||||
def preview_stem_conversion(body: StemConvert) -> dict:
|
||||
"""What a conversion would do — converted, skipped (and why), disk space."""
|
||||
_adapter, planned = _stem_plan(body)
|
||||
return planned.as_dict()
|
||||
|
||||
|
||||
@app.post("/api/tracks/stems/convert", response_model=JobStatus)
|
||||
def convert_to_stems(body: StemConvert) -> JobStatus:
|
||||
"""Convert tracks to stem files as a job; the swap lands at its end."""
|
||||
from .stems import convert
|
||||
from .stems import engine_manager as em
|
||||
|
||||
_require_no_batch()
|
||||
if JOBS.active("import"):
|
||||
raise HTTPException(409, "Wait for the import to finish")
|
||||
adapter, planned = _stem_plan(body)
|
||||
if planned.blocked:
|
||||
raise HTTPException(409, planned.blocked)
|
||||
if not planned.items:
|
||||
raise HTTPException(400, "None of these tracks can be converted")
|
||||
if any(p.reuse is None for p in planned.items) and not em.default_manager().ready():
|
||||
raise HTTPException(409, "The stem engine is not installed")
|
||||
opts = _stem_options(body)
|
||||
|
||||
def run(handle):
|
||||
return convert.run(handle, adapter, planned, opts, STATE.pending, mutation=STATE.mutation,
|
||||
still_current=lambda: STATE.adapter is adapter)
|
||||
|
||||
try:
|
||||
job = JOBS.submit(STEM_JOB, run, exclusive_with=BATCH_JOBS + (ENGINE_JOB, "import"))
|
||||
except JobBusy:
|
||||
raise HTTPException(409, "Another batch, download or import is running")
|
||||
return JobStatus(**job.as_dict())
|
||||
|
||||
|
||||
@app.post("/api/stems/engine/sideload")
|
||||
def side_load_stem_engine(body: StemSideLoad) -> dict:
|
||||
"""Install the engine or the weights from files the user already has."""
|
||||
@@ -845,6 +923,7 @@ def discard_changes() -> EditState:
|
||||
|
||||
@app.post("/api/reload")
|
||||
def reload_collection() -> dict:
|
||||
_require_no_pending_stems("Reloading")
|
||||
if not STATE.loaded:
|
||||
raise HTTPException(409, "No collection loaded")
|
||||
STATE.open(STATE.path) # re-parse current file from disk
|
||||
@@ -1140,7 +1219,7 @@ class _AnalysisError(Exception):
|
||||
# beats that no longer exist.
|
||||
GRID_JOB = "grid-analysis"
|
||||
CUE_JOB = "auto-hotcues"
|
||||
BATCH_JOBS = (GRID_JOB, CUE_JOB)
|
||||
BATCH_JOBS = (GRID_JOB, CUE_JOB, STEM_JOB)
|
||||
|
||||
|
||||
def _stop_batches() -> None:
|
||||
@@ -1457,6 +1536,7 @@ def restore_version(commit_id: str) -> CollectionStatus:
|
||||
"""Restore the collection to a past version. Writes that version back as a
|
||||
NEW forward save (a fresh commit on top of history — never a rewind), then
|
||||
reloads. The user should close Traktor first (it overwrites on exit)."""
|
||||
_require_no_pending_stems("Restoring a version")
|
||||
require_adapter()
|
||||
data = history.read_version(STATE.path, commit_id)
|
||||
if data is None:
|
||||
@@ -1789,6 +1869,7 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
@app.post("/api/folder/add", response_model=JobStatus)
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
if not plan.importable and not plan.existing:
|
||||
raise HTTPException(400, "Nothing to add (none of those files exist)")
|
||||
@@ -1853,6 +1934,7 @@ def import_preview(body: ImportRequest) -> dict:
|
||||
@app.post("/api/import", response_model=JobStatus)
|
||||
def start_import(body: ImportRequest) -> JobStatus:
|
||||
"""Start an import. Returns immediately; poll the job for progress."""
|
||||
_require_no_pending_stems("Importing")
|
||||
source, dest, destination, plan = _import_plan(body)
|
||||
if not plan.importable:
|
||||
raise HTTPException(400, "Nothing to import (no tracks, or none of their files exist)")
|
||||
|
||||
@@ -164,9 +164,29 @@ class StemSideLoad(BaseModel):
|
||||
kind: Literal["engine", "weights"]
|
||||
|
||||
|
||||
class StemConvert(BaseModel):
|
||||
track_ids: list[str]
|
||||
# "replace": the stem file supersedes the original where it lives (the
|
||||
# original is parked until Save deletes it); "destination": a chosen folder,
|
||||
# originals never touched.
|
||||
mode: Literal["replace", "destination"]
|
||||
destination: str | None = None
|
||||
# "repoint": the entry now names the stem file; "add": a new entry beside it
|
||||
# (destination mode only).
|
||||
collection: Literal["repoint", "add"] = "repoint"
|
||||
playlist_id: str | None = None # add mode: into this existing playlist…
|
||||
new_playlist: str | None = None # …or a new one with this name
|
||||
|
||||
|
||||
class EditState(BaseModel):
|
||||
dirty: bool # unsaved in-memory changes exist
|
||||
library: LibraryInfo
|
||||
# Converted tracks awaiting Save/Discard: {tracks, parked, bytes}.
|
||||
pending_stems: dict | None = None
|
||||
# A running stem conversion's job id, so a reloaded page finds it again.
|
||||
stem_job: str | None = None
|
||||
# What this open's crash recovery did about an interrupted conversion.
|
||||
stem_recovery: dict | None = None
|
||||
|
||||
|
||||
# ---- collection selection ----
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
"""The Convert to Stems batch: plan it, run it, swap it in.
|
||||
|
||||
**The collection is untouched while tracks convert** — for hours, on a big batch
|
||||
— so edits made meanwhile carry over, and Cancel only deletes new files. Each
|
||||
track becomes a verified `<target>.konduktor-partial`. Then one short END STEP,
|
||||
under the app's mutation lock, publishes each file (a rename that refuses to
|
||||
overwrite), parks each original in Replace mode, and swaps every entry at once
|
||||
(`adapter.apply_stem_swaps`). From there the swap is an unsaved edit that Save
|
||||
commits and Discard undoes (`pending.py`).
|
||||
|
||||
Skipped and reported, never failed (decided): a file that is already a stem
|
||||
container (by its CONTENTS — the collection's `<STEMS>` element is on some
|
||||
plain MP3s), a missing file, a target that already exists, two sources that
|
||||
would write one target, a target the collection already names. A track that
|
||||
fails keeps its original and is reported; the rest carry on.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import shutil
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from .. import paths
|
||||
from ..core import stem_file as sf
|
||||
from ..core.adapter import AdapterError, StemSwap
|
||||
from ..core.pathmap import common_dir_prefix
|
||||
from ..importer import SPACE_HEADROOM, free_bytes
|
||||
from . import engine_manager as em
|
||||
from .engine_process import EngineCancelled, EngineProcess, keep_awake
|
||||
from .pending import Pending, _replace_no_overwrite, _retrying, parked_name, partial_name, source_facts
|
||||
|
||||
_LOSSLESS = (".wav", ".aif", ".aiff", ".flac")
|
||||
#: Five AAC streams at up to 320 kbps plus container overhead.
|
||||
_BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * 1.03}
|
||||
#: Raw float32 stereo, mix + four stems, while a track is being separated.
|
||||
_WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR
|
||||
|
||||
|
||||
class ConvertError(Exception):
|
||||
"""User-facing; refuses the whole batch."""
|
||||
|
||||
|
||||
class _Cancel(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Options:
|
||||
mode: str # "replace" | "destination"
|
||||
destination: Path | None = None
|
||||
collection: str = "repoint" # "repoint" | "add"
|
||||
playlist_id: str | None = None # add mode: an existing playlist
|
||||
new_playlist: str | None = None # add mode: create one with this name
|
||||
device: str = "auto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Planned:
|
||||
track_id: str
|
||||
title: str
|
||||
source: Path
|
||||
target: Path
|
||||
seconds: float
|
||||
reuse: dict | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Plan:
|
||||
items: list[Planned] = field(default_factory=list)
|
||||
skipped: list[dict] = field(default_factory=list)
|
||||
space: list[dict] = field(default_factory=list)
|
||||
blocked: str | None = None
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {"convert": [{"track_id": p.track_id, "title": p.title, "target": str(p.target),
|
||||
"reuse": p.reuse is not None} for p in self.items],
|
||||
"skipped": self.skipped, "space": self.space, "blocked": self.blocked}
|
||||
|
||||
|
||||
def _title(track) -> str:
|
||||
if track is None:
|
||||
return "?"
|
||||
if track.artist and track.title:
|
||||
return f"{track.artist} - {track.title}"
|
||||
return track.title or Path(track.filepath or "").name or track.id
|
||||
|
||||
|
||||
def _mirror(sources: list[Path], destination: Path) -> dict[Path, Path]:
|
||||
"""Target folder per source: the source tree under `destination`, relative
|
||||
to the sources' common folder, so same-named files cannot collide. Tracks
|
||||
on different drives share no folder; each then keeps its full path (drive
|
||||
or volume first)."""
|
||||
prefix = common_dir_prefix([str(s) for s in sources])
|
||||
out: dict[Path, Path] = {}
|
||||
for s in sources:
|
||||
if prefix:
|
||||
rel = Path(str(s.parent)[len(prefix):].lstrip("/\\"))
|
||||
else:
|
||||
parts = s.parent.parts[1:]
|
||||
head = s.drive.rstrip(":") if s.drive else ""
|
||||
rel = Path(head, *parts) if head else Path(*parts)
|
||||
out[s] = destination / rel
|
||||
return out
|
||||
|
||||
|
||||
def _output_rate(track, source: Path) -> int:
|
||||
if source.suffix.lower() in _LOSSLESS:
|
||||
return 320_000
|
||||
bitrate = getattr(track, "bitrate", None) or 0
|
||||
return 256_000 if 0 < bitrate < 256_000 else 320_000
|
||||
|
||||
|
||||
def plan(adapter, track_ids: list[str], opts: Options, pending: Pending | None) -> Plan:
|
||||
"""What the batch would do, without touching anything."""
|
||||
result = Plan()
|
||||
if opts.mode not in ("replace", "destination"):
|
||||
raise ConvertError(f"Unknown mode {opts.mode!r}")
|
||||
if opts.mode == "replace" and opts.collection != "repoint":
|
||||
raise ConvertError("Replace mode replaces the entry; adding a second one needs a destination folder")
|
||||
if opts.mode == "destination" and not opts.destination:
|
||||
raise ConvertError("Choose a destination folder")
|
||||
|
||||
in_library = {str(p) for t in adapter.tracks if (p := adapter.audio_path(t.id)) is not None}
|
||||
candidates: list[tuple[str, object, Path]] = []
|
||||
for tid in dict.fromkeys(track_ids):
|
||||
track = adapter.track(tid)
|
||||
src = adapter.audio_path(tid) if track is not None else None
|
||||
if track is None:
|
||||
result.skipped.append({"track_id": tid, "title": tid, "reason": "not in the library"})
|
||||
elif src is None or not Path(src).is_file():
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "the file is missing"})
|
||||
elif sf.is_stem_file(src):
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": "already a stem file"})
|
||||
else:
|
||||
candidates.append((tid, track, Path(src)))
|
||||
|
||||
folders = ({s: s.parent for _, _, s in candidates} if opts.mode == "replace"
|
||||
else _mirror([s for _, _, s in candidates], Path(opts.destination)))
|
||||
claimed: set[str] = set()
|
||||
need: dict[str, dict] = {}
|
||||
for tid, track, src in candidates:
|
||||
target = folders[src] / sf.stem_target_name(src.name)
|
||||
key = str(target).casefold() # APFS and NTFS are case-insensitive by default
|
||||
reuse = pending.find_leftover(src) if pending is not None else None
|
||||
if reuse is not None and Path(reuse["partial"]) != partial_name(target):
|
||||
reuse = None
|
||||
if key in claimed:
|
||||
reason = "another selected track converts to the same file"
|
||||
elif target.exists():
|
||||
reason = f"a stem file already exists: {target.name}"
|
||||
elif str(target) in in_library:
|
||||
reason = f"the collection already has {target.name}"
|
||||
else:
|
||||
reason = None
|
||||
if reason:
|
||||
result.skipped.append({"track_id": tid, "title": _title(track), "reason": reason})
|
||||
continue
|
||||
claimed.add(key)
|
||||
seconds = float(getattr(track, "length", 0) or 0) or src.stat().st_size / (320_000 / 8)
|
||||
result.items.append(Planned(tid, _title(track), src, target, seconds, reuse))
|
||||
vol = _volume_key(target)
|
||||
entry = need.setdefault(vol, {"folder": str(target.parent), "bytes": 0})
|
||||
entry["bytes"] += int(seconds * _BYTES_PER_SECOND[_output_rate(track, src)]) if reuse is None else 0
|
||||
|
||||
# Both copies coexist until Save, so every target volume needs the stem files'
|
||||
# room on top of what is there; the work folder needs the largest track's.
|
||||
for vol, entry in need.items():
|
||||
free = free_bytes(Path(entry["folder"]))
|
||||
entry.update(volume=vol, free=free)
|
||||
result.space.append(entry)
|
||||
if free is not None and entry["bytes"] + SPACE_HEADROOM > free:
|
||||
result.blocked = (f"Not enough space on {vol}: the stem files need about "
|
||||
f"{entry['bytes'] / 1e9:.1f} GB and {free / 1e9:.1f} GB is free")
|
||||
if result.items and result.blocked is None:
|
||||
work = work_root()
|
||||
biggest = max(p.seconds for p in result.items) * _WORK_BYTES_PER_SECOND
|
||||
free = free_bytes(work)
|
||||
if free is not None and biggest + SPACE_HEADROOM > free:
|
||||
result.blocked = (f"Not enough space for working files: about {biggest / 1e9:.1f} GB is "
|
||||
f"needed while a track converts, {free / 1e9:.1f} GB is free")
|
||||
return result
|
||||
|
||||
|
||||
def _volume_key(path: Path) -> str:
|
||||
p = path
|
||||
while not p.exists() and p != p.parent:
|
||||
p = p.parent
|
||||
if sys.platform == "win32":
|
||||
return (p.drive or str(p))
|
||||
parts = p.parts
|
||||
return f"/{parts[1]}/{parts[2]}" if len(parts) > 2 and parts[1] == "Volumes" else "this computer"
|
||||
|
||||
|
||||
def work_root() -> Path:
|
||||
root = paths.app_data_dir() / "stems" / "work"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *,
|
||||
mutation, still_current: Callable[[], bool], manager: em.EngineManager | None = None) -> dict:
|
||||
"""The job. Returns the result dict; the job's state says cancelled/done."""
|
||||
mgr = manager or em.default_manager()
|
||||
result = {"converted": [], "renamed": {}, "added": {}, "skipped": list(planned.skipped),
|
||||
"failed": [], "clamped": {}, "cancelled": False}
|
||||
items = planned.items
|
||||
handle.progress(done=0, total=len(items), unit="tracks", message="Starting the stem engine…")
|
||||
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)
|
||||
if needs_engine and not mgr.ready():
|
||||
raise ConvertError("The stem engine is not installed")
|
||||
|
||||
def checkpoint() -> None:
|
||||
if handle.cancelled:
|
||||
raise _Cancel()
|
||||
|
||||
with contextlib.ExitStack() as stack:
|
||||
engine: EngineProcess | None = None
|
||||
try:
|
||||
for i, item in enumerate(items):
|
||||
checkpoint()
|
||||
handle.progress(done=i, message=item.title)
|
||||
partial = partial_name(item.target)
|
||||
if item.reuse is not None:
|
||||
written = sf.Written(path=partial, **{k: item.reuse["written"][k] for k in ("bit_rate", "duration", "size")},
|
||||
tags={})
|
||||
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
|
||||
"stem": str(item.target), "state": "converted", "facts": source_facts(item.source),
|
||||
"written": item.reuse["written"]})
|
||||
pending.forget_leftover(item.reuse, delete=False)
|
||||
finished.append((item, pitem, written))
|
||||
continue
|
||||
if engine is None:
|
||||
handle.progress(message="Starting the stem engine…")
|
||||
engine = stack.enter_context(EngineProcess(mgr.executable(), mgr.weights_dir(), device=opts.device))
|
||||
stack.enter_context(keep_awake(engine.proc.pid))
|
||||
pitem = pending.add({"track_id": item.track_id, "mode": opts.collection, "source": str(item.source),
|
||||
"stem": str(item.target), "state": "converting", "facts": source_facts(item.source)})
|
||||
item.target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def on_progress(f: float, i=i, item=item) -> None:
|
||||
handle.progress(message=f"{item.title} — separating {f * 100:.0f} %")
|
||||
|
||||
try:
|
||||
written = sf.build(item.source, partial,
|
||||
lambda pcm: engine.separate(pcm, work, on_progress=on_progress,
|
||||
cancelled=lambda: handle.cancelled),
|
||||
checkpoint=checkpoint)
|
||||
except (_Cancel, EngineCancelled):
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
raise
|
||||
except Exception as ex: # noqa: BLE001 — one track's failure is reported, not fatal
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
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 # it died: the next track starts a fresh one
|
||||
continue
|
||||
pending.update(pitem, state="converted",
|
||||
written={"bit_rate": written.bit_rate, "duration": written.duration, "size": written.size})
|
||||
finished.append((item, pitem, written))
|
||||
except (_Cancel, EngineCancelled):
|
||||
# Cancel = delete what this run made; nothing else was touched.
|
||||
for _item, pitem, written in finished:
|
||||
if pitem.get("state") == "converted":
|
||||
Path(written.path).unlink(missing_ok=True)
|
||||
pending.drop([p for _, p, _ in finished])
|
||||
result["cancelled"] = True
|
||||
return result
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
handle.progress(done=len(items), message="Swapping the converted tracks into the collection…")
|
||||
with mutation:
|
||||
if not still_current():
|
||||
for _item, pitem, written in finished:
|
||||
Path(written.path).unlink(missing_ok=True)
|
||||
pending.drop([p for _, p, _ in finished])
|
||||
raise ConvertError("The library changed while converting; nothing was swapped in")
|
||||
_end_step(adapter, finished, opts, pending, result)
|
||||
return result
|
||||
|
||||
|
||||
def _end_step(adapter, finished, opts: Options, pending: Pending, result: dict) -> None:
|
||||
swaps: list[StemSwap] = []
|
||||
staged: list[tuple[Planned, dict]] = []
|
||||
for item, pitem, written in finished:
|
||||
partial = Path(written.path)
|
||||
try:
|
||||
_replace_no_overwrite(partial, item.target)
|
||||
except FileExistsError:
|
||||
partial.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title,
|
||||
"reason": f"a file appeared at {item.target.name} while converting"})
|
||||
continue
|
||||
pending.update(pitem, state="published")
|
||||
original_now = item.source
|
||||
if opts.mode == "replace":
|
||||
parked = parked_name(item.source)
|
||||
try:
|
||||
_retrying(lambda: _replace_no_overwrite(item.source, parked))
|
||||
except OSError as ex:
|
||||
item.target.unlink(missing_ok=True)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title,
|
||||
"reason": f"the original could not be moved aside (in use?): {ex}"})
|
||||
continue
|
||||
_hide(parked)
|
||||
pending.update(pitem, state="parked", parked=str(parked))
|
||||
original_now = parked
|
||||
swaps.append(StemSwap(item.track_id, item.target, opts.collection, original_now,
|
||||
written.bit_rate, written.duration, written.size))
|
||||
staged.append((item, pitem))
|
||||
if not swaps:
|
||||
return
|
||||
playlist = opts.playlist_id
|
||||
try:
|
||||
if opts.collection == "add" and opts.new_playlist:
|
||||
playlist = adapter.create_playlist(opts.new_playlist)
|
||||
elif playlist is not None and adapter.playlist_entries(playlist) is None:
|
||||
result["playlist_missing"] = True # deleted while converting: the tracks are still added
|
||||
playlist = None
|
||||
res = adapter.apply_stem_swaps(swaps, add_to_playlist=playlist if opts.collection == "add" else None)
|
||||
except AdapterError as ex:
|
||||
# Nothing was swapped (the command validates everything first): undo the files.
|
||||
for item, pitem in staged:
|
||||
pending._undo(pitem, keep_leftover=False)
|
||||
pending.drop([pitem])
|
||||
result["failed"].append({"track_id": item.track_id, "title": item.title, "reason": str(ex)})
|
||||
return
|
||||
for item, pitem in staged:
|
||||
new_id = res.renamed[item.track_id]
|
||||
pending.update(pitem, state="swapped", new_id=new_id)
|
||||
result["converted"].append({"track_id": item.track_id, "new_id": new_id, "title": item.title})
|
||||
(result["renamed"] if opts.collection == "repoint" else result["added"])[item.track_id] = new_id
|
||||
result["clamped"] = res.clamped
|
||||
|
||||
|
||||
def _hide(path: Path) -> None:
|
||||
"""Windows ignores dot-names; set the hidden attribute so a parked original
|
||||
does not show in Explorer (or a naive folder scan)."""
|
||||
if sys.platform != "win32":
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.kernel32.SetFileAttributesW(str(path), 0x02)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Conversions that are done on disk but not yet committed by a Save.
|
||||
|
||||
A Convert to Stems batch leaves, per track: a stem file, and — in Replace mode —
|
||||
the original PARKED beside it (`.<name>.<ext>.konduktor-parked`, the same
|
||||
folder, so the rename is atomic and nothing looks like audio). The collection
|
||||
swap itself is an ordinary unsaved edit. So the files must follow what happens
|
||||
to the edits:
|
||||
|
||||
* **Save** commits them: parked originals are deleted (the user chose Replace,
|
||||
and was told Save deletes them), export sets follow the new ids.
|
||||
* **Discard** — or opening another library, after its confirm — undoes them:
|
||||
originals go back under their own names, the stem files are removed.
|
||||
* **A crash** leaves this ledger on disk. The next open of the library
|
||||
decides each item from the SAVED collection: if it names the stem file the
|
||||
swap was committed (finish deleting the original), otherwise it was not
|
||||
(put the original back). Verified stem files of an uncommitted item are
|
||||
kept — renamed to their `.konduktor-partial` name, so neither the user nor
|
||||
Traktor mistakes them for finished files — and a later batch converting the
|
||||
same source reuses one instead of spending minutes separating it again.
|
||||
|
||||
The ledger is Konduktor's own curated state, written atomically
|
||||
(`paths.write_json`), one file per library id. Every step is taken from what is
|
||||
actually ON DISK, never from the recorded state alone: a crash can fall between
|
||||
any two renames.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .. import paths
|
||||
|
||||
PARTIAL = ".konduktor-partial"
|
||||
PARKED = ".konduktor-parked"
|
||||
|
||||
|
||||
def parked_name(original: Path) -> Path:
|
||||
return original.with_name(f".{original.name}{PARKED}")
|
||||
|
||||
|
||||
def partial_name(stem: Path) -> Path:
|
||||
return stem.with_name(stem.name + PARTIAL)
|
||||
|
||||
|
||||
def source_facts(path: Path) -> dict | None:
|
||||
try:
|
||||
st = path.stat()
|
||||
except OSError:
|
||||
return None
|
||||
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
|
||||
|
||||
def _replace_no_overwrite(src: Path, dst: Path) -> None:
|
||||
"""Rename refusing to overwrite: POSIX link+unlink (link fails if dst
|
||||
exists), Windows rename (which already refuses)."""
|
||||
if os.name == "nt":
|
||||
os.rename(src, dst)
|
||||
return
|
||||
os.link(src, dst)
|
||||
os.unlink(src)
|
||||
|
||||
|
||||
def _retrying(fn, *, attempts: int = 6, delay: float = 0.25):
|
||||
"""Windows cannot rename a file another process has open (Traktor, the
|
||||
deck's stream, an antivirus scan of a file just written): retry briefly."""
|
||||
for i in range(attempts):
|
||||
try:
|
||||
return fn()
|
||||
except PermissionError:
|
||||
if os.name != "nt" or i == attempts - 1:
|
||||
raise
|
||||
time.sleep(delay * (2 ** i))
|
||||
|
||||
|
||||
class Pending:
|
||||
"""The ledger for ONE library."""
|
||||
|
||||
def __init__(self, library_id: str | None) -> None:
|
||||
self.library_id = library_id
|
||||
self._lock = threading.RLock()
|
||||
self._path = (paths.app_data_dir() / "stems" / f"pending-{library_id}.json") if library_id else None
|
||||
data = paths.read_json(self._path, None) if self._path else None
|
||||
self.items: list[dict] = (data or {}).get("items", [])
|
||||
self.leftovers: list[dict] = (data or {}).get("leftovers", [])
|
||||
|
||||
# ---- persistence ----------------------------------------------------------
|
||||
def _write(self) -> None:
|
||||
if self._path is None:
|
||||
return
|
||||
if not self.items and not self.leftovers:
|
||||
self._path.unlink(missing_ok=True)
|
||||
return
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
paths.write_json(self._path, {"items": self.items, "leftovers": self.leftovers})
|
||||
|
||||
def add(self, item: dict) -> dict:
|
||||
with self._lock:
|
||||
self.items.append(item)
|
||||
self._write()
|
||||
return item
|
||||
|
||||
def update(self, item: dict, **fields) -> None:
|
||||
with self._lock:
|
||||
item.update(fields)
|
||||
self._write()
|
||||
|
||||
def drop(self, items: list[dict]) -> None:
|
||||
with self._lock:
|
||||
ids = {id(i) for i in items}
|
||||
self.items = [i for i in self.items if id(i) not in ids]
|
||||
self._write()
|
||||
|
||||
# ---- what the rest of the app asks ----------------------------------------------
|
||||
def swapped(self) -> list[dict]:
|
||||
return [i for i in self.items if i.get("state") == "swapped"]
|
||||
|
||||
def blocking(self) -> bool:
|
||||
"""Conversions awaiting Save or Discard — while there are any, import,
|
||||
remap, reload and history restore must refuse: each would save or drop
|
||||
the swap as a side effect."""
|
||||
return bool(self.swapped())
|
||||
|
||||
def summary(self) -> dict:
|
||||
parked = [Path(i["parked"]) for i in self.swapped() if i.get("parked")]
|
||||
return {"tracks": len(self.swapped()),
|
||||
"parked": len(parked),
|
||||
"bytes": sum(p.stat().st_size for p in parked if p.exists())}
|
||||
|
||||
# ---- leftovers (reuse after a crash) -----------------------------------------------
|
||||
def find_leftover(self, source: Path) -> dict | None:
|
||||
facts = source_facts(source)
|
||||
for lo in self.leftovers:
|
||||
if lo["source"] == str(source) and lo.get("facts") == facts and Path(lo["partial"]).is_file():
|
||||
return lo
|
||||
return None
|
||||
|
||||
def forget_leftover(self, leftover: dict, *, delete: bool) -> None:
|
||||
with self._lock:
|
||||
if delete:
|
||||
Path(leftover["partial"]).unlink(missing_ok=True)
|
||||
self.leftovers = [lo for lo in self.leftovers if lo is not leftover]
|
||||
self._write()
|
||||
|
||||
def _keep_as_leftover(self, item: dict) -> None:
|
||||
"""A verified stem file whose swap was not committed: keep it under its
|
||||
partial name for reuse (rather than hours of separation lost)."""
|
||||
stem = Path(item["stem"])
|
||||
partial = partial_name(stem)
|
||||
try:
|
||||
if _published(item) and stem.is_file() and not partial.exists():
|
||||
os.replace(stem, partial)
|
||||
except OSError:
|
||||
return
|
||||
if partial.is_file() and item.get("written"):
|
||||
self.leftovers.append({"source": item["source"], "facts": item.get("facts"),
|
||||
"partial": str(partial), "written": item["written"]})
|
||||
|
||||
# ---- Save / Discard / recovery ---------------------------------------------------
|
||||
def commit(self) -> dict[str, str]:
|
||||
"""After a successful Save: delete what the swap replaced. Returns the
|
||||
repoint renames so the caller retargets export sets."""
|
||||
renames: dict[str, str] = {}
|
||||
with self._lock:
|
||||
for item in self.swapped():
|
||||
if item.get("parked"):
|
||||
try:
|
||||
Path(item["parked"]).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass # a file still open on Windows: recovery tries again
|
||||
if item.get("mode") == "repoint" and item.get("new_id"):
|
||||
renames[item["track_id"]] = item["new_id"]
|
||||
item["state"] = "committed"
|
||||
self.items = [i for i in self.items if i.get("state") != "committed"
|
||||
or (i.get("parked") and Path(i["parked"]).exists())]
|
||||
self._write()
|
||||
return renames
|
||||
|
||||
def restore(self) -> int:
|
||||
"""Undo every uncommitted conversion: originals back, stem files gone.
|
||||
Returns how many originals were put back."""
|
||||
restored = 0
|
||||
with self._lock:
|
||||
for item in list(self.items):
|
||||
restored += self._undo(item, keep_leftover=False)
|
||||
self.items = []
|
||||
self._write()
|
||||
return restored
|
||||
|
||||
def recover(self, is_committed) -> dict:
|
||||
"""At open, after a crash: decide each leftover item from the SAVED
|
||||
collection (`is_committed(item)` — does it name the stem file?)."""
|
||||
report = {"committed": 0, "restored": 0, "kept": 0}
|
||||
with self._lock:
|
||||
before = len(self.leftovers)
|
||||
for item in list(self.items):
|
||||
if item.get("new_id") and is_committed(item):
|
||||
if item.get("parked"):
|
||||
Path(item["parked"]).unlink(missing_ok=True)
|
||||
report["committed"] += 1
|
||||
else:
|
||||
report["restored"] += self._undo(item, keep_leftover=True)
|
||||
report["kept"] = len(self.leftovers) - before
|
||||
self.items = []
|
||||
self._write()
|
||||
return report
|
||||
|
||||
def _undo(self, item: dict, *, keep_leftover: bool) -> int:
|
||||
"""Put one item's files back as they were. Filesystem-driven."""
|
||||
restored = 0
|
||||
original = Path(item["source"])
|
||||
parked = Path(item["parked"]) if item.get("parked") else None
|
||||
if parked is not None and parked.exists() and not original.exists():
|
||||
_retrying(lambda: _replace_no_overwrite(parked, original))
|
||||
restored = 1
|
||||
stem = Path(item["stem"])
|
||||
if keep_leftover and item.get("written"):
|
||||
self._keep_as_leftover(item)
|
||||
else:
|
||||
try:
|
||||
# Only a stem file THIS batch published is ours to delete: before
|
||||
# that, a file at the target name belongs to someone else.
|
||||
if _published(item):
|
||||
stem.unlink(missing_ok=True)
|
||||
partial_name(stem).unlink(missing_ok=True) # unverified: worthless
|
||||
except OSError:
|
||||
pass
|
||||
return restored
|
||||
|
||||
|
||||
def _published(item: dict) -> bool:
|
||||
return item.get("state") in ("published", "parked", "swapped", "committed")
|
||||
|
||||
|
||||
__all__ = ["PARKED", "PARTIAL", "Pending", "parked_name", "partial_name", "source_facts",
|
||||
"_replace_no_overwrite", "_retrying"]
|
||||
@@ -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_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.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_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.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
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Test helpers for Convert to Stems: a FAKE engine and generated audio.
|
||||
|
||||
Not a test itself. The fake engine speaks the real `serve` protocol
|
||||
(`engine/konduktor_engine/serve.py`) — no torch — returning scaled copies of
|
||||
the mix as its "stems". Environment switches, read per separation:
|
||||
FAKE_DELAY seconds per progress step (10 steps) FAKE_ERROR reply "error"
|
||||
FAKE_CRASH die mid-request (stderr says why) FAKE_COUNT append a line
|
||||
per separation to this file
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
|
||||
FAKE_ENGINE = r'''#!{python}
|
||||
import json, os, queue, sys, threading, time
|
||||
import numpy as np
|
||||
if sys.argv[1] == "info":
|
||||
print(json.dumps({{"event": "info", "version": "{version}", "devices": ["cpu"]}}))
|
||||
sys.exit(0)
|
||||
print(json.dumps({{"event": "ready", "device": "cpu"}}), flush=True)
|
||||
cancel, Q = set(), queue.Queue()
|
||||
def reader():
|
||||
for line in sys.stdin:
|
||||
m = json.loads(line)
|
||||
(cancel.add(m["id"]) if m.get("cmd") == "cancel" else Q.put(m))
|
||||
os._exit(0)
|
||||
threading.Thread(target=reader, daemon=True).start()
|
||||
while True:
|
||||
m = Q.get()
|
||||
rid = m["id"]
|
||||
x = np.fromfile(m["input"], dtype=np.float32).reshape(2, -1)
|
||||
if os.environ.get("FAKE_COUNT"):
|
||||
with open(os.environ["FAKE_COUNT"], "a") as f:
|
||||
f.write(rid + "\n")
|
||||
if os.environ.get("FAKE_CRASH"):
|
||||
print("boom: out of cheese", file=sys.stderr, flush=True); os._exit(3)
|
||||
if os.environ.get("FAKE_ERROR"):
|
||||
print(json.dumps({{"id": rid, "event": "error", "message": "bad input"}}), flush=True); continue
|
||||
stopped = False
|
||||
for i in range(10):
|
||||
time.sleep(float(os.environ.get("FAKE_DELAY", "0.005")))
|
||||
if rid in cancel:
|
||||
print(json.dumps({{"id": rid, "event": "cancelled"}}), flush=True); stopped = True; break
|
||||
print(json.dumps({{"id": rid, "event": "progress", "fraction": (i + 1) / 10}}), flush=True)
|
||||
if stopped:
|
||||
continue
|
||||
os.makedirs(m["output_dir"], exist_ok=True)
|
||||
for k, g in zip(("drums", "bass", "other", "vocals"), (0.5, 0.25, -0.2, 0.1)):
|
||||
(x * g).astype(np.float32).tofile(os.path.join(m["output_dir"], k + ".f32"))
|
||||
print(json.dumps({{"id": rid, "event": "done", "device": "cpu"}}), flush=True)
|
||||
'''
|
||||
|
||||
|
||||
def write_fake_engine(path: Path, version: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(FAKE_ENGINE.format(python=sys.executable, version=version))
|
||||
path.chmod(path.stat().st_mode | stat.S_IEXEC)
|
||||
return path
|
||||
|
||||
|
||||
def install_fake_engine(root: Path):
|
||||
"""An `EngineManager` whose engine is the fake one and whose weights are two
|
||||
tiny files — `ready()` without any download."""
|
||||
from konduktor.stems import engine_manager as em
|
||||
|
||||
files = [("htdemucs_ft.yaml", b"models: [a]\n"), ("a.safetensors", b"\0" * 64)]
|
||||
weights = {"repo": "x/y", "revision": "fake", "url": "http://invalid/{name}",
|
||||
"files": [{"name": n, "size": len(d), "sha256": hashlib.sha256(d).hexdigest()} for n, d in files]}
|
||||
mgr = em.EngineManager(root=root, weights=weights, target="macos-arm64")
|
||||
exe = write_fake_engine(root / mgr.version / "macos-arm64" / "konduktor-engine" / "konduktor-engine", mgr.version)
|
||||
(root / "installed.json").write_text(json.dumps(
|
||||
{"version": mgr.version, "target": "macos-arm64", "size": 1, "executable": str(exe), "info": {}}))
|
||||
wd = mgr.weights_dir()
|
||||
wd.mkdir(parents=True, exist_ok=True)
|
||||
for n, d in files:
|
||||
(wd / n).write_bytes(d)
|
||||
assert mgr.ready()
|
||||
return mgr
|
||||
|
||||
|
||||
def make_mp3(path: Path, seconds: float = 4, seed: int = 3) -> Path:
|
||||
"""An MP3 WITH a Xing/Info header (so Traktor's 2257-sample offset applies)."""
|
||||
sr = 44100
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(sr * seconds)
|
||||
x = np.zeros((2, n), np.float32)
|
||||
for start in range(sr // 2, n - sr // 10, sr // 2):
|
||||
x[:, start:start + 2000] = rng.uniform(-0.5, 0.5, (2, 2000))
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with av.open(str(path), "w", format="mp3") as c:
|
||||
s = c.add_stream("libmp3lame", rate=sr, layout="stereo")
|
||||
s.bit_rate = 320_000
|
||||
for o in range(0, n, 1152):
|
||||
f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, o:o + 1152]), format="fltp", layout="stereo")
|
||||
f.sample_rate, f.pts = sr, o
|
||||
for p in s.encode(f):
|
||||
c.mux(p)
|
||||
for p in s.encode(None):
|
||||
c.mux(p)
|
||||
return path
|
||||
@@ -45,41 +45,7 @@ def check(label, cond, detail=""):
|
||||
failed = True
|
||||
|
||||
|
||||
FAKE_ENGINE = r'''#!{python}
|
||||
import json, os, queue, sys, threading, time
|
||||
import numpy as np
|
||||
if sys.argv[1] == "info":
|
||||
print(json.dumps({{"event": "info", "version": "{version}", "devices": ["cpu"]}}))
|
||||
sys.exit(0)
|
||||
print(json.dumps({{"event": "ready", "device": "cpu"}}), flush=True)
|
||||
cancel, Q = set(), queue.Queue()
|
||||
def reader():
|
||||
for line in sys.stdin:
|
||||
m = json.loads(line)
|
||||
(cancel.add(m["id"]) if m.get("cmd") == "cancel" else Q.put(m))
|
||||
os._exit(0)
|
||||
threading.Thread(target=reader, daemon=True).start()
|
||||
while True:
|
||||
m = Q.get()
|
||||
rid = m["id"]
|
||||
x = np.fromfile(m["input"], dtype=np.float32).reshape(2, -1)
|
||||
if os.environ.get("FAKE_CRASH"):
|
||||
print("boom: out of cheese", file=sys.stderr, flush=True); os._exit(3)
|
||||
if os.environ.get("FAKE_ERROR"):
|
||||
print(json.dumps({{"id": rid, "event": "error", "message": "bad input"}}), flush=True); continue
|
||||
stopped = False
|
||||
for i in range(10):
|
||||
time.sleep(float(os.environ.get("FAKE_DELAY", "0.005")))
|
||||
if rid in cancel:
|
||||
print(json.dumps({{"id": rid, "event": "cancelled"}}), flush=True); stopped = True; break
|
||||
print(json.dumps({{"id": rid, "event": "progress", "fraction": (i + 1) / 10}}), flush=True)
|
||||
if stopped:
|
||||
continue
|
||||
os.makedirs(m["output_dir"], exist_ok=True)
|
||||
for k, g in zip(("drums", "bass", "other", "vocals"), (0.5, 0.25, -0.2, 0.1)):
|
||||
(x * g).astype(np.float32).tofile(os.path.join(m["output_dir"], k + ".f32"))
|
||||
print(json.dumps({{"id": rid, "event": "done", "device": "cpu"}}), flush=True)
|
||||
'''
|
||||
from stem_test_support import FAKE_ENGINE # noqa: E402 — the one fake engine, shared
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""The Convert to Stems batch end to end, through the routes, with a FAKE engine.
|
||||
|
||||
Against temp copies of the real collection whose playlisted tracks are pointed
|
||||
at generated MP3s. What would fail silently or destroy something:
|
||||
|
||||
* skips are reported with reasons (missing, already a stem file, target
|
||||
exists, two sources onto one target) and never converted;
|
||||
* a Replace batch leaves the SAVED collection untouched, parks the originals,
|
||||
swaps every entry at the end — prep unmoved in decoded time — and blocks
|
||||
the operations that would save or drop the swap;
|
||||
* Save deletes the parked originals and retargets export sets; Discard and
|
||||
opening another library put them back;
|
||||
* Cancel deletes what the run made and nothing else; one bad track fails
|
||||
alone;
|
||||
* destination + add mirrors the tree, never touches the originals, fills a
|
||||
new playlist;
|
||||
* after a CRASH, the next open restores (or, if the save got through,
|
||||
finishes) from what the saved collection says — and keeps the finished
|
||||
stem files, which the next batch reuses without separating again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-stemsbatch-appdata-")
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import konduktor.main as main # noqa: E402
|
||||
from konduktor import exports # 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.core import stem_file as sf # noqa: E402
|
||||
from konduktor.stems import engine_manager as em # 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
|
||||
|
||||
|
||||
ROOT = Path(tempfile.mkdtemp(prefix="konduktor-stemsbatch-"))
|
||||
em._DEFAULT = install_fake_engine(ROOT / "engine")
|
||||
|
||||
|
||||
def library(name: str, files: list[str]) -> tuple[Path, list[str], Path]:
|
||||
"""A temp collection whose first len(files) playlisted tracks point at
|
||||
`files` in a music folder (each created as an MP3 unless it is 'missing'),
|
||||
each with a hotcue at 1.000 s and a grid at 0.500 s, saved."""
|
||||
d = ROOT / name
|
||||
music = d / "Music"
|
||||
music.mkdir(parents=True)
|
||||
work = d / "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]
|
||||
ids = []
|
||||
for f, e in zip(files, entries):
|
||||
path = music / f
|
||||
if f.endswith(".mp3") and not f.startswith("missing"):
|
||||
make_mp3(path, seed=len(ids) + 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 n in st._iter_nodes(st._root()):
|
||||
for pe in (n.playlist.entry if n.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 = []
|
||||
if path.exists():
|
||||
st.set_hotcue(new, 1, 1.0, 0, name="Drop")
|
||||
st.replace_grid(new, [(0.5, 120.0)])
|
||||
ids.append(new)
|
||||
st.save()
|
||||
return work, ids, music
|
||||
|
||||
|
||||
def open_lib(c, work):
|
||||
r = c.post("/api/library/open", json={"path": str(work)})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def wait(c, jid, timeout=60):
|
||||
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")
|
||||
|
||||
|
||||
def convert(c, ids, **opts):
|
||||
r = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace", **opts})
|
||||
assert r.status_code == 200, r.text
|
||||
return wait(c, r.json()["id"])
|
||||
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
print("== preview: skips, with reasons ==")
|
||||
work, ids, music = library("preview", ["ok.mp3", "missing.mp3", "have.mp3", "dup.mp3", "dup.m4a", "stemsrc.mp3"])
|
||||
sf.build(make_mp3(ROOT / "tmp-src.mp3"), music / "already.stem.m4a", lambda p: [p * g for g in (0.5, 0.25, -0.2, 0.1)])
|
||||
(music / "have.stem.m4a").write_bytes(b"a stem the user already owns")
|
||||
make_mp3(music / "dup.m4a") # (MP3 bytes under an .m4a name: only its target name matters here)
|
||||
st = TraktorStore(work)
|
||||
e = st.model_entry(ids[5])
|
||||
e.location.file = "already.stem.m4a"
|
||||
st._entry_by_key = {st._key_of(x): x for x in st._nml.collection.entry if x.location}
|
||||
ids[5] = st._key_of(e)
|
||||
st.save()
|
||||
open_lib(c, work)
|
||||
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
|
||||
reasons = [s["reason"] for s in pv["skipped"]]
|
||||
check("the convertible tracks are planned (ok.mp3, dup.mp3)",
|
||||
sorted(Path(x["target"]).name for x in pv["convert"]) == ["dup.stem.m4a", "ok.stem.m4a"], str(pv["convert"]))
|
||||
check("a missing file is skipped, saying so", any("missing" in r for r in reasons), str(reasons))
|
||||
check("a file that is already a stem file is skipped", any("already a stem file" in r for r in reasons))
|
||||
check("an existing target is skipped, NEVER overwritten", any("already exists" in r for r in reasons)
|
||||
and (music / "have.stem.m4a").read_bytes() == b"a stem the user already owns")
|
||||
check("two sources onto one target (dup.mp3 + dup.m4a): the second is skipped",
|
||||
any("same file" in r for r in reasons), str(reasons))
|
||||
check("no disk-space block for a few small files", pv["blocked"] is None, str(pv["blocked"]))
|
||||
|
||||
print("== Replace: convert, park, swap at the end; the saved file untouched ==")
|
||||
work, ids, music = library("replace", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
a = main.require_adapter()
|
||||
before = {t: a.track_cues(t) for t in ids}
|
||||
disk = work.read_bytes()
|
||||
lib_id = main.STATE.library_id
|
||||
es = exports.create(lib_id, name="Gig", targets=["traktor"], destination=str(ROOT / "stick"))
|
||||
exports.add(lib_id, es.id, track_ids=[ids[0]])
|
||||
j = convert(c, ids)
|
||||
res = j["result"]
|
||||
check("the job finishes, both converted", j["state"] == "done" and len(res["converted"]) == 2, str(j)[:400])
|
||||
new = [res["renamed"][t] for t in ids]
|
||||
check("stem files sit beside the originals", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
|
||||
check("the originals are PARKED, not gone",
|
||||
all(parked_name(music / n).is_file() and not (music / n).exists() for n in ("a.mp3", "b.mp3")))
|
||||
check("no unfinished files are left", not list(music.glob("*.konduktor-partial")))
|
||||
check("the saved collection is untouched until Save", work.read_bytes() == disk)
|
||||
state = c.get("/api/state").json()
|
||||
check("the library is dirty and reports the pending conversions",
|
||||
state["dirty"] and state["pending_stems"]["tracks"] == 2 and state["pending_stems"]["parked"] == 2, str(state))
|
||||
a = main.require_adapter()
|
||||
check("the entries are stems now", all(a.track(n).media_kind == "stem" for n in new))
|
||||
check("prep reads back at the same decoded seconds",
|
||||
all([round(x.start, 6) for x in a.track_cues(n).cues] == [round(x.start, 6) for x in before[o].cues]
|
||||
for o, n in zip(ids, new)))
|
||||
for route, body in (("/api/reload", None), ("/api/library/remap-paths", {"from": "/x", "to": "/y"}),
|
||||
("/api/history/deadbeef/restore", None)):
|
||||
r = c.post(route, json=body) if body else c.post(route)
|
||||
check(f"{route} is refused while conversions await Save (409)", r.status_code == 409, f"{r.status_code} {r.text[:120]}")
|
||||
r = c.post("/api/save")
|
||||
check("Save succeeds", r.status_code == 200, r.text[:200])
|
||||
check("…and deletes the parked originals", not any(music.glob(".*.konduktor-parked")))
|
||||
check("…keeps the stem files", all((music / n).is_file() for n in ("a.stem.m4a", "b.stem.m4a")))
|
||||
check("…and nothing is pending any more", c.get("/api/state").json()["pending_stems"] is None)
|
||||
check("the saved collection names the stem files as STEM entries", all(n in TraktorStore(work).stem_keys() for n in new))
|
||||
check("the export set follows the converted track to its new id", exports.get(lib_id, es.id).track_ids == [new[0]],
|
||||
str(exports.get(lib_id, es.id).track_ids))
|
||||
|
||||
print("== Discard puts everything back ==")
|
||||
work, ids, music = library("discard", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
r = c.post("/api/discard")
|
||||
check("discard succeeds", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200])
|
||||
check("the originals are back under their own names", all((music / n).is_file() for n in ("a.mp3", "b.mp3")))
|
||||
check("the stem files are gone, and nothing parked is left",
|
||||
not list(music.glob("*.stem.m4a")) and not list(music.glob(".*.konduktor-parked")))
|
||||
check("the entries name the MP3s again", all(main.require_adapter().track(t) is not None for t in ids))
|
||||
|
||||
print("== opening another library also puts them back ==")
|
||||
convert(c, ids)
|
||||
other, _o, _m = library("other", [])
|
||||
open_lib(c, other)
|
||||
check("the originals are back when switching library", all((music / n).is_file() for n in ("a.mp3", "b.mp3"))
|
||||
and not list(music.glob("*.stem.m4a")))
|
||||
|
||||
print("== Cancel deletes what the run made, nothing else ==")
|
||||
work, ids, music = library("cancel", ["a.mp3", "b.mp3", "c.mp3"])
|
||||
open_lib(c, work)
|
||||
os.environ["FAKE_DELAY"] = "0.15"
|
||||
jid = c.post("/api/tracks/stems/convert", json={"track_ids": ids, "mode": "replace"}).json()["id"]
|
||||
end = time.time() + 30
|
||||
while time.time() < end and "separating" not in c.get(f"/api/jobs/{jid}").json()["message"]:
|
||||
time.sleep(0.05)
|
||||
time.sleep(1.8) # into the second track
|
||||
c.post(f"/api/jobs/{jid}/cancel")
|
||||
j = wait(c, jid)
|
||||
os.environ.pop("FAKE_DELAY")
|
||||
check("the job is cancelled", j["state"] == "cancelled" and j["result"]["cancelled"], str(j)[:300])
|
||||
check("no stem file, no unfinished file is left",
|
||||
not list(music.glob("*.stem.m4a*")) and not list(music.glob("*.konduktor-partial")), str(list(music.iterdir())))
|
||||
check("the originals were never touched", all((music / n).is_file() for n in ("a.mp3", "b.mp3", "c.mp3")))
|
||||
check("nothing is dirty", c.get("/api/state").json()["dirty"] is False)
|
||||
|
||||
print("== one bad track fails alone ==")
|
||||
work, ids, music = library("fail", ["a.mp3", "bad.mp3"])
|
||||
(music / "bad.mp3").write_bytes(b"not audio at all")
|
||||
open_lib(c, work)
|
||||
j = convert(c, ids)
|
||||
res = j["result"]
|
||||
check("the good track converts", ids[0] in res["renamed"], str(res)[:300])
|
||||
check("the bad one is reported with a reason and keeps its original",
|
||||
len(res["failed"]) == 1 and res["failed"][0]["reason"] and (music / "bad.mp3").is_file(), str(res["failed"]))
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== destination + add: a new playlist, originals untouched ==")
|
||||
work, ids, music = library("dest", ["x.mp3", "sub/y.mp3"])
|
||||
open_lib(c, work)
|
||||
dest = ROOT / "dest-out"
|
||||
j = convert(c, ids, mode="destination", destination=str(dest), collection="add", new_playlist="Stems")
|
||||
res = j["result"]
|
||||
check("both added", len(res["added"]) == 2 and not res["renamed"], str(res)[:300])
|
||||
check("the source tree is mirrored under the destination",
|
||||
(dest / "x.stem.m4a").is_file() and (dest / "sub" / "y.stem.m4a").is_file(), str(list(dest.rglob("*"))))
|
||||
check("the originals are untouched, not parked", (music / "x.mp3").is_file() and not list(music.rglob("*.konduktor-parked")))
|
||||
a = main.require_adapter()
|
||||
pl = next(n for n in a.store._iter_nodes(a.store._root()) if n.playlist is not None and n.name == "Stems")
|
||||
check("the new entries fill the new playlist", a.playlist_entries(pl.playlist.uuid) == [res["added"][t] for t in ids])
|
||||
check("the original entries are still plain tracks", all(a.track(t).media_kind != "stem" for t in ids))
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== after a crash: restore from the saved file, keep the work, reuse it ==")
|
||||
work, ids, music = library("crash", ["a.mp3", "b.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
main.STATE.pending = None # the process died: nothing ran the discard
|
||||
open_lib(c, work)
|
||||
rec = c.get("/api/state").json()["stem_recovery"]
|
||||
check("the next open restored the originals", all((music / n).is_file() for n in ("a.mp3", "b.mp3")) and rec["restored"] == 2, str(rec))
|
||||
check("…and kept the finished stem files aside (not as finished files)",
|
||||
all(partial_name(music / n).is_file() and not (music / n).exists() for n in ("a.stem.m4a", "b.stem.m4a"))
|
||||
and rec["kept"] == 2, str(list(music.iterdir())))
|
||||
count = ROOT / "count.txt"
|
||||
os.environ["FAKE_COUNT"] = str(count)
|
||||
pv = c.post("/api/tracks/stems/preview", json={"track_ids": ids, "mode": "replace"}).json()
|
||||
check("a new batch plans to REUSE them", all(x["reuse"] for x in pv["convert"]), str(pv))
|
||||
j = convert(c, ids)
|
||||
check("…and converts without separating again", j["state"] == "done" and len(j["result"]["converted"]) == 2
|
||||
and not count.exists(), f"{j['result']} engine calls: {count.read_text() if count.exists() else 0}")
|
||||
os.environ.pop("FAKE_COUNT")
|
||||
c.post("/api/discard")
|
||||
|
||||
print("== after a crash between the save and the clean-up ==")
|
||||
work, ids, music = library("crash2", ["a.mp3"])
|
||||
open_lib(c, work)
|
||||
convert(c, ids)
|
||||
main.require_adapter().save() # the library write happened…
|
||||
main.STATE.pending = None # …then the process died before deleting the parked original
|
||||
open_lib(c, work)
|
||||
rec = c.get("/api/state").json()["stem_recovery"]
|
||||
check("the next open sees the swap was committed and finishes it",
|
||||
rec["committed"] == 1 and not list(music.glob(".*.konduktor-parked")) and (music / "a.stem.m4a").is_file(), str(rec))
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Reference in new issue
Block a user