| 1 |
"""Determine BPM by pressing a key to the rhythm.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import time |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
from beets import ui |
| 9 |
from beets.plugins import BeetsPlugin |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
import optparse |
| 13 |
from collections.abc import Sequence |
| 14 |
|
| 15 |
from beets.library import Item, Library |
| 16 |
|
| 17 |
|
| 18 |
def bpm(max_strokes: int) -> float: |
| 19 |
"""Returns average BPM (possibly of a playing song) |
| 20 |
listening to Enter keystrokes. |
| 21 |
""" |
| 22 |
t0 = None |
| 23 |
dt = [] |
| 24 |
for i in range(max_strokes): |
| 25 |
# Press enter to the rhythm... |
| 26 |
s = input() |
| 27 |
if s == "": |
| 28 |
t1 = time.time() |
| 29 |
# Only start measuring at the second stroke |
| 30 |
if t0: |
| 31 |
dt.append(t1 - t0) |
| 32 |
t0 = t1 |
| 33 |
else: |
| 34 |
break |
| 35 |
|
| 36 |
# Return average BPM |
| 37 |
# bpm = (max_strokes-1) / sum(dt) * 60 |
| 38 |
return sum([1.0 / dti * 60 for dti in dt]) / len(dt) |
| 39 |
|
| 40 |
|
| 41 |
class BPMPlugin(BeetsPlugin): |
| 42 |
def __init__(self) -> None: |
| 43 |
super().__init__() |
| 44 |
self.config.add({"max_strokes": 3, "overwrite": True}) |
| 45 |
|
| 46 |
def commands(self) -> list[ui.Subcommand]: |
| 47 |
cmd = ui.Subcommand( |
| 48 |
"bpm", |
| 49 |
help="determine bpm of a song by pressing a key to the rhythm", |
| 50 |
) |
| 51 |
cmd.func = self.command |
| 52 |
return [cmd] |
| 53 |
|
| 54 |
def command( |
| 55 |
self, lib: Library, opts: optparse.Values, args: list[str] |
| 56 |
) -> None: |
| 57 |
write = ui.should_write() |
| 58 |
self.get_bpm(lib.items(args), write) |
| 59 |
|
| 60 |
def get_bpm(self, items: Sequence[Item], write: bool = False) -> None: |
| 61 |
overwrite = self.config["overwrite"].get(bool) |
| 62 |
if len(items) > 1: |
| 63 |
raise ValueError("Can only get bpm of one song at time") |
| 64 |
|
| 65 |
item = items[0] |
| 66 |
if item["bpm"]: |
| 67 |
self._log.info("Found bpm {}", item["bpm"]) |
| 68 |
if not overwrite: |
| 69 |
return |
| 70 |
|
| 71 |
self._log.info( |
| 72 |
"Press Enter {} times to the rhythm or Ctrl-D to exit", |
| 73 |
self.config["max_strokes"].get(int), |
| 74 |
) |
| 75 |
new_bpm = bpm(self.config["max_strokes"].get(int)) |
| 76 |
item["bpm"] = int(new_bpm) |
| 77 |
if write: |
| 78 |
item.try_write() |
| 79 |
item.store() |
| 80 |
self._log.info("Added new bpm {}", item["bpm"]) |