mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented efficient re-exporting
This commit is contained in:
1 parent
3a9dc90344
commit
bb9f6e2bd3
14 files changed
+727
-63
No files matched your search
@@ -41,7 +41,6 @@ import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core import waveform
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from ..rekordbox import anlz_writer as W
|
||||
@@ -165,7 +164,7 @@ class OneLibraryExporter:
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
# Each track is DECODED for its waveform, so this loop is the slow
|
||||
# part of the write — report it, and let a cancel land between tracks.
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})")
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
by_source[item.source_id] = n
|
||||
written += self._write_track(con, n, item, root, lookups)
|
||||
|
||||
@@ -301,7 +300,7 @@ class OneLibraryExporter:
|
||||
# shifted as they are packed, and the waveform frames are measured with
|
||||
# the same lead so they line up with the beats.
|
||||
off = timebase.offset(item.destination)
|
||||
measured = waveform.analyse(item.destination, lead=off)
|
||||
measured = item.waveform(lead=off)
|
||||
# The DECODED length where there is one: `Track.length` is whole seconds
|
||||
# rounded down, and a grid expanded to it loses the track's last beat.
|
||||
beats = self._beats(item, measured.duration if measured else None)
|
||||
|
||||
@@ -101,7 +101,7 @@ class RekordboxDeviceExporter:
|
||||
art_n = 0
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})")
|
||||
payload.checkpoint(f"Writing the device library: {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
track = item.track
|
||||
by_source[item.source_id] = n
|
||||
rel = _drive_relative(item.destination, root)
|
||||
|
||||
@@ -57,7 +57,6 @@ from pathlib import Path
|
||||
from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core import waveform
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import anlz_writer as W
|
||||
from . import artwork, palette
|
||||
@@ -177,7 +176,7 @@ class RekordboxExporter:
|
||||
total = len(payload.tracks)
|
||||
for n, item in enumerate(payload.tracks, start=1):
|
||||
# Each track is decoded for its waveform: the slow part.
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})")
|
||||
payload.checkpoint(f"Analysing {item.track.title or item.destination.name} ({n}/{total})", step=n, of=total)
|
||||
content = self._add_track(db, item)
|
||||
rows[item.source_id] = content
|
||||
ids[item.source_id] = str(content.ID)
|
||||
@@ -366,7 +365,7 @@ class RekordboxExporter:
|
||||
# `.EXT`/`.2EX` carry the drawn waveforms. Cue lists are present but
|
||||
# EMPTY — master.db keeps cues in djmdCue.
|
||||
off = timebase.offset(item.destination)
|
||||
measured = waveform.analyse(item.destination, lead=off)
|
||||
measured = item.waveform(lead=off)
|
||||
path = str(item.destination)
|
||||
tags = [W.path_tag(path), W.vbr_tag(W.mp3_samples(item.destination))]
|
||||
markers = item.cues.grid_markers if item.cues else []
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Waveform analysis kept on the export's own drive, so a re-export decodes only
|
||||
what changed.
|
||||
|
||||
Decoding is the slow part of a Pioneer export (~1.5 s a track, where copying a
|
||||
track to a stick is well under a second), so skipping unchanged copies alone
|
||||
would leave most of a re-export's time in place. What is cached is the
|
||||
MEASUREMENT (`waveform.Analysis`), not any platform's tags: every Pioneer target
|
||||
turns the same measurement into its own files, and the Rekordbox Library target
|
||||
names its analysis folders after a fresh UUID each time, so reusing old ANLZ
|
||||
files by path could never have worked there.
|
||||
|
||||
## Where, and keyed by what
|
||||
|
||||
It lives on the destination (`.konduktor-cache/`), beside the manifest, for the
|
||||
manifest's reason: it describes that drive, and should travel, be cloned or be
|
||||
wiped with it. An entry is keyed by the SOURCE file's path, size and mtime —
|
||||
the same facts the runner uses to decide a copy is unchanged — so an edited
|
||||
track is re-measured exactly when it is re-copied, and the same stick plugged
|
||||
into another computer (other source paths) simply misses and re-decodes.
|
||||
|
||||
`waveform.ANALYSIS_VERSION` is part of every key: change what `analyse()`
|
||||
measures without bumping it and every re-export serves the old measurement.
|
||||
|
||||
Best-effort in both directions: an unreadable entry is a miss, and a failed
|
||||
store is logged, never fatal — the cache can cost time, never an export.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from . import waveform
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: The folder, relative to the export's destination.
|
||||
CACHE_DIR = ".konduktor-cache"
|
||||
|
||||
|
||||
def fingerprint(source: Path | str, size: int, mtime_ns: int) -> str:
|
||||
"""The identity of one version of one source file."""
|
||||
text = f"{waveform.ANALYSIS_VERSION}|{source}|{size}|{mtime_ns}"
|
||||
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:24]
|
||||
|
||||
|
||||
class AnalysisCache:
|
||||
def __init__(self, folder: Path):
|
||||
self.folder = Path(folder)
|
||||
|
||||
def _path(self, key: str, lead: float, n_columns: int) -> Path:
|
||||
# One source can be measured with different leads (a target's clock
|
||||
# offset), so each variant is its own entry under the same key prefix.
|
||||
return self.folder / f"{key}-{int(round(lead * 1_000_000))}-{n_columns}.npz"
|
||||
|
||||
def analyse(self, audio: Path, key: str, *, lead: float = 0.0,
|
||||
n_columns: int = 400) -> waveform.Analysis | None:
|
||||
"""`waveform.analyse(audio, …)`, served from the cache when it can be."""
|
||||
path = self._path(key, lead, n_columns)
|
||||
hit, value = self._load(path, n_columns)
|
||||
if hit:
|
||||
return value
|
||||
value = waveform.analyse(audio, n_columns=n_columns, lead=lead)
|
||||
self._store(path, value)
|
||||
return value
|
||||
|
||||
def prune(self, keep: set[str]) -> None:
|
||||
"""Drop every entry whose key is not in `keep`."""
|
||||
try:
|
||||
for entry in self.folder.iterdir():
|
||||
if entry.name.split("-", 1)[0] not in keep:
|
||||
entry.unlink()
|
||||
self.folder.rmdir() # only succeeds when nothing is left
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def clear(self) -> None:
|
||||
self.prune(set())
|
||||
|
||||
# ---- storage -----------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _load(path: Path, n_columns: int) -> tuple[bool, waveform.Analysis | None]:
|
||||
try:
|
||||
with np.load(path, allow_pickle=False) as data:
|
||||
if bool(data["undecodable"]):
|
||||
# Remembered too: a file nothing can decode would otherwise
|
||||
# be retried, slowly, on every export.
|
||||
return True, None
|
||||
rms = data["rms"]
|
||||
if len(rms) != n_columns:
|
||||
return False, None
|
||||
return True, waveform.Analysis(
|
||||
columns=waveform.Columns(
|
||||
rms=rms, brightness=data["brightness"],
|
||||
duration=float(data["duration"]),
|
||||
),
|
||||
frames=waveform.Frames(bands=data["bands"], duration=float(data["duration"])),
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return False, None
|
||||
except Exception as ex: # noqa: BLE001 — a damaged entry is a miss
|
||||
log.debug("ignoring unreadable analysis cache entry %s: %s", path, ex)
|
||||
return False, None
|
||||
|
||||
@staticmethod
|
||||
def _store(path: Path, value: waveform.Analysis | None) -> None:
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = path.with_name(path.name + ".partial")
|
||||
with partial.open("wb") as out:
|
||||
if value is None:
|
||||
np.savez_compressed(out, undecodable=np.array(True))
|
||||
else:
|
||||
# Full precision: a cached export must write the same bytes
|
||||
# a fresh one would.
|
||||
np.savez_compressed(
|
||||
out, undecodable=np.array(False),
|
||||
rms=value.columns.rms, brightness=value.columns.brightness,
|
||||
bands=value.frames.bands, duration=np.array(value.columns.duration),
|
||||
)
|
||||
os.replace(partial, path)
|
||||
except OSError as ex:
|
||||
log.warning("could not cache the analysis of %s: %s", path.name, ex)
|
||||
@@ -29,11 +29,14 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, Protocol, runtime_checkable
|
||||
from typing import TYPE_CHECKING, Callable, Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .model import Track, TrackCues
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .analysis_cache import AnalysisCache
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExportTrack:
|
||||
@@ -50,6 +53,20 @@ class ExportTrack:
|
||||
#: copied file, because a library's art is not always embedded in the audio
|
||||
#: (rekordbox keeps its own copy under `share/`).
|
||||
art: tuple[bytes, str] | None = None
|
||||
#: The source file's identity (`analysis_cache.fingerprint`), and the cache
|
||||
#: on the destination drive — both set by the runner, so a re-export does
|
||||
#: not decode an unchanged track again. Either may be None.
|
||||
fingerprint: str | None = None
|
||||
analysis_cache: "AnalysisCache | None" = field(default=None, repr=False)
|
||||
|
||||
def waveform(self, *, lead: float = 0.0):
|
||||
"""`waveform.analyse()` of the copied audio — the call every exporter that
|
||||
measures audio makes, so all of them share the cache."""
|
||||
from . import waveform
|
||||
|
||||
if self.analysis_cache is not None and self.fingerprint:
|
||||
return self.analysis_cache.analyse(self.destination, self.fingerprint, lead=lead)
|
||||
return waveform.analyse(self.destination, lead=lead)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
@@ -80,10 +97,12 @@ class ExportPayload:
|
||||
#: The export's name, used for the folder its playlists are nested under.
|
||||
name: str = "Export"
|
||||
#: Called by a writer before each slow step (e.g. decoding a track for its
|
||||
#: waveform) with a message for the status bar. RAISES when the user has
|
||||
#: waveform) with a message for the status bar, and — for a per-track loop —
|
||||
#: `step` of `of`, which drives the progress bar. RAISES when the user has
|
||||
#: cancelled — so a writer that analyses audio stays cancellable. The runner
|
||||
#: sets it; a writer may call it freely and never needs to check for None.
|
||||
checkpoint: Callable[[str], None] = field(default=lambda message: None, repr=False)
|
||||
checkpoint: Callable[..., None] = field(
|
||||
default=lambda message, step=None, of=None: None, repr=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -31,6 +31,12 @@ import numpy as np
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: BUMP THIS whenever `analyse()`'s output changes (a constant below, the
|
||||
#: decoder, the maths). Exports cache these measurements on the stick
|
||||
#: (`analysis_cache`), keyed by this number — so an unbumped change keeps
|
||||
#: serving the old measurement to every re-export.
|
||||
ANALYSIS_VERSION = 1
|
||||
|
||||
#: Plenty for a waveform, and half the decode cost of 44.1 kHz. The high band
|
||||
#: runs to 11 kHz, which is where most of its visible energy is anyway.
|
||||
SR = 22050
|
||||
|
||||
+266
-41
@@ -19,13 +19,36 @@ in-flight one behind, which is a bug the import feature had and was fixed there.
|
||||
|
||||
## Konduktor only deletes what Konduktor wrote
|
||||
|
||||
A re-export clears its destination first, which combined with "the user picks
|
||||
A re-export clears its previous export first, which combined with "the user picks
|
||||
the destination" is a folder-deletion hazard: point an export at `~/Documents`
|
||||
and a confirm dialog is the only thing between a click and real loss. So every
|
||||
export writes a **manifest** of what it put there, and a destination that is
|
||||
non-empty without one is REFUSED rather than confirmed. Clearing then removes
|
||||
exactly the manifest's files — anything the user added themselves survives.
|
||||
|
||||
## A re-export copies only what changed
|
||||
|
||||
The manifest also records, per copied file, the SOURCE's path, size and mtime
|
||||
and the COPY's size and mtime as read back. A re-export keeps a previous copy
|
||||
when all four still match — the same quick check rsync makes, and no
|
||||
checksums: hashing the copy means reading it back over USB, which costs about
|
||||
what copying it again does. A tag edit rewrites the source file, so its mtime
|
||||
moves and the file is copied again. Copies are matched by SOURCE path, not by
|
||||
where they sit, because adding a track from another folder moves the shared
|
||||
root below and with it every destination path; a kept copy whose path changed
|
||||
is renamed, not copied. No record, or an unreadable one, means copy everything.
|
||||
|
||||
The ORDER keeps the safety properties: the previous export's libraries and
|
||||
every file not kept go first, then the kept copies are moved, then what
|
||||
changed is copied (under a temporary name, renamed into place), and the
|
||||
libraries are written last. A cancel removes what THIS run wrote and rewrites
|
||||
the manifest around what it kept — deleting the manifest with kept files still
|
||||
there would leave a folder the next export refuses as not ours.
|
||||
|
||||
Decoding every track for its Pioneer waveforms is the other slow part, so the
|
||||
measurements are cached on the drive too (`core/analysis_cache.py`), keyed by
|
||||
the same source facts.
|
||||
|
||||
## Several targets, one copy of the audio
|
||||
|
||||
An export can target several platforms at once. The audio is copied ONCE and
|
||||
@@ -49,12 +72,14 @@ top of one.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from . import exports
|
||||
from .core import registry
|
||||
from .core.analysis_cache import CACHE_DIR, AnalysisCache, fingerprint
|
||||
from .core.export import ExportPayload, ExportPlaylist, ExportTrack, for_platform
|
||||
from .core.pathmap import common_dir_prefix
|
||||
from .core.places import is_drive_root, is_os_housekeeping
|
||||
@@ -66,6 +91,10 @@ log = logging.getLogger(__name__)
|
||||
MANIFEST_NAME = ".konduktor-export.json"
|
||||
#: Every exported audio file lives under this folder, never at the root.
|
||||
AUDIO_DIR = "Contents"
|
||||
#: Where kept copies wait while being moved, and the suffix a copy is written
|
||||
#: under until it is complete. Both are listed in the manifest while in use.
|
||||
MOVING_DIR = ".konduktor-moving"
|
||||
PARTIAL_SUFFIX = ".konduktor-partial"
|
||||
|
||||
#: Why an export cannot run. The UI words these; they are facts, not sentences.
|
||||
BLOCKED_OCCUPIED = "destination_not_empty"
|
||||
@@ -81,6 +110,12 @@ class PlannedTrack:
|
||||
destination: Path | None
|
||||
size: int = 0
|
||||
missing: bool = False
|
||||
#: The source's mtime when planned, recorded in the manifest with `size`.
|
||||
mtime_ns: int = 0
|
||||
#: Where the previous export's copy of this very file sits, when it can be
|
||||
#: kept instead of copied again — possibly a different path from
|
||||
#: `destination`, in which case it is moved. None means copy.
|
||||
reuse: Path | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -103,12 +138,19 @@ class ExportPlan:
|
||||
|
||||
@property
|
||||
def total_bytes(self) -> int:
|
||||
return sum(t.size for t in self.exportable)
|
||||
"""What will actually be COPIED — a kept file costs neither time nor
|
||||
space, since the previous export's other files are removed first."""
|
||||
return sum(t.size for t in self.exportable if t.reuse is None)
|
||||
|
||||
@property
|
||||
def unchanged(self) -> int:
|
||||
return sum(1 for t in self.exportable if t.reuse is not None)
|
||||
|
||||
def as_dict(self, free: int | None = None) -> dict:
|
||||
return {
|
||||
"tracks": len(self.tracks),
|
||||
"exportable": len(self.exportable),
|
||||
"unchanged": self.unchanged,
|
||||
"missing": [t.title for t in self.tracks if t.missing],
|
||||
"playlists": [p.name for p in self.playlists],
|
||||
"total_bytes": self.total_bytes,
|
||||
@@ -161,8 +203,9 @@ def destination_blocked(destination: Path) -> str | None:
|
||||
return BLOCKED_OCCUPIED
|
||||
|
||||
|
||||
def _clear(destination: Path) -> None:
|
||||
"""Remove the previous export, and only it.
|
||||
def _clear(destination: Path, keep: set[Path] = frozenset()) -> None:
|
||||
"""Remove the previous export, and only it — except the audio in `keep`,
|
||||
which this export reuses.
|
||||
|
||||
Driven by the manifest rather than by wiping the folder: the manifest lists
|
||||
everything the last export wrote, so anything the user put there themselves
|
||||
@@ -171,8 +214,11 @@ def _clear(destination: Path) -> None:
|
||||
"""
|
||||
data = _read_manifest(destination)
|
||||
for name in data.get("files", []):
|
||||
path = destination / name
|
||||
if path in keep:
|
||||
continue
|
||||
try:
|
||||
(destination / name).unlink()
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
# `library` is the single-target manifest an older export left behind.
|
||||
@@ -208,7 +254,8 @@ def _read_manifest(destination: Path) -> dict:
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_manifest(destination: Path, *, libraries: list[str], files: list[str], name: str) -> None:
|
||||
def _write_manifest(destination: Path, *, libraries: list[str], files: list[str],
|
||||
audio: dict[str, dict], name: str) -> None:
|
||||
from . import paths
|
||||
|
||||
paths.write_json(
|
||||
@@ -220,10 +267,64 @@ def _write_manifest(destination: Path, *, libraries: list[str], files: list[str]
|
||||
"written": time.time(),
|
||||
"libraries": libraries,
|
||||
"files": files,
|
||||
"audio": audio,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _record(planned: PlannedTrack, copy: Path) -> dict:
|
||||
"""What the manifest remembers about one copied file.
|
||||
|
||||
The SOURCE's size and mtime as planned — if it changed during the copy, the
|
||||
next export sees a mismatch and copies again, which is the safe direction —
|
||||
and the COPY's as read back now, never assumed equal to the source's: a
|
||||
FAT32 stick keeps mtimes to 2 s, so `copystat` does not round-trip there.
|
||||
"""
|
||||
st = copy.stat()
|
||||
return {
|
||||
"source": str(planned.source_path),
|
||||
"size": planned.size,
|
||||
"mtime_ns": planned.mtime_ns,
|
||||
"copy_size": st.st_size,
|
||||
"copy_mtime_ns": st.st_mtime_ns,
|
||||
}
|
||||
|
||||
|
||||
def _previous_copies(destination: Path) -> dict[str, tuple[Path, dict]]:
|
||||
"""The last export's copies, by SOURCE path — not by where they sit, since
|
||||
adding a track from another folder moves the shared root and with it every
|
||||
destination path. No record (none yet, an older manifest, an unreadable
|
||||
one) means nothing is reused: never guess from the files on disk."""
|
||||
if not is_ours(destination):
|
||||
return {}
|
||||
audio = _read_manifest(destination).get("audio")
|
||||
out: dict[str, tuple[Path, dict]] = {}
|
||||
if isinstance(audio, dict):
|
||||
for rel, record in audio.items():
|
||||
if isinstance(record, dict) and isinstance(record.get("source"), str):
|
||||
out[record["source"]] = (destination / rel, record)
|
||||
return out
|
||||
|
||||
|
||||
def _reusable(planned: PlannedTrack, previous: dict[str, tuple[Path, dict]]) -> Path | None:
|
||||
"""The previous copy of this file, if neither it nor its source changed."""
|
||||
found = previous.get(str(planned.source_path))
|
||||
if found is None:
|
||||
return None
|
||||
copy, record = found
|
||||
if (record.get("size"), record.get("mtime_ns")) != (planned.size, planned.mtime_ns):
|
||||
return None
|
||||
try:
|
||||
st = copy.stat()
|
||||
except OSError:
|
||||
return None
|
||||
# The copy is checked too: a file edited or replaced ON the stick is not
|
||||
# the one this export would have written.
|
||||
if (st.st_size, st.st_mtime_ns) != (record.get("copy_size"), record.get("copy_mtime_ns")):
|
||||
return None
|
||||
return copy
|
||||
|
||||
|
||||
# ---- planning ----------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -251,25 +352,36 @@ def plan(adapter, export_set) -> ExportPlan:
|
||||
present = [str(p) for p in sources.values() if p]
|
||||
root = common_dir_prefix(present) if present else ""
|
||||
|
||||
previous = _previous_copies(destination)
|
||||
claimed: set[Path] = set()
|
||||
for track in tracks:
|
||||
source = sources[track.id]
|
||||
exists = False
|
||||
size = 0
|
||||
size = mtime_ns = 0
|
||||
try:
|
||||
exists = bool(source and source.is_file())
|
||||
size = source.stat().st_size if exists else 0
|
||||
if exists:
|
||||
st = source.stat()
|
||||
size, mtime_ns = st.st_size, st.st_mtime_ns
|
||||
except OSError:
|
||||
exists = False
|
||||
built.tracks.append(
|
||||
PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / AUDIO_DIR / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
missing=not exists,
|
||||
)
|
||||
planned = PlannedTrack(
|
||||
track_id=track.id,
|
||||
title=track.title or (source.name if source else track.id),
|
||||
source_path=source,
|
||||
destination=(destination / AUDIO_DIR / _relative(source, root)) if exists else None,
|
||||
size=size,
|
||||
mtime_ns=mtime_ns,
|
||||
missing=not exists,
|
||||
)
|
||||
if exists:
|
||||
reuse = _reusable(planned, previous)
|
||||
# One kept copy can serve one planned file: two entries sharing a
|
||||
# source would otherwise both try to move it.
|
||||
if reuse is not None and reuse not in claimed:
|
||||
planned.reuse = reuse
|
||||
claimed.add(reuse)
|
||||
built.tracks.append(planned)
|
||||
|
||||
names = {p.id: p for p in resolved.playlists}
|
||||
folders = _folder_paths(adapter)
|
||||
@@ -324,10 +436,13 @@ def _folder_paths(adapter) -> dict[str, list[str]]:
|
||||
|
||||
|
||||
def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
"""Copy the audio once, then write every target's library over it.
|
||||
"""Copy what changed, then write every target's library over the audio.
|
||||
|
||||
Rolls back EVERYTHING on cancel or on any failure — including the libraries
|
||||
of targets that had already been written when a later one failed.
|
||||
Rolls back EVERYTHING this run wrote on cancel or on any failure —
|
||||
including the libraries of targets that had already been written when a
|
||||
later one failed. What it KEPT from the previous export stays, and the
|
||||
manifest is rewritten to say so: deleting the manifest with kept files
|
||||
still there would leave a folder the next export refuses as not ours.
|
||||
"""
|
||||
exporters = [for_platform(t) for t in export_set.targets]
|
||||
if not exporters or None in exporters:
|
||||
@@ -337,13 +452,16 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
|
||||
destination = Path(built.destination)
|
||||
items = built.exportable
|
||||
total = sum(t.size for t in items)
|
||||
handle.progress(done=0, total=total, message="Preparing…")
|
||||
handle.progress(done=0, total=built.total_bytes, unit="bytes", message="Preparing…")
|
||||
cache = AnalysisCache(destination / CACHE_DIR)
|
||||
|
||||
# Registered BEFORE each write, so a cancel mid-file removes the partial one
|
||||
# too. Cleaning up only completed copies leaves debris the retry then
|
||||
# suffixes around — a bug the import feature had.
|
||||
created: list[Path] = []
|
||||
# The previous export's copies this one keeps, by where they are NOW — so a
|
||||
# rollback during the moves still records each at its real location.
|
||||
kept: dict[Path, dict] = {}
|
||||
# What was on disk before the libraries were written. An exporter that
|
||||
# raises midway has written files it never got to REPORT (a OneLibrary
|
||||
# drive's analysis files, say), so rollback also removes anything that
|
||||
@@ -355,34 +473,74 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if is_ours(destination):
|
||||
handle.progress(message="Replacing the previous export…")
|
||||
_clear(destination)
|
||||
old = _read_manifest(destination).get("audio") or {}
|
||||
for planned in items:
|
||||
if planned.reuse is not None:
|
||||
record = old.get(_rel(planned.reuse, destination))
|
||||
if record is None:
|
||||
# The manifest changed since the plan: copy after all.
|
||||
planned.reuse = None
|
||||
else:
|
||||
kept[planned.reuse] = record
|
||||
_clear(destination, keep=set(kept))
|
||||
else:
|
||||
for planned in items:
|
||||
planned.reuse = None
|
||||
reused = [t for t in items if t.reuse is not None]
|
||||
handle.progress(total=built.total_bytes)
|
||||
# Written before anything moves or is copied, listing every path this
|
||||
# run may leave behind, so even a crash (not a cancel — nothing gets to
|
||||
# clean up after a crash) leaves a folder the next export can clear.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted({_rel(p, destination) for p in (*kept, *(t.destination for t in items))}
|
||||
| {_rel(_partial(t.destination), destination) for t in items}
|
||||
| {_rel(_staging(destination, i), destination) for i in range(len(reused))}),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
if reused:
|
||||
handle.progress(message=f"Keeping {len(reused)} unchanged track{'' if len(reused) == 1 else 's'}…")
|
||||
_move_kept(destination, reused, kept)
|
||||
|
||||
payload_tracks: list[ExportTrack] = []
|
||||
for planned in items:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
created.append(target)
|
||||
if planned.reuse is None:
|
||||
handle.progress(message=f"Copying {planned.title}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Copied beside the target and renamed into place, so a cancel
|
||||
# can never leave a half-written file under a real track's name.
|
||||
partial = _partial(target)
|
||||
created += [partial, target]
|
||||
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
def advance(n: int) -> None:
|
||||
nonlocal done
|
||||
done += n
|
||||
handle.progress(done=done)
|
||||
|
||||
copy_file(planned.source_path, target, handle, advance)
|
||||
copy_file(planned.source_path, partial, handle, advance)
|
||||
os.replace(partial, target)
|
||||
payload_tracks.append(
|
||||
ExportTrack(
|
||||
track=adapter.track(planned.track_id),
|
||||
destination=target,
|
||||
cues=adapter.track_cues(planned.track_id),
|
||||
art=_cover(adapter, planned.track_id),
|
||||
fingerprint=_fingerprint(planned),
|
||||
analysis_cache=cache,
|
||||
)
|
||||
)
|
||||
|
||||
def checkpoint(message: str) -> None:
|
||||
def checkpoint(message: str, step: int | None = None, of: int | None = None) -> None:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=message)
|
||||
if step is not None and of:
|
||||
# The bar follows the library being written, in tracks: after
|
||||
# the copy, the slow part is decoding — and a re-export may
|
||||
# have copied nothing at all.
|
||||
handle.progress(done=step - 1, total=of, unit="tracks", message=message)
|
||||
else:
|
||||
handle.progress(message=message)
|
||||
|
||||
payload = ExportPayload(
|
||||
name=export_set.name,
|
||||
@@ -394,7 +552,9 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
libraries: list[tuple[str, Path]] = []
|
||||
for exporter in exporters:
|
||||
handle.raise_if_cancelled()
|
||||
handle.progress(message=f"Writing the {_display_name(exporter.platform)} library…")
|
||||
# Indeterminate until the writer reports its tracks.
|
||||
handle.progress(done=0, total=0, unit="tracks",
|
||||
message=f"Writing the {_display_name(exporter.platform)} library…")
|
||||
written = exporter.write(payload, destination)
|
||||
# Everything the exporter reported, not just the library: a target
|
||||
# can write a database PLUS a per-track analysis file, and anything
|
||||
@@ -403,21 +563,29 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
libraries.append((exporter.platform, written.library))
|
||||
|
||||
library_paths = {path for _, path in libraries}
|
||||
audio_paths = {Path(t.destination) for t in items}
|
||||
_write_manifest(
|
||||
destination,
|
||||
libraries=[str(p.relative_to(destination)) for _, p in libraries],
|
||||
libraries=[_rel(p, destination) for _, p in libraries],
|
||||
files=sorted(
|
||||
{str(p.relative_to(destination)) for p in created if p not in library_paths}
|
||||
{_rel(p, destination) for p in (*created, *audio_paths)
|
||||
if p not in library_paths and p.exists()}
|
||||
),
|
||||
audio={_rel(Path(t.destination), destination): _record(t, Path(t.destination))
|
||||
for t in items},
|
||||
name=export_set.name,
|
||||
)
|
||||
# Only what this export's tracks need; an unticked Pioneer target
|
||||
# keeps its entries, since they are keyed by source, not by target.
|
||||
cache.prune({_fingerprint(t) for t in items})
|
||||
return {
|
||||
"tracks": len(payload_tracks),
|
||||
"unchanged": len(reused),
|
||||
"playlists": len(built.playlists),
|
||||
"skipped": len(built.tracks) - len(items),
|
||||
"destination": str(destination),
|
||||
"libraries": [
|
||||
{"platform": platform, "library": str(path.relative_to(destination))}
|
||||
{"platform": platform, "library": _rel(path, destination)}
|
||||
for platform, path in libraries
|
||||
],
|
||||
}
|
||||
@@ -427,18 +595,75 @@ def run(adapter, export_set, built: ExportPlan, handle: JobHandle) -> dict:
|
||||
# different things is worse than either behaviour on its own.
|
||||
leftovers = (_files(destination) - before) if before is not None else set()
|
||||
for path in (*created, *leftovers):
|
||||
if CACHE_DIR in path.relative_to(destination).parts:
|
||||
continue # measurements of the SOURCE: still true, and ours
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
if kept:
|
||||
# The previous export's files this one kept are still here, so the
|
||||
# folder must still say it is ours — with no library, which is what
|
||||
# marks an export unfinished.
|
||||
_write_manifest(
|
||||
destination, libraries=[], name=export_set.name,
|
||||
files=sorted(_rel(p, destination) for p in kept),
|
||||
audio={_rel(p, destination): r for p, r in kept.items()},
|
||||
)
|
||||
else:
|
||||
# Nothing kept: the folder goes back to having no export in it at
|
||||
# all, cache included, as a first export's cancel always has.
|
||||
cache.clear()
|
||||
try:
|
||||
manifest_path(destination).unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_prune_empty(destination)
|
||||
raise
|
||||
|
||||
|
||||
def _move_kept(destination: Path, reused: list[PlannedTrack], kept: dict[Path, dict]) -> None:
|
||||
"""Rename each kept copy to where this export puts it — instant on one drive.
|
||||
|
||||
In two steps, through a staging folder, because one kept file's new path
|
||||
can be another's old one (the shared root moved), and a direct rename
|
||||
would overwrite a copy that has not moved out of the way yet. `kept` is
|
||||
updated after every rename, so a failure part-way still knows where each
|
||||
file really is.
|
||||
"""
|
||||
moving = [t for t in reused if t.reuse != Path(t.destination)]
|
||||
staged: list[tuple[Path, PlannedTrack]] = []
|
||||
for i, planned in enumerate(moving):
|
||||
stage = _staging(destination, i)
|
||||
stage.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(planned.reuse, stage)
|
||||
kept[stage] = kept.pop(planned.reuse)
|
||||
staged.append((stage, planned))
|
||||
for stage, planned in staged:
|
||||
target = Path(planned.destination)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(stage, target)
|
||||
kept[target] = kept.pop(stage)
|
||||
if staged:
|
||||
_prune_empty(destination)
|
||||
|
||||
|
||||
def _staging(destination: Path, i: int) -> Path:
|
||||
return destination / MOVING_DIR / str(i)
|
||||
|
||||
|
||||
def _partial(target: Path) -> Path:
|
||||
return target.with_name(target.name + PARTIAL_SUFFIX)
|
||||
|
||||
|
||||
def _rel(path: Path, destination: Path) -> str:
|
||||
return str(Path(path).relative_to(destination))
|
||||
|
||||
|
||||
def _fingerprint(planned: PlannedTrack) -> str:
|
||||
return fingerprint(planned.source_path, planned.size, planned.mtime_ns)
|
||||
|
||||
|
||||
def _cover(adapter, track_id: str):
|
||||
"""The source's cover art, or None. A missing or unreadable cover costs the
|
||||
artwork on the stick, never the export."""
|
||||
|
||||
@@ -49,6 +49,9 @@ class Job:
|
||||
# the UI is expected to show an indeterminate bar until it is positive.
|
||||
total: int = 0
|
||||
done: int = 0
|
||||
#: What `done`/`total` count — "bytes" while copying, "tracks" while a
|
||||
#: library is written — so the UI can word them. Empty = unspecified.
|
||||
unit: str = ""
|
||||
message: str = ""
|
||||
result: Any = None
|
||||
error: str | None = None
|
||||
@@ -67,6 +70,7 @@ class Job:
|
||||
"state": self.state,
|
||||
"total": self.total,
|
||||
"done": self.done,
|
||||
"unit": self.unit,
|
||||
"message": self.message,
|
||||
"result": self.result,
|
||||
"error": self.error,
|
||||
@@ -87,7 +91,9 @@ class JobHandle:
|
||||
self._job = job
|
||||
|
||||
def progress(self, done: int | None = None, total: int | None = None,
|
||||
message: str | None = None) -> None:
|
||||
message: str | None = None, unit: str | None = None) -> None:
|
||||
if unit is not None:
|
||||
self._job.unit = unit
|
||||
if done is not None:
|
||||
self._job.done = done
|
||||
if total is not None:
|
||||
|
||||
@@ -201,7 +201,7 @@ both_payload = ExportPayload(name="GIG", tracks=moved, playlists=payload.playlis
|
||||
ol_written = core_export.for_platform("onelibrary").write(both_payload, both)
|
||||
stamp = {p: p.stat().st_mtime_ns for p in ol_written.extra if p.suffix in (".DAT", ".EXT", ".2EX")}
|
||||
calls = []
|
||||
both_payload.checkpoint = calls.append
|
||||
both_payload.checkpoint = lambda m, **_progress: calls.append(m)
|
||||
dev_written = dev.write(both_payload, both)
|
||||
dat_files = sorted(both.rglob("*.DAT"))
|
||||
check("still one .DAT per track", len(dat_files) == 3, len(dat_files))
|
||||
|
||||
@@ -433,6 +433,233 @@ check("nothing at all is left behind — no audio, no Traktor library, no stray
|
||||
exports.update(LIB, eset.id, destination=str(dest), targets=["traktor"])
|
||||
eset = exports.get(LIB, eset.id)
|
||||
|
||||
print("== a re-export copies only what changed ==")
|
||||
from konduktor.core import analysis_cache, waveform # noqa: E402
|
||||
|
||||
calls = {"copy": 0, "analyse": 0}
|
||||
_real_copy, _real_analyse = exporter.copy_file, waveform.analyse
|
||||
|
||||
|
||||
def _counting_copy(*a, **kw):
|
||||
calls["copy"] += 1
|
||||
return _real_copy(*a, **kw)
|
||||
|
||||
|
||||
def _counting_analyse(*a, **kw):
|
||||
calls["analyse"] += 1
|
||||
return _real_analyse(*a, **kw)
|
||||
|
||||
|
||||
exporter.copy_file, waveform.analyse = _counting_copy, _counting_analyse
|
||||
|
||||
|
||||
def run_set(s, plan, handle=None):
|
||||
if handle is not None:
|
||||
return exporter.run(ad, s, plan, handle)
|
||||
job = JOBS.submit("export", lambda h: exporter.run(ad, s, plan, h))
|
||||
while not job.finished:
|
||||
time.sleep(0.02)
|
||||
return job
|
||||
|
||||
|
||||
def reset():
|
||||
calls["copy"] = calls["analyse"] = 0
|
||||
|
||||
|
||||
def inodes(root):
|
||||
return {str(p.relative_to(root)): p.stat().st_ino
|
||||
for p in (root / exporter.AUDIO_DIR).rglob("*") if p.is_file()}
|
||||
|
||||
|
||||
inc = Path(tempfile.mkdtemp()) / "INC"
|
||||
iset = exports.create(LIB, name="INC", targets=["traktor", "onelibrary"], destination=str(inc))
|
||||
exports.add(LIB, iset.id, track_ids=[t.id for t in ad.tracks[:4]])
|
||||
iset = exports.get(LIB, iset.id)
|
||||
|
||||
first = exporter.plan(ad, iset)
|
||||
check("a first export reuses nothing", first.unchanged == 0 and first.total_bytes == 4 * 300_000,
|
||||
(first.unchanged, first.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, first)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("every file was copied and measured once", calls == {"copy": 4, "analyse": 4}, calls)
|
||||
manifest = json.loads((inc / exporter.MANIFEST_NAME).read_text())
|
||||
check("the manifest records each copy's source",
|
||||
sorted(r["source"] for r in manifest["audio"].values())
|
||||
== sorted(str(ad.audio_path(t.id)) for t in ad.tracks[:4]))
|
||||
check("no temporary files are left", not any(
|
||||
p.name.endswith(exporter.PARTIAL_SUFFIX) for p in inc.rglob("*")))
|
||||
before_ino = inodes(inc)
|
||||
|
||||
again = exporter.plan(ad, iset)
|
||||
check("nothing changed, so nothing is to be copied",
|
||||
again.unchanged == 4 and again.total_bytes == 0 and again.as_dict()["unchanged"] == 4,
|
||||
(again.unchanged, again.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, again)
|
||||
check("the re-export finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("no audio was copied and no track decoded", calls == {"copy": 0, "analyse": 0}, calls)
|
||||
check("the kept files are the very same files", inodes(inc) == before_ino)
|
||||
check("both libraries were still rewritten and re-open with every track",
|
||||
len(TraktorDriver().open(inc / "collection.nml").tracks) == 4
|
||||
and len(OneLibraryDriver().open(inc).tracks) == 4)
|
||||
|
||||
|
||||
|
||||
class _Recorder:
|
||||
"""A handle that keeps every progress report."""
|
||||
|
||||
def __init__(self):
|
||||
self.reports = []
|
||||
|
||||
def progress(self, **kw):
|
||||
self.reports.append(kw)
|
||||
|
||||
cancelled = False
|
||||
|
||||
def raise_if_cancelled(self):
|
||||
pass
|
||||
|
||||
|
||||
rec = _Recorder()
|
||||
run_set(iset, exporter.plan(ad, iset), rec)
|
||||
track_steps = [(r["done"], r["total"]) for r in rec.reports
|
||||
if r.get("unit") == "tracks" and r.get("total")]
|
||||
# The bug: the bar counted only bytes, so a re-export that copied nothing sat
|
||||
# on an indeterminate bar through the whole (slow) library write.
|
||||
check("with nothing to copy, the bar still moves — per track, while writing",
|
||||
track_steps and track_steps[-1] == (3, 4) and len(track_steps) >= 4, track_steps)
|
||||
|
||||
print("== an edited source is copied again, and only it ==")
|
||||
edited = ad.audio_path(ad.tracks[0].id)
|
||||
edited.write_bytes(b"\1" * 310_000) # what a tag write does: new bytes, new mtime
|
||||
plan3 = exporter.plan(ad, iset)
|
||||
check("one track is to be copied", plan3.unchanged == 3 and plan3.total_bytes == 310_000,
|
||||
(plan3.unchanged, plan3.total_bytes))
|
||||
reset()
|
||||
j = run_set(iset, plan3)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("one file copied, one decoded", calls == {"copy": 1, "analyse": 1}, calls)
|
||||
edited_copy = next(Path(t.destination) for t in plan3.exportable if t.source_path == edited)
|
||||
check("the copy on the stick is the new version", edited_copy.read_bytes() == b"\1" * 310_000)
|
||||
|
||||
print("== a copy changed ON the stick is not trusted ==")
|
||||
tampered = next(Path(t.destination) for t in plan3.exportable if t.source_path != edited)
|
||||
with tampered.open("ab") as f:
|
||||
f.write(b"junk")
|
||||
plan4 = exporter.plan(ad, iset)
|
||||
check("it alone is copied again",
|
||||
[Path(t.destination) for t in plan4.exportable if t.reuse is None] == [tampered],
|
||||
[str(t.destination) for t in plan4.exportable if t.reuse is None])
|
||||
j = run_set(iset, plan4)
|
||||
check("and the original is restored", j.state == "done" and tampered.stat().st_size == 300_000)
|
||||
|
||||
print("== a moved shared root renames kept copies instead of copying them ==")
|
||||
house = [t for t in ad.tracks[:4] if "/House/" in str(ad.audio_path(t.id))]
|
||||
techno = [t for t in ad.tracks[:4] if t not in house]
|
||||
moved = Path(tempfile.mkdtemp()) / "MOVED"
|
||||
mset = exports.create(LIB, name="MOVED", targets=["traktor"], destination=str(moved))
|
||||
exports.add(LIB, mset.id, track_ids=[t.id for t in house])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
run_set(mset, exporter.plan(ad, mset))
|
||||
old_paths = inodes(moved)
|
||||
check("with only House tracks, the root is House itself",
|
||||
all(not r.startswith("Contents/House/") for r in old_paths), sorted(old_paths))
|
||||
exports.add(LIB, mset.id, track_ids=[techno[0].id])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
mplan = exporter.plan(ad, mset)
|
||||
check("adding a Techno track moves every path, yet the House copies are reused",
|
||||
mplan.unchanged == len(house)
|
||||
and mplan.total_bytes == ad.audio_path(techno[0].id).stat().st_size,
|
||||
(mplan.unchanged, mplan.total_bytes))
|
||||
reset()
|
||||
j = run_set(mset, mplan)
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("only the new track was copied", calls["copy"] == 1, calls)
|
||||
new_paths = inodes(moved)
|
||||
check("the kept copies now sit under House/, as the same files",
|
||||
sorted(v for r, v in new_paths.items() if r.startswith("Contents/House/"))
|
||||
== sorted(old_paths.values()), sorted(new_paths))
|
||||
check("and nothing is left at the old paths or in staging",
|
||||
not any((moved / r).exists() for r in old_paths)
|
||||
and not (moved / exporter.MOVING_DIR).exists())
|
||||
check("the collection points at the moved copies",
|
||||
all(TraktorDriver().open(moved / "collection.nml").audio_path(t.id).is_file()
|
||||
for t in TraktorDriver().open(moved / "collection.nml").tracks))
|
||||
|
||||
print("== a removed track's copy is removed ==")
|
||||
exports.remove(LIB, mset.id, track_ids=[techno[0].id])
|
||||
mset = exports.get(LIB, mset.id)
|
||||
j = run_set(mset, exporter.plan(ad, mset))
|
||||
check("it finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("the Techno copy is gone", not any("Techno" in str(p) for p in moved.rglob("*")),
|
||||
sorted(str(p.relative_to(moved)) for p in moved.rglob("*")))
|
||||
|
||||
print("== cancelling a re-export keeps what it kept, and the folder stays ours ==")
|
||||
edited.write_bytes(b"\2" * 320_000)
|
||||
cplan = exporter.plan(ad, iset)
|
||||
kept_before = {Path(t.destination) for t in cplan.exportable if t.reuse is not None}
|
||||
try:
|
||||
run_set(iset, cplan, _CancelAfter(2))
|
||||
check("it stops", False, "it did not raise")
|
||||
except JobCancelled:
|
||||
check("it stops", True)
|
||||
check("no library was left", not (inc / "collection.nml").exists()
|
||||
and not (inc / "PIONEER" / "rekordbox" / "exportLibrary.db").exists())
|
||||
check("the kept copies are still there", all(p.is_file() for p in kept_before))
|
||||
check("the half-copied file is not", not (edited_copy.exists() or any(
|
||||
p.name.endswith(exporter.PARTIAL_SUFFIX) for p in inc.rglob("*"))))
|
||||
retry = exporter.plan(ad, iset)
|
||||
check("the folder is still ours, not refused", retry.blocked is None, str(retry.blocked))
|
||||
check("and the retry still reuses the kept copies", retry.unchanged == len(kept_before),
|
||||
(retry.unchanged, len(kept_before)))
|
||||
reset()
|
||||
j = run_set(iset, retry)
|
||||
check("the retry finishes", j.state == "done", f"{j.state}: {j.error}")
|
||||
check("decoding only the changed track — the rest came from the cache", calls["analyse"] == 1, calls)
|
||||
|
||||
print("== the analysis cache ==")
|
||||
cache_dir = inc / analysis_cache.CACHE_DIR
|
||||
check("it lives on the drive", cache_dir.is_dir() and len(list(cache_dir.iterdir())) == 4,
|
||||
sorted(p.name for p in cache_dir.iterdir()) if cache_dir.exists() else "")
|
||||
check("and is not in the manifest, so a re-export never clears it",
|
||||
not any(f.startswith(analysis_cache.CACHE_DIR)
|
||||
for f in json.loads((inc / exporter.MANIFEST_NAME).read_text())["files"]))
|
||||
exports.remove(LIB, iset.id, track_ids=[ad.tracks[3].id])
|
||||
iset = exports.get(LIB, iset.id)
|
||||
run_set(iset, exporter.plan(ad, iset))
|
||||
check("a removed track's entry is pruned", len(list(cache_dir.iterdir())) == 3)
|
||||
# Round-trips a real measurement, not just the undecodable marker the silent
|
||||
# fixture files produce.
|
||||
import numpy as np # noqa: E402
|
||||
import soundfile as sf # noqa: E402
|
||||
|
||||
tone_dir = Path(tempfile.mkdtemp())
|
||||
tone = tone_dir / "tone.wav"
|
||||
sf.write(tone, 0.5 * np.sin(np.linspace(0, 2000 * np.pi, 44100 * 3)), 44100)
|
||||
c = analysis_cache.AnalysisCache(tone_dir / "cache")
|
||||
key = analysis_cache.fingerprint(tone, tone.stat().st_size, tone.stat().st_mtime_ns)
|
||||
fresh_a = c.analyse(tone, key, lead=0.025)
|
||||
reset()
|
||||
cached_a = c.analyse(tone, key, lead=0.025)
|
||||
check("a hit does not decode", calls["analyse"] == 0, calls)
|
||||
check("and returns the same measurement, exactly",
|
||||
fresh_a is not None and cached_a is not None
|
||||
and np.array_equal(fresh_a.columns.rms, cached_a.columns.rms)
|
||||
and np.array_equal(fresh_a.columns.brightness, cached_a.columns.brightness)
|
||||
and np.array_equal(fresh_a.frames.bands, cached_a.frames.bands)
|
||||
and fresh_a.duration == cached_a.duration)
|
||||
c.analyse(tone, key, lead=0.0)
|
||||
check("a different lead is a separate entry", calls["analyse"] == 1, calls)
|
||||
next((tone_dir / "cache").glob("*-25000-400.npz")).write_bytes(b"garbage")
|
||||
reset()
|
||||
check("a damaged entry is a miss, not a failure",
|
||||
c.analyse(tone, key, lead=0.025) is not None and calls["analyse"] == 1)
|
||||
|
||||
exporter.copy_file, waveform.analyse = _real_copy, _real_analyse
|
||||
exports.delete(LIB, iset.id)
|
||||
exports.delete(LIB, mset.id)
|
||||
|
||||
print("== targets are validated and migrated ==")
|
||||
check("a set saved with the old single `target` loads as a list",
|
||||
exports._targets({"target": "onelibrary"}) == ["onelibrary"])
|
||||
|
||||
@@ -309,7 +309,7 @@ seen: list[str] = []
|
||||
wf_written = core_export.for_platform("onelibrary").write(
|
||||
ExportPayload(name="WF", tracks=[ExportTrack(track=dead_t, destination=dead, cues=grid),
|
||||
ExportTrack(track=live_t, destination=live, cues=grid)],
|
||||
checkpoint=seen.append),
|
||||
checkpoint=lambda m, **_progress: seen.append(m)),
|
||||
wf_root,
|
||||
)
|
||||
dats = [p for p in wf_written.extra if p.suffix == ".DAT"]
|
||||
@@ -371,7 +371,7 @@ class _Stop(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _cancel_on_second(message: str, calls=[]): # noqa: B006 — deliberate counter
|
||||
def _cancel_on_second(message: str, calls=[], **_progress): # noqa: B006 — deliberate counter
|
||||
calls.append(message)
|
||||
if len(calls) == 2:
|
||||
raise _Stop()
|
||||
|
||||
Reference in new issue
Block a user