| 1 |
"""Uses Librosa to calculate the `bpm` field.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import TYPE_CHECKING, Protocol |
| 6 |
|
| 7 |
import librosa |
| 8 |
import numpy as np |
| 9 |
|
| 10 |
from beets.plugins import BeetsPlugin |
| 11 |
from beets.ui import Subcommand, should_write |
| 12 |
from beets.util.deprecation import deprecate_for_user |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from collections.abc import Iterable |
| 16 |
|
| 17 |
from beets.importer import ImportTask |
| 18 |
from beets.library import Item, Library |
| 19 |
|
| 20 |
|
| 21 |
class AutoBPMCLIOpts(Protocol): |
| 22 |
force: bool |
| 23 |
quiet: bool |
| 24 |
|
| 25 |
|
| 26 |
class AutoBPMPlugin(BeetsPlugin): |
| 27 |
def __init__(self) -> None: |
| 28 |
super().__init__() |
| 29 |
self.config.add( |
| 30 |
{ |
| 31 |
"auto": True, |
| 32 |
"force": False, |
| 33 |
"quiet": False, |
| 34 |
"beat_track_kwargs": {}, |
| 35 |
} |
| 36 |
) |
| 37 |
|
| 38 |
if self.config["overwrite"].exists(): |
| 39 |
deprecate_for_user( |
| 40 |
self._log, |
| 41 |
f"'{self.name}.overwrite' configuration option", |
| 42 |
f"'{self.name}.force'", |
| 43 |
) |
| 44 |
self.config["force"] = self.config["overwrite"].get() |
| 45 |
|
| 46 |
if self.config["auto"]: |
| 47 |
self.import_stages = [self.imported] |
| 48 |
|
| 49 |
def commands(self) -> list[Subcommand]: |
| 50 |
cmd = Subcommand( |
| 51 |
"autobpm", help="detect and add bpm from audio using Librosa" |
| 52 |
) |
| 53 |
cmd.parser.add_option( |
| 54 |
"-f", |
| 55 |
"--force", |
| 56 |
dest="force", |
| 57 |
action="store_true", |
| 58 |
default=False, |
| 59 |
help="Overwrite existing BPM values", |
| 60 |
) |
| 61 |
cmd.parser.add_option( |
| 62 |
"-q", |
| 63 |
"--quiet", |
| 64 |
dest="quiet", |
| 65 |
action="store_true", |
| 66 |
default=False, |
| 67 |
help="Suppress message when item already has BPM", |
| 68 |
) |
| 69 |
cmd.func = self.command |
| 70 |
return [cmd] |
| 71 |
|
| 72 |
def command( |
| 73 |
self, lib: Library, opts: AutoBPMCLIOpts, args: list[str] |
| 74 |
) -> None: |
| 75 |
force = self.config["force"].get(bool) or opts.force |
| 76 |
quiet = self.config["quiet"].get(bool) or opts.quiet |
| 77 |
self.calculate_bpm( |
| 78 |
list(lib.items(args)), |
| 79 |
write=should_write(), |
| 80 |
force=force, |
| 81 |
quiet=quiet, |
| 82 |
) |
| 83 |
|
| 84 |
def imported(self, _, task: ImportTask) -> None: |
| 85 |
self.calculate_bpm( |
| 86 |
task.imported_items(), |
| 87 |
force=self.config["force"].get(bool), |
| 88 |
quiet=self.config["quiet"].get(bool), |
| 89 |
) |
| 90 |
|
| 91 |
def calculate_bpm( |
| 92 |
self, |
| 93 |
items: Iterable[Item], |
| 94 |
write: bool = False, |
| 95 |
force: bool = False, |
| 96 |
quiet: bool = False, |
| 97 |
) -> None: |
| 98 |
for item in items: |
| 99 |
path = item.filepath |
| 100 |
if bpm := item.bpm: |
| 101 |
if not quiet: |
| 102 |
self._log.info("BPM for {} already exists: {}", path, bpm) |
| 103 |
if not force: |
| 104 |
continue |
| 105 |
try: |
| 106 |
y, sr = librosa.load(item.filepath, res_type="kaiser_fast") |
| 107 |
except Exception as exc: |
| 108 |
self._log.error("Failed to load {}: {}", path, exc) |
| 109 |
continue |
| 110 |
|
| 111 |
kwargs = self.config["beat_track_kwargs"].flatten() |
| 112 |
try: |
| 113 |
tempo, _ = librosa.beat.beat_track(y=y, sr=sr, **kwargs) |
| 114 |
except Exception as exc: |
| 115 |
self._log.error("Failed to measure BPM for {}: {}", path, exc) |
| 116 |
continue |
| 117 |
|
| 118 |
bpm = round( |
| 119 |
float(tempo[0] if isinstance(tempo, np.ndarray) else tempo) |
| 120 |
) |
| 121 |
|
| 122 |
item["bpm"] = bpm |
| 123 |
self._log.info("Computed BPM for {}: {}", path, bpm) |
| 124 |
|
| 125 |
if write: |
| 126 |
item.try_write() |
| 127 |
item.store() |