DEV Community

Cover image for From Spotify to YouTube: How I Built a Python Script to Convert Playlists
YOGESHWARAN R
YOGESHWARAN R

Posted on • Edited on

From Spotify to YouTube: How I Built a Python Script to Convert Playlists

I developed the script to convert the Spotify playlist to YouTube playlist. I am here to share how I done this.

GitHub logo yogeshwaran01 / spotify-playlist-to-youtube-playlist

From Spotify's Groove to YouTube's Show: Spot2Tube

Spot2Tube

Convert Spotify Playlist to YouTube Playlist

image

GitHub stars GitHub forks GitHub license Code style GitHub Repo size

About

Python script to convert Spotify playlist to YouTube playlist.

Features

  1. Convert Spotify playlist to YouTube Playlist
  2. Sync YouTube Playliset with Spotify playlist Sync Multiple Playlists

Setup

Requirements

  1. Install Python (https://www.python.org/)
  2. Install all required package (After cloning the repo, inside the folder)
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

YouTube

  1. Go to the Google Cloud Console, sign in with your Google account, and create a new project.
  2. Once your project is created, select it from the project dropdown menu in the top navigation bar.
  3. Go to the Credentials page in the API & Services section of the left sidebar.
  4. Click on the "Create Credentials" button and select "OAuth client ID".
  5. After creating select edit button in the OAuth 2.0 Client IDs, Select application type as Desktop App and then click create.
  6. Click the download button to download the credentials in your project directory. Rename…




Setting up environment

Install the required python packages

pip install google-auth google-auth-oauthlib google-auth-httplib2 spotipy pytube
Enter fullscreen mode Exit fullscreen mode

Spotify part

  • Go to the Spotify Developer Dashboard and log in with your Spotify account.
  • Click on the "Create an App" button and fill out the necessary information, such as the name and description of your application.
  • Once you've created the app, you'll be taken to the app dashboard. Here, you'll find your client ID and client secret, which are used to authenticate your application with the Spotify API.
  • After getting your client ID and client secret.
  • Create a file spotify_client.py
  • Add required import statement
from dataclasses import dataclass

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
Enter fullscreen mode Exit fullscreen mode
  • Create data class Playlist to access data easily
@dataclass
class Playlist:
    name: str
    description: str
    tracks: list[str]
Enter fullscreen mode Exit fullscreen mode
  • Create class SpotipyClient
class SpotifyClient:

    def __init__(self) -> None:
        client_id = "<your_client_id>"
        client_secret = "<your_client_secret>"
        auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
        self.spotify = spotipy.Spotify(auth_manager=auth_manager)

    def get_playlist(self, id: str):
        playlist = self.spotify.playlist(id)
        queries = []
        tracks = playlist['tracks']['items']
        for track in tracks:
            track_name = track['track']['name']
            artists = ', '.join([artist['name'] for artist in track['track']['artists']])
            queries.append(f'{track_name} by {artists}')
        return(Playlist(playlist['name'], playlist['description'], queries))
Enter fullscreen mode Exit fullscreen mode

On class initialization, login into the Spotify using credentials and get_playlist method fetch the playlist name, description and track name for search query and return a Playlist.

YouTube part

  • Go to the Google Cloud Console, sign in with your Google account, and create a new project.
  • Once your project is created, select it from the project dropdown menu in the top navigation bar.
  • Go to the Credentials page in the API & Services section of the left sidebar.
  • Click on the "Create Credentials" button and select "OAuth client ID".
  • After creating select edit button in the OAuth 2.0 Client IDs, Under 'Authorized JavaScript origins' add this URI http://localhost:8080 and under "Authorized redirect URIs
  • " add this URI http://localhost:8080/ and then click save.
  • Click the download button to download the credentials in your project directory. Rename the file to client_secret.json
  • Go to the OAuth consent screen in the API & Services section of the left sidebar. Under test user add your Gmail id.
  • Create file youtube_client.py
  • Add import statements
from pytube import Search
from pytube.contrib.search import logger

from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

logger. Disabled = True
Enter fullscreen mode Exit fullscreen mode

The logger of pytube is disabled to avoid unnecessary warings.

  • Create class YouTubeClient
class YouTubeClient:
    def __init__(self) -> None:
        flow = InstalledAppFlow.from_client_secrets_file(
            "client_secret.json",
            scopes=["https://www.googleapis.com/auth/youtube.force-ssl"],
        )

        creds = flow.run_local_server()

        self.youtube = build("youtube", "v3", credentials=creds)

    def create_playlist(self, name: str, description: str):
        playlist = (
            self.youtube.playlists()
            .insert(
                part="snippet,status",
                body={
                    "snippet": {
                        "title": name,
                        "description": description,
                        "defaultLanguage": "en",
                    },
                    "status": {"privacyStatus": "public"},
                },
            )
            .execute()
        )

        return playlist

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

    def search_video(self, query: str):

        return Search(query).results[0].video_id
Enter fullscreen mode Exit fullscreen mode

On class initialization, login into the YouTube using OAuth. Method create_playlist just create playlist with given name and description and add_song_playlist method add video to the given playlist.

Driving Code

  • Finally to drive a code, create new file, main.py
import sys
import time
from spotify_client import SpotifyClient
from youtube_client import YouTubeClient

spotify = SpotifyClient()
youtube = YouTubeClient()

spotify_playlist_id = sys.argv[1]

spotify_playlist = spotify.get_playlist(spotify_playlist_id)

youtube_playlist_id = youtube.create_playlist(spotify_playlist.name, spotify_playlist.description)['id']


for track in spotify_playlist.tracks:
    print(f"Searching for {track}")
    id = youtube.search_video(track)
    youtube.add_song_playlist(youtube_playlist_id, id)
    print("Added...")
    time.sleep(1)

print("Done πŸ‘")
print(f"https://www.youtube.com/playlist?list={youtube_playlist_id}")

You get playlist id from the playlist URL of spotify. In this script, the playlist id get as command line args.

Enter fullscreen mode Exit fullscreen mode
  • Run this script
python main.py <playlist_id>
Enter fullscreen mode Exit fullscreen mode

This will open a browser window to login into the google account. Just login into it. After execution of script it will print the playlist link.

Thank you

Top comments (6)

Collapse
 
arjunace profile image
Arjun Mudhaliyar

Great work. Just wanted to know what if youtube does not have a particular song that is present in your spotify playlist?
id = youtube.search_video(track) # what if this returns NONE?

Collapse
 
yogeshwaran01 profile image
YOGESHWARAN R • Edited

Thank You,

def search_video(self, query: str):

    return Search(query).results[0].video_id
Enter fullscreen mode Exit fullscreen mode

This method return the result from pytube.Search. It works based on web scraping. It search for song by track name and by artist. It never returns None. In YouTube search also, it never says no result found. Otherwise update this method to

def search_video(self, query: str):
    try:
        return Search(query).results[0].video_id
    except IndexError:
        return None
Enter fullscreen mode Exit fullscreen mode

and

for track in spotify_playlist.tracks:
    print(f"Searching for {track}")
    id = youtube.search_video(track)
    if id:
        youtube.add_song_playlist(youtube_playlist_id, id)
        print("Added...")
        time.sleep(1)
    else:
        print(f"No result found for {track}")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
arjunace profile image
Arjun Mudhaliyar

Yeah, got it. Thanks for the clarification. Cheers!

Collapse
 
edblv profile image
edblv

Nice !
I just have a problem, the process stopped after 100 items.
Why ?

Collapse
 
edblv profile image
edblv

Ok, I have found the solution : github.com/spotipy-dev/spotipy/blo...

Collapse
 
davidhomer profile image
Jason David

Nice submission mate. Want to know if its possible to only some track from a spotify playlists to youtube playlists. Is that possible with your script?