Top 100 instrumentals

This blog post is for everyone who needs background music and enjoys pop. After years of not listening to the radio or having any contact with mainstream pop music, I suddenly found myself interested in it again. To catch up on what I missed, I started listening to the yearly charts from Germany over the past few years. However, I feel distracted from maker projects when listening to music with lyrics. To solve this problem, I had ChatGPT generate a Python script, which I then tweaked, to create YouTube playlists from a text listing. Here’s how you can do the same.

Step-by-Step Guide to Creating Your Instrumental Pop Playlist

1. Setting Up Your Google Developer Account

To use the YouTube API, you need a Google Developer account. Follow these steps to set it up:

  1. Go to the Google Cloud Console and sign in with your Google account.
  2. Create a new project: Click on the project drop-down menu at the top of the page, then select “New Project.” Give your project a name and click “Create.”
  3. Enable the YouTube Data API v3: In the API library, search for “YouTube Data API v3” and click on it. Then, click “Enable.”
  4. Create credentials: Go to the “Credentials” tab on the sidebar, click “Create Credentials,” and select “OAuth client ID.” You’ll need to configure the OAuth consent screen first if you haven’t already. Choose “Desktop app” and click “Create.”
  5. Download your credentials: Click the download icon next to your new credentials to get a JSON file. Save this file as config.json.

2. Installing the Required Python Library

Ensure you have Python installed. Then, install the necessary library using pip:

pip install google-auth-oauthlib google-api-python-client

3. Preparing Your Input File

The input text file has to be passed as a command-line parameter and needs to have one artist and song title per row. To get the data, copy it manually from a website, such as Offizielle Deutsche Charts, and let ChatGPT format it.

You can use the following prompt to do that:

This is a list of the german top 100 charts of 2022: 
1 Udo Lindenberg & Apache 207 Komet Warner
2 Miley Cyrus Flowers Columbia
[...]

please remove the attached names of record labels and format in the following format:

Udo Lindenberg & Apache - 207 Komet
Miley Cyrus - Flowers 

4. Running the Script

Here is the Python script you’ll be using (Download):

import os
import argparse
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

# Set up YouTube API
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def youtube_authenticate():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "config.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes
    )
    credentials = flow.run_local_server(port=0)
    return googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials
    )

def search_video(youtube, query):
    request = youtube.search().list(
        part="snippet", maxResults=1, q=query + " instrumental"
    )
    response = request.execute()
    return response["items"][0]["id"]["videoId"] if response["items"] else None

def create_playlist(youtube, title, description):
    request = youtube.playlists().insert(
        part="snippet,status",
        body={
            "snippet": {
                "title": title,
                "description": description,
                "tags": ["instrumental", "music", "playlist"],
                "defaultLanguage": "en",
            },
            "status": {"privacyStatus": "public"},
        },
    )
    response = request.execute()
    return response["id"]

def add_video_to_playlist(youtube, playlist_id, video_id):
    request = youtube.playlistItems().insert(
        part="snippet",
        body={
            "snippet": {
                "playlistId": playlist_id,
                "resourceId": {"kind": "youtube#video", "videoId": video_id},
            }
        },
    )
    request.execute()

def load_songs_from_file(songs_file):
    if not os.path.exists(songs_file):
        raise FileNotFoundError(f"File {songs_file} does not exist.")
    with open(songs_file, "r") as file:
        songs = [line.strip() for line in file if line.strip()]
    return songs

def main():
    # Set up argument parser
    parser = argparse.ArgumentParser(
        description="Create a YouTube playlist from a list of songs."
    )
    parser.add_argument("songs_file", type=str, help="Path to the songs .txt file")
    args = parser.parse_args()

    youtube = youtube_authenticate()

    # Load songs from the file
    try:
        songs = load_songs_from_file(args.songs_file)
    except FileNotFoundError as e:
        print(e)
        return

    # Extract the filename without extension
    filename = os.path.splitext(os.path.basename(args.songs_file))[0]

    # Create a new playlist
    playlist_id = create_playlist(
        youtube,
        f"{filename} Instrumentals",
        f"Instrumental versions of the {filename}",
    )

    # Search for each song and add the instrumental version to the playlist
    for song in songs:
        video_id = search_video(youtube, song)
        if video_id:
            add_video_to_playlist(youtube, playlist_id, video_id)
            print(f"Added {song} instrumental to the playlist")
        else:
            print(f"Instrumental version of {song} not found")

if __name__ == "__main__":
    main()

5. Handling Daily Quotas and Combining Playlists

After about 40 to 50 songs, the script might stop because the daily quota for the Google API is exhausted. You can continue the process over several days to complete your playlist.

Combining YouTube Playlists

Once you have created multiple playlists, you can combine them into one using the YouTube interface:

  1. Go to your YouTube channel and open “YouTube Studio.”
  2. Select “Playlists” from the sidebar.
  3. Open one of your playlists and click on the three-dot menu.
  4. Select “Add all to” and choose the playlist you want to combine it with.

Example Playlist and Script

Here are the YouTube playlists I created using this script:

Feel free to use and modify the script as needed to create your own instrumental pop playlists. Happy listening!