Ejemplo n.º 1
0
 async def lyric(self, ctx, *, songes=None):
     f"""Under Construction. Useable but not 100% Operational!\nViews the lyric for a specific song\nUsage: {self.clean_prefix}lyrics <Song Name (If None/Blank, it gets the current song playing lyrics)>"""
     async with ctx.message.channel.typing():
         extract_lyrics = SongLyrics(
             'AIzaSyCd2mUKNe8eGbTvDfTgE8fdKEMvdt3vyYU', '3d527b3474c25fe39')
         try:
             if songes == None:
                 player = music.get_player(guild_id=ctx.guild.id)
                 song = player.now_playing()
                 if song.duration == 0.0:
                     embed = discord.Embed(
                         color=ctx.author.color,
                         title=f'🎵 Lyric - {song.name}',
                         description=
                         f'We cannot detect lyrics of a LIVE Video!')
                     embed.set_thumbnail(url=song.thumbnail)
                     await ctx.send(embed=embed)
                 else:
                     lyrics = extract_lyrics.get_lyrics(str(song.name))
                     embed = discord.Embed(
                         color=ctx.author.color,
                         title=f'Lyric - {song.name}',
                         description=f"{lyrics['lyrics']}")
                     embed.set_thumbnail(url=song.thumbnail)
                     await ctx.send(embed=embed)
             else:
                 lyrics = extract_lyrics.get_lyrics(str(songes))
                 embed = discord.Embed(color=ctx.author.color,
                                       title=f'Lyric - {lyrics["title"]}',
                                       description=f"{lyrics['lyrics']}")
                 await ctx.send(embed=embed)
         except lyrics_extractor.LyricScraperException:
             await ctx.send("No results found found. Sorry!")
             return
Ejemplo n.º 2
0
class TestSongLyrics(unittest.TestCase):
    extract_lyrics = None

    def setUp(self):
        self.extract_lyrics = SongLyrics(GCS_API_KEY, GCS_ENGINE_ID)

    def test_unavailable_lyrics(self):
        """
            Random unavailable song name passed.
            Expected custom exception.
        """

        self.assertRaises(LyricScraperException,
                          self.extract_lyrics.get_lyrics,
                          UNAVAILABLE_SONG_NAME)

    def test_incorrect_spelled_lyrics(self):
        """
            Misspelled song name passed.
            Expected autocorrection and successful data return.
        """

        data = self.extract_lyrics.get_lyrics(MISSPELLED_SONG_NAME)
        self.assertIn('title', data)
        self.assertIn('lyrics', data)

    def test_lyrics_success(self):
        """
            Correct song name passed.
            Expected successful data return.
        """

        data = self.extract_lyrics.get_lyrics(SONG_NAME)
        self.assertIn('title', data)
        self.assertIn('lyrics', data)
Ejemplo n.º 3
0
def update_lyrics():
    lyrics_extractor = SongLyrics(GCS_API_KEY, GCS_ENGINE_ID)

    lyrics_dir = Path(to_absolute_path(DIR_DATA_LYRICS))
    ensure_dirs_exist([lyrics_dir])

    tracks = pd.read_csv('data/tracks.csv')
    data = []
    for _, track in tracks.iterrows():
        if pd.isna(track.lyrics_path) or not os.path.isfile(track.lyrics_path):
            data = lyrics_extractor.get_lyrics(track[Column.TRACK_TITLE])
            if data and data['lyrics']:
                lyrics_filename = f'{track.id}.txt'
                with open(lyrics_dir / Path(lyrics_filename), "w") as lyrics_file:
                    print(data['lyrics'], file=lyrics_file)
                    track.lyrics_path = DIR_DATA_LYRICS + lyrics_filename
            else:
                tracks.lyrics_path = None
        else:
            print('Lyrics file already exists')

        data.append(track)

    tracks = pd.DataFrame(data=data, columns=tracks.columns)
    print(tracks)
Ejemplo n.º 4
0
def getlyrics(song):

    if (not song):
        popup_showinfo('Please fill the information')
        return

    e2.delete(0, END)
    extract_lyrics = SongLyrics("AIzaSyB_2KRVPtP7AxWwTxKC4C9UecXbQTMASr4",
                                "1bf00c72a4acb9c4a")

    song = song
    spotify = requests.get(BASE_URL,
                           params={
                               'q': song,
                               'limit': 1,
                               'type': 'track'
                           },
                           headers=headers)
    spotify_response = spotify.json()
    itunes = 'https://itunes.apple.com/search?term=' + song + '&limit=1'
    itunes_response = requests.get(itunes).json()
    try:
        artist_image = spotify_response['tracks']['items'][0]['album'][
            'images'][1]["url"]
    except:
        popup_showinfo('No info found')
        return

    c = 'https://itunes.apple.com/lookup?id=' + str(
        itunes_response['results'][0]["artistId"]) + '&entity=album'
    d = requests.get(c).json()

    links_array = []
    links_array.append(
        str(spotify_response['tracks']['items'][0]['album']['artists'][0]
            ["external_urls"]['spotify']))
    links_array.append(str(itunes_response['results'][0]["artistViewUrl"]))

    artist_name = itunes_response['results'][0]['artistName']
    a_sl = 'Top tracks on Spotify: ' + spotify_response['tracks']['items'][0][
        'album']['artists'][0]["external_urls"]['spotify']
    a_al = 'Top tracks on Apple Music: ' + itunes_response['results'][0][
        "artistViewUrl"]
    l = []
    for i in range(1, 5):
        l.append(d['results'][i]["collectionName"] + ' : ' +
                 d['results'][i]["collectionViewUrl"])
        links_array.append(d['results'][i]['collectionViewUrl'])

    arr = [artist_image, artist_name, a_sl, a_al, l]

    try:
        l = extract_lyrics.get_lyrics(song)
    except:
        popup_showinfo('No lyrics found')
        printlyrics(0, arr, links_array)
    else:

        printlyrics(1, arr, links_array, l['lyrics'])
