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"]
|
||||
Reference in new issue
Block a user