5 Best Ways to Create a GUI to Extract Lyrics from a Song Using Python

πŸ’‘ Problem Formulation: Music lovers often like to follow along with the lyrics of their favorite songs. But pulling lyrics from a song isn’t always straightforward. This article provides solutions for creating a graphical user interface (GUI) in Python to scrape lyrics from songs. An input example could be the song title and artist name, and the desired output is the corresponding song lyrics displayed on the GUI.

Method 1: Utilizing Tkinter and Genius API

Creating a GUI in Python for lyric extraction can be done using Tkinter, the standard Python interface to the Tk GUI toolkit, and the Genius API, which holds an extensive collection of song lyrics. With the Genius API, you can search for songs by artist and title, then retrieve the lyrics.

Here’s an example:

import tkinter as tk
from lyricsgenius import Genius

def get_lyrics():
    genius = Genius('your_access_token')
    song = genius.search_song(song_title.get(), artist_name.get())
    lyrics.insert('1.0', song.lyrics)

root = tk.Tk()
root.title('Lyrics Finder')

song_title = tk.Entry(root)
song_title.pack()

artist_name = tk.Entry(root)
artist_name.pack()

search_button = tk.Button(root, text='Get Lyrics', command=get_lyrics)
search_button.pack()

lyrics = tk.Text(root, height=20, width=60)
lyrics.pack()

root.mainloop()

Output: A GUI window with entry fields for song title and artist, and a display area for the lyrics after pressing ‘Get Lyrics’.

This snippet creates a simple GUI where the user can enter the song title and artist name. After pressing the ‘Get Lyrics’ button, it uses the Genius API to fetch the lyrics of the indicated song and displays them in the text area.

Method 2: Using PyQt5 and Musixmatch API

PyQt5 provides a professional level of completeness for creating GUIs in Python. Together with the Musixmatch API, which allows you to retrieve lyrics based on track or artist data, you can craft a more feature-rich application.

Here’s an example:

from PyQt5 import QtWidgets
from musixmatch import Musixmatch

