Debian Codegraph @

beetsplug/mbpseudo.py

raw
1 """Adds pseudo-releases from MusicBrainz as candidates during import."""
2
3 from __future__ import annotations
4
5 import itertools
6 from copy import deepcopy
7 from functools import cached_property
8 from typing import TYPE_CHECKING, Any
9
10 import mediafile
11 from typing_extensions import Self, override
12
13 from beets import config
14 from beets.autotag import AlbumInfo, Source, assign_items, distance
15 from beets.plugins import find_plugins
16 from beets.util.id_extractors import extract_release_id
17 from beetsplug.musicbrainz import (
18 MusicBrainzPlugin,
19 _merge_pseudo_and_actual_album,
20 _preferred_alias,
21 )
22
23 if TYPE_CHECKING:
24 from collections.abc import Iterable, Sequence
25
26 from beets.autotag import AlbumMatch, Distance
27 from beets.library import Item
28
29 from ._typing import JSONDict
30 from ._utils.musicbrainz import (
31 Release,
32 ReleaseRelation,
33 ReleaseRelationRelease,
34 )
35
36 _STATUS_PSEUDO = "Pseudo-Release"
37
38
39 class MusicBrainzPseudoReleasePlugin(MusicBrainzPlugin):
40 def __init__(self) -> None:
41 super().__init__()
42
43 self.config.add(
44 {
45 "scripts": [],
46 "custom_tags_only": False,
47 "album_custom_tags": {
48 "album_transl": "album",
49 "album_artist_transl": "artist",
50 },
51 "track_custom_tags": {
52 "title_transl": "title",
53 "artist_transl": "artist",
54 },
55 }
56 )
57
58 self._scripts = self.config["scripts"].as_str_seq()
59 self._log.debug("Desired scripts: {0}", self._scripts)
60
61 album_custom_tags = self.config["album_custom_tags"].get().keys()
62 track_custom_tags = self.config["track_custom_tags"].get().keys()
63 self._log.debug(
64 "Custom tags for albums and tracks: {0} + {1}",
65 album_custom_tags,
66 track_custom_tags,
67 )
68 for custom_tag in album_custom_tags | track_custom_tags:
69 if not isinstance(custom_tag, str):
70 continue
71
72 media_field = mediafile.MediaField(
73 mediafile.MP3DescStorageStyle(custom_tag),
74 mediafile.MP4StorageStyle(
75 f"----:com.apple.iTunes:{custom_tag}"
76 ),
77 mediafile.StorageStyle(custom_tag),
78 mediafile.ASFStorageStyle(custom_tag),
79 )
80 try:
81 self.add_media_field(custom_tag, media_field)
82 except ValueError:
83 # ignore errors due to duplicates
84 pass
85
86 self.register_listener("pluginload", self._on_plugins_loaded)
87 self.register_listener("album_matched", self._adjust_final_album_match)
88
89 # noinspection PyMethodMayBeStatic
90 def _on_plugins_loaded(self) -> None:
91 for plugin in find_plugins():
92 if isinstance(plugin, MusicBrainzPlugin) and not isinstance(
93 plugin, MusicBrainzPseudoReleasePlugin
94 ):
95 raise RuntimeError(
96 "The musicbrainz plugin should not be enabled together with"
97 " the mbpseudo plugin"
98 )
99
100 @override
101 def candidates(
102 self, items: Sequence[Item], artist: str, album: str, va_likely: bool
103 ) -> Iterable[AlbumInfo]:
104 if len(self._scripts) == 0:
105 yield from super().candidates(items, artist, album, va_likely)
106 else:
107 for album_info in super().candidates(
108 items, artist, album, va_likely
109 ):
110 if isinstance(album_info, PseudoAlbumInfo):
111 self._log.debug(
112 "Using {0} release for distance calculations for album {1}",
113 album_info.determine_best_ref(items),
114 album_info.album_id,
115 )
116 yield album_info # first yield pseudo to give it priority
117 yield album_info.get_official_release()
118 else:
119 yield album_info
120
121 @override
122 def album_info(self, release: Release) -> AlbumInfo:
123 official_release = super().album_info(release)
124
125 if release.get("status") == _STATUS_PSEUDO:
126 return official_release
127
128 if (ids := self._intercept_mb_release(release)) and (
129 album_id := self._extract_id(ids[0])
130 ):
131 raw_pseudo_release = self.mb_api.get_release(album_id)
132 pseudo_release = super().album_info(raw_pseudo_release)
133
134 if self.config["custom_tags_only"].get(bool):
135 self._replace_artist_with_alias(
136 raw_pseudo_release, pseudo_release
137 )
138 self._add_custom_tags(official_release, pseudo_release)
139 return official_release
140 return PseudoAlbumInfo(
141 pseudo_release=_merge_pseudo_and_actual_album(
142 pseudo_release, official_release
143 ),
144 official_release=official_release,
145 )
146 return official_release
147
148 def _intercept_mb_release(self, data: Release) -> list[str]:
149 album_id = data["id"] if "id" in data else None
150 if self._has_desired_script(data) or not isinstance(album_id, str):
151 return []
152
153 return [
154 pr_id
155 for rel in data.get("release_relations", [])
156 if (pr_id := self._wanted_pseudo_release_id(album_id, rel))
157 is not None
158 ]
159
160 def _has_desired_script(
161 self, release: Release | ReleaseRelationRelease
162 ) -> bool:
163 if len(self._scripts) == 0:
164 return False
165 if script := release.get("text_representation", {}).get("script"):
166 return script in self._scripts
167 return False
168
169 def _wanted_pseudo_release_id(
170 self, album_id: str, relation: ReleaseRelation
171 ) -> str | None:
172 if (
173 len(self._scripts) == 0
174 or relation.get("type", "") != "transl-tracklisting"
175 or relation.get("direction", "") != "forward"
176 or "release" not in relation
177 ):
178 return None
179
180 release = relation["release"]
181 if "id" in release and self._has_desired_script(release):
182 self._log.debug(
183 "Adding pseudo-release {0} for main release {1}",
184 release["id"],
185 album_id,
186 )
187 return release["id"]
188 return None
189
190 def _replace_artist_with_alias(
191 self, raw_pseudo_release: Release, pseudo_release: AlbumInfo
192 ) -> None:
193 """Use the pseudo-release's language to search for artist
194 alias if the user hasn't configured import languages."""
195
196 if len(config["import"]["languages"].as_str_seq()) > 0:
197 return
198
199 lang = raw_pseudo_release.get("text_representation", {}).get("language")
200 artist_credits = raw_pseudo_release.get("release_group", {}).get(
201 "artist_credit", []
202 )
203 aliases = [
204 artist_credit.get("artist", {}).get("aliases", [])
205 for artist_credit in artist_credits
206 ]
207
208 if lang and len(lang) >= 2 and len(aliases) > 0:
209 locale = lang[0:2]
210 aliases_flattened = list(itertools.chain.from_iterable(aliases))
211 self._log.debug(
212 "Using locale '{0}' to search aliases {1}",
213 locale,
214 aliases_flattened,
215 )
216 if alias_dict := _preferred_alias(aliases_flattened, [locale]):
217 if alias := alias_dict.get("name"):
218 self._log.debug("Got alias '{0}'", alias)
219 pseudo_release.artist = alias
220 for track in pseudo_release.tracks:
221 track.artist = alias
222
223 def _add_custom_tags(
224 self, official_release: AlbumInfo, pseudo_release: AlbumInfo
225 ) -> None:
226 for tag_key, pseudo_key in (
227 self.config["album_custom_tags"].get().items()
228 ):
229 official_release[tag_key] = pseudo_release[pseudo_key]
230
231 track_custom_tags = self.config["track_custom_tags"].get().items()
232 for track, pseudo_track in zip(
233 official_release.tracks, pseudo_release.tracks
234 ):
235 for tag_key, pseudo_key in track_custom_tags:
236 track[tag_key] = pseudo_track[pseudo_key]
237
238 def _adjust_final_album_match(self, match: AlbumMatch) -> None:
239 album_info = match.info
240 if isinstance(album_info, PseudoAlbumInfo):
241 self._log.debug(
242 "Switching {0} to pseudo-release source for final proposal",
243 album_info.album_id,
244 )
245 album_info.use_pseudo_as_ref()
246 new_pairs, *_ = assign_items(match.items, album_info.tracks)
247 match.mapping = dict(new_pairs)
248
249 if album_info.data_source == self.data_source:
250 album_info.data_source = "MusicBrainz"
251
252 @override
253 def _extract_id(self, url: str) -> str | None:
254 return extract_release_id("MusicBrainz", url)
255
256
257 class PseudoAlbumInfo(AlbumInfo):
258 """This is a not-so-ugly hack.
259
260 We want the pseudo-release to result in a distance that is lower or equal to that of
261 the official release, otherwise it won't qualify as a good candidate. However, if
262 the input is in a script that's different from the pseudo-release (and we want to
263 translate/transliterate it in the library), it will receive unwanted penalties.
264
265 This class is essentially a view of the ``AlbumInfo`` of both official and
266 pseudo-releases, where it's possible to change the details that are exposed to other
267 parts of the auto-tagger, enabling a "fair" distance calculation based on the
268 current input's script but still preferring the translation/transliteration in the
269 final proposal.
270 """
271
272 def __init__(
273 self, pseudo_release: AlbumInfo, official_release: AlbumInfo, **kwargs
274 ) -> None:
275 super().__init__(pseudo_release.tracks, **kwargs)
276 self.__dict__["_pseudo_source"] = True
277 self.__dict__["_official_release"] = official_release
278 for k, v in pseudo_release.items():
279 if k not in kwargs:
280 self[k] = v
281
282 @cached_property
283 def raw_data(self) -> JSONDict:
284 # Info.raw_data does self.__class__(**self.copy()) which fails for
285 # PseudoAlbumInfo since __init__ requires pseudo_release and
286 # official_release. Construct a plain AlbumInfo instead.
287 return AlbumInfo(**self.copy()).raw_data
288
289 def get_official_release(self) -> AlbumInfo:
290 return self.__dict__["_official_release"]
291
292 def determine_best_ref(self, items: Sequence[Item]) -> str:
293 self.use_pseudo_as_ref()
294 pseudo_dist = self._compute_distance(items)
295
296 self.use_official_as_ref()
297 official_dist = self._compute_distance(items)
298
299 if official_dist < pseudo_dist:
300 self.use_official_as_ref()
301 return "official"
302 self.use_pseudo_as_ref()
303 return "pseudo"
304
305 def _compute_distance(self, items: Sequence[Item]) -> Distance:
306 mapping, _, _ = assign_items(items, self.tracks)
307 return distance(
308 Source.from_items(items).data,
309 self,
310 mapping,
311 len(items) - len(mapping),
312 )
313
314 def use_pseudo_as_ref(self) -> None:
315 self.__dict__["_pseudo_source"] = True
316
317 def use_official_as_ref(self) -> None:
318 self.__dict__["_pseudo_source"] = False
319
320 def __getattr__(self, attr: str) -> Any:
321 # ensure we don't duplicate an official release's id, always return pseudo's
322 if self.__dict__["_pseudo_source"] or attr == "album_id":
323 return super().__getattr__(attr)
324 return self.__dict__["_official_release"].__getattr__(attr)
325
326 def __deepcopy__(self, memo: dict[int, Any]) -> Self:
327 cls = self.__class__
328 result = cls.__new__(cls)
329
330 memo[id(self)] = result
331 result.__dict__.update(self.__dict__)
332 for k, v in self.items():
333 result[k] = deepcopy(v, memo)
334
335 return result