DEV Community

YOGESHWARAN R
YOGESHWARAN R

Posted on

A Python script that search and add lyrics to offline songs

In this tutorial, let make a simple python script that search and add lyrics to the song.

We use spotifydl to download songs but it does not add lyrics to it. So we write a script to add lyrics to that songs.

Requirements

beautifulsoup4==4.11.1
certifi==2022.6.15
charset-normalizer==2.1.0
idna==3.3
music-tag==0.4.3
mutagen==1.45.1
requests==2.28.1
soupsieve==2.3.2.post1
urllib3==1.26.9
Enter fullscreen mode Exit fullscreen mode

Script

By Using this requirements, we have to write three functions to search, get and set the lyrics.

First Function to search lyrics, to search lyrics we have to use https://rclyricsband.com/?s= this site. It is the source of all lyrics. Send requests to this site using request and scrape it using BeautifulSoup4.

search_link = "https://rclyricsband.com/?s="

def search_lyrics(song_name: str, one=True):
    print(f"Searching for {song_name}")
    markup = requests.get(search_link + quote_plus(song_name)).text
    soup = BeautifulSoup(markup, "html.parser")
    outer_tags = soup.find_all("h2", {"class": "search-entry-title"})
    results = []
    for outer_tag in outer_tags:
        inner_tag = outer_tag.find("a")
        results.append({"title": inner_tag.get("title"), "link": inner_tag.get("href")})
    if len(results) == 0:
        return None
    if one:
        print(f"Found Best Match: {results[0]['title']}")
        return results[0]
    else:
        results
Enter fullscreen mode Exit fullscreen mode

This function search the lyrics and return the first result which contain title of the song and link to lyrics

Second function to get the lyrics using the link from the first function

def get_lyrics(link: str):
    print("Getting Lyrics ...")
    markup = requests.get(link).text
    soup = BeautifulSoup(markup, "html.parser")
    return soup.find("div", {"class": "su-box su-box-style-default"}).text
Enter fullscreen mode Exit fullscreen mode

This function send request to link and scrape the lyric using Beautifulsoup and return the lyrics.

Last function to set the lyric to song

def set_lyrics_to_song(song_path: str):
    f = music_tag.load_file(song_path)
    title = str(f["title"])
    search_results = search_lyrics(title)
    if search_results:
        lyrics = get_lyrics(search_results["link"])
        print("Setting Lyrics ...")
        f["lyrics"] = lyrics
        f.save()
        print("Done :)")
    else:
        print("No Lyrics Found")
Enter fullscreen mode Exit fullscreen mode

This function use music_tag package to edit the metadata of the song.

And the full script with main function,

import requests
from bs4 import BeautifulSoup
from urllib.parse import quote_plus
import music_tag

search_link = "https://rclyricsband.com/?s="


def search_lyrics(song_name: str, one=True):
    print(f"Searching for {song_name}")
    markup = requests.get(search_link + quote_plus(song_name)).text
    soup = BeautifulSoup(markup, "html.parser")
    outer_tags = soup.find_all("h2", {"class": "search-entry-title"})
    results = []
    for outer_tag in outer_tags:
        inner_tag = outer_tag.find("a")
        results.append({"title": inner_tag.get("title"), "link": inner_tag.get("href")})
    if len(results) == 0:
        return None
    if one:
        print(f"Found Best Match: {results[0]['title']}")
        return results[0]
    else:
        results


def get_lyrics(link: str):
    print("Getting Lyrics ...")
    markup = requests.get(link).text
    soup = BeautifulSoup(markup, "html.parser")
    return soup.find("div", {"class": "su-box su-box-style-default"}).text


def set_lyrics_to_song(song_path: str):
    f = music_tag.load_file(song_path)
    title = str(f["title"])
    search_results = search_lyrics(title)
    if search_results:
        lyrics = get_lyrics(search_results["link"])
        print("Setting Lyrics ...")
        f["lyrics"] = lyrics
        f.save()
        print("Done :)")
    else:
        print("No Lyrics Found")


if __name__ == "__main__":
    import sys

    path = sys.argv[1]
    set_lyrics_to_song(path)

Enter fullscreen mode Exit fullscreen mode

Save the file as script.py

Running the script

Download any song using spotifydl which must contain title of track. Open terminal window and run

python script.py <path_to_song>
Enter fullscreen mode Exit fullscreen mode

It will search and add lyric to the song

GitHub logo yogeshwaran01 / lyricy

A command line lyrics utility tool which search and add lyrics to your offline songs. 🎵

🎼 lyricy

A command line lyrics utility tool which search and add lyrics to your offline songs.

PyPi Downloads GitHub stars GitHub forks GitHub license Code style GitHub Repo size Upload lyricy to pypi Python package

Why lyricy ?

We can use spotDL/spotify-downloader to download our spotify playlist and songs along with album art and metadata. But it does not add the lyrics of the songs in song metadata. lyricy search for the lyrics of the song add to song metadata.

you can use Retro music player for android to listen the offline local songs with synced lyrics.

Features

  • Used as a Python package, Desktop application and mobile application (PWA)
  • Easy to add lyrics to your offline songs
  • Preview of lyrics
  • Synced lyrics with lrc time tags
  • Lyrics without lrc tags
  • Save lyrics as lrc file
  • Add your own lyrics or downloaded lyrics to songs

Usage

GUI

GUI is built with flet

demo





Thank you for the reading :)

Top comments (6)

Collapse
 
yogeshwaran01 profile image
YOGESHWARAN R

@moesalim88, I am added some more feature on it and developed a tool. check out this github.com/yogeshwaran01/lyricy. This may be helpfull.

Collapse
 
moesalim88 profile image
Moe Salim

Thanks for this. I tested it with one mp3 file - 'The Shacks - Crimson and Clover', the script says it found the lyrics, but it's a different song. Maybe adding more lyrics search engines to the script might help? Also not sure where it is saving the lyrics to exactly:

PS C:\Users\Mojojo\Desktop\Developer\lyricy-master> python lyricy.py ".\The Shacks - Crimson and Clover.mp3"
Searching for
Found Best Match: Ava Max – Into Your Arms (No Rap) Lyrics Download LRC x PDF File
Getting Lyrics ...
Setting Lyrics ...
Done :)

Collapse
 
yogeshwaran01 profile image
YOGESHWARAN R

It save to same mp3 itself. Lyrics added to song metadata.

Collapse
 
moesalim88 profile image
Moe Salim

OK I see, thanks. Unfortunately, it seems to pick the wrong lyrics for the song I selected.

Thread Thread
 
yogeshwaran01 profile image
YOGESHWARAN R

search_lyrics function return only first lyrics of list of lyrics scraped which has 5 to 6 lyrics. Chage the script accordingly to get all lyrics and select the lyrics manually and then added it to song.

Thread Thread
 
moesalim88 profile image
Moe Salim

That' beyond my Python capabilities at the moment. Maybe I shall make this a project when my skills have improved... like A LOT, lol. Thanks nonetheless :)