A Python script that search and add lyrics to offline songs
Tags: python, tutorial, beginners, programming
Published: 2022-07-05 08:51:44

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

We use [spotifydl](https://github.com/BharatKalluri/spotifydl) to download songs but it does not add lyrics to it. So we write a script to add lyrics to that songs.

## Requirements
```txt
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
```
## 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.

```python
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
```
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

```python
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
```

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

Last function to set the lyric to song

```python
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")
```
This function use `music_tag` package to edit the metadata of the song.

And the full script with main function, 
```python
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)

```
Save the file as `script.py`

## Running the script

Download any song using [spotifydl](https://github.com/BharatKalluri/spotifydl) which must contain title of track. Open terminal window and run

```bash
python script.py <path_to_song>
```
It will search and add lyric to the song
{% embed https://github.com/yogeshwaran01/lyricy %}

Thank you for the reading :)