Debian Codegraph @

beetsplug/keyfinder.py

raw
1 """Uses the `KeyFinder` program to add the `initial_key` field."""
2
3 from __future__ import annotations
4
5 import os.path
6 import subprocess
7 from typing import TYPE_CHECKING
8
9 from beets import ui, util
10 from beets.plugins import BeetsPlugin
11
12 if TYPE_CHECKING:
13 import optparse
14 from collections.abc import Sequence
15
16 from beets.importer import ImportSession, ImportTask
17 from beets.library import Item, Library
18
19
20 class KeyFinderPlugin(BeetsPlugin):
21 def __init__(self) -> None:
22 super().__init__()
23 self.config.add({"bin": "KeyFinder", "auto": True, "overwrite": False})
24
25 if self.config["auto"].get(bool):
26 self.import_stages = [self.imported]
27
28 def commands(self) -> list[ui.Subcommand]:
29 cmd = ui.Subcommand(
30 "keyfinder", help="detect and add initial key from audio"
31 )
32 cmd.func = self.command
33 return [cmd]
34
35 def command(
36 self, lib: Library, opts: optparse.Values, args: list[str]
37 ) -> None:
38 self.find_key(lib.items(args), write=ui.should_write())
39
40 def imported(self, session: ImportSession, task: ImportTask) -> None:
41 self.find_key(task.imported_items())
42
43 def find_key(self, items: Sequence[Item], write: bool = False) -> None:
44 overwrite = self.config["overwrite"].get(bool)
45 command = [self.config["bin"].as_str()]
46 # The KeyFinder GUI program needs the -f flag before the path.
47 # keyfinder-cli is similar, but just wants the path with no flag.
48 if "keyfinder-cli" not in os.path.basename(command[0]).lower():
49 command.append("-f")
50
51 for item in items:
52 if item["initial_key"] and not overwrite:
53 continue
54
55 try:
56 output = util.command_output(
57 [*command, util.syspath(item.path)]
58 ).stdout
59 except (subprocess.CalledProcessError, OSError) as exc:
60 self._log.error("execution failed: {}", exc)
61 continue
62
63 try:
64 key_raw = output.rsplit(None, 1)[-1]
65 except IndexError:
66 # Sometimes keyfinder-cli returns 0 but with no key, usually
67 # when the file is silent or corrupt, so we log and skip.
68 self._log.error("no key returned for path: {.path}", item)
69 continue
70
71 try:
72 key = key_raw.decode("utf-8")
73 except UnicodeDecodeError:
74 self._log.error("output is invalid UTF-8")
75 continue
76
77 item["initial_key"] = key
78 self._log.info(
79 "added computed initial key {} for {.filepath}", key, item
80 )
81
82 if write:
83 item.try_write()
84 item.store()