File size: 3,319 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Beat/downbeat tracking (beat_this, librosa fallback) and key detection (Krumhansl profiles)."""

from __future__ import annotations

import logging
from dataclasses import asdict, dataclass
from pathlib import Path

import numpy as np

from stemdeck.audio_io import SAMPLE_RATE

log = logging.getLogger(__name__)

KEYS = ("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
MAJOR_PROFILE = np.array([6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88])
MINOR_PROFILE = np.array([6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17])
ANALYSIS_SR = 22050


@dataclass(frozen=True)
class Analysis:
    bpm: float
    time_signature: str
    beats: list[float]
    downbeats: list[float]
    key: str
    key_confidence: float

    def to_dict(self) -> dict[str, object]:
        return asdict(self)


def track_beats(source_wav: Path, device: str) -> tuple[np.ndarray, np.ndarray]:
    try:
        from beat_this.inference import File2Beats

        f2b = File2Beats(checkpoint_path="final0", device="cuda" if device == "cuda" else "cpu", dbn=False)
        beats, downbeats = f2b(str(source_wav))
        return np.asarray(beats, dtype=float), np.asarray(downbeats, dtype=float)
    except Exception:  # noqa: BLE001 - fall back to librosa on any beat_this failure
        log.warning("beat_this failed, falling back to librosa", exc_info=True)
        return _librosa_beats(source_wav)


def _librosa_beats(source_wav: Path) -> tuple[np.ndarray, np.ndarray]:
    import librosa

    y, sr = librosa.load(str(source_wav), sr=ANALYSIS_SR, mono=True)
    _, frames = librosa.beat.beat_track(y=y, sr=sr)
    beats = librosa.frames_to_time(frames, sr=sr)
    return beats, beats[::4]  # assume 4/4 with the first beat as a downbeat


def detect_key(mono: np.ndarray, sr: int) -> tuple[str, float]:
    import librosa

    y = librosa.resample(mono, orig_sr=sr, target_sr=ANALYSIS_SR) if sr != ANALYSIS_SR else mono
    chroma = librosa.feature.chroma_cqt(y=y, sr=ANALYSIS_SR).mean(axis=1)
    best_name, best_r = "C major", -2.0
    for mode, profile in (("major", MAJOR_PROFILE), ("minor", MINOR_PROFILE)):
        for shift in range(12):
            r = float(np.corrcoef(chroma, np.roll(profile, shift))[0, 1])
            if r > best_r:
                best_name, best_r = f"{KEYS[shift]} {mode}", r
    return best_name, max(0.0, best_r)


def analyse(source_wav: Path, harmonic_mix: np.ndarray, device: str) -> Analysis:
    """`harmonic_mix` should exclude drums (source minus drums) for a cleaner key estimate."""
    beats, downbeats = track_beats(source_wav, device)
    ibi = np.diff(beats)
    bpm = 60.0 / float(np.median(ibi)) if ibi.size else 0.0
    if downbeats.size > 1:
        per_bar = np.diff(np.searchsorted(beats, downbeats))
        per_bar = per_bar[per_bar > 0]
        meter = int(np.bincount(per_bar).argmax()) if per_bar.size else 4
    else:
        meter = 4
    key, confidence = detect_key(harmonic_mix.mean(axis=1), SAMPLE_RATE)
    return Analysis(
        bpm=round(bpm, 1),
        time_signature=f"{meter}/4" if meter in (2, 3, 4, 5, 6, 7) else "4/4",
        beats=[round(float(b), 3) for b in beats],
        downbeats=[round(float(b), 3) for b in downbeats],
        key=key,
        key_confidence=round(confidence, 3),
    )