Spaces:
Running on Zero
Running on Zero
Download stemdeck/pipeline/analysis.py from AnjaneyaTurai/stemdeck-gpu: direct link, hf CLI and curl.
- Browser
- Download file 3.32 kB
-
https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/pipeline/analysis.py
- Command line
-
hf download hf://spaces/AnjaneyaTurai/stemdeck-gpu/stemdeck/pipeline/analysis.py
-
curl -L -o analysis.py https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/pipeline/analysis.py
3.32 kB
| """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 | |
| 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), | |
| ) | |