loopcutter 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loopcutter/manifest.py ADDED
@@ -0,0 +1,245 @@
1
+ """Manifest parsing.
2
+
3
+ The manifest is the source of truth. Keep it in git. Never edit outputs by
4
+ hand - change the manifest and re-cut, so every loop on disk is reproducible
5
+ from a single text file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ from .timing import bar_start_seconds, parse_position
15
+
16
+ REQUIRED = {"source", "label", "bars", "bpm"}
17
+
18
+ # A row must resolve a start position by exactly one of these routes.
19
+ START_BY_TIME = {"start"}
20
+ START_BY_BAR = {"downbeat", "start_bar"}
21
+
22
+
23
+ @dataclass
24
+ class LoopSpec:
25
+ source: Path
26
+ label: str
27
+ bars: float
28
+ bpm: float
29
+ start_seconds: float
30
+ beats_per_bar: int = 4
31
+ stem: str | None = None
32
+ artist: str | None = None
33
+ track: str | None = None
34
+ key: str | None = None
35
+ notes: str = ""
36
+ row_number: int = 0
37
+ extra: dict[str, str] = field(default_factory=dict)
38
+ track_id: str | None = None
39
+ snap: str = ""
40
+ kind: str = "loop"
41
+ end_seconds: float | None = None
42
+ xfade_ms: float | None = None # None: use the command line's --xfade-ms
43
+
44
+ @property
45
+ def slug(self) -> str:
46
+ parts = [p for p in (self.artist, self.track) if p]
47
+ stub = " - ".join(parts) if parts else self.source.stem
48
+ stem = f"[{self.stem}]" if self.stem else ""
49
+ if self.kind == "oneshot":
50
+ return f"{stub} [{self.label}][oneshot]{stem}"
51
+ bars = int(self.bars) if float(self.bars).is_integer() else self.bars
52
+ return f"{stub} [{self.label}][{bars}bar]{stem}"
53
+
54
+
55
+ class ManifestError(ValueError):
56
+ """Raised with the offending row number so failures are addressable."""
57
+
58
+
59
+ def _require(row: dict[str, str], row_number: int) -> None:
60
+ missing = REQUIRED - {k for k, v in row.items() if v not in (None, "")}
61
+ if missing:
62
+ raise ManifestError(
63
+ f"row {row_number}: missing required column(s) {sorted(missing)}"
64
+ )
65
+
66
+
67
+ def _resolve_start(row: dict[str, str], bpm: float, beats_per_bar: int,
68
+ row_number: int) -> float:
69
+ has_time = bool(row.get("start"))
70
+ has_bar = bool(row.get("downbeat")) and bool(row.get("start_bar"))
71
+
72
+ if has_time and has_bar:
73
+ raise ManifestError(
74
+ f"row {row_number}: give either 'start' or 'downbeat'+'start_bar', not both"
75
+ )
76
+ if has_time:
77
+ return parse_position(row["start"])
78
+ if has_bar:
79
+ return bar_start_seconds(
80
+ downbeat=parse_position(row["downbeat"]),
81
+ bar_index=int(row["start_bar"]),
82
+ bpm=bpm,
83
+ beats_per_bar=beats_per_bar,
84
+ )
85
+ raise ManifestError(
86
+ f"row {row_number}: no start position - give 'start', or 'downbeat' and 'start_bar'"
87
+ )
88
+
89
+
90
+ def _parse_variations(row: dict[str, str], row_number: int) -> list[float]:
91
+ """Bar lengths this row should produce.
92
+
93
+ A `variations` cell like "4,2,1,0.5" expands one cue point into four loops
94
+ that all share a start, so they can live in a Launchpad column and be
95
+ launched in Legato mode for beat-division rolls. Each is a real file cut to
96
+ an exact sample count, so they stay locked to the grid in a way a mapped
97
+ loop-length control does not.
98
+
99
+ `bars` is always included, and duplicates are dropped, so "4" with bars=4
100
+ yields one loop rather than two identical ones.
101
+ """
102
+ base = float(row["bars"])
103
+ raw = (row.get("variations") or "").strip()
104
+ if not raw:
105
+ return [base]
106
+
107
+ lengths = [base]
108
+ for token in raw.replace(";", ",").split(","):
109
+ token = token.strip()
110
+ if not token:
111
+ continue
112
+ try:
113
+ value = float(token)
114
+ except ValueError as exc:
115
+ raise ManifestError(
116
+ f"row {row_number}: variations must be bar numbers, got {token!r}"
117
+ ) from exc
118
+ if value <= 0:
119
+ raise ManifestError(
120
+ f"row {row_number}: variation bar counts must be positive, got {value}"
121
+ )
122
+ lengths.append(value)
123
+
124
+ seen: list[float] = []
125
+ for value in lengths:
126
+ if value not in seen:
127
+ seen.append(value)
128
+ return sorted(seen, reverse=True)
129
+
130
+
131
+ def _xfade(row: dict[str, str], row_number: int) -> float | None:
132
+ raw = row.get("xfade_ms")
133
+ if raw in (None, ""):
134
+ return None
135
+ try:
136
+ value = float(raw)
137
+ except ValueError:
138
+ raise ManifestError(f"row {row_number}: xfade_ms must be a number, got {raw!r}") from None
139
+ if value < 0:
140
+ raise ManifestError(f"row {row_number}: xfade_ms can't be negative, got {value:g}")
141
+ return value
142
+
143
+
144
+ def load_manifest(path: str | Path, audio_root: str | Path | None = None) -> list[LoopSpec]:
145
+ """Load a manifest.
146
+
147
+ Relative `source` paths resolve against `audio_root`, which defaults to the
148
+ current working directory - not the manifest's own directory - so that
149
+ manifests/session.csv can refer to audio/track.aiff the way you would type
150
+ it from the repo root.
151
+ """
152
+ path = Path(path)
153
+ root = Path(audio_root) if audio_root else Path.cwd()
154
+
155
+ specs: list[LoopSpec] = []
156
+ with path.open(newline="", encoding="utf-8") as handle:
157
+ reader = csv.DictReader(handle)
158
+ if reader.fieldnames is None:
159
+ raise ManifestError(f"{path} has no header row")
160
+
161
+ known = REQUIRED | START_BY_TIME | START_BY_BAR | {
162
+ "beats_per_bar", "stem", "artist", "track", "key", "notes",
163
+ "variations", "track_id", "snap", "kind", "end", "xfade_ms",
164
+ }
165
+
166
+ for offset, row in enumerate(reader, start=2):
167
+ row = {k: (v.strip() if isinstance(v, str) else v)
168
+ for k, v in row.items() if k}
169
+ if not any(row.values()):
170
+ continue
171
+ if row.get("source", "").startswith("#"):
172
+ continue
173
+
174
+ kind = (row.get("kind") or "loop").lower()
175
+ if kind not in {"loop", "oneshot"}:
176
+ raise ManifestError(f"row {offset}: kind must be loop or oneshot, got {kind!r}")
177
+ if kind == "oneshot":
178
+ missing = [c for c in ("source", "label", "start", "end") if not row.get(c)]
179
+ if missing:
180
+ raise ManifestError(f"row {offset}: a oneshot needs {missing}")
181
+ start, end = parse_position(row["start"]), parse_position(row["end"])
182
+ if start < 0:
183
+ raise ManifestError(f"row {offset}: start can't be before the file")
184
+ if end <= start:
185
+ raise ManifestError(f"row {offset}: end must be after start")
186
+ source = Path(row["source"])
187
+ specs.append(LoopSpec(
188
+ source=source if source.is_absolute() else root / source, label=row["label"],
189
+ bars=0.0, bpm=float(row.get("bpm") or 0), start_seconds=start,
190
+ stem=(row.get("stem") or "").lower() or None, artist=row.get("artist") or None,
191
+ track=row.get("track") or None, key=row.get("key") or None,
192
+ notes=row.get("notes") or "", row_number=offset, kind="oneshot",
193
+ end_seconds=end, track_id=row.get("track_id") or None))
194
+ continue
195
+
196
+ snap = (row.get("snap") or "").lower()
197
+ if snap in {"beat", "bar"}:
198
+ raise ManifestError(f"row {offset}: start not snapped yet - run "
199
+ f"`loopcutter resolve {path}`")
200
+ if snap:
201
+ raise ManifestError(f"row {offset}: snap must be beat, bar or empty, got {snap!r}")
202
+ if row.get("track_id") and not (row.get("bpm") and row.get("source")):
203
+ raise ManifestError(f"row {offset}: source or bpm missing - run "
204
+ f"`loopcutter resolve {path}` to fill them from tracks.csv")
205
+ _require(row, offset)
206
+ bpm = float(row["bpm"])
207
+ beats_per_bar = int(row.get("beats_per_bar") or 4)
208
+ lengths = _parse_variations(row, offset)
209
+
210
+ source = Path(row["source"])
211
+ if not source.is_absolute():
212
+ source = root / source
213
+
214
+ start = _resolve_start(row, bpm, beats_per_bar, offset)
215
+ for bars in lengths:
216
+ specs.append(
217
+ LoopSpec(
218
+ source=source,
219
+ label=row["label"],
220
+ bars=bars,
221
+ bpm=bpm,
222
+ start_seconds=start,
223
+ beats_per_bar=beats_per_bar,
224
+ stem=(row.get("stem") or "").lower() or None,
225
+ artist=row.get("artist") or None,
226
+ track=row.get("track") or None,
227
+ key=row.get("key") or None,
228
+ notes=row.get("notes") or "",
229
+ row_number=offset,
230
+ extra={k: v for k, v in row.items() if k not in known and v},
231
+ track_id=row.get("track_id") or None,
232
+ snap=snap,
233
+ xfade_ms=_xfade(row, offset),
234
+ )
235
+ )
236
+
237
+ if not specs:
238
+ raise ManifestError(f"{path} contains no usable rows")
239
+
240
+ labels = [s.slug for s in specs]
241
+ duplicates = {name for name in labels if labels.count(name) > 1}
242
+ if duplicates:
243
+ raise ManifestError(f"duplicate output names would collide: {sorted(duplicates)}")
244
+
245
+ return specs
loopcutter/markers.py ADDED
@@ -0,0 +1,175 @@
1
+ """Markers placed by hand in DJ software, read back as (file, start, end, name).
2
+
3
+ Times are in each app's own timeline. snap.py removes the app's measured offset
4
+ and resolves them against the cutter's grid; never cut at an app's timestamp.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import warnings
11
+ from pathlib import Path
12
+ from typing import Callable, Iterable
13
+
14
+ import mutagen
15
+ import numpy as np
16
+ from mutagen.aiff import AIFF
17
+ from mutagen.mp3 import MP3
18
+
19
+ from .model import Marker, MarkerNote
20
+
21
+ STEMS = {"full", "drums", "bass", "other", "vocals", "guitar", "piano", "instrumental"}
22
+ SERATO_SUFFIXES = {".mp3", ".aif", ".aiff"} # serato-tools' own opener misses ".aif"; we open it ourselves
23
+ _ROLLS = re.compile(r"^\d+(?:\.\d+)?(?:,\d+(?:\.\d+)?)*$")
24
+
25
+
26
+ def parse_note(text: str | None) -> MarkerNote:
27
+ """'A1 bass 2,1' -> label A1, stem bass, roll lengths (2, 1).
28
+
29
+ The first word that isn't a stem is the label, unless it contains a comma.
30
+ A later number, or list of numbers, gives the rolls. So '16.2 bass' keeps
31
+ 16.2 as its label, and 'bass 2,1' has rolls but no label.
32
+ """
33
+ label = stem = None
34
+ rolls: tuple[float, ...] = ()
35
+ for token in (text or "").split():
36
+ if token.lower() in STEMS and stem is None:
37
+ stem = token.lower()
38
+ elif label is None and "," not in token:
39
+ label = token
40
+ elif _ROLLS.match(token) and not rolls:
41
+ rolls = tuple(float(v) for v in token.split(","))
42
+ return MarkerNote(label, stem, rolls)
43
+
44
+
45
+ def _open_tagfile(path: Path):
46
+ """serato-tools' SeratoTrack only opens path *strings* ending ".mp3"/".aiff";
47
+ ".aif" falls through and leaves it with no tag file at all. Open it ourselves.
48
+ """
49
+ return MP3(str(path)) if path.suffix.lower() == ".mp3" else AIFF(str(path))
50
+
51
+
52
+ def _serato_entries(path: Path):
53
+ from serato_tools.track_cues_v2 import TrackCuesV2
54
+
55
+ return TrackCuesV2(_open_tagfile(path)).entries
56
+
57
+
58
+ def from_serato(paths: Iterable, reader: Callable | None = None) -> list[Marker]:
59
+ reader = reader or _serato_entries
60
+ markers = []
61
+ for path in (Path(p) for p in paths):
62
+ if path.suffix.lower() not in SERATO_SUFFIXES:
63
+ continue
64
+ try:
65
+ entries = reader(path)
66
+ except (mutagen.MutagenError, ValueError) as exc:
67
+ warnings.warn(f"{path.name}: can't read Serato cues ({exc})")
68
+ continue
69
+ for entry in entries:
70
+ if hasattr(entry, "startposition"):
71
+ markers.append(Marker(path, entry.startposition / 1000,
72
+ entry.endposition / 1000, entry.name or "", "serato"))
73
+ elif hasattr(entry, "position"):
74
+ markers.append(Marker(path, entry.position / 1000, None, entry.name or "", "serato"))
75
+ return markers
76
+
77
+
78
+ def _one(result):
79
+ return result.one_or_none() if hasattr(result, "one_or_none") else result
80
+
81
+
82
+ def open_rekordbox():
83
+ from pyrekordbox import Rekordbox6Database
84
+
85
+ return Rekordbox6Database()
86
+
87
+
88
+ def from_rekordbox_db(playlist: str, db=None) -> list[Marker]:
89
+ """Memory cues and memory loops of every track in a playlist. Hot cues are left alone."""
90
+ db = db or open_rekordbox()
91
+ found = _one(db.get_playlist(Name=playlist))
92
+ if found is None:
93
+ raise ValueError(f"rekordbox has no playlist called {playlist!r}")
94
+ markers = []
95
+ for content in db.get_playlist_contents(found):
96
+ path = Path(content.FolderPath)
97
+ for cue in db.get_cue(ContentID=content.ID):
98
+ if cue.Kind != 0:
99
+ continue
100
+ out = cue.OutMsec if cue.OutMsec is not None and cue.OutMsec > cue.InMsec else None
101
+ markers.append(Marker(path, cue.InMsec / 1000, None if out is None else out / 1000,
102
+ cue.Comment or "", "rekordbox"))
103
+ return sorted(markers, key=lambda m: (str(m.path), m.start))
104
+
105
+
106
+ def _xml_track_path(track) -> Path:
107
+ """pyrekordbox's own Track.GETTERS already runs decode_path() on `Location`
108
+ (rbxml.py), so track["Location"] never carries the "file:" prefix by the
109
+ time we see it here - it's always pre-decoded. That decode strips exactly
110
+ one leading "/" (its URL_PREFIX is "file://localhost/"), which round-trips
111
+ fine for the Windows example in pyrekordbox's own docstring (localhost/ +
112
+ C:/...) but not for a real Mac/Linux export, whose path already starts
113
+ with "/": "file://localhost" + "/Users/..." decodes to "Users/..." with
114
+ the leading slash silently eaten. Put it back unless this looks like a
115
+ Windows drive path.
116
+ """
117
+ location = str(track["Location"])
118
+ if location and location[0] != "/" and not re.match(r"^[A-Za-z]:", location):
119
+ location = "/" + location
120
+ return Path(location)
121
+
122
+
123
+ def from_rekordbox_xml(xml_path, playlist: str | None = None) -> list[Marker]:
124
+ """Memory cues and loops (Num -1) from a rekordbox XML export."""
125
+ from pyrekordbox.rbxml import RekordboxXml, decode_path
126
+
127
+ xml = RekordboxXml(str(xml_path))
128
+ if playlist:
129
+ node = xml.get_playlist(*playlist.split("/"))
130
+ if node.key_type == "TrackID":
131
+ tracks = [xml.get_track(TrackID=key) for key in node.get_tracks()]
132
+ else:
133
+ tracks = [xml.get_track(Location=decode_path(key)) for key in node.get_tracks()]
134
+ else:
135
+ tracks = xml.get_tracks()
136
+ markers = []
137
+ for track in tracks:
138
+ path = _xml_track_path(track)
139
+ for mark in track.marks:
140
+ if int(mark.get("Num", -1)) != -1:
141
+ continue
142
+ end = mark.get("End")
143
+ markers.append(Marker(path, float(mark["Start"]),
144
+ float(end) if end not in (None, "") else None,
145
+ mark.get("Name") or "", "rekordbox-xml"))
146
+ return markers
147
+
148
+
149
+ def serato_beats(path) -> np.ndarray:
150
+ """Every beat of Serato's stored grid, in seconds of Serato's own timeline."""
151
+ path = Path(path)
152
+ if path.suffix.lower() not in SERATO_SUFFIXES:
153
+ return np.array([])
154
+ from serato_tools.track_beatgrid import TrackBeatgrid
155
+
156
+ try:
157
+ beats = TrackBeatgrid(_open_tagfile(path)).get_beats()
158
+ except (mutagen.MutagenError, ValueError):
159
+ return np.array([])
160
+ return np.array([b.position_s for b in beats], dtype=float)
161
+
162
+
163
+ def rekordbox_beats(db, audio_path) -> np.ndarray:
164
+ content = _one(db.get_content(FolderPath=str(audio_path)))
165
+ if content is None:
166
+ return np.array([])
167
+ anlz = db.read_anlz_file(content, "DAT")
168
+ if anlz is None:
169
+ return np.array([])
170
+ try:
171
+ _beats, _bpms, times = anlz.get("beat_grid")
172
+ except IndexError:
173
+ # pyrekordbox raises this when the analysis file has no PQTZ (beat grid) tag.
174
+ return np.array([])
175
+ return np.asarray(times, dtype=float)
loopcutter/model.py ADDED
@@ -0,0 +1,114 @@
1
+ """Shared data types. Every module codes against these; they change only in Wave 0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, replace
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Grid:
12
+ """A constant-tempo beat grid. Beat n sits at phase + n * period seconds."""
13
+
14
+ period: float
15
+ phase: float
16
+ bar_phase: int = 0
17
+ beats_per_bar: int = 4
18
+ inlier_ratio: float = 1.0
19
+ bar_agreement: float = 1.0
20
+ phase_agreement: float = 1.0
21
+ phase_offset: float = 0.0
22
+
23
+ @property
24
+ def bpm(self) -> float:
25
+ return 60.0 / self.period
26
+
27
+ def beat_time(self, n):
28
+ return self.phase + n * self.period
29
+
30
+ def beat_index(self, t: float) -> int:
31
+ return int(round((t - self.phase) / self.period))
32
+
33
+ def nearest_beat(self, t: float) -> float:
34
+ return self.beat_time(self.beat_index(t))
35
+
36
+ def is_bar_start(self, n: int) -> bool:
37
+ return (n - self.bar_phase) % self.beats_per_bar == 0
38
+
39
+ def nearest_bar(self, t: float) -> float:
40
+ n = self.beat_index(t)
41
+ below = n - ((n - self.bar_phase) % self.beats_per_bar)
42
+ best = min((below, below + self.beats_per_bar), key=lambda m: abs(self.beat_time(m) - t))
43
+ return self.beat_time(best)
44
+
45
+ def shifted(self, seconds: float) -> "Grid":
46
+ """The same grid moved later by `seconds`. Beat n becomes beat n + wraps."""
47
+ raw = self.phase + seconds
48
+ wraps = math.floor(raw / self.period)
49
+ return replace(self, phase=raw - wraps * self.period,
50
+ bar_phase=(self.bar_phase + wraps) % self.beats_per_bar,
51
+ phase_offset=self.phase_offset + seconds)
52
+
53
+
54
+ @dataclass
55
+ class TrackRecord:
56
+ """One row of tracks.csv. scan writes the analysis; the override fields are yours."""
57
+
58
+ track_id: str
59
+ source: str
60
+ master: str
61
+ sample_rate: int
62
+ duration: float
63
+ bpm: float
64
+ phase: float
65
+ bar_phase: int
66
+ bpm_fitted: float = 0.0
67
+ beats_per_bar: int = 4
68
+ inlier_ratio: float = 0.0
69
+ bar_agreement: float = 0.0
70
+ phase_agreement: float = 0.0
71
+ phase_offset_ms: float = 0.0
72
+ key: str = ""
73
+ key_source: str = ""
74
+ key_alt: str = ""
75
+ app: str = ""
76
+ app_bpm: float | None = None
77
+ app_offset_ms: float | None = None
78
+ flags: str = ""
79
+ override_bpm: float | None = None
80
+ override_phase_ms: float | None = None
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Marker:
85
+ """A cue or loop placed in DJ software; times are in that app's own timeline."""
86
+
87
+ path: Path
88
+ start: float
89
+ end: float | None
90
+ name: str
91
+ app: str
92
+
93
+ @property
94
+ def kind(self) -> str:
95
+ return "loop" if self.end is not None else "cue"
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class MarkerNote:
100
+ label: str | None
101
+ stem: str | None
102
+ variations: tuple[float, ...]
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class SnapResult:
107
+ original: float
108
+ snapped: float
109
+ beat_index: int
110
+ on_bar: bool
111
+
112
+ @property
113
+ def shift_ms(self) -> float:
114
+ return (self.snapped - self.original) * 1000
loopcutter/naming.py ADDED
@@ -0,0 +1,95 @@
1
+ """Output filename convention.
2
+
3
+ The bracketed label, tempo, bar count, key and stem make a loop library
4
+ sortable and searchable by eye in any file browser. DAWs take tempo from the
5
+ audio, not the name. Keep the pattern stable: renaming files breaks any set
6
+ or sampler project that points at them.
7
+
8
+ Artist - Track [16.2][128][4bar][bass].aiff
9
+ Artist - Track [16.2][128][4bar][bass][LC-1a2b3c4d].aiff (with a provenance code)
10
+
11
+ The code, last so the library still sorts by artist, is a short hash of what the loop is: track, label, length,
12
+ stem and kind. Re-marking a start keeps it; a different loop gets a different one. It lets a loop be traced back
13
+ to its record from a set, a collected project or a sampler that only kept the file name.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import re
20
+ import unicodedata
21
+ from pathlib import Path
22
+
23
+ from .manifest import LoopSpec
24
+
25
+ _ILLEGAL = re.compile(r'[/\\:*?"<>|]')
26
+
27
+
28
+ def sanitise(text: str) -> str:
29
+ cleaned = _ILLEGAL.sub("-", text)
30
+ return re.sub(r"\s+", " ", cleaned).strip(" .")
31
+
32
+
33
+ def loop_code(spec: LoopSpec) -> str:
34
+ """LC- and 8 hex of a SHA-1 over the loop's identity (not its start, so re-marking keeps the code)."""
35
+ bars = f"{float(spec.bars):g}"
36
+ identity = "|".join([spec.track_id or spec.source.stem, spec.label, getattr(spec, "kind", "loop"), bars,
37
+ spec.stem or "full"])
38
+ identity = unicodedata.normalize("NFC", identity) # macOS file names come back NFD
39
+ return "LC-" + hashlib.sha1(identity.encode()).hexdigest()[:8]
40
+
41
+
42
+ CODE_SUFFIX = re.compile(r"\[LC-[0-9a-f]{8}\]$")
43
+
44
+
45
+ def same_name(a: str, b: str) -> bool:
46
+ """File names compared the way APFS does: NFC and NFD spellings are the same file."""
47
+ return unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b)
48
+
49
+
50
+ def copies_of(out_dir: Path, spec: LoopSpec, fmt: str) -> list[Path]:
51
+ """Files in out_dir that are this loop: its plain name, or its name with any provenance code."""
52
+ plain = unicodedata.normalize("NFC", build_filename(spec, fmt))
53
+ stem = plain[: -len(fmt) - 1]
54
+ out_dir = Path(out_dir)
55
+ if not out_dir.is_dir():
56
+ return []
57
+ found = []
58
+ for p in out_dir.iterdir():
59
+ name = unicodedata.normalize("NFC", p.name)
60
+ if name == plain or (name.endswith("." + fmt) and CODE_SUFFIX.sub("", name[: -len(fmt) - 1]) == stem
61
+ and name != plain):
62
+ found.append(p)
63
+ return sorted(found)
64
+
65
+
66
+ def build_filename(spec: LoopSpec, fmt: str = "aiff", code: str | None = None) -> str:
67
+ stub_parts = [p for p in (spec.artist, spec.track) if p]
68
+ stub = " - ".join(stub_parts) if stub_parts else spec.source.stem
69
+
70
+ if getattr(spec, "kind", "loop") == "oneshot":
71
+ tags = [spec.label, "oneshot"]
72
+ else:
73
+ bpm = int(spec.bpm) if float(spec.bpm).is_integer() else round(spec.bpm, 2)
74
+ bars = int(spec.bars) if float(spec.bars).is_integer() else spec.bars
75
+ tags = [spec.label, str(bpm), f"{bars}bar"]
76
+ if spec.key:
77
+ tags.append(spec.key)
78
+ if spec.stem:
79
+ tags.append(spec.stem)
80
+ if code:
81
+ tags.append(code)
82
+
83
+ suffix = "".join(f"[{sanitise(str(t))}]" for t in tags)
84
+ return f"{sanitise(stub)} {suffix}.{fmt}"
85
+
86
+
87
+ def bpm_band(bpm: float, width: int = 5) -> str:
88
+ low = int(bpm // width) * width
89
+ return f"{low}-{low + width - 1}"
90
+
91
+
92
+ def library_subdir(spec) -> Path:
93
+ """<stem>/<bpm band>, e.g. bass/125-129; loops without a stem under full/, one-shots in oneshots/."""
94
+ stem = Path(sanitise(spec.stem or "full"))
95
+ return stem / "oneshots" if getattr(spec, "kind", "loop") == "oneshot" else stem / bpm_band(spec.bpm)