Ejemplo n.º 5
0
    def getHymn(name: str) -> dict:
        start = 0
        end = 0
        hymnName = ""
        lyrics = ""

        # ==========================================================================================
        # ====================================== SQL LOOKUP ========================================
        # ==========================================================================================

        con = sqlite3.connect("Data/HymnDatabase.db")

        for row in con.execute(
                f"SELECT * FROM Hymn WHERE Replace(HymnName, ',', '') LIKE \"%{name.replace(',', '')}%\" \
                                                AND VERSION = 1 ORDER BY HymnName, Number"
        ):
            hymnName = row[0]
            start = row[2]
            end = row[3]

            lyrics += row[4] + ("\n\n" if start != end else "")

            # In case there're multiple matches
            if start == end:
                break

        con.close()

        if start != end:
            print(
                f"ERROR: Database consistency error, {start}/{end} lyrics found."
            )
        elif len(lyrics) > 0:
            print("  LYRICS SOURCE: SQL")
            return {"source": "SQL", "title": hymnName, "lyrics": lyrics}

        # ==========================================================================================
        # ====================================== WEB LOOKUP ========================================
        # ==========================================================================================

        # API Key and Engine ID of Google Custom Search JSON API
        # Refer to https://pypi.org/project/lyrics-extractor/ for more detail
        GCS_API_KEY = "AIzaSyA8jw1Ws2yXn7BDqj4yYYJmE1BAK_J53zA"
        GCS_ENGINE_ID = "501493627fe694701"

        extract_lyrics = SongLyrics(GCS_API_KEY, GCS_ENGINE_ID)

        data = {"source": "Web", "title": "Not Found", "lyrics": "Not Found"}

        try:
            data = extract_lyrics.get_lyrics(name)
            data["source"] = "Web"
        except:
            pass

        print("  LYRICS SOURCE: Web")

        return data
Ejemplo n.º 6
0
class LyricsFinder:
    __extract_lyrics = None

    def __init__(self):
        self.__extract_lyrics = SongLyrics()

    def find_lyrics(self, title: str, artist: str = ''):
        result = self.__extract_lyrics.get_lyrics(f'{title} {artist}'.strip())
        lyrics = result.get('lyrics')
        return lyrics
Ejemplo n.º 7
0
def get_lyrics(track):
    extract_lyrics = SongLyrics(getenv("GCS_API_KEY"), getenv("GCS_ENGINE_ID"))

    try:
        data = extract_lyrics.get_lyrics(track)

    except LyricScraperException:
        return None

    return data["lyrics"]
Ejemplo n.º 8
0
 def fetch_lyrics(self, labels):
     keys = open("keys.txt").readlines()
     api_key = keys[0]
     engine_id = keys[1]
     extract_lyrics = SongLyrics(api_key, engine_id)
     lyrics = []
     for song in labels:
         lyric = extract_lyrics.get_lyrics(song)['lyrics']
         lyric = re.sub("[\(\[].*?[\)\]]", "", lyrics)
         lyric = lyric.replace('\n', ' ').lower()
         lyric = lyric.translate(str.maketrans('', '', string.punctuation))
         lyrics.append(lyric)
     lyrics.append(lyric)
     return lyrics
Ejemplo n.º 9
0
def song_lyrics(song: str) -> dict:
    """
    Gets the lyrics of a song
    :param song: Name of the song
    :return: Dictionary
    """
    if song:
        extract_lyrics = SongLyrics(os.environ.get(
            "lyrics_token"), os.environ.get("GCS_ENGINE_ID")
        )

        lyrics = extract_lyrics.get_lyrics(" ".join(song)).get(
            "lyrics", "No lyrics was found")
        return {"output": lyrics}

    return {"output": "Also please send the name of the song"}
Ejemplo n.º 10
0
async def lyrics(ctx, lyr):
    extract_lyrics = SongLyrics("AIzaSyCsCDLwP1nuvU_jUGXNoSLP-UZgkIjqeaQ",
                                "db8bfd43f907ee403")
    temp = extract_lyrics.get_lyrics(str(lyr))
    res = temp['lyrics']
    await ctx.send(f"COFFEE TIME:  {res}")