Debian Codegraph @

beetsplug/_utils/musicbrainz.py

raw
1 """Helpers for communicating with the MusicBrainz webservice.
2
3 Provides rate-limited HTTP session and convenience methods to fetch and
4 normalize API responses.
5
6 This module centralizes request handling and response shaping so callers can
7 work with consistently structured data without embedding HTTP or rate-limit
8 logic throughout the codebase.
9 """
10
11 from __future__ import annotations
12
13 import operator
14 import re
15 from dataclasses import dataclass, field
16 from functools import cached_property, singledispatchmethod, wraps
17 from http import HTTPStatus
18 from itertools import groupby, starmap
19 from typing import (
20 TYPE_CHECKING,
21 Any,
22 ClassVar,
23 Literal,
24 ParamSpec,
25 TypedDict,
26 TypeVar,
27 )
28
29 from requests_ratelimiter import LimiterMixin
30 from typing_extensions import NotRequired, Unpack
31
32 from beets import config, logging
33
34 from .requests import BeetsHTTPError, RequestHandler, TimeoutAndRetrySession
35
36 if TYPE_CHECKING:
37 from collections.abc import Callable
38
39 from requests import Response
40
41 from beets.metadata_plugins import IDResponse
42
43 from .._typing import JSONDict
44
45 log = logging.getLogger("beets")
46
47
48 LUCENE_SPECIAL_CHAR_PAT = re.compile(r'([-+&|!(){}[\]^"~*?:\\/])')
49
50 RELEASE_INCLUDES = [
51 "artists",
52 "media",
53 "recordings",
54 "release-groups",
55 "labels",
56 "artist-credits",
57 "aliases",
58 "recording-level-rels",
59 "work-rels",
60 "work-level-rels",
61 "artist-rels",
62 "isrcs",
63 "url-rels",
64 "release-rels",
65 "genres",
66 "tags",
67 ]
68
69 RECORDING_INCLUDES = [
70 "artists",
71 "aliases",
72 "isrcs",
73 "work-level-rels",
74 "artist-rels",
75 ]
76
77
78 class LimiterTimeoutSession(LimiterMixin, TimeoutAndRetrySession):
79 """HTTP session that enforces rate limits."""
80
81
82 Entity = Literal[
83 "area",
84 "artist",
85 "collection",
86 "event",
87 "genre",
88 "instrument",
89 "label",
90 "place",
91 "recording",
92 "release",
93 "release-group",
94 "series",
95 "work",
96 "url",
97 ]
98
99
100 class LookupKwargs(TypedDict, total=False):
101 includes: NotRequired[list[str]]
102
103
104 class PagingKwargs(TypedDict, total=False):
105 limit: NotRequired[int]
106 offset: NotRequired[int]
107
108
109 class SearchKwargs(PagingKwargs):
110 query: NotRequired[str]
111
112
113 class BrowseKwargs(LookupKwargs, PagingKwargs, total=False):
114 pass
115
116
117 class BrowseReleaseGroupsKwargs(BrowseKwargs, total=False):
118 artist: NotRequired[str]
119 collection: NotRequired[str]
120 release: NotRequired[str]
121 type: NotRequired[str]
122
123
124 class BrowseRecordingsKwargs(BrowseReleaseGroupsKwargs, total=False):
125 work: NotRequired[str]
126
127
128 P = ParamSpec("P")
129 R = TypeVar("R")
130
131
132 class _Period(TypedDict):
133 begin: str | None
134 end: str | None
135 ended: bool
136
137
138 class Alias(_Period):
139 locale: str | None
140 name: str
141 primary: bool | None
142 sort_name: str
143 type: (
144 Literal[
145 "Artist name",
146 "Label name",
147 "Legal name",
148 "Recording name",
149 "Release name",
150 "Release group name",
151 "Search hint",
152 ]
153 | None
154 )
155 type_id: str | None
156
157
158 class Artist(TypedDict):
159 country: str | None
160 disambiguation: str
161 id: str
162 name: str
163 sort_name: str
164 type: (
165 Literal["Character", "Choir", "Group", "Orchestra", "Other", "Person"]
166 | None
167 )
168 type_id: str | None
169 aliases: NotRequired[list[Alias]]
170 genres: NotRequired[list[Genre]]
171 tags: NotRequired[list[Tag]]
172
173
174 class ArtistCredit(TypedDict):
175 artist: Artist
176 joinphrase: str
177 name: str
178
179
180 class Genre(TypedDict):
181 count: int
182 disambiguation: str
183 id: str
184 name: str
185
186
187 class Tag(TypedDict):
188 count: int
189 name: str
190
191
192 ReleaseStatus = Literal[
193 "Bootleg",
194 "Cancelled",
195 "Expunged",
196 "Official",
197 "Promotion",
198 "Pseudo-Release",
199 "Withdrawn",
200 ]
201
202 ReleasePackaging = Literal[
203 "Book",
204 "Box",
205 "Cardboard/Paper Sleeve",
206 "Cassette Case",
207 "Clamshell Case",
208 "Digibook",
209 "Digifile",
210 "Digipak",
211 "Discbox Slider",
212 "Fatbox",
213 "Gatefold Cover",
214 "Jewel Case",
215 "None",
216 "Keep Case",
217 "Longbox",
218 "Metal Tin",
219 "Other",
220 "Plastic Sleeve",
221 "Slidepack",
222 "Slipcase",
223 "Snap Case",
224 "SnapPack",
225 "Slim Jewel Case",
226 "Super Jewel Box",
227 ]
228
229
230 ReleaseQuality = Literal["high", "low", "normal"]
231
232
233 class ReleaseGroup(TypedDict):
234 aliases: list[Alias]
235 artist_credit: list[ArtistCredit]
236 disambiguation: str
237 first_release_date: str
238 genres: list[Genre]
239 id: str
240 primary_type: Literal["Album", "Broadcast", "EP", "Other", "Single"] | None
241 primary_type_id: str | None
242 secondary_type_ids: list[str]
243 secondary_types: list[
244 Literal[
245 "Audiobook",
246 "Audio drama",
247 "Compilation",
248 "DJ-mix",
249 "Demo",
250 "Field recording",
251 "Interview",
252 "Live",
253 "Mixtape/Street",
254 "Remix",
255 "Soundtrack",
256 "Spokenword",
257 ]
258 ]
259 tags: list[Tag]
260 title: str
261
262
263 class CoverArtArchive(TypedDict):
264 artwork: bool
265 back: bool
266 count: int
267 darkened: bool
268 front: bool
269
270
271 class TextRepresentation(TypedDict):
272 language: str | None
273 script: str | None
274
275
276 class Area(TypedDict):
277 disambiguation: str
278 id: str
279 iso_3166_1_codes: list[str]
280 iso_3166_2_codes: NotRequired[list[str]]
281 name: str
282 sort_name: str
283 type: None
284 type_id: None
285
286
287 class ReleaseEvent(TypedDict):
288 area: Area | None
289 date: str
290
291
292 class Label(TypedDict):
293 aliases: list[Alias]
294 disambiguation: str
295 genres: list[Genre]
296 id: str
297 label_code: int | None
298 name: str
299 sort_name: str
300 tags: list[Tag]
301 type: (
302 Literal[
303 "Bootleg Production",
304 "Broadcaster",
305 "Distributor",
306 "Holding",
307 "Imprint",
308 "Manufacturer",
309 "Original Production",
310 "Publisher",
311 "Reissue Production",
312 "Rights Society",
313 ]
314 | None
315 )
316 type_id: str | None
317
318
319 class LabelInfo(TypedDict):
320 catalog_number: str | None
321 label: Label | None
322
323
324 class Url(TypedDict):
325 id: str
326 resource: str
327
328
329 class RelationBase(_Period):
330 attribute_ids: dict[str, str]
331 attribute_values: dict[str, str]
332 attributes: list[str]
333 direction: Literal["backward", "forward"]
334 source_credit: str
335 target_credit: str
336 type_id: str
337
338
339 ArtistRelationType = Literal[
340 "arranger",
341 "art direction",
342 "artwork",
343 "composer",
344 "conductor",
345 "copyright",
346 "design",
347 "design/illustration",
348 "editor",
349 "engineer",
350 "graphic design",
351 "illustration",
352 "instrument",
353 "instrument arranger",
354 "liner notes",
355 "lyricist",
356 "mastering",
357 "misc",
358 "mix",
359 "mix-DJ",
360 "performer",
361 "phonographic copyright",
362 "photography",
363 "previous attribution",
364 "producer",
365 "programming",
366 "recording",
367 "remixer",
368 "sound",
369 "vocal",
370 "vocal arranger",
371 "writer",
372 ]
373
374
375 class ArtistRelation(RelationBase):
376 type: ArtistRelationType
377 artist: Artist
378 attribute_credits: NotRequired[dict[str, str]]
379
380
381 class UrlRelation(RelationBase):
382 type: Literal[
383 "IMDB samples",
384 "IMDb",
385 "allmusic",
386 "amazon asin",
387 "discography entry",
388 "discogs",
389 "download for free",
390 "fanpage",
391 "free streaming",
392 "lyrics",
393 "other databases",
394 "purchase for download",
395 "purchase for mail-order",
396 "secondhandsongs",
397 "show notes",
398 "songfacts",
399 "streaming",
400 "wikidata",
401 "wikipedia",
402 ]
403 url: Url
404
405
406 class WorkRelation(RelationBase):
407 type: Literal[
408 "adaptation",
409 "arrangement",
410 "based on",
411 "included works",
412 "lyrical quotation",
413 "medley",
414 "musical quotation",
415 "named after work",
416 "orchestration",
417 "other version",
418 "parts",
419 "revision of",
420 ]
421 ordering_key: NotRequired[int]
422 work: Work
423
424
425 class Work(TypedDict):
426 attributes: list[str]
427 disambiguation: str
428 id: str
429 iswcs: list[str]
430 language: str | None
431 languages: list[str]
432 title: str
433 type: str | None
434 type_id: str | None
435 artist_relations: NotRequired[list[ArtistRelation]]
436 url_relations: NotRequired[list[UrlRelation]]
437 work_relations: NotRequired[list[WorkRelation]]
438
439
440 class Recording(TypedDict):
441 aliases: list[Alias]
442 artist_credit: list[ArtistCredit]
443 disambiguation: str
444 id: str
445 isrcs: list[str]
446 length: int | None
447 title: str
448 video: bool
449 artist_relations: NotRequired[list[ArtistRelation]]
450 first_release_date: NotRequired[str]
451 genres: NotRequired[list[Genre]]
452 tags: NotRequired[list[Tag]]
453 url_relations: NotRequired[list[UrlRelation]]
454 work_relations: NotRequired[list[WorkRelation]]
455
456
457 class RecordingWithReleases(Recording):
458 releases: list[BaseRelease]
459
460
461 class Track(TypedDict):
462 artist_credit: list[ArtistCredit]
463 id: str
464 length: int | None
465 number: str
466 position: int
467 recording: Recording
468 title: str
469
470
471 class Medium(TypedDict):
472 format: str | None
473 format_id: str | None
474 id: str
475 position: int
476 title: str
477 track_count: int
478 data_tracks: NotRequired[list[Track]]
479 pregap: NotRequired[Track]
480 track_offset: NotRequired[int]
481 tracks: NotRequired[list[Track]]
482
483
484 class ReleaseRelationRelease(TypedDict):
485 artist_credit: list[ArtistCredit]
486 barcode: str | None
487 disambiguation: str
488 id: str
489 media: list[Medium]
490 packaging: ReleasePackaging | None
491 packaging_id: str | None
492 quality: ReleaseQuality
493 release_group: ReleaseGroup | None
494 status: ReleaseStatus | None
495 status_id: str | None
496 text_representation: TextRepresentation
497 title: str
498 country: NotRequired[str | None]
499 date: NotRequired[str]
500 release_events: NotRequired[list[ReleaseEvent]]
501
502
503 class ReleaseRelation(RelationBase):
504 type: Literal["remaster", "transl-tracklisting", "replaced by"]
505 release: ReleaseRelationRelease
506
507
508 class BaseRelease(TypedDict):
509 artist_credit: list[ArtistCredit]
510 barcode: str | None
511 disambiguation: str
512 id: str
513 packaging: ReleasePackaging | None
514 packaging_id: str | None
515 status: ReleaseStatus | None
516 status_id: str | None
517 quality: ReleaseQuality
518 text_representation: TextRepresentation
519 country: NotRequired[str | None]
520 date: NotRequired[str]
521 title: str
522 release_events: NotRequired[list[ReleaseEvent]]
523
524
525 class Release(BaseRelease):
526 aliases: list[Alias]
527 asin: str | None
528 cover_art_archive: CoverArtArchive
529 genres: list[Genre]
530 label_info: list[LabelInfo]
531 media: list[Medium]
532 release_group: ReleaseGroup
533 tags: list[Tag]
534 artist_relations: NotRequired[list[ArtistRelation]]
535 release_relations: NotRequired[list[ReleaseRelation]]
536 url_relations: NotRequired[list[UrlRelation]]
537
538
539 def require_one_of(*keys: str) -> Callable[[Callable[P, R]], Callable[P, R]]:
540 required = frozenset(keys)
541
542 def deco(func: Callable[P, R]) -> Callable[P, R]:
543 @wraps(func)
544 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
545 # kwargs is a real dict at runtime; safe to inspect here
546 if not required & kwargs.keys():
547 required_str = ", ".join(sorted(required))
548 raise ValueError(
549 f"At least one of {required_str} filter is required"
550 )
551 return func(*args, **kwargs)
552
553 return wrapper
554
555 return deco
556
557
558 class UnauthorizedMBError(BeetsHTTPError):
559 """Raised when the MusicBrainz API returns a 401 Unauthorized response."""
560
561 STATUS = HTTPStatus.UNAUTHORIZED
562
563 def __init__(self, *args, message: str | None = None, **kwargs) -> None:
564 message = (
565 f"HTTP Error: {self.STATUS.value} {self.STATUS.phrase}."
566 " Check your musicbrainz.user and musicbrainz.pass configuration"
567 )
568 super().__init__(*args, message=message, **kwargs)
569
570
571 @dataclass
572 class MusicBrainzAPI(RequestHandler):
573 """High-level interface to the MusicBrainz WS/2 API.
574
575 Responsibilities:
576
577 - Configure the API host and request rate from application configuration.
578 - Offer helpers to fetch common entity types and to run searches.
579 - Normalize MusicBrainz responses so relation lists are grouped by target
580 type for easier downstream consumption.
581
582 Documentation: https://musicbrainz.org/doc/MusicBrainz_API
583 """
584
585 explicit_http_errors: ClassVar[list[type[BeetsHTTPError]]] = [
586 *RequestHandler.explicit_http_errors,
587 UnauthorizedMBError,
588 ]
589
590 api_host: str = field(init=False)
591 rate_limit: float = field(init=False)
592
593 def __post_init__(self) -> None:
594 mb_config = config["musicbrainz"]
595 mb_config.add(
596 {
597 "host": "musicbrainz.org",
598 "https": False,
599 "ratelimit": 1,
600 "ratelimit_interval": 1,
601 }
602 )
603
604 hostname = mb_config["host"].as_str()
605 if hostname == "musicbrainz.org":
606 self.api_host, self.rate_limit = "https://musicbrainz.org", 1.0
607 else:
608 https = mb_config["https"].get(bool)
609 self.api_host = f"http{'s' if https else ''}://{hostname}"
610 self.rate_limit = (
611 mb_config["ratelimit"].get(int)
612 / mb_config["ratelimit_interval"].as_number()
613 )
614
615 @cached_property
616 def api_root(self) -> str:
617 return f"{self.api_host}/ws/2"
618
619 def create_session(self) -> LimiterTimeoutSession:
620 return LimiterTimeoutSession(per_second=self.rate_limit)
621
622 def request(self, *args, **kwargs) -> Response:
623 """Ensure all requests specify JSON response format by default."""
624 kwargs.setdefault("params", {})
625 kwargs["params"]["fmt"] = "json"
626 return super().request(*args, **kwargs)
627
628 def get_json(self, *args, **kwargs) -> JSONDict:
629 """Fetch JSON data from MusicBrainz and normalize its field names."""
630 return self._normalize_data(super().get_json(*args, **kwargs))
631
632 def _get_resource(
633 self, resource: str, includes: list[str] | None = None, **kwargs
634 ) -> JSONDict:
635 """Retrieve and normalize data from the API resource endpoint.
636
637 If requested, includes are appended to the request. The response is
638 passed through a normalizer that groups relation entries by their
639 target type so that callers receive a consistently structured mapping.
640 """
641 if includes:
642 kwargs["inc"] = "+".join(includes)
643
644 return self.get_json(f"{self.api_root}/{resource}", params=kwargs)
645
646 def _lookup(
647 self, entity: Entity, id_: str, **kwargs: Unpack[LookupKwargs]
648 ) -> Any:
649 return self._get_resource(f"{entity}/{id_}", **kwargs)
650
651 def _browse(self, entity: Entity, **kwargs) -> list[Any]:
652 normalised_entity = entity.replace("-", "_")
653 return self._get_resource(entity, **kwargs).get(
654 f"{normalised_entity}s", []
655 )
656
657 @staticmethod
658 def format_search_term(field: str, term: str) -> str:
659 """Format a search term for the MusicBrainz API.
660
661 See https://lucene.apache.org/core/4_3_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html
662 """
663 if not (term := term.lower().strip()):
664 return ""
665
666 term = LUCENE_SPECIAL_CHAR_PAT.sub(r"\\\1", term)
667 if field:
668 term = f"{field}:({term})"
669
670 return term
671
672 def search(
673 self,
674 entity: Entity,
675 filters: dict[str, str],
676 **kwargs: Unpack[SearchKwargs],
677 ) -> list[IDResponse]:
678 """Search for MusicBrainz entities matching the given filters.
679
680 * Query is constructed by combining the provided filters using AND logic
681 * Each filter key-value pair is formatted as 'key:"value"' unless
682 - 'key' is empty, in which case only the value is used, '"value"'
683 - 'value' is empty, in which case the filter is ignored
684 * Values are lowercased and stripped of whitespace.
685 """
686 query = " ".join(
687 filter(None, starmap(self.format_search_term, filters.items()))
688 )
689 log.debug("Searching for MusicBrainz {}s with: {!r}", entity, query)
690 kwargs["query"] = query
691 normalised_entity = entity.replace("-", "_")
692 return self._get_resource(entity, **kwargs)[f"{normalised_entity}s"]
693
694 def get_release(self, id_: str, **kwargs: Unpack[LookupKwargs]) -> Release:
695 """Retrieve a release by its MusicBrainz ID."""
696 kwargs.setdefault("includes", RELEASE_INCLUDES)
697 return self._lookup("release", id_, **kwargs)
698
699 def get_recording(
700 self, id_: str, **kwargs: Unpack[LookupKwargs]
701 ) -> Recording:
702 """Retrieve a recording by its MusicBrainz ID."""
703 kwargs.setdefault("includes", RECORDING_INCLUDES)
704 return self._lookup("recording", id_, **kwargs)
705
706 def get_base_recording_with_releases(
707 self, id_: str, **kwargs: Unpack[LookupKwargs]
708 ) -> RecordingWithReleases:
709 """Retrieve a recording by its MusicBrainz ID."""
710 kwargs.setdefault("includes", [])
711 kwargs["includes"].append("releases")
712 return self._lookup("recording", id_, **kwargs)
713
714 def get_work(self, id_: str, **kwargs: Unpack[LookupKwargs]) -> Work:
715 """Retrieve a work by its MusicBrainz ID."""
716 return self._lookup("work", id_, **kwargs)
717
718 @require_one_of("artist", "collection", "release", "work")
719 def browse_recordings(
720 self, **kwargs: Unpack[BrowseRecordingsKwargs]
721 ) -> list[Recording]:
722 """Browse recordings related to the given entities.
723
724 At least one of artist, collection, release, or work must be provided.
725 """
726 return self._browse("recording", **kwargs)
727
728 @require_one_of("artist", "collection", "release")
729 def browse_release_groups(
730 self, **kwargs: Unpack[BrowseReleaseGroupsKwargs]
731 ) -> list[ReleaseGroup]:
732 """Browse release groups related to the given entities.
733
734 At least one of artist, collection, or release must be provided.
735 Optionally filter by type (e.g., "album|ep").
736 """
737 return self._browse("release-group", **kwargs)
738
739 @singledispatchmethod
740 @classmethod
741 def _normalize_data(cls, data: Any) -> Any:
742 """Normalize MusicBrainz relation structures into easier-to-use shapes.
743
744 This default handler is a no-op that returns non-container values
745 unchanged. Specialized handlers for sequences and mappings perform the
746 actual transformations described below.
747 """
748 return data
749
750 @_normalize_data.register(list)
751 @classmethod
752 def _(cls, data: list[Any]) -> list[Any]:
753 """Apply normalization to each element of a sequence recursively.
754
755 Sequences received from the MusicBrainz API may contain nested mappings
756 that require transformation. This handler maps the normalization step
757 over the sequence and preserves order.
758 """
759 return [cls._normalize_data(i) for i in data]
760
761 @_normalize_data.register(dict)
762 @classmethod
763 def _(cls, data: JSONDict) -> JSONDict:
764 """Transform mappings by regrouping relationships and normalizing keys.
765
766 When a mapping contains a generic 'relations' list, entries are grouped
767 by their 'target-type' and placed under keys like
768 '<target-type>_relations' with the 'target-type' field removed from each
769 entry. All other mapping keys have hyphens converted to underscores and
770 their values are normalized recursively to ensure a consistent shape
771 throughout the payload.
772 """
773 output_data = {}
774 for k, v in list(data.items()):
775 if k == "relations":
776 get_target_type = operator.methodcaller("get", "target-type")
777 for target_type, group in groupby(
778 sorted(v, key=get_target_type), get_target_type
779 ):
780 relations = [
781 {k: v for k, v in item.items() if k != "target-type"}
782 for item in group
783 ]
784 normalized_target_type = target_type.replace("-", "_")
785 output_data[f"{normalized_target_type}_relations"] = (
786 cls._normalize_data(relations)
787 )
788 else:
789 output_data[k.replace("-", "_")] = cls._normalize_data(v)
790 return output_data
791
792
793 class MusicBrainzAPIMixin:
794 """Mixin that provides a cached MusicBrainzAPI helper instance."""
795
796 @cached_property
797 def mb_api(self) -> MusicBrainzAPI:
798 return MusicBrainzAPI()