Debian Codegraph @

beetsplug/lyrics.py

raw
1 """Fetches, embeds, and displays lyrics."""
2
3 from __future__ import annotations
4
5 import itertools
6 import math
7 import re
8 import textwrap
9 from contextlib import contextmanager, suppress
10 from dataclasses import dataclass
11 from functools import cached_property, partial, total_ordering
12 from html import unescape
13 from itertools import filterfalse, groupby
14 from pathlib import Path
15 from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, Protocol
16 from urllib.parse import quote, quote_plus, urlencode, urlparse
17
18 import requests
19 from bs4 import BeautifulSoup
20 from confuse import Optional
21 from unidecode import unidecode
22
23 from beets import plugins, ui
24 from beets.autotag import string_dist
25 from beets.dbcore import types
26 from beets.dbcore.query import FalseQuery
27 from beets.library import Item, parse_query_string
28 from beets.util.config import sanitize_choices
29 from beets.util.lyrics import INSTRUMENTAL_LYRICS, Lyrics
30
31 from ._utils.requests import (
32 HTTPNotFoundError,
33 RequestHandler,
34 TimeoutAndRetrySession,
35 )
36
37 if TYPE_CHECKING:
38 from collections.abc import Callable, Iterable, Iterator
39
40 import confuse
41
42 from beets.importer import ImportTask
43 from beets.library import Library
44 from beets.logging import BeetsLogger as Logger
45
46 from ._typing import (
47 GeniusAPI,
48 GoogleCustomSearchAPI,
49 JSONDict,
50 LRCLibAPI,
51 TranslatorAPI,
52 )
53
54 HtmlTransformer = Callable[[str], str]
55
56
57 class LyricsCLIOpts(Protocol):
58 print: bool
59 rest_directory: str | None
60
61
62 class CaptchaError(requests.exceptions.HTTPError):
63 def __init__(self, *args, **kwargs) -> None:
64 super().__init__("Captcha is required", *args, **kwargs)
65
66
67 class GeniusHTTPError(requests.exceptions.HTTPError):
68 pass
69
70
71 # Utilities.
72
73
74 def search_pairs(item: Item) -> Iterable[tuple[str, list[str]]]:
75 """Yield a pairs of artists and titles to search for.
76
77 The first item in the pair is the name of the artist, the second
78 item is a list of song names.
79
80 In addition to the artist and title obtained from the `item` the
81 method tries to strip extra information like paranthesized suffixes
82 and featured artists from the strings and add them as candidates.
83 The artist sort name is added as a fallback candidate to help in
84 cases where artist name includes special characters or is in a
85 non-latin script.
86 The method also tries to split multiple titles separated with `/`.
87 """
88
89 def generate_alternatives(
90 string: str, patterns: Iterable[str]
91 ) -> list[str]:
92 """Generate string alternatives by extracting first matching group for
93 each given pattern.
94 """
95 alternatives = [string]
96 for pattern in patterns:
97 match = re.search(pattern, string, re.IGNORECASE)
98 if match:
99 alternatives.append(match.group(1))
100 return alternatives
101
102 title, artist, artist_sort = (
103 item.title.strip(),
104 item.artist.strip(),
105 item.artist_sort.strip(),
106 )
107 if not title or not artist:
108 return ()
109
110 patterns = [
111 # Remove any featuring artists from the artists name
112 rf"(.*?) {plugins.feat_tokens()}"
113 ]
114
115 # Skip various artists
116 artists = []
117 lower_artist = artist.lower()
118 if "various" not in lower_artist:
119 artists.extend(generate_alternatives(artist, patterns))
120 # Use the artist_sort as fallback only if it differs from artist to avoid
121 # repeated remote requests with the same search terms
122 artist_sort_lower = artist_sort.lower()
123 if (
124 artist_sort
125 and lower_artist != artist_sort_lower
126 and "various" not in artist_sort_lower
127 ):
128 artists.append(artist_sort)
129
130 patterns = [
131 # Remove a parenthesized suffix from a title string. Common
132 # examples include (live), (remix), and (acoustic).
133 r"(.+?)\s+[(].*[)]$",
134 # Remove any featuring artists from the title
135 rf"(.*?) {plugins.feat_tokens(for_artist=False)}",
136 # Remove part of title after colon ':' for songs with subtitles
137 r"(.+?)\s*:.*",
138 ]
139 titles = generate_alternatives(title, patterns)
140
141 # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe)
142 # and each of them.
143 multi_titles = []
144 for title in titles:
145 multi_titles.append([title])
146 if " / " in title:
147 multi_titles.append([x.strip() for x in title.split(" / ")])
148
149 return itertools.product(artists, multi_titles)
150
151
152 def slug(text: str) -> str:
153 """Make a URL-safe, human-readable version of the given text
154
155 This will do the following:
156
157 1. decode unicode characters into ASCII
158 2. shift everything to lowercase
159 3. strip whitespace
160 4. replace other non-word characters with dashes
161 5. strip extra dashes
162 """
163 return re.sub(r"\W+", "-", unidecode(text).lower().strip()).strip("-")
164
165
166 class LyricsRequestHandler(RequestHandler):
167 _log: Logger
168
169 def create_session(self) -> TimeoutAndRetrySession:
170 """Return a rate-limited session for lyrics HTTP requests."""
171 return TimeoutAndRetrySession()
172
173 def status_to_error(self, code: int) -> type[requests.HTTPError] | None:
174 if err := super().status_to_error(code):
175 return err
176
177 if 300 <= code < 400:
178 return CaptchaError
179
180 return None
181
182 def debug(self, message: str, *args) -> None:
183 """Log a debug message with the class name."""
184 self._log.debug(f"{self.__class__.__name__}: {message}", *args)
185
186 def info(self, message: str, *args) -> None:
187 """Log an info message with the class name."""
188 self._log.info(f"{self.__class__.__name__}: {message}", *args)
189
190 def warn(self, message: str, *args) -> None:
191 """Log warning with the class name."""
192 self._log.warning(f"{self.__class__.__name__}: {message}", *args)
193
194 @staticmethod
195 def format_url(url: str, params: JSONDict | None) -> str:
196 if not params:
197 return url
198
199 return f"{url}?{urlencode(params)}"
200
201 def get_text(
202 self, url: str, params: JSONDict | None = None, **kwargs
203 ) -> str:
204 """Return text / HTML data from the given URL.
205
206 Set the encoding to None to let requests handle it because some sites
207 set it incorrectly.
208 """
209 url = self.format_url(url, params)
210 self.debug("Fetching HTML from {}", url)
211 r = self.get(url, **kwargs)
212 r.encoding = None
213 return r.text
214
215 def get_json(
216 self, url: str, params: JSONDict | None = None, **kwargs
217 ) -> Any:
218 """Return JSON data from the given URL."""
219 url = self.format_url(url, params)
220 self.debug("Fetching JSON from {}", url)
221 return super().get_json(url, **kwargs)
222
223 def post_json(
224 self, url: str, params: JSONDict | None = None, **kwargs
225 ) -> Any:
226 """Send POST request and return JSON response."""
227 url = self.format_url(url, params)
228 self.debug("Posting JSON to {}", url)
229 return self.request("post", url, **kwargs).json()
230
231 @contextmanager
232 def handle_request(self) -> Iterator[None]:
233 try:
234 yield
235 except requests.JSONDecodeError:
236 self.warn("Could not decode response JSON data")
237 except requests.RequestException as exc:
238 self.warn("Request error: {}", exc)
239
240
241 class BackendClass(type):
242 @property
243 def name(cls) -> str:
244 """Return lowercase name of the backend class."""
245 return cls.__name__.lower()
246
247
248 class Backend(LyricsRequestHandler, metaclass=BackendClass):
249 config: confuse.Subview
250
251 def __init__(self, config: confuse.Subview, log: Logger) -> None:
252 self._log = log
253 self.config = config
254
255 def fetch(
256 self, artist: str, title: str, album: str, length: int
257 ) -> Lyrics | None:
258 """Return lyrics for a song, or ``None`` when no match is found."""
259 raise NotImplementedError
260
261
262 @dataclass
263 @total_ordering
264 class LRCLyrics:
265 """Hold LRCLib candidate data and ranking helpers for matching."""
266
267 #: Percentage tolerance for max duration difference between lyrics and item.
268 DURATION_DIFF_TOLERANCE = 0.05
269
270 target_duration: float
271 id: int
272 duration: float
273 instrumental: bool
274 plain: str | None
275 synced: str | None
276
277 def __le__(self, other: LRCLyrics) -> bool:
278 """Compare two lyrics items by their score."""
279 return self.dist < other.dist
280
281 @classmethod
282 def verify_synced_lyrics(
283 cls, duration: float, lyrics: str | None
284 ) -> str | None:
285 """Accept synced lyrics only when the final timestamp fits duration."""
286 if lyrics and (
287 m := Lyrics.LINE_PARTS_PAT.match(lyrics.splitlines()[-1])
288 ):
289 ts, _ = m.groups()
290 if ts:
291 mm, ss = map(float, ts.strip("[]").split(":"))
292 if 60 * mm + ss <= duration:
293 return lyrics
294
295 return None
296
297 @classmethod
298 def make(
299 cls, candidate: LRCLibAPI.Item, target_duration: float
300 ) -> LRCLyrics:
301 """Build a scored candidate from LRCLib payload data."""
302 duration = candidate["duration"] or 0.0
303 return cls(
304 target_duration,
305 candidate["id"],
306 duration,
307 candidate["instrumental"],
308 candidate["plainLyrics"],
309 cls.verify_synced_lyrics(
310 target_duration, candidate["syncedLyrics"]
311 ),
312 )
313
314 @cached_property
315 def duration_dist(self) -> float:
316 """Return the absolute difference between lyrics and target duration."""
317 return abs(self.duration - self.target_duration)
318
319 @cached_property
320 def has_text(self) -> bool:
321 """Return whether this candidate can supply any lyrics.
322
323 LRCLib entries carry track metadata independently of the lyrics
324 themselves, so a record may have neither ``plainLyrics`` nor
325 ``syncedLyrics`` while ``instrumental`` is still False: the lyrics
326 simply have not been contributed. Such a candidate has nothing to
327 offer, in contrast to an instrumental track, for which "no lyrics" is
328 itself the answer.
329 """
330 return bool(self.instrumental or self.plain or self.synced)
331
332 @cached_property
333 def is_valid(self) -> bool:
334 """Return whether the lyrics item is valid.
335 Lyrics duration must be within the tolerance defined by
336 :attr:`DURATION_DIFF_TOLERANCE`, and the item must be able to supply
337 lyrics at all.
338 """
339 return (
340 self.has_text
341 and self.duration_dist
342 <= self.target_duration * self.DURATION_DIFF_TOLERANCE
343 )
344
345 @cached_property
346 def dist(self) -> tuple[bool, float]:
347 """Distance/score of the given lyrics item.
348
349 Return a tuple with the following values:
350 1. Absolute difference between lyrics and target duration
351 2. Boolean telling whether synced lyrics are available.
352
353 Best lyrics match is the one that has the closest duration to
354 ``target_duration`` and has synced lyrics available.
355 """
356 return not self.synced, self.duration_dist
357
358 @staticmethod
359 def _format_synced(synced: str) -> str:
360 """Return synced lyrics with surrounding whitespace trimmed."""
361 return "\n".join(map(str.strip, synced.splitlines()))
362
363 @staticmethod
364 def _synced_as_plain(synced: str) -> str:
365 """Return synced lyrics as plain text, without the LRC timestamps."""
366 return "\n".join(
367 m[2]
368 for line in synced.splitlines()
369 if (m := Lyrics.LINE_PARTS_PAT.match(line))
370 )
371
372 def get_text(self, want_synced: bool) -> str:
373 """Return the preferred text form for this candidate."""
374 if self.instrumental:
375 return INSTRUMENTAL_LYRICS
376
377 if want_synced and self.synced:
378 return self._format_synced(self.synced)
379
380 if self.plain:
381 return self.plain
382
383 # 'plainLyrics' may be null while synced lyrics are available. Use the
384 # latter as the plain text, dropping the timestamps.
385 if self.synced:
386 return self._synced_as_plain(self.synced)
387
388 # Unreachable for a candidate that passed :attr:`is_valid`, which
389 # requires some lyrics to be available. Kept so that this method always
390 # returns a string.
391 return ""
392
393
394 class LRCLib(Backend):
395 """Fetch lyrics from the LRCLib API."""
396
397 BASE_URL = "https://lrclib.net/api"
398 GET_URL = f"{BASE_URL}/get"
399 SEARCH_URL = f"{BASE_URL}/search"
400
401 def fetch_candidates(
402 self, artist: str, title: str, album: str, length: int
403 ) -> Iterator[list[LRCLibAPI.Item]]:
404 """Yield lyrics candidates for the given song data.
405
406 I found that the ``/get`` endpoint sometimes returns inaccurate or
407 unsynced lyrics, while ``search`` yields more suitable candidates.
408 Therefore, we prioritize the latter and rank the results using our own
409 algorithm. If the search does not give suitable lyrics, we fall back to
410 the ``/get`` endpoint.
411
412 Return an iterator over lists of candidates.
413 """
414 base_params = {"artist_name": artist, "track_name": title}
415 get_params = {**base_params, "duration": length}
416 if album:
417 get_params["album_name"] = album
418
419 yield self.get_json(self.SEARCH_URL, params=base_params)
420
421 with suppress(HTTPNotFoundError):
422 yield [self.get_json(self.GET_URL, params=get_params)]
423
424 @classmethod
425 def pick_best_match(cls, lyrics: Iterable[LRCLyrics]) -> LRCLyrics | None:
426 """Return best matching lyrics item from the given list."""
427 return min((li for li in lyrics if li.is_valid), default=None)
428
429 def fetch(
430 self, artist: str, title: str, album: str, length: int
431 ) -> Lyrics | None:
432 """Fetch lyrics text for the given song data."""
433 evaluate_item = partial(LRCLyrics.make, target_duration=length)
434
435 for group in self.fetch_candidates(artist, title, album, length):
436 candidates = [evaluate_item(item) for item in group]
437 if item := self.pick_best_match(candidates):
438 lyrics = item.get_text(self.config["synced"].get(bool))
439 return Lyrics(
440 lyrics, self.__class__.name, f"{self.GET_URL}/{item.id}"
441 )
442
443 return None
444
445
446 class MusiXmatch(Backend):
447 URL_TEMPLATE = "https://www.musixmatch.com/lyrics/{}/{}"
448
449 REPLACEMENTS: ClassVar[dict[str, str]] = {
450 "['\u2018\u2019]": "-",
451 r"\s+": "-",
452 "<": "Less_Than",
453 ">": "Greater_Than",
454 "#": "Number_",
455 r"[\[\{]": "(",
456 r"[\]\}]": ")",
457 }
458
459 @classmethod
460 def encode(cls, text: str) -> str:
461 for old, new in cls.REPLACEMENTS.items():
462 text = re.sub(old, new, text)
463
464 return quote(unidecode(text))
465
466 @classmethod
467 def build_url(cls, *args: str) -> str:
468 return cls.URL_TEMPLATE.format(*map(cls.encode, args))
469
470 def fetch(self, artist: str, title: str, *_) -> Lyrics | None:
471 url = self.build_url(artist, title)
472
473 html = self.get_text(url)
474 if "We detected that your IP is blocked" in html:
475 self.warn("Failed: Blocked IP address")
476 return None
477 html_parts = html.split('<p class="mxm-lyrics__content')
478 # Sometimes lyrics come in 2 or more parts
479 lyrics_parts = []
480 for html_part in html_parts:
481 lyrics_parts.append(re.sub(r"^[^>]+>|</p>.*", "", html_part))
482 lyrics = "\n".join(lyrics_parts)
483 lyrics = lyrics.strip(',"').replace("\\n", "\n")
484 # another odd case: sometimes only that string remains, for
485 # missing songs. this seems to happen after being blocked
486 # above, when filling in the CAPTCHA.
487 if "Instant lyrics for all your music." in lyrics:
488 return None
489 # sometimes there are non-existent lyrics with some content
490 if "Lyrics | Musixmatch" in lyrics:
491 return None
492 return Lyrics(lyrics, self.__class__.name, url)
493
494
495 def apply_transforms(html: str, methods: Iterable[HtmlTransformer]) -> str:
496 for method in methods:
497 html = method(html)
498
499 return html
500
501
502 class Html:
503 collapse_space = partial(re.compile(r"(^| ) +", re.M).sub, r"\1")
504 expand_br = partial(re.compile(r"\s*<br[^>]*>\s*", re.I).sub, "\n")
505 #: two newlines between paragraphs on the same line (musica, letras.mus.br)
506 merge_blocks = partial(
507 re.compile(r"(?<!>)(</p><p[^>]*>)+", re.S).sub, "\n\n"
508 )
509 #: a single new line between paragraphs on separate lines
510 #: (paroles.net, sweetslyrics.com, lacoccinelle.net)
511 merge_lines = partial(re.compile(r"</p>\s+<p[^>]*>(?!___)").sub, "\n")
512 #: remove empty divs (lacoccinelle.net)
513 remove_empty_tags = partial(
514 re.compile(r"(<(div|span)[^>]*>\s*</\2>)").sub, ""
515 )
516 #: remove Google Ads tags (musica.com)
517 remove_aside = partial(re.compile("<aside .+?</aside>").sub, "")
518 #: remove inline script blocks that split lyrics paragraphs
519 remove_scripts = partial(
520 re.compile(r"<script\b[^>]*>.*?</script\b[^>]*>", re.I | re.S).sub, ""
521 )
522 #: remove comments that split lyrics paragraphs
523 remove_comments = partial(re.compile(r"<!--.*?-->", re.S).sub, "")
524 #: remove title-only paragraph from the musica.com lyrics block
525 remove_musica_title = partial(
526 re.compile(
527 r"(<div\s+id=['\"]letra['\"][^>]*>.*?)"
528 r"<p>\s*<strong>[^<]+</strong>\s*</p>",
529 re.I | re.S,
530 ).sub,
531 r"\1",
532 )
533 #: remove non-lyrics explanation blocks (musica.com)
534 remove_significado = partial(
535 re.compile(r"<div\s+id=['\"]significado['\"][^>]*>.*", re.I | re.S).sub,
536 "",
537 )
538 #: remove adslot-Content_1 div from the lyrics text (paroles.net)
539 remove_adslot = partial(
540 re.compile(r"\n</div>[^\n]+-- Content_\d+ --.*?\n<div>", re.S).sub, "\n"
541 )
542 #: remove text formatting (azlyrics.com, lacocinelle.net)
543 remove_formatting = partial(
544 re.compile(r" *</?(i|em|pre|strong)[^>]*>").sub, ""
545 )
546
547 @classmethod
548 def normalize_space(cls, text: str) -> str:
549 text = unescape(text).replace("\r", "").replace("\xa0", " ")
550 return apply_transforms(text, [cls.collapse_space, cls.expand_br])
551
552 @classmethod
553 def remove_ads(cls, text: str) -> str:
554 return apply_transforms(text, [cls.remove_aside, cls.remove_adslot])
555
556 @classmethod
557 def merge_paragraphs(cls, text: str) -> str:
558 return apply_transforms(
559 text, [cls.remove_empty_tags, cls.merge_lines, cls.merge_blocks]
560 )
561
562
563 class SoupMixin:
564 @classmethod
565 def pre_process_html(cls, html: str) -> str:
566 """Pre-process the HTML content before scraping."""
567 return apply_transforms(
568 html,
569 [
570 Html.normalize_space,
571 Html.remove_significado,
572 Html.remove_scripts,
573 Html.remove_musica_title,
574 ],
575 )
576
577 @classmethod
578 def get_soup(cls, html: str) -> BeautifulSoup:
579 return BeautifulSoup(cls.pre_process_html(html), "html.parser")
580
581
582 class SearchResult(NamedTuple):
583 artist: str
584 title: str
585 url: str
586
587 @property
588 def source(self) -> str:
589 return urlparse(self.url).netloc
590
591
592 class SearchBackend(SoupMixin, Backend):
593 @cached_property
594 def dist_thresh(self) -> float:
595 return self.config["dist_thresh"].get(float)
596
597 def check_match(
598 self, target_artist: str, target_title: str, result: SearchResult
599 ) -> bool:
600 """Check if the given search result is a 'good enough' match."""
601 max_dist = max(
602 string_dist(target_artist, result.artist),
603 string_dist(target_title, result.title),
604 )
605
606 if (max_dist := round(max_dist, 2)) <= self.dist_thresh:
607 return True
608
609 if math.isclose(max_dist, self.dist_thresh, abs_tol=0.4):
610 # log out the candidate that did not make it but was close.
611 # This may show a matching candidate with some noise in the name
612 self.debug(
613 "({0.artist}, {0.title}) does not match ({1}, {2}) but dist"
614 " was close: {3:.2f}",
615 result,
616 target_artist,
617 target_title,
618 max_dist,
619 )
620
621 return False
622
623 def search(self, artist: str, title: str) -> Iterable[SearchResult]:
624 """Search for the given query and yield search results."""
625 raise NotImplementedError
626
627 def get_results(self, artist: str, title: str) -> Iterable[SearchResult]:
628 check_match = partial(self.check_match, artist, title)
629 for candidate in self.search(artist, title):
630 if check_match(candidate):
631 yield candidate
632
633 def fetch(self, artist: str, title: str, *_) -> Lyrics | None:
634 """Fetch lyrics for the given artist and title."""
635 for result in self.get_results(artist, title):
636 if (html := self.get_text(result.url)) and (
637 lyrics := self.scrape(html)
638 ):
639 return Lyrics(lyrics, self.__class__.name, result.url)
640
641 return None
642
643 @classmethod
644 def scrape(cls, html: str) -> str | None:
645 """Scrape the lyrics from the given HTML."""
646 raise NotImplementedError
647
648
649 class Genius(SearchBackend):
650 """Fetch lyrics from Genius via genius-api.
651
652 Because genius doesn't allow accessing lyrics via the api, we first query
653 the api for a url matching our artist & title, then scrape the HTML text
654 for the JSON data containing the lyrics.
655 """
656
657 SEARCH_URL = "https://api.genius.com/search"
658 LYRICS_IN_JSON_RE = re.compile(r'(?<=.\\"html\\":\\").*?(?=(?<!\\)\\")')
659 remove_backslash = partial(re.compile(r"\\(?=[^\\])").sub, "")
660
661 @cached_property
662 def headers(self) -> dict[str, str]:
663 return {"Authorization": f"Bearer {self.config['genius_api_key']}"}
664
665 def get_json(self, *args, **kwargs) -> GeniusAPI.Search:
666 response: GeniusAPI.Response = super().get_json(*args, **kwargs)
667 if "response" in response:
668 return response # type: ignore[return-value]
669
670 meta = response["meta"]
671 raise GeniusHTTPError(f"{meta['message']} Status: {meta['status']}")
672
673 def search(self, artist: str, title: str) -> Iterable[SearchResult]:
674 search_data = self.get_json(
675 self.SEARCH_URL,
676 params={"q": f"{artist} {title}"},
677 headers=self.headers,
678 )
679 for r in (hit["result"] for hit in search_data["response"]["hits"]):
680 yield SearchResult(r["artist_names"], r["title"], r["url"])
681
682 @classmethod
683 def scrape(cls, html: str) -> str | None:
684 if m := cls.LYRICS_IN_JSON_RE.search(html):
685 html_text = cls.remove_backslash(m[0]).replace(r"\n", "\n")
686 return cls.get_soup(html_text).get_text().strip()
687
688 return None
689
690
691 class Tekstowo(SearchBackend):
692 """Fetch lyrics from Tekstowo.pl."""
693
694 BASE_URL = "https://www.tekstowo.pl"
695 SEARCH_URL = f"{BASE_URL}/szukaj,{{}}.html"
696
697 def build_url(self, artist: str, title: str) -> str:
698 artistitle = f"{artist.title()} {title.title()}"
699
700 return self.SEARCH_URL.format(quote_plus(unidecode(artistitle)))
701
702 def search(self, artist: str, title: str) -> Iterable[SearchResult]:
703 if html := self.get_text(self.build_url(title, artist)):
704 soup = self.get_soup(html)
705 for tag in soup.select("div[class=flex-group] > a[title*=' - ']"):
706 artist, title = str(tag["title"]).split(" - ", 1)
707 yield SearchResult(
708 artist, title, f"{self.BASE_URL}{tag['href']}"
709 )
710
711 return None
712
713 @classmethod
714 def scrape(cls, html: str) -> str | None:
715 soup = cls.get_soup(html)
716
717 if lyrics_div := soup.select_one("div.song-text > div.inner-text"):
718 return lyrics_div.get_text()
719
720 return None
721
722
723 class Google(SearchBackend):
724 """Fetch lyrics from Google search results."""
725
726 SEARCH_URL = "https://www.googleapis.com/customsearch/v1"
727
728 #: Exclude some letras.mus.br pages which do not contain lyrics.
729 EXCLUDE_PAGES: ClassVar[list[str]] = [
730 "significado.html",
731 "traduccion.html",
732 "traducao.html",
733 "significados.html",
734 ]
735
736 #: Regular expression to match noise in the URL title.
737 URL_TITLE_NOISE_RE = re.compile(
738 r"""
739 \b
740 (
741 paroles(\ et\ traduction|\ de\ chanson)?
742 | letras?(\ de)?
743 | liedtexte
744 | dainų\ žodžiai
745 | original\ song\ full\ text\.
746 | official
747 | 20[12]\d\ version
748 | (absolute\ |az)?lyrics(\ complete)?
749 | www\S+
750 | \S+\.(com|net|mus\.br)
751 )
752 ([^\w.]|$)
753 """,
754 re.IGNORECASE | re.VERBOSE,
755 )
756 #: Split cleaned up URL title into artist and title parts.
757 URL_TITLE_PARTS_RE = re.compile(r" +(?:[ :|-]+|par|by) +|, ")
758
759 SOURCE_DIST_FACTOR: ClassVar[dict[str, float]] = {
760 "www.azlyrics.com": 0.5,
761 "www.songlyrics.com": 0.6,
762 }
763
764 ignored_domains: ClassVar[set[str]] = set()
765
766 @classmethod
767 def pre_process_html(cls, html: str) -> str:
768 """Pre-process the HTML content before scraping."""
769 return apply_transforms(
770 html,
771 [
772 super().pre_process_html,
773 Html.remove_ads,
774 Html.remove_comments,
775 Html.merge_paragraphs,
776 Html.remove_formatting,
777 ],
778 )
779
780 def get_text(self, *args, **kwargs) -> str:
781 """Handle an error so that we can continue with the next URL."""
782 kwargs.setdefault("allow_redirects", False)
783 with self.handle_request():
784 try:
785 return super().get_text(*args, **kwargs)
786 except CaptchaError:
787 self.ignored_domains.add(urlparse(args[0]).netloc)
788 raise
789
790 @staticmethod
791 def get_part_dist(artist: str, title: str, part: str) -> float:
792 """Return the distance between the given part and the artist and title.
793
794 A number between -1 and 1 is returned, where -1 means the part is
795 closer to the artist and 1 means it is closer to the title.
796 """
797 return string_dist(artist, part) - string_dist(title, part)
798
799 @classmethod
800 def make_search_result(
801 cls, artist: str, title: str, item: GoogleCustomSearchAPI.Item
802 ) -> SearchResult:
803 """Parse artist and title from the URL title and return a search result."""
804 url_title = (
805 # get full title from metatags if available
806 item.get("pagemap", {}).get("metatags", [{}])[0].get("og:title")
807 # default to the dispolay title
808 or item["title"]
809 )
810 clean_title = cls.URL_TITLE_NOISE_RE.sub("", url_title).strip(" .-|")
811 # split it into parts which may be part of the artist or the title
812 # `dict.fromkeys` removes duplicates keeping the order
813 parts = list(dict.fromkeys(cls.URL_TITLE_PARTS_RE.split(clean_title)))
814
815 if len(parts) == 1:
816 part = parts[0]
817 if m := re.search(rf"(?i)\W*({re.escape(title)})\W*", part):
818 # artist and title may not have a separator
819 result_title = m[1]
820 result_artist = part.replace(m[0], "")
821 else:
822 # assume that this is the title
823 result_artist, result_title = "", parts[0]
824 else:
825 # sort parts by their similarity to the artist
826 result_artist = min(parts, key=lambda p: string_dist(artist, p))
827 result_title = min(parts, key=lambda p: string_dist(title, p))
828
829 return SearchResult(result_artist, result_title, item["link"])
830
831 def search(self, artist: str, title: str) -> Iterable[SearchResult]:
832 params = {
833 "key": self.config["google_API_key"].as_str(),
834 "cx": self.config["google_engine_ID"].as_str(),
835 "q": f"{artist} {title}",
836 "siteSearch": "www.musixmatch.com",
837 "siteSearchFilter": "e",
838 "excludeTerms": ", ".join(self.EXCLUDE_PAGES),
839 }
840
841 data: GoogleCustomSearchAPI.Response = self.get_json(
842 self.SEARCH_URL, params=params
843 )
844 for item in data.get("items", []):
845 yield self.make_search_result(artist, title, item)
846
847 def get_results(self, *args) -> Iterable[SearchResult]:
848 """Try results from preferred sources first."""
849 for result in sorted(
850 super().get_results(*args),
851 key=lambda r: self.SOURCE_DIST_FACTOR.get(r.source, 1),
852 ):
853 if result.source not in self.ignored_domains:
854 yield result
855
856 @classmethod
857 def scrape(cls, html: str) -> str | None:
858 # Get the longest text element (if any).
859 if strings := sorted(cls.get_soup(html).stripped_strings, key=len):
860 return strings[-1]
861
862 return None
863
864
865 @dataclass
866 class Translator(LyricsRequestHandler):
867 """Translate lyrics text while preserving existing structured metadata."""
868
869 TRANSLATE_URL = "https://api.cognitive.microsofttranslator.com/translate"
870 SEPARATOR = " | "
871
872 _log: Logger
873 api_key: str
874 to_language: str
875 from_languages: list[str]
876
877 @classmethod
878 def from_config(
879 cls,
880 log: Logger,
881 api_key: str,
882 to_language: str,
883 from_languages: list[str] | None = None,
884 ) -> Translator:
885 """Construct a translator with normalized language configuration."""
886 return cls(
887 log,
888 api_key,
889 to_language.upper(),
890 [x.upper() for x in from_languages or []],
891 )
892
893 def get_translations(self, texts: Iterable[str]) -> list[str]:
894 """Return translations for the given texts.
895
896 To reduce the translation 'cost', we translate unique texts, and then
897 map the translations back to the original texts.
898 """
899 unique_texts = list(dict.fromkeys(texts))
900 text = self.SEPARATOR.join(unique_texts)
901 data: list[TranslatorAPI.Response] = self.post_json(
902 self.TRANSLATE_URL,
903 headers={"Ocp-Apim-Subscription-Key": self.api_key},
904 json=[{"text": text}],
905 params={"api-version": "3.0", "to": self.to_language},
906 )
907
908 translated_text = data[0]["translations"][0]["text"]
909 translations = translated_text.split(self.SEPARATOR)
910 trans_by_text = dict(zip(unique_texts, translations))
911 return [trans_by_text.get(t, "") for t in texts]
912
913 def translate(self, lyrics: Lyrics, old_lyrics: Lyrics) -> Lyrics:
914 """Translate the given lyrics to the target language.
915
916 Check old lyrics for existing translations and return them if their
917 original text matches the new lyrics. This is to avoid translating
918 the same lyrics multiple times.
919
920 If the lyrics are already in the target language or not in any of
921 of the source languages (if configured), they are returned as is.
922 """
923 if (
924 lyrics.original_text
925 ) == old_lyrics.original_text and old_lyrics.translated:
926 self.info("🔵 Translations already exist")
927 return old_lyrics
928
929 if (lyrics_language := lyrics.language) == self.to_language:
930 self.info(
931 "🔵 Lyrics are already in the target language {.to_language}",
932 self,
933 )
934 elif (
935 from_lang_config := self.from_languages
936 ) and lyrics_language not in from_lang_config:
937 self.info(
938 "🔵 Configuration {} does not permit translating from {}",
939 from_lang_config,
940 lyrics_language,
941 )
942 else:
943 with self.handle_request():
944 lyrics.translations = self.get_translations(lyrics.text_lines)
945 lyrics.translation_language = self.to_language
946 self.info("🟢 Translated lyrics to {.to_language}", self)
947
948 return lyrics
949
950
951 class LRCMux(Backend):
952 """Fetch lyrics from the lrcmux API."""
953
954 DEFAULT_URL = "https://api.lrcmux.dev"
955
956 @cached_property
957 def url(self) -> str:
958 base = self.config["lrcmux"]["url"].get(str)
959 return f"{base.rstrip('/')}/get"
960
961 def fetch(
962 self, artist: str, title: str, album: str, length: int
963 ) -> Lyrics | None:
964 synced = self.config["synced"].get(bool)
965 sources = self.config["lrcmux"]["sources"].as_str_seq()
966
967 params: JSONDict = {
968 "artist": artist,
969 "title": title,
970 "duration": int(length),
971 "format": "lrc" if synced else "txt",
972 "level": "line" if synced else "none",
973 }
974 if album:
975 params["album"] = album
976 if sources:
977 params["sources"] = ",".join(sources)
978
979 full_url = self.format_url(self.url, params)
980 with suppress(HTTPNotFoundError):
981 if text := self.get_text(self.url, params=params).strip():
982 return Lyrics(text, self.__class__.name, full_url)
983
984 return None
985
986
987 @dataclass
988 class RestFiles:
989 # The content for the base index.rst generated in ReST mode.
990 REST_INDEX_TEMPLATE = textwrap.dedent("""
991 Lyrics
992 ======
993
994 * :ref:`Song index <genindex>`
995 * :ref:`search`
996
997 Artist index:
998
999 .. toctree::
1000 :maxdepth: 1
1001 :glob:
1002
1003 artists/*
1004 """).strip()
1005
1006 # The content for the base conf.py generated.
1007 REST_CONF_TEMPLATE = textwrap.dedent("""
1008 master_doc = "index"
1009 project = "Lyrics"
1010 copyright = "none"
1011 author = "Various Authors"
1012 latex_documents = [
1013 (master_doc, "Lyrics.tex", project, author, "manual"),
1014 ]
1015 epub_exclude_files = ["search.html"]
1016 epub_tocdepth = 1
1017 epub_tocdup = False
1018 """).strip()
1019
1020 directory: Path
1021
1022 @cached_property
1023 def artists_dir(self) -> Path:
1024 dir_ = self.directory / "artists"
1025 dir_.mkdir(parents=True, exist_ok=True)
1026 return dir_
1027
1028 def write_indexes(self) -> None:
1029 """Write conf.py and index.rst files necessary for Sphinx
1030
1031 We write minimal configurations that are necessary for Sphinx
1032 to operate. We do not overwrite existing files so that
1033 customizations are respected."""
1034 index_file = self.directory / "index.rst"
1035 if not index_file.exists():
1036 index_file.write_text(self.REST_INDEX_TEMPLATE)
1037 conf_file = self.directory / "conf.py"
1038 if not conf_file.exists():
1039 conf_file.write_text(self.REST_CONF_TEMPLATE)
1040
1041 def write_artist(self, artist: str, items: Iterable[Item]) -> None:
1042 parts = [f"{artist}\n{'=' * len(artist)}", ".. contents::\n :local:"]
1043 for album, items in groupby(items, key=lambda i: i.album):
1044 parts.append(f"{album}\n{'-' * len(album)}")
1045 parts.extend(
1046 part
1047 for i in items
1048 if (title := f":index:`{i.title.strip()}`")
1049 for part in (
1050 f"{title}\n{'~' * len(title)}",
1051 textwrap.indent(i.lyrics, "| "),
1052 )
1053 )
1054 file = self.artists_dir / f"{slug(artist)}.rst"
1055 file.write_text("\n\n".join(parts).strip())
1056
1057 def write(self, items: list[Item]) -> None:
1058 self.directory.mkdir(exist_ok=True, parents=True)
1059 self.write_indexes()
1060
1061 items.sort(key=lambda i: i.albumartist)
1062 for artist, artist_items in groupby(items, key=lambda i: i.albumartist):
1063 self.write_artist(artist.strip(), artist_items)
1064
1065 d = self.directory
1066 text = f"""
1067 ReST files generated. to build, use one of:
1068 sphinx-build -b html {d} {d / "html"}
1069 sphinx-build -b epub {d} {d / "epub"}
1070 sphinx-build -b latex {d} {d / "latex"} && make -C {d / "latex"} all-pdf
1071 """
1072 ui.print_(textwrap.dedent(text))
1073
1074
1075 BACKEND_BY_NAME = {
1076 b.name: b for b in [LRCLib, Google, Genius, Tekstowo, MusiXmatch, LRCMux]
1077 }
1078
1079
1080 class LyricsPlugin(LyricsRequestHandler, plugins.BeetsPlugin):
1081 item_types: ClassVar[dict[str, types.Type]] = {
1082 "lyrics_url": types.STRING,
1083 "lyrics_instrumental": types.BOOLEAN,
1084 "lyrics_backend": types.STRING,
1085 "lyrics_language": types.STRING,
1086 "lyrics_translation_language": types.STRING,
1087 }
1088
1089 @cached_property
1090 def backends(self) -> list[Backend]:
1091 user_sources = self.config["sources"].as_str_seq()
1092
1093 chosen = sanitize_choices(user_sources, BACKEND_BY_NAME)
1094 if "google" in chosen and not self.config["google_API_key"].get():
1095 self.warn("Disabling Google source: no API key configured.")
1096 chosen.remove("google")
1097
1098 return [BACKEND_BY_NAME[c](self.config, self._log) for c in chosen]
1099
1100 @cached_property
1101 def translator(self) -> Translator | None:
1102 config = self.config["translate"]
1103 if config["api_key"].get() and config["to_language"].get():
1104 return Translator.from_config(self._log, **config.flatten())
1105 return None
1106
1107 def __init__(self) -> None:
1108 super().__init__()
1109 self.config.add(
1110 {
1111 "auto": True,
1112 "auto_ignore": None,
1113 "translate": {
1114 "api_key": None,
1115 "from_languages": [],
1116 "to_language": None,
1117 },
1118 "dist_thresh": 0.11,
1119 "google_API_key": None,
1120 "google_engine_ID": "009217259823014548361:lndtuqkycfu",
1121 "genius_api_key": (
1122 "Ryq93pUGm8bM6eUWwD_M3NOFFDAtp2yEE7W"
1123 "76V-uFL5jks5dNvcGCdarqFjDhP9c"
1124 ),
1125 "lrcmux": {"url": LRCMux.DEFAULT_URL, "sources": []},
1126 "fallback": None,
1127 "force": False,
1128 "keep_synced": False,
1129 "local": False,
1130 "print": False,
1131 "rest_directory": None,
1132 "synced": False,
1133 # Musixmatch and Tekstowo are disabled by default as they
1134 # currently block requests with the beets user agent.
1135 "sources": [
1136 n
1137 for n in BACKEND_BY_NAME
1138 if n not in {"musixmatch", "tekstowo"}
1139 ],
1140 }
1141 )
1142 self.config["translate"]["api_key"].redact = True
1143 self.config["google_API_key"].redact = True
1144 self.config["google_engine_ID"].redact = True
1145 self.config["genius_api_key"].redact = True
1146
1147 if self.config["auto"]:
1148 self.import_stages = [self.imported]
1149
1150 def commands(self) -> list[ui.Subcommand]:
1151 cmd = ui.Subcommand("lyrics", help="fetch song lyrics")
1152 cmd.parser.add_option(
1153 "-p",
1154 "--print",
1155 action="store_true",
1156 default=self.config["print"].get(),
1157 help="print lyrics to console",
1158 )
1159 cmd.parser.add_option(
1160 "-r",
1161 "--write-rest",
1162 dest="rest_directory",
1163 action="store",
1164 default=self.config["rest_directory"].get(Optional(str)),
1165 metavar="dir",
1166 help="write lyrics to given directory as ReST files",
1167 )
1168 cmd.parser.add_option(
1169 "-f",
1170 "--force",
1171 action="store_true",
1172 default=self.config["force"].get(),
1173 help="always re-download lyrics",
1174 )
1175 cmd.parser.add_option(
1176 "--keep-synced",
1177 action="store_true",
1178 default=self.config["keep_synced"].get(),
1179 help="skip items that already have synced lyrics",
1180 )
1181 cmd.parser.add_option(
1182 "--no-keep-synced",
1183 action="store_false",
1184 dest="keep_synced",
1185 default=self.config["keep_synced"].get(),
1186 help="do not skip items that already have synced lyrics",
1187 )
1188 cmd.parser.add_option(
1189 "-l",
1190 "--local",
1191 action="store_true",
1192 default=self.config["local"].get(),
1193 help="do not fetch missing lyrics",
1194 )
1195
1196 def func(lib: Library, opts: LyricsCLIOpts, args: list[str]) -> None:
1197 # The "write to files" option corresponds to the
1198 # import_write config value.
1199 self.config.set(vars(opts))
1200 items = list(lib.items(args))
1201 for item in items:
1202 self.add_item_lyrics(item, ui.should_write())
1203 if item.lyrics and opts.print:
1204 ui.print_(item.lyrics)
1205
1206 if opts.rest_directory and (
1207 items := [i for i in items if i.lyrics]
1208 ):
1209 RestFiles(Path(opts.rest_directory).expanduser()).write(items)
1210
1211 cmd.func = func
1212 return [cmd]
1213
1214 def imported(self, _, task: ImportTask) -> None:
1215 """Import hook for fetching lyrics automatically."""
1216 if query_str := self.config["auto_ignore"].get():
1217 query, _ = parse_query_string(query_str, Item)
1218 else:
1219 # matches nothing, so all items proceed normally
1220 query = FalseQuery()
1221
1222 for item in filterfalse(query.match, task.imported_items()):
1223 self.add_item_lyrics(item, False)
1224
1225 def find_lyrics(self, item: Item) -> Lyrics | None:
1226 """Return the first lyrics match from the configured source search."""
1227 album, length = item.album, round(item.length)
1228 matches = (
1229 self.get_lyrics(a, t, album, length)
1230 for a, titles in search_pairs(item)
1231 for t in titles
1232 )
1233
1234 return next(filter(None, matches), None)
1235
1236 def add_item_lyrics(self, item: Item, write: bool) -> None:
1237 """Fetch and store lyrics for a single item. If ``write``, then the
1238 lyrics will also be written to the file itself.
1239 """
1240 if self.config["local"]:
1241 return
1242
1243 if not self.config["force"] and item.lyrics:
1244 self.info("🔵 Lyrics already present: {}", item)
1245 return
1246
1247 existing_lyrics = Lyrics.from_item(item)
1248 if self.config["keep_synced"] and existing_lyrics.synced:
1249 self.info("🔵 Keeping synced lyrics: {}", item)
1250 return
1251
1252 if new_lyrics := self.find_lyrics(item):
1253 self.info("🟢 Found lyrics: {}", item)
1254 if translator := self.translator:
1255 new_lyrics = translator.translate(new_lyrics, existing_lyrics)
1256
1257 synced_mode = self.config["synced"].get(bool)
1258 if synced_mode and existing_lyrics.synced and not new_lyrics.synced:
1259 self.info(
1260 "🔴 Not updating synced lyrics with non-synced ones: {}",
1261 item,
1262 )
1263 return
1264
1265 for key in (
1266 "backend",
1267 "url",
1268 "instrumental",
1269 "language",
1270 "translation_language",
1271 ):
1272 item_key = f"lyrics_{key}"
1273 if (value := getattr(new_lyrics, key)) is not None:
1274 item[item_key] = value
1275 elif item_key in item:
1276 del item[item_key]
1277
1278 # Keep the canonical LRC text (with timestamps) in both the
1279 # database and USLT so that Lyrics.from_item() can still detect
1280 # synced lyrics on the next run and so that players that parse
1281 # LRC timestamps in USLT continue to work. Pass SYLT data
1282 # separately so that players with native SYLT support also work.
1283 lyrics_text = new_lyrics.full_text
1284 sylt_data = new_lyrics.sylt if new_lyrics.synced else None
1285 else:
1286 self.info("🔴 Lyrics not found: {}", item)
1287 lyrics_text = self.config["fallback"].get()
1288 sylt_data = None
1289
1290 if lyrics_text not in {None, item.lyrics}:
1291 item.lyrics = lyrics_text
1292 item.store()
1293 if write:
1294 item.try_write(tags={"synced_lyrics": sylt_data})
1295
1296 def get_lyrics(self, artist: str, title: str, *args) -> Lyrics | None:
1297 """Get first found lyrics, trying each source in turn."""
1298 self.info("Fetching lyrics for {} - {}", artist, title)
1299 for backend in self.backends:
1300 with backend.handle_request():
1301 if lyrics_info := backend.fetch(artist, title, *args):
1302 return lyrics_info
1303
1304 return None