| 1 |
"""Fetch various AcousticBrainz metadata using MBID.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections import defaultdict |
| 6 |
from typing import TYPE_CHECKING, Any, ClassVar, Protocol |
| 7 |
|
| 8 |
import requests |
| 9 |
|
| 10 |
from beets import plugins, ui |
| 11 |
from beets.dbcore import types |
| 12 |
from beets.exceptions import UserError |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from collections.abc import Iterator, Sequence |
| 16 |
|
| 17 |
from beets.importer import ImportSession, ImportTask |
| 18 |
from beets.library import Item, Library |
| 19 |
|
| 20 |
from ._typing import JSONDict |
| 21 |
|
| 22 |
|
| 23 |
class AcousticBrainzCLIOpts(Protocol): |
| 24 |
force_refetch: bool |
| 25 |
|
| 26 |
|
| 27 |
LEVELS = ["/low-level", "/high-level"] |
| 28 |
ABSCHEME = { |
| 29 |
"highlevel": { |
| 30 |
"danceability": {"all": {"danceable": "danceable"}}, |
| 31 |
"gender": {"value": "gender"}, |
| 32 |
"genre_rosamerica": {"value": "genre_rosamerica"}, |
| 33 |
"mood_acoustic": {"all": {"acoustic": "mood_acoustic"}}, |
| 34 |
"mood_aggressive": {"all": {"aggressive": "mood_aggressive"}}, |
| 35 |
"mood_electronic": {"all": {"electronic": "mood_electronic"}}, |
| 36 |
"mood_happy": {"all": {"happy": "mood_happy"}}, |
| 37 |
"mood_party": {"all": {"party": "mood_party"}}, |
| 38 |
"mood_relaxed": {"all": {"relaxed": "mood_relaxed"}}, |
| 39 |
"mood_sad": {"all": {"sad": "mood_sad"}}, |
| 40 |
"moods_mirex": {"value": "moods_mirex"}, |
| 41 |
"ismir04_rhythm": {"value": "rhythm"}, |
| 42 |
"tonal_atonal": {"all": {"tonal": "tonal"}}, |
| 43 |
"timbre": {"value": "timbre"}, |
| 44 |
"voice_instrumental": {"value": "voice_instrumental"}, |
| 45 |
}, |
| 46 |
"lowlevel": {"average_loudness": "average_loudness"}, |
| 47 |
"rhythm": {"bpm": "bpm"}, |
| 48 |
"tonal": { |
| 49 |
"chords_changes_rate": "chords_changes_rate", |
| 50 |
"chords_key": "chords_key", |
| 51 |
"chords_number_rate": "chords_number_rate", |
| 52 |
"chords_scale": "chords_scale", |
| 53 |
"key_key": ("initial_key", 0), |
| 54 |
"key_scale": ("initial_key", 1), |
| 55 |
"key_strength": "key_strength", |
| 56 |
}, |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
class AcousticPlugin(plugins.BeetsPlugin): |
| 61 |
item_types: ClassVar[dict[str, types.Type]] = { |
| 62 |
"average_loudness": types.Float(6), |
| 63 |
"chords_changes_rate": types.Float(6), |
| 64 |
"chords_key": types.STRING, |
| 65 |
"chords_number_rate": types.Float(6), |
| 66 |
"chords_scale": types.STRING, |
| 67 |
"danceable": types.Float(6), |
| 68 |
"gender": types.STRING, |
| 69 |
"genre_rosamerica": types.STRING, |
| 70 |
"initial_key": types.STRING, |
| 71 |
"key_strength": types.Float(6), |
| 72 |
"mood_acoustic": types.Float(6), |
| 73 |
"mood_aggressive": types.Float(6), |
| 74 |
"mood_electronic": types.Float(6), |
| 75 |
"mood_happy": types.Float(6), |
| 76 |
"mood_party": types.Float(6), |
| 77 |
"mood_relaxed": types.Float(6), |
| 78 |
"mood_sad": types.Float(6), |
| 79 |
"moods_mirex": types.STRING, |
| 80 |
"rhythm": types.Float(6), |
| 81 |
"timbre": types.STRING, |
| 82 |
"tonal": types.Float(6), |
| 83 |
"voice_instrumental": types.STRING, |
| 84 |
} |
| 85 |
|
| 86 |
def __init__(self) -> None: |
| 87 |
super().__init__() |
| 88 |
|
| 89 |
self._log.warning("This plugin is deprecated.") |
| 90 |
|
| 91 |
self.config.add( |
| 92 |
{"auto": True, "force": False, "tags": [], "base_url": ""} |
| 93 |
) |
| 94 |
|
| 95 |
self.base_url = self.config["base_url"].as_str() |
| 96 |
if self.base_url: |
| 97 |
if not self.base_url.startswith("http"): |
| 98 |
raise UserError( |
| 99 |
"AcousticBrainz server base URL must start " |
| 100 |
"with an HTTP scheme" |
| 101 |
) |
| 102 |
if self.base_url[-1] != "/": |
| 103 |
self.base_url = f"{self.base_url}/" |
| 104 |
|
| 105 |
if self.config["auto"]: |
| 106 |
self.register_listener("import_task_files", self.import_task_files) |
| 107 |
|
| 108 |
def commands(self) -> list[ui.Subcommand]: |
| 109 |
cmd = ui.Subcommand( |
| 110 |
"acousticbrainz", help="fetch metadata from AcousticBrainz" |
| 111 |
) |
| 112 |
cmd.parser.add_option( |
| 113 |
"-f", |
| 114 |
"--force", |
| 115 |
dest="force_refetch", |
| 116 |
action="store_true", |
| 117 |
default=False, |
| 118 |
help="re-download data when already present", |
| 119 |
) |
| 120 |
|
| 121 |
def func( |
| 122 |
lib: Library, opts: AcousticBrainzCLIOpts, args: list[str] |
| 123 |
) -> None: |
| 124 |
items = lib.items(args) |
| 125 |
self._fetch_info( |
| 126 |
items, |
| 127 |
ui.should_write(), |
| 128 |
opts.force_refetch or self.config["force"].get(bool), |
| 129 |
) |
| 130 |
|
| 131 |
cmd.func = func |
| 132 |
return [cmd] |
| 133 |
|
| 134 |
def import_task_files( |
| 135 |
self, session: ImportSession, task: ImportTask |
| 136 |
) -> None: |
| 137 |
"""Function is called upon beet import.""" |
| 138 |
self._fetch_info(task.imported_items(), False, True) |
| 139 |
|
| 140 |
def _get_data(self, mbid: str) -> JSONDict: |
| 141 |
if not self.base_url: |
| 142 |
raise UserError( |
| 143 |
"This plugin is deprecated since AcousticBrainz has shut " |
| 144 |
"down. See the base_url configuration option." |
| 145 |
) |
| 146 |
data = {} |
| 147 |
for url in _generate_urls(self.base_url, mbid): |
| 148 |
self._log.debug("fetching URL: {}", url) |
| 149 |
|
| 150 |
try: |
| 151 |
res = requests.get(url, timeout=10) |
| 152 |
except requests.RequestException as exc: |
| 153 |
self._log.info("request error: {}", exc) |
| 154 |
return {} |
| 155 |
|
| 156 |
if res.status_code == 404: |
| 157 |
self._log.info("recording ID {} not found", mbid) |
| 158 |
return {} |
| 159 |
|
| 160 |
try: |
| 161 |
data.update(res.json()) |
| 162 |
except ValueError: |
| 163 |
self._log.debug("Invalid Response: {.text}", res) |
| 164 |
return {} |
| 165 |
|
| 166 |
return data |
| 167 |
|
| 168 |
def _fetch_info( |
| 169 |
self, items: Sequence[Item], write: bool, force: bool |
| 170 |
) -> None: |
| 171 |
"""Fetch additional information from AcousticBrainz for the `item`s.""" |
| 172 |
tags = self.config["tags"].as_str_seq() |
| 173 |
for item in items: |
| 174 |
# If we're not forcing re-downloading for all tracks, check |
| 175 |
# whether the data is already present. We use one |
| 176 |
# representative field name to check for previously fetched |
| 177 |
# data. |
| 178 |
if not force: |
| 179 |
mood_str = item.get("mood_acoustic", "") |
| 180 |
if mood_str: |
| 181 |
self._log.info("data already present for: {}", item) |
| 182 |
continue |
| 183 |
|
| 184 |
# We can only fetch data for tracks with MBIDs. |
| 185 |
if not item.mb_trackid: |
| 186 |
continue |
| 187 |
|
| 188 |
self._log.info("getting data for: {}", item) |
| 189 |
data = self._get_data(item.mb_trackid) |
| 190 |
if data: |
| 191 |
for attr, val in self._map_data_to_scheme(data, ABSCHEME): |
| 192 |
if not tags or attr in tags: |
| 193 |
self._log.debug( |
| 194 |
"attribute {} of {} set to {}", attr, item, val |
| 195 |
) |
| 196 |
setattr(item, attr, val) |
| 197 |
else: |
| 198 |
self._log.debug( |
| 199 |
"skipping attribute {} of {}" |
| 200 |
" (value {}) due to config", |
| 201 |
attr, |
| 202 |
item, |
| 203 |
val, |
| 204 |
) |
| 205 |
item.store() |
| 206 |
if write: |
| 207 |
item.try_write() |
| 208 |
|
| 209 |
def _map_data_to_scheme( |
| 210 |
self, data: JSONDict, scheme: JSONDict |
| 211 |
) -> Iterator[tuple[str, Any]]: |
| 212 |
"""Given `data` as a structure of nested dictionaries, and |
| 213 |
`scheme` as a structure of nested dictionaries , `yield` tuples |
| 214 |
`(attr, val)` where `attr` and `val` are corresponding leaf |
| 215 |
nodes in `scheme` and `data`. |
| 216 |
|
| 217 |
As its name indicates, `scheme` defines how the data is structured, |
| 218 |
so this function tries to find leaf nodes in `data` that correspond |
| 219 |
to the leafs nodes of `scheme`, and not the other way around. |
| 220 |
Leaf nodes of `data` that do not exist in the `scheme` do not matter. |
| 221 |
If a leaf node of `scheme` is not present in `data`, |
| 222 |
no value is yielded for that attribute and a simple warning is issued. |
| 223 |
|
| 224 |
Finally, to account for attributes of which the value is split between |
| 225 |
several leaf nodes in `data`, leaf nodes of `scheme` can be tuples |
| 226 |
`(attr, order)` where `attr` is the attribute to which the leaf node |
| 227 |
belongs, and `order` is the place at which it should appear in the |
| 228 |
value. The different `value`s belonging to the same `attr` are simply |
| 229 |
joined with `' '`. This is hardcoded and not very flexible, but it gets |
| 230 |
the job done. |
| 231 |
|
| 232 |
For example: |
| 233 |
|
| 234 |
>>> scheme = { |
| 235 |
'key1': 'attribute', |
| 236 |
'key group': { |
| 237 |
'subkey1': 'subattribute', |
| 238 |
'subkey2': ('composite attribute', 0) |
| 239 |
}, |
| 240 |
'key2': ('composite attribute', 1) |
| 241 |
} |
| 242 |
>>> data = { |
| 243 |
'key1': 'value', |
| 244 |
'key group': { |
| 245 |
'subkey1': 'subvalue', |
| 246 |
'subkey2': 'part 1 of composite attr' |
| 247 |
}, |
| 248 |
'key2': 'part 2' |
| 249 |
} |
| 250 |
>>> print(list(_map_data_to_scheme(data, scheme))) |
| 251 |
[('subattribute', 'subvalue'), |
| 252 |
('attribute', 'value'), |
| 253 |
('composite attribute', 'part 1 of composite attr part 2')] |
| 254 |
""" |
| 255 |
# First, we traverse `scheme` and `data`, `yield`ing all the non |
| 256 |
# composites attributes straight away and populating the dictionary |
| 257 |
# `composites` with the composite attributes. |
| 258 |
|
| 259 |
# When we are finished traversing `scheme`, `composites` should |
| 260 |
# map each composite attribute to an ordered list of the values |
| 261 |
# belonging to the attribute, for example: |
| 262 |
# `composites = {'initial_key': ['B', 'minor']}`. |
| 263 |
|
| 264 |
# The recursive traversal. |
| 265 |
composites = defaultdict[str, list[str]](list) |
| 266 |
yield from self._data_to_scheme_child(data, scheme, composites) |
| 267 |
|
| 268 |
# When composites has been populated, yield the composite attributes |
| 269 |
# by joining their parts. |
| 270 |
for composite_attr, value_parts in composites.items(): |
| 271 |
yield composite_attr, " ".join(value_parts) |
| 272 |
|
| 273 |
def _data_to_scheme_child( |
| 274 |
self, |
| 275 |
subdata: JSONDict, |
| 276 |
subscheme: JSONDict, |
| 277 |
composites: dict[str, list[str]], |
| 278 |
) -> Iterator[tuple[str, Any]]: |
| 279 |
"""The recursive business logic of :meth:`_map_data_to_scheme`: |
| 280 |
Traverse two structures of nested dictionaries in parallel and `yield` |
| 281 |
tuples of corresponding leaf nodes. |
| 282 |
|
| 283 |
If a leaf node belongs to a composite attribute (is a `tuple`), |
| 284 |
populate `composites` rather than yielding straight away. |
| 285 |
All the child functions for a single traversal share the same |
| 286 |
`composites` instance, which is passed along. |
| 287 |
""" |
| 288 |
for k, v in subscheme.items(): |
| 289 |
if k in subdata: |
| 290 |
if isinstance(v, dict): |
| 291 |
yield from self._data_to_scheme_child( |
| 292 |
subdata[k], v, composites |
| 293 |
) |
| 294 |
elif isinstance(v, tuple): |
| 295 |
composite_attribute, part_number = v |
| 296 |
attribute_parts = composites[composite_attribute] |
| 297 |
# Parts are not guaranteed to be inserted in order |
| 298 |
while len(attribute_parts) <= part_number: |
| 299 |
attribute_parts.append("") |
| 300 |
attribute_parts[part_number] = subdata[k] |
| 301 |
else: |
| 302 |
yield v, subdata[k] |
| 303 |
else: |
| 304 |
self._log.warning( |
| 305 |
"Acousticbrainz did not provide info about {}", k |
| 306 |
) |
| 307 |
self._log.debug( |
| 308 |
"Data {} could not be mapped to scheme {} " |
| 309 |
"because key {} was not found", |
| 310 |
subdata, |
| 311 |
v, |
| 312 |
k, |
| 313 |
) |
| 314 |
|
| 315 |
|
| 316 |
def _generate_urls(base_url: str, mbid: str) -> Iterator[str]: |
| 317 |
"""Generates AcousticBrainz end point urls for given `mbid`.""" |
| 318 |
for level in LEVELS: |
| 319 |
yield f"{base_url}{mbid}{level}" |