| 1 |
"""Calculate acoustic information and submit to AcousticBrainz.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import errno |
| 6 |
import hashlib |
| 7 |
import json |
| 8 |
import os |
| 9 |
import shutil |
| 10 |
import subprocess |
| 11 |
import tempfile |
| 12 |
from typing import TYPE_CHECKING, Protocol |
| 13 |
|
| 14 |
import requests |
| 15 |
|
| 16 |
from beets import plugins, ui, util |
| 17 |
from beets.exceptions import UserError |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from collections.abc import Sequence |
| 21 |
|
| 22 |
from beets.library import Item, Library |
| 23 |
|
| 24 |
from ._typing import JSONDict |
| 25 |
|
| 26 |
|
| 27 |
class ABSubmitCLIOpts(Protocol): |
| 28 |
force_refetch: bool |
| 29 |
pretend_fetch: bool |
| 30 |
|
| 31 |
|
| 32 |
# We use this field to check whether AcousticBrainz info is present. |
| 33 |
PROBE_FIELD = "mood_acoustic" |
| 34 |
|
| 35 |
|
| 36 |
class ABSubmitError(Exception): |
| 37 |
"""Raised when failing to analyse file with extractor.""" |
| 38 |
|
| 39 |
|
| 40 |
def call(args: Sequence[str]) -> bytes: |
| 41 |
"""Execute the command and return its output. |
| 42 |
|
| 43 |
Raise a AnalysisABSubmitError on failure. |
| 44 |
""" |
| 45 |
try: |
| 46 |
return util.command_output(args).stdout |
| 47 |
except subprocess.CalledProcessError as e: |
| 48 |
raise ABSubmitError(f"{args[0]} exited with status {e.returncode}") |
| 49 |
|
| 50 |
|
| 51 |
class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): |
| 52 |
extractor: str |
| 53 |
|
| 54 |
def __init__(self) -> None: |
| 55 |
super().__init__() |
| 56 |
|
| 57 |
self._log.warning("This plugin is deprecated.") |
| 58 |
|
| 59 |
self.config.add( |
| 60 |
{"extractor": "", "force": False, "pretend": False, "base_url": ""} |
| 61 |
) |
| 62 |
|
| 63 |
if extractor := self.config["extractor"].as_str(): |
| 64 |
extractor = os.fsdecode(util.normpath(extractor)) |
| 65 |
# Explicit path to extractor |
| 66 |
if not os.path.isfile(extractor): |
| 67 |
raise UserError( |
| 68 |
f"Extractor command does not exist: {extractor}." |
| 69 |
) |
| 70 |
else: |
| 71 |
# Implicit path to extractor, search for it in path |
| 72 |
extractor = "streaming_extractor_music" |
| 73 |
try: |
| 74 |
call([extractor]) |
| 75 |
except OSError: |
| 76 |
raise UserError( |
| 77 |
"No extractor command found: please install the extractor" |
| 78 |
" binary from https://essentia.upf.edu/" |
| 79 |
) |
| 80 |
except ABSubmitError: |
| 81 |
# Extractor found, will exit with an error if not called with |
| 82 |
# the correct amount of arguments. |
| 83 |
pass |
| 84 |
|
| 85 |
# Get the executable location on the system, which we need |
| 86 |
# to calculate the SHA-1 hash. |
| 87 |
if extractor_cmd_path := shutil.which(extractor): |
| 88 |
extractor = extractor_cmd_path |
| 89 |
else: |
| 90 |
raise UserError( |
| 91 |
f"Path to extractor command {extractor} not found" |
| 92 |
) |
| 93 |
|
| 94 |
self.extractor = extractor |
| 95 |
|
| 96 |
# Calculate extractor hash. |
| 97 |
extractor_sha = hashlib.sha1() |
| 98 |
if extractor: |
| 99 |
with open(extractor, "rb") as f: |
| 100 |
extractor_sha.update(f.read()) |
| 101 |
self.extractor_sha = extractor_sha.hexdigest() |
| 102 |
|
| 103 |
self.url = "" |
| 104 |
base_url = self.config["base_url"].as_str() |
| 105 |
if base_url: |
| 106 |
if not base_url.startswith("http"): |
| 107 |
raise UserError( |
| 108 |
"AcousticBrainz server base URL must start " |
| 109 |
"with an HTTP scheme" |
| 110 |
) |
| 111 |
if base_url[-1] != "/": |
| 112 |
base_url = f"{base_url}/" |
| 113 |
self.url = f"{base_url}{{mbid}}/low-level" |
| 114 |
|
| 115 |
def commands(self) -> list[ui.Subcommand]: |
| 116 |
cmd = ui.Subcommand( |
| 117 |
"absubmit", help="calculate and submit AcousticBrainz analysis" |
| 118 |
) |
| 119 |
cmd.parser.add_option( |
| 120 |
"-f", |
| 121 |
"--force", |
| 122 |
dest="force_refetch", |
| 123 |
action="store_true", |
| 124 |
default=False, |
| 125 |
help="re-download data when already present", |
| 126 |
) |
| 127 |
cmd.parser.add_option( |
| 128 |
"-p", |
| 129 |
"--pretend", |
| 130 |
dest="pretend_fetch", |
| 131 |
action="store_true", |
| 132 |
default=False, |
| 133 |
help=( |
| 134 |
"pretend to perform action, but show only files which would be" |
| 135 |
" processed" |
| 136 |
), |
| 137 |
) |
| 138 |
cmd.func = self.command |
| 139 |
return [cmd] |
| 140 |
|
| 141 |
def command( |
| 142 |
self, lib: Library, opts: ABSubmitCLIOpts, args: list[str] |
| 143 |
) -> None: |
| 144 |
if not self.url: |
| 145 |
raise UserError( |
| 146 |
"This plugin is deprecated since AcousticBrainz no longer " |
| 147 |
"accepts new submissions. See the base_url configuration " |
| 148 |
"option." |
| 149 |
) |
| 150 |
# Get items from arguments |
| 151 |
items = lib.items(args) |
| 152 |
self.opts = opts |
| 153 |
util.par_map(self.analyze_submit, items) |
| 154 |
|
| 155 |
def analyze_submit(self, item: Item) -> None: |
| 156 |
analysis = self._get_analysis(item) |
| 157 |
if analysis: |
| 158 |
self._submit_data(item, analysis) |
| 159 |
|
| 160 |
def _get_analysis(self, item: Item) -> JSONDict | None: |
| 161 |
mbid = item["mb_trackid"] |
| 162 |
|
| 163 |
# Avoid re-analyzing files that already have AB data. |
| 164 |
if not self.opts.force_refetch and not self.config["force"]: |
| 165 |
if item.get(PROBE_FIELD): |
| 166 |
return None |
| 167 |
|
| 168 |
# If file has no MBID, skip it. |
| 169 |
if not mbid: |
| 170 |
self._log.info( |
| 171 |
"Not analysing {}, missing musicbrainz track id.", item |
| 172 |
) |
| 173 |
return None |
| 174 |
|
| 175 |
if self.opts.pretend_fetch or self.config["pretend"]: |
| 176 |
self._log.info("pretend action - extract item: {}", item) |
| 177 |
return None |
| 178 |
|
| 179 |
# Temporary file to save extractor output to, extractor only works |
| 180 |
# if an output file is given. Here we use a temporary file to copy |
| 181 |
# the data into a python object and then remove the file from the |
| 182 |
# system. |
| 183 |
tmp_file, filename = tempfile.mkstemp(suffix=".json") |
| 184 |
try: |
| 185 |
# Close the file, so the extractor can overwrite it. |
| 186 |
os.close(tmp_file) |
| 187 |
try: |
| 188 |
call([self.extractor, util.syspath(item.path), filename]) |
| 189 |
except ABSubmitError as e: |
| 190 |
self._log.warning( |
| 191 |
"Failed to analyse {} for AcousticBrainz: {}", item, e |
| 192 |
) |
| 193 |
return None |
| 194 |
with open(filename) as f: |
| 195 |
analysis = json.load(f) |
| 196 |
# Add the hash to the output. |
| 197 |
analysis["metadata"]["version"]["essentia_build_sha"] = ( |
| 198 |
self.extractor_sha |
| 199 |
) |
| 200 |
return analysis |
| 201 |
finally: |
| 202 |
try: |
| 203 |
os.remove(filename) |
| 204 |
except OSError as e: |
| 205 |
# ENOENT means file does not exist, just ignore this error. |
| 206 |
if e.errno != errno.ENOENT: |
| 207 |
raise |
| 208 |
|
| 209 |
def _submit_data(self, item: Item, data: JSONDict) -> None: |
| 210 |
mbid = item["mb_trackid"] |
| 211 |
headers = {"Content-Type": "application/json"} |
| 212 |
response = requests.post( |
| 213 |
self.url.format(mbid=mbid), json=data, headers=headers, timeout=10 |
| 214 |
) |
| 215 |
# Test that request was successful and raise an error on failure. |
| 216 |
if response.status_code != 200: |
| 217 |
try: |
| 218 |
message = response.json()["message"] |
| 219 |
except (ValueError, KeyError) as e: |
| 220 |
message = f"unable to get error message: {e}" |
| 221 |
self._log.error( |
| 222 |
"Failed to submit AcousticBrainz analysis for {}: {}.", |
| 223 |
item, |
| 224 |
message, |
| 225 |
) |
| 226 |
else: |
| 227 |
self._log.debug( |
| 228 |
"Successfully submitted AcousticBrainz analysis for {}.", item |
| 229 |
) |