Reworked analysis menu

This commit is contained in:
patben8 committed 2026-10-04 16:18:43 +02:00
1 parent c3571fd054
commit 72a52d3291
7 files changed
+303 -19

No files matched your search

+50 -11
View File
@@ -213,12 +213,27 @@ def detect_grid(
*,
y: np.ndarray | None = None,
sr: int = _SR,
bpm: float | None = None,
anchor: float | None = None,
) -> GridResult:
"""Detect a track's constant tempo and first beat.
``y``/``sr`` let a caller (or a test) pass decoded mono audio directly.
Raises ``ValueError`` when there is no pulse to fit (silence, a one-shot).
Either half can be held fixed — the Analyze dialog's BPM and Grid ticks:
- ``bpm`` given ("Grid" alone): that tempo is KEPT — no search, no
round-BPM snap — and only where its beats fall is found. For a BPM the
user trusts (typed, or a store's) and a grid that sits off the beat.
- ``anchor`` given ("BPM" alone): the tempo is detected and the anchor
returned as given, so the grid's downbeat stays where the user put it.
``drift_ms`` is then measured against THAT anchor: large means the kept
anchor does not sit on the detected beat.
"""
if bpm is not None and anchor is not None:
raise ValueError("Hold the BPM or the anchor, not both — there would be nothing to detect")
if bpm is not None and not (20.0 <= bpm <= 400.0):
raise ValueError(f"Not a usable BPM: {bpm}")
if y is None:
import librosa
y, sr = librosa.load(audio_path, sr=sr, mono=True)
@@ -227,10 +242,42 @@ def detect_grid(
if duration < 1.5:
raise ValueError("Track is too short to detect a tempo")
lo, hi = bpm_range
low = _onset(_band_env(y, sr, 30.0, 150.0))
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
attack = _onset(_band_env(y, sr, _ATTACK_LO_HZ, _ATTACK_HI_HZ, smooth_ms=3))
if bpm is not None:
period = 60.0 / bpm
if not np.isfinite(attack).all() or attack.max() <= 0:
raise ValueError("No onsets found")
phase = _phase(low, attack, period)
return GridResult(
bpm=float(bpm),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(_drift(attack, bpm, phase) * 1000.0, 1),
)
found_bpm, phase, drift = _detect_tempo(y, sr, low, attack, bpm_range, duration)
period = 60.0 / found_bpm
if anchor is not None:
return GridResult(
bpm=round(found_bpm, 4),
anchor=float(anchor),
duration=duration,
drift_ms=round(_drift(attack, found_bpm, float(anchor) % period) * 1000.0, 1),
)
return GridResult(
bpm=round(found_bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
def _detect_tempo(y, sr, low, attack, bpm_range, duration) -> tuple[float, float, float]:
"""(bpm, phase, drift) — the tempo search, octave rule and round snap."""
lo, hi = bpm_range
mid = _onset(_band_env(y, sr, 150.0, 4000.0, smooth_ms=3))
full = _onset(_band_env(y, sr, None, None, smooth_ms=3))
o_tempo = low + mid + 0.5 * full
if not np.isfinite(o_tempo).all() or o_tempo.max() <= 0:
@@ -260,15 +307,7 @@ def detect_grid(
bpm, _ = _refine(o_t, bpm, 0.02, 0.001)
phase = _phase(low, attack, 60.0 / bpm)
drift = _drift(attack, bpm, phase)
bpm, phase, drift = _snap_round(low, attack, bpm, phase, drift, duration)
period = 60.0 / bpm
return GridResult(
bpm=round(bpm, 4),
anchor=round(_first_beat(low + attack, phase, period), 4),
duration=duration,
drift_ms=round(drift * 1000.0, 1),
)
return _snap_round(low, attack, bpm, phase, drift, duration)
def _peaks(f: np.ndarray, k: int, min_sep: int) -> list[int]:
+63
View File
@@ -0,0 +1,63 @@
"""What an analysis does to one track's grid, given the BPM / Grid ticks.
One pure function, so the batch, the dialog's counts and the tests cannot come
to mean different things. Decided with the user (2026-10-04, see
`.claude/discussions/discuss-key-analysis-2026-10-04.md`):
- BPM + Grid: a full analysis. A track that already has a grid is replaced
only when the user ticked "Replace" — a grid may hold hand edits.
- BPM alone: re-detect the tempo, KEEP the anchor (the first marker).
- Grid alone: KEEP the BPM, find only where the beats fall.
- With one tick, adjusting the existing grid is the point, so "Replace" does
not apply; a track with nothing to keep (no grid / no BPM) is analysed in
full rather than skipped — one tick never leaves a track worse off.
- A multi-marker (flexible) grid is skipped by BPM alone and Grid alone: its
tempo changes are exactly what one constant tempo would flatten.
- A locked grid is skipped whatever is ticked.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Sequence
Action = Literal["none", "full", "bpm", "phase", "skip"]
SkipReason = Literal["locked", "existing", "flexible"]
@dataclass(frozen=True)
class GridStep:
action: Action
reason: SkipReason | None = None
hold_bpm: float | None = None # "phase": the tempo kept
hold_anchor: float | None = None # "bpm": the anchor kept (seconds)
def plan_grid(
*,
bpm: bool,
grid: bool,
markers: Sequence, # the track's grid markers (`.start`, `.bpm`), any order
track_bpm: float | None,
locked: bool,
replace_existing: bool,
) -> GridStep:
if not (bpm or grid):
return GridStep("none")
if locked:
return GridStep("skip", "locked")
ordered = sorted(markers, key=lambda m: m.start)
if bpm and grid:
if ordered and not replace_existing:
return GridStep("skip", "existing")
return GridStep("full")
if len(ordered) > 1:
return GridStep("skip", "flexible")
if bpm: # BPM alone
if not ordered:
return GridStep("full")
return GridStep("bpm", hold_anchor=float(ordered[0].start))
# Grid alone
held = float(ordered[0].bpm) if ordered else (float(track_bpm) if track_bpm else None)
if not held or held <= 0:
return GridStep("full")
return GridStep("phase", hold_bpm=held)
+35 -6
View File
@@ -18,6 +18,7 @@ from . import __version__, exporter, exports, history, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect, structure
from .core.grid_plan import GridStep
from . import importer
from .core import export as core_export
from .core import places, registry
@@ -1285,16 +1286,44 @@ def _submit_batch(kind: str, run) -> "Job":
raise HTTPException(409, "A batch analysis is already running")
def _analyse_grid(a, track_id: str) -> TrackCues:
def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *,
y=None, sr: int | None = None) -> TrackCues:
"""Detect and write one track's grid — shared by the deck's Analyze and the
batch job, so the two cannot come to mean different things."""
path = a.audio_path(track_id)
if path is None or not path.exists():
raise _AnalysisError("Audio file not found (is the drive mounted?)")
batch job, so the two cannot come to mean different things.
`step` is `core/grid_plan`'s decision. Each kind is written through the
command a hand edit of the same thing uses, so it inherits that command's
handling (Traktor's beat-1 companion cue, the time base, the BPM column):
- "full": `set_analysed_grid` — one marker, written as the platform's
own analyser would (on Traktor also hotcue 1 on the first beat);
- "bpm": `set_grid_marker_bpm` on the first marker — the anchor, the
marker's name and its companion stay exactly where they are;
- "phase": `move_grid_marker` on the first marker (dragging its
companion), or a fresh marker at the kept BPM when there was
only a TEMPO and no grid.
`y`/`sr` let a caller that already decoded the file share it."""
if step.action in ("none", "skip"):
raise ValueError(f"nothing to write for a {step.action!r} step")
if y is None:
path = a.audio_path(track_id)
if path is None or not path.exists():
raise _AnalysisError("Audio file not found (is the drive mounted?)")
try:
found = grid_detect.detect_grid(str(path))
kw = {"y": y, "sr": sr} if y is not None else {}
found = grid_detect.detect_grid(
"" if y is not None else str(path),
bpm=step.hold_bpm if step.action == "phase" else None,
anchor=step.hold_anchor if step.action == "bpm" else None,
**kw,
)
except Exception as ex: # analysis is best-effort; never 500 the UI
raise _AnalysisError(f"Analysis failed: {ex}") from ex
if step.action == "bpm":
return a.set_grid_marker_bpm(track_id, 0, found.bpm)
if step.action == "phase":
cues = a.track_cues(track_id)
if cues is not None and cues.grid_markers:
return a.move_grid_marker(track_id, 0, found.anchor)
# "Analysed", not "replace": each platform writes an analysis result in its
# own shape (Traktor pairs the first marker with a beat-1 cue).
return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)])