class LyricApp(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QtWidgets.QVBoxLayout()

        self.song_title = QtWidgets.QLineEdit(self)
        self.artist_name = QtWidgets.QLineEdit(self)
        self.lyrics_text = QtWidgets.QTextBrowser(self)
        self.search_button = QtWidgets.QPushButton('Get Lyrics', self)
        self.search_button.clicked.connect(self.show_lyrics)
        
        layout.addWidget(self.song_title)
        layout.addWidget(self.artist_name)
        layout.addWidget(self.search_button)
        layout.addWidget(self.lyrics_text)

        self.setLayout(layout)
        self.setWindowTitle('Lyrics Finder')

    def show_lyrics(self):
        musixmatch = Musixmatch('your_api_key')
        song = musixmatch.matcher_lyrics_get(self.song_title.text(), self.artist_name.text())
        self.lyrics_text.setText(song['message']['body']['lyrics']['lyrics_body'])

app = QtWidgets.QApplication([])
ex = LyricApp()
ex.show()
app.exec_()

Output: A PyQt5 window with input fields for the song title and artist name, and a display area for the lyrics after the search button is clicked.

This code initializes a PyQt5 application and creates a simple yet visually appealing GUI. When the user inputs the song and artist names and clicks the ‘Get Lyrics’ button, it calls the Musixmatch API to display the lyrics.

Method 3: Building with Kivy and Lyrics.ovh API

Kivy is an open-source Python library for developing multitouch applications. It is cross-platform (Linux/Windows/Mac) and works on mobile devices as well. The Lyrics.ovh API is a simple service that retrieves lyrics for a provided song title and artist name, perfect for inclusion in Kivy-based GUIs.

Here’s an example:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.network.urlrequest import UrlRequest
import json

class LyricsGUI(BoxLayout):
    def search_lyrics(self, artist, title):
        url = f"https://api.lyrics.ovh/v1/{artist}/{title}"
        UrlRequest(url, on_success=self.display_lyrics)

    def display_lyrics(self, request, result):
        self.ids.lyrics.text = result['lyrics']

class LyricsApp(App):
    def build(self):
        return LyricsGUI()

if __name__ == '__main__':
    LyricsApp().run()

Output: A mobile-friendly GUI where upon entering the song title and artist name, the lyrics are displayed after initiating a search.

This Kivy based application creates a touchscreen-friendly GUI. It uses UrlRequest to fetch lyrics from the Lyrics.ovh API asynchronously, which means the application remains responsive while loading the lyrics.

Method 4: Implementing with wxPython and AZLyrics API

wxPython is another GUI toolkit for the Python programming language. Using wxPython in tandem with a scraper for the AZLyrics website can yield lyrics for a wide range of songs without the need for an official API.

Here’s an example:

import wx
import requests
from bs4 import BeautifulSoup

def get_lyrics(artist, title):
    search_url = f"https://search.azlyrics.com/search.php?q={artist} {title}"
    search_page = requests.get(search_url)
    soup = BeautifulSoup(search_page.text, 'html.parser')
    lyric_url = soup.find('a', target='_blank')['href']
    lyrics_page = requests.get(lyric_url)
    lyrics_soup = BeautifulSoup(lyrics_page.text, 'html.parser')
    lyrics = lyrics_soup.find('div', class_=False, id=False).get_text()
    return lyrics

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Lyrics Finder")
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.artist = wx.TextCtrl(panel)
        self.title = wx.TextCtrl(panel)
        self.lyrics = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        self.search_button = wx.Button(panel, label="Search")
        self.search_button.Bind(wx.EVT_BUTTON, self.OnSearch)
        
        sizer.Add(self.artist, 0, wx.ALL, 5)
        sizer.Add(self.title, 0, wx.ALL, 5)
        sizer.Add(self.search_button, 0, wx.ALL, 5)
        sizer.Add(self.lyrics, 1, wx.EXPAND | wx.ALL, 5)

        panel.SetSizer(sizer)
        self.Show()
        
    def OnSearch(self, event):
        artist = self.artist.GetValue()
        title = self.title.GetValue()
        self.lyrics.SetValue(get_lyrics(artist, title))

app = wx.App(False)
frame = MyFrame()
app.MainLoop()

Output: A wxPython GUI with fields for song title and artist, a button to fetch lyrics, and a multiline text box to display the retrieved lyrics.

The example provided demonstrates how to create a wxPython application with functionalities for scraping lyrics from the AZLyrics website. Upon user input and button press, it fetches the lyrics and displays them in the interface.

Bonus One-Liner Method 5: Using PySimpleGUI with lyrics-extractor

PySimpleGUI is a wrapper for Tkinter and enables Python developers to create simple GUIs quickly. The lyrics-extractor library can be used to pull lyrics without dealing directly with APIs or HTML scraping.

Here’s an example:

import PySimpleGUI as sg
from lyrics_extractor import SongLyrics

def extract_lyrics():
    gcs_engine_id = "your_google_custom_search_engine_id"
    gcs_api_key = "your_google_api_key"
    extract_lyrics = SongLyrics(gcs_api_key, gcs_engine_id)
    lyrics, _ = extract_lyrics.get_lyrics(values['-SONG-'])
    window['-LYRICS-'].update(lyrics)

layout = [[sg.Text('Song Title:'), sg.InputText(key='-SONG-')],
          [sg.Button('Get Lyrics'), sg.Exit()],
          [sg.Multiline(key='-LYRICS-', size=(40, 15))]]

window = sg.Window('Lyrics Extractor', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'Get Lyrics':
        extract_lyrics()

window.close()

Output: A compact GUI to input a song and display lyrics in a multiline area after a button is clicked.

The code above creates a simple GUI window using PySimpleGUI. The user enters a song title, clicks the ‘Get Lyrics’ button, and the lyrics-extractor library provides the lyrics which are then shown in the GUI.

Summary/Discussion

  • Method 1: Tkinter and Genius API. Simple and well-documented, making it great for beginners. However, it requires an API key and has limited styling options.
  • Method 2: PyQt5 and Musixmatch API. Offers more advanced GUI features and styling. Requires more overhead and an API key. Better for professional-grade applications.
  • Method 3: Kivy and Lyrics.ovh API. Ideal for touch applications and cross-platform support. Not as widely used as other options, which could lead to a steeper learning curve.
  • Method 4: wxPython and AZLyrics. Good for native-looking apps and doesn’t rely on an official API, but scraping websites may break with site updates.
  • Bonus Method 5: PySimpleGUI and lyrics-extractor. Extremely easy to implement and doesn’t directly require API handling, but may be limited in extensibility and features.