/
/
/
1"""Helpers for the Genius Lyrics provider."""
2
3import re
4from typing import TYPE_CHECKING
5
6if TYPE_CHECKING:
7 from lyricsgenius.types import Song
8
9
10def clean_song_title(song_title: str) -> str:
11 """Clean song title string by removing metadata that may appear."""
12 # Keywords to look for in parentheses, brackets, or after a hyphen
13 keywords = (
14 r"(remaster(?:ed)?|anniversary|instrumental|live|edit(?:ion)?|"
15 r"single(s)?|stereo|album|radio|version|feat(?:uring)?|mix|bonus)"
16 )
17
18 # Regex pattern to match metadata within parentheses or brackets
19 paren_bracket_pattern = rf"[\(\[][^\)\]]*\b({keywords})\b[^\)\]]*[\)\]]"
20 cleaned_title = re.sub(paren_bracket_pattern, "", song_title, flags=re.IGNORECASE)
21
22 # Regex pattern to match a hyphen followed by metadata (keywords or a year)
23 hyphen_pattern = rf"(\s*-\s*(\d{{4}}|{keywords}).*)$"
24 cleaned_title = re.sub(hyphen_pattern, "", cleaned_title, flags=re.IGNORECASE)
25
26 # Remove any dangling hyphens or extra spaces
27 cleaned_title = re.sub(r"\s*-\s*$", "", cleaned_title).strip()
28
29 # Remove any leftover unmatched parentheses or brackets
30 return re.sub(r"\s[\(\[\{\]\)\}\s]+$", "", cleaned_title).strip()
31
32
33def cleanup_lyrics(song: Song) -> str:
34 """Clean lyrics string hackishly remove erroneous text that may appear."""
35 # Pattern1: match digits at beginning followed by "Contributors" and text followed by "Lyrics"
36 pattern1 = r"^(\d+) Contributor(.*?) Lyrics"
37 lyrics = re.sub(pattern1, "", song.lyrics, flags=re.DOTALL)
38
39 # Pattern2: match ending with "Embed"
40 lyrics = lyrics.rstrip("Embed")
41
42 # Pattern3: match ending with Pyong Count
43 lyrics = lyrics.rstrip(str(song.pyongs_count))
44
45 # Pattern4: match "See [artist] LiveGet tickets as low as $[price]"
46 pattern4 = rf"See {song.artist} LiveGet tickets as low as \$\d+"
47 lyrics = re.sub(pattern4, "", lyrics)
48
49 # Pattern5: match "You might also like" not followed by whitespace
50 pattern5 = r"You might also like(?!\s)"
51 return re.sub(pattern5, "", lyrics)
52