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/cut.py ADDED
@@ -0,0 +1,197 @@
1
+ """Loop extraction.
2
+
3
+ Two things stop loops clicking at the seam:
4
+
5
+ 1. Snapping the start to a nearby zero crossing, so the waveform begins near
6
+ silence rather than mid-swing.
7
+ 2. A sub-millisecond fade at each edge to catch whatever the snap missed.
8
+
9
+ The snap moves the start, so the end moves with it by exactly the same amount.
10
+ The length in samples is never recomputed - that would reintroduce drift.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import soundfile as sf
20
+
21
+ from .manifest import LoopSpec
22
+ from .timing import resolve_window
23
+
24
+ DEFAULT_SNAP_MS = 2.0
25
+ DEFAULT_FADE_MS = 0.5
26
+
27
+
28
+ @dataclass
29
+ class CutResult:
30
+ spec: LoopSpec
31
+ output: Path
32
+ sample_rate: int
33
+ length_samples: int
34
+ snap_offset_samples: int
35
+ peak: float
36
+ start_sample: int
37
+ source_peak: float
38
+ trim_db: float = 0.0
39
+ timing_source: Path | None = None # the full mix, when this loop was cut from a stem
40
+
41
+
42
+ def _find_zero_crossing(audio: np.ndarray, centre: int, radius: int,
43
+ direction: str = "both") -> int:
44
+ """Nearest sample to `centre` where the summed waveform crosses zero.
45
+
46
+ `direction="backward"` only looks earlier. Returns `centre` unchanged if
47
+ nothing is found inside the radius.
48
+ """
49
+ if radius <= 0:
50
+ return centre
51
+ mono = audio.mean(axis=1) if audio.ndim > 1 else audio
52
+ lo = max(1, centre - radius)
53
+ hi = min(len(mono) - 1, centre + radius)
54
+ if lo >= hi:
55
+ return centre
56
+ for offset in range(0, hi - lo + 1):
57
+ candidates = (centre - offset,) if direction == "backward" else (centre + offset, centre - offset)
58
+ for candidate in candidates:
59
+ if lo <= candidate <= hi:
60
+ if mono[candidate - 1] <= 0.0 <= mono[candidate]:
61
+ return candidate
62
+ if mono[candidate - 1] >= 0.0 >= mono[candidate]:
63
+ return candidate
64
+ return centre
65
+
66
+
67
+ def _apply_edge_fades(audio: np.ndarray, fade_samples: int) -> np.ndarray:
68
+ if fade_samples <= 0 or len(audio) < fade_samples * 2:
69
+ return audio
70
+
71
+ out = audio.copy()
72
+ ramp = np.linspace(0.0, 1.0, fade_samples, dtype=out.dtype)
73
+ if out.ndim > 1:
74
+ ramp = ramp[:, None]
75
+ out[:fade_samples] *= ramp
76
+ out[-fade_samples:] *= ramp[::-1]
77
+ return out
78
+
79
+
80
+ def cut_loop(
81
+ spec: LoopSpec,
82
+ out_dir: str | Path,
83
+ fmt: str = "aiff",
84
+ subtype: str = "PCM_24",
85
+ snap_ms: float = DEFAULT_SNAP_MS,
86
+ fade_ms: float = DEFAULT_FADE_MS,
87
+ trim_db: float = 0.0,
88
+ xfade_ms: float = 0.0,
89
+ filename: str | None = None,
90
+ ) -> CutResult:
91
+ out_dir = Path(out_dir)
92
+ out_dir.mkdir(parents=True, exist_ok=True)
93
+
94
+ if not spec.source.exists():
95
+ raise FileNotFoundError(f"row {spec.row_number}: source not found: {spec.source}")
96
+
97
+ info = sf.info(str(spec.source))
98
+ window = resolve_window(
99
+ spec.start_seconds, spec.bars, spec.bpm, info.samplerate, spec.beats_per_bar
100
+ )
101
+
102
+ snap_radius = int(round(snap_ms / 1000.0 * info.samplerate))
103
+ xfade = int(round(xfade_ms / 1000.0 * info.samplerate))
104
+ if xfade < 0 or xfade >= window.length_samples:
105
+ raise ValueError(f"row {spec.row_number}: a {xfade_ms:g} ms crossfade doesn't fit "
106
+ f"inside a {window.length_samples}-sample loop")
107
+ read_start = max(0, window.start_sample - snap_radius - xfade)
108
+ read_stop = min(info.frames, window.end_sample + snap_radius + 1)
109
+
110
+ if read_start >= info.frames:
111
+ raise ValueError(
112
+ f"row {spec.row_number}: start {spec.start_seconds:.3f}s is past the end of "
113
+ f"{spec.source.name} ({info.duration:.3f}s)"
114
+ )
115
+
116
+ block, _ = sf.read(
117
+ str(spec.source), start=read_start, stop=read_stop, dtype="float32", always_2d=True
118
+ )
119
+
120
+ centre = window.start_sample - read_start
121
+ snapped = _find_zero_crossing(block, centre, snap_radius, direction="backward")
122
+ offset = snapped - centre
123
+
124
+ if snapped + window.length_samples > len(block):
125
+ # Not enough audio after the snap; fall back to the unsnapped start.
126
+ snapped, offset = centre, 0
127
+
128
+ if snapped + window.length_samples > len(block):
129
+ raise ValueError(
130
+ f"row {spec.row_number}: {spec.source.name} is too short for a "
131
+ f"{spec.bars}-bar loop at {spec.bpm} BPM starting at {spec.start_seconds:.3f}s"
132
+ )
133
+
134
+ audio = block[snapped : snapped + window.length_samples]
135
+ if xfade and snapped < xfade:
136
+ raise ValueError(f"row {spec.row_number}: a {xfade_ms:g} ms crossfade needs that much audio "
137
+ "before the start, and the file begins too soon")
138
+ pre = block[snapped - xfade : snapped] if xfade else None
139
+ source_peak = max(float(np.max(np.abs(audio))) if len(audio) else 0.0,
140
+ float(np.max(np.abs(pre))) if pre is not None else 0.0)
141
+ if pre is not None:
142
+ # The tail fades into the audio just before the start, so the wrap plays
143
+ # exactly what the source played there: no dip, no step.
144
+ ramp = np.linspace(0.0, 1.0, xfade, dtype=audio.dtype)[:, None]
145
+ audio = audio.copy()
146
+ audio[-xfade:] = audio[-xfade:] * (1.0 - ramp) + pre * ramp
147
+ else:
148
+ audio = _apply_edge_fades(audio, int(round(fade_ms / 1000.0 * info.samplerate)))
149
+ if trim_db:
150
+ audio = np.clip(audio * 10.0 ** (trim_db / 20.0), -1.0, 1.0)
151
+
152
+ destination = out_dir / (filename or f"{spec.slug}.{fmt}")
153
+ sf.write(str(destination), audio, info.samplerate, format=fmt.upper(), subtype=subtype)
154
+
155
+ return CutResult(
156
+ spec=spec, output=destination, sample_rate=info.samplerate,
157
+ length_samples=len(audio), snap_offset_samples=offset,
158
+ peak=float(np.max(np.abs(audio))) if len(audio) else 0.0,
159
+ start_sample=read_start + snapped, source_peak=source_peak, trim_db=trim_db,
160
+ )
161
+
162
+
163
+ def cut_oneshot(spec: LoopSpec, out_dir, fmt: str = "aiff", subtype: str = "PCM_24",
164
+ snap_ms: float = DEFAULT_SNAP_MS, fade_out_ms: float = 10.0,
165
+ filename: str | None = None, trim_db: float = 0.0) -> CutResult:
166
+ """A single hit or phrase from start to end: snapped backward to a zero crossing,
167
+ a sub-millisecond fade in, a short fade out."""
168
+ out_dir = Path(out_dir)
169
+ out_dir.mkdir(parents=True, exist_ok=True)
170
+ if not spec.source.exists():
171
+ raise FileNotFoundError(f"row {spec.row_number}: source not found: {spec.source}")
172
+ info = sf.info(str(spec.source))
173
+ start = int(round(spec.start_seconds * info.samplerate))
174
+ end = int(round(spec.end_seconds * info.samplerate))
175
+ if end > info.frames:
176
+ raise ValueError(f"row {spec.row_number}: the one-shot ends at {spec.end_seconds:.3f}s, "
177
+ f"past the end of the file ({info.frames / info.samplerate:.3f}s)")
178
+ radius = int(round(snap_ms / 1000.0 * info.samplerate))
179
+ if end - start < 2 * int(round(DEFAULT_FADE_MS / 1000.0 * info.samplerate)):
180
+ raise ValueError(f"row {spec.row_number}: the one-shot is too short to fade")
181
+ read_start = max(0, start - radius)
182
+ block, _ = sf.read(str(spec.source), start=read_start, stop=end, dtype="float32", always_2d=True)
183
+ snapped = _find_zero_crossing(block, start - read_start, radius, direction="backward")
184
+ audio = block[snapped:].copy()
185
+ source_peak = float(np.max(np.abs(audio))) if len(audio) else 0.0
186
+ fade_in = int(round(DEFAULT_FADE_MS / 1000.0 * info.samplerate))
187
+ fade_out = min(len(audio) // 2, int(round(fade_out_ms / 1000.0 * info.samplerate)))
188
+ audio[:fade_in] *= np.linspace(0.0, 1.0, fade_in, dtype=audio.dtype)[:, None]
189
+ audio[len(audio) - fade_out:] *= np.linspace(1.0, 0.0, fade_out, dtype=audio.dtype)[:, None]
190
+ if trim_db:
191
+ audio = np.clip(audio * 10.0 ** (trim_db / 20.0), -1.0, 1.0)
192
+ destination = out_dir / (filename or f"{spec.slug}.{fmt}")
193
+ sf.write(str(destination), audio, info.samplerate, format=fmt.upper(), subtype=subtype)
194
+ return CutResult(spec=spec, output=destination, sample_rate=info.samplerate,
195
+ length_samples=len(audio), snap_offset_samples=snapped - (start - read_start),
196
+ peak=float(np.max(np.abs(audio))) if len(audio) else 0.0,
197
+ start_sample=read_start + snapped, source_peak=source_peak, trim_db=trim_db)
loopcutter/grid.py ADDED
@@ -0,0 +1,205 @@
1
+ """Beat grids.
2
+
3
+ Fit a constant-tempo grid to detected beats, find which beat is the one, then
4
+ move the grid onto the audio's own onsets, 2 ms early, because a late start
5
+ clips the attack on every wrap.
6
+
7
+ beat_this reports beats on a 50 fps frame grid, so single intervals are
8
+ quantised to 20 ms. The first estimate of the period therefore comes from a
9
+ line fitted through the longest unbroken run of beats, not from the median
10
+ interval. That run can still hide a stretch the detector followed in triplets
11
+ or swing, so the estimate is then refined against every beat at once: the
12
+ period, within 5%, at which the beats line up best.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import replace
18
+ from functools import lru_cache
19
+ from pathlib import Path
20
+ from typing import Callable
21
+
22
+ import numpy as np
23
+
24
+ from .model import Grid
25
+ from .onsets import attacks_near, detect_onsets
26
+
27
+ INLIER_S = 0.030
28
+ MIN_BEATS = 16
29
+ PHASE_WINDOW_S = 0.040
30
+ MIN_PHASE_AGREEMENT = 0.35 # 10 of 11 calibration tracks agreed at 0.38-0.76
31
+ ONSET_LEAD_S = 0.002
32
+ LOCAL_SPAN_BEATS = 64
33
+ PERIOD_SEARCH = 0.05
34
+
35
+ Detector = Callable[[np.ndarray, int], tuple[np.ndarray, np.ndarray]]
36
+
37
+
38
+ class GridError(ValueError):
39
+ """Raised when the detected beats can't support a grid."""
40
+
41
+
42
+ def nominal_bpm(bpm: float) -> float:
43
+ """Machine-made tracks sit on whole BPMs; keep anything else to 0.01."""
44
+ whole = round(bpm)
45
+ return float(whole) if abs(bpm - whole) < 0.01 else round(bpm, 2)
46
+
47
+
48
+ def _initial_period(beats: np.ndarray) -> float:
49
+ intervals = np.diff(beats)
50
+ rough = float(np.median(intervals))
51
+ breaks = np.nonzero((intervals > 1.5 * rough) | (intervals < 0.5 * rough))[0]
52
+ edges = np.concatenate([[0], breaks + 1, [beats.size]])
53
+ start, stop = max(zip(edges[:-1], edges[1:]), key=lambda e: e[1] - e[0])
54
+ run = beats[start:stop]
55
+ if run.size < 8:
56
+ return rough
57
+ slope, _ = np.polyfit(np.arange(run.size), run, 1)
58
+ return float(slope)
59
+
60
+
61
+ def _coherence(beats: np.ndarray, periods: np.ndarray) -> np.ndarray:
62
+ """How well the beats line up on each candidate period (1 = every beat on the grid)."""
63
+ t = beats - beats[0]
64
+ blocks = np.array_split(periods, max(1, periods.size // 256)) # bounded memory on long files
65
+ return np.concatenate([np.abs(np.exp(2j * np.pi * t[None, :] / b[:, None]).mean(axis=1))
66
+ for b in blocks])
67
+
68
+
69
+ def _refine_period(beats: np.ndarray, rough: float) -> tuple[float, float]:
70
+ """The period within PERIOD_SEARCH of `rough` at which the most beats line up, and
71
+ the time of one beat on it. Every beat votes, so quantisation, stray detections and
72
+ gaps average out; the narrow search can't land on half or double time."""
73
+ step = 0.2 * rough / (beats[-1] - beats[0]) # a fifth of the peak's width
74
+ coarse = rough * (1 + np.arange(-PERIOD_SEARCH, PERIOD_SEARCH + step, step))
75
+ best = coarse[np.argmax(_coherence(beats, coarse))]
76
+ fine = best + np.linspace(-1, 1, 41) * step * rough
77
+ period = float(fine[np.argmax(_coherence(beats, fine))])
78
+ angle = np.angle(np.mean(np.exp(2j * np.pi * (beats - beats[0]) / period)))
79
+ return period, float(beats[0] + angle / (2 * np.pi) * period)
80
+
81
+
82
+ def fit_grid(beats, beats_per_bar: int = 4) -> Grid:
83
+ beats = np.sort(np.asarray(beats, dtype=float))
84
+ if beats.size < MIN_BEATS:
85
+ raise GridError(f"only {beats.size} beats detected; a grid needs {MIN_BEATS}")
86
+ slope, intercept = _refine_period(beats, _initial_period(beats))
87
+ keep = np.ones(beats.size, dtype=bool)
88
+ for _ in range(4):
89
+ n = np.round((beats - intercept) / slope)
90
+ keep = np.abs(beats - (intercept + n * slope)) < INLIER_S
91
+ if keep.sum() < MIN_BEATS:
92
+ break
93
+ slope, intercept = np.polyfit(n[keep], beats[keep], 1)
94
+ return Grid(period=float(slope), phase=float(intercept % slope),
95
+ beats_per_bar=beats_per_bar, inlier_ratio=float(keep.mean()))
96
+
97
+
98
+ def bar_phase(grid: Grid, downbeats) -> tuple[int, float]:
99
+ downbeats = np.asarray(downbeats, dtype=float)
100
+ if downbeats.size == 0:
101
+ return 0, 0.0
102
+ n = np.round((downbeats - grid.phase) / grid.period).astype(int)
103
+ on_grid = np.abs(downbeats - (grid.phase + n * grid.period)) < INLIER_S
104
+ if not on_grid.any():
105
+ return 0, 0.0
106
+ counts = np.bincount(n[on_grid] % grid.beats_per_bar, minlength=grid.beats_per_bar)
107
+ best = int(counts.argmax())
108
+ return best, float(counts[best] / counts.sum())
109
+
110
+
111
+ def local_grid(beats, downbeats, t: float, span_beats: int = LOCAL_SPAN_BEATS,
112
+ beats_per_bar: int = 4) -> Grid:
113
+ """A grid fitted only to the beats around time t, for tracks whose tempo moves."""
114
+ beats = np.asarray(beats, dtype=float)
115
+ downbeats = np.asarray(downbeats, dtype=float)
116
+ if beats.size < MIN_BEATS:
117
+ raise GridError(f"only {beats.size} beats detected; a grid needs {MIN_BEATS}")
118
+ half = span_beats * float(np.median(np.diff(beats))) / 2
119
+ grid = fit_grid(beats[np.abs(beats - t) <= half], beats_per_bar)
120
+ phase, agreement = bar_phase(grid, downbeats[np.abs(downbeats - t) <= half])
121
+ return replace(grid, bar_phase=phase, bar_agreement=agreement)
122
+
123
+
124
+ def local_inliers(grid: Grid, beats, t: float, span_beats: int = LOCAL_SPAN_BEATS) -> float:
125
+ """Share of the detected beats within span_beats of time t that sit on `grid`."""
126
+ beats = np.asarray(beats, dtype=float)
127
+ near = beats[np.abs(beats - t) <= span_beats * grid.period / 2]
128
+ if near.size < MIN_BEATS:
129
+ return 0.0
130
+ n = np.round((near - grid.phase) / grid.period)
131
+ return float(np.mean(np.abs(near - (grid.phase + n * grid.period)) < INLIER_S))
132
+
133
+
134
+ def attack_phase(mono, sr: int, grid: Grid) -> tuple[float, float]:
135
+ """Where the attack sits against the grid's beats (the strongest onset within 40 ms of
136
+ each beat, strength-weighted median), and the share of beats that agree to within 5 ms."""
137
+ times, strengths = detect_onsets(mono, sr)
138
+ beats = grid.beat_time(np.arange(int((len(mono) / sr - grid.phase) / grid.period)))
139
+ found = attacks_near(times, strengths, beats, PHASE_WINDOW_S)
140
+ if len(found) < 2:
141
+ return 0.0, 0.0
142
+ return found.placement, found.agreement(beats.size)
143
+
144
+
145
+ @lru_cache(maxsize=2)
146
+ def _model(device: str):
147
+ from beat_this.inference import Audio2Beats
148
+
149
+ return Audio2Beats(checkpoint_path="final0", device=device, dbn=False)
150
+
151
+
152
+ def _device() -> str:
153
+ import torch
154
+
155
+ if torch.backends.mps.is_available():
156
+ return "mps"
157
+ return "cuda" if torch.cuda.is_available() else "cpu"
158
+
159
+
160
+ def detect(mono: np.ndarray, sr: int) -> tuple[np.ndarray, np.ndarray]:
161
+ beats, downbeats = _model(_device())(np.asarray(mono, dtype=np.float32), sr)
162
+ return np.asarray(beats, dtype=float), np.asarray(downbeats, dtype=float)
163
+
164
+
165
+ def analyse_grid(mono: np.ndarray, sr: int, beats_per_bar: int = 4,
166
+ detector: Detector | None = None) -> tuple[Grid, np.ndarray, np.ndarray]:
167
+ beats, downbeats = (detector or detect)(mono, sr)
168
+ grid = fit_grid(beats, beats_per_bar)
169
+ phase, bar_share = bar_phase(grid, downbeats)
170
+ grid = replace(grid, bar_phase=phase, bar_agreement=bar_share)
171
+ offset, agreement = attack_phase(mono, sr, grid)
172
+ if agreement >= MIN_PHASE_AGREEMENT:
173
+ grid = grid.shifted(offset - ONSET_LEAD_S)
174
+ return replace(grid, phase_agreement=agreement), np.asarray(beats), np.asarray(downbeats)
175
+
176
+
177
+ def compare_grids(grid: Grid, app_beats) -> dict:
178
+ """How a DJ app's beat times sit against ours. app_offset_ms = app minus ours.
179
+
180
+ The offset is a circular mean, so a grid half a beat out reads as half a
181
+ beat whichever way rounding would have fallen.
182
+ """
183
+ app = np.asarray(app_beats, dtype=float)
184
+ if app.size < 2:
185
+ return {}
186
+ resultant = np.mean(np.exp(2j * np.pi * (app - grid.phase) / grid.period))
187
+ offset = float(np.angle(resultant)) / (2 * np.pi) * grid.period
188
+ # Across the whole grid, not one interval: rekordbox keeps beat times in whole
189
+ # milliseconds, so single intervals alternate (468 and 469 ms at 128 BPM).
190
+ span = float(app[-1] - app[0])
191
+ beats = max(1, round(span / float(np.median(np.diff(app)))))
192
+ return {"app_bpm": 60.0 * beats / span,
193
+ "app_offset_ms": offset * 1000,
194
+ "half_beat": abs(offset) > 0.4 * grid.period,
195
+ "app_agreement": float(abs(resultant))} # 1 = every app beat at the same offset
196
+
197
+
198
+ def save_beats(path, beats, downbeats) -> None:
199
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
200
+ np.savez(path, beats=np.asarray(beats), downbeats=np.asarray(downbeats))
201
+
202
+
203
+ def load_beats(path) -> tuple[np.ndarray, np.ndarray]:
204
+ with np.load(path) as data:
205
+ return data["beats"], data["downbeats"]
@@ -0,0 +1,77 @@
1
+ """Key per track: the file's own tag first (Mixed In Key writes it), keyfinder-cli second."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Callable
12
+
13
+ import mutagen
14
+ import soundfile as sf
15
+
16
+ from .audio_io import read_audio
17
+ from .keys import Key, KeyParseError, parse_key
18
+
19
+ _CAMELOT_IN_TEXT = re.compile(r"\b(1[0-2]|[1-9])\s*([AB])\b", re.IGNORECASE)
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class KeyResult:
24
+ key: Key | None
25
+ source: str
26
+ alternative: Key | None = None
27
+
28
+ @property
29
+ def disagrees(self) -> bool:
30
+ return self.alternative is not None
31
+
32
+
33
+ def key_from_tags(path) -> tuple[Key | None, str]:
34
+ tags = getattr(mutagen.File(str(path)), "tags", None)
35
+ if not tags:
36
+ return None, ""
37
+ candidates: list[tuple[str, str]] = []
38
+ if hasattr(tags, "getall"):
39
+ candidates += [("tag", str(f.text[0])) for f in tags.getall("TKEY") if f.text]
40
+ candidates += [("comment", str(f.text[0])) for f in tags.getall("COMM") if f.text]
41
+ else:
42
+ candidates += [("tag", str(tags[n][0])) for n in ("initialkey", "key") if n in tags]
43
+ for source, text in candidates:
44
+ match = _CAMELOT_IN_TEXT.search(text) if source == "comment" else None
45
+ if source == "comment" and not match:
46
+ continue
47
+ try:
48
+ return parse_key(match.group(0) if match else text), source
49
+ except KeyParseError:
50
+ continue
51
+ return None, ""
52
+
53
+
54
+ def key_from_keyfinder(path) -> Key | None:
55
+ """keyfinder-cli can't resample 24-bit or float PCM itself, so hand it 16-bit instead."""
56
+ binary = shutil.which("keyfinder-cli")
57
+ if not binary:
58
+ return None
59
+ audio, sr = read_audio(path)
60
+ with tempfile.TemporaryDirectory() as tmp_dir:
61
+ wav_path = Path(tmp_dir) / "keyfinder.wav"
62
+ sf.write(str(wav_path), audio, sr, subtype="PCM_16")
63
+ run = subprocess.run([binary, "-n", "camelot", str(wav_path)], capture_output=True, text=True)
64
+ if run.returncode != 0:
65
+ return None
66
+ try:
67
+ return parse_key(run.stdout.strip())
68
+ except KeyParseError:
69
+ return None
70
+
71
+
72
+ def detect_key(path, keyfinder: Callable = key_from_keyfinder) -> KeyResult:
73
+ tagged, source = key_from_tags(path)
74
+ found = keyfinder(path)
75
+ if tagged is None:
76
+ return KeyResult(found, "keyfinder" if found else "")
77
+ return KeyResult(tagged, source, found if found is not None and found != tagged else None)