I developed the script to convert the Spotify playlist to YouTube playlist. I am here to share how I done this.
yogeshwaran01 / spotify-playlist-to-youtube-playlist
From Spotify's Groove to YouTube's Show: Spot2Tube
Spot2Tube
Convert Spotify Playlist to YouTube Playlist
About
Python script to convert Spotify playlist to YouTube playlist.
Features
- Convert Spotify playlist to YouTube Playlist
- Sync YouTube Playliset with Spotify playlist Sync Multiple Playlists
Setup
Requirements
- Install Python (https://www.python.org/)
- Install all required package (After cloning the repo, inside the folder)
pip install -r requirements.txt
YouTube
- 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, Select application type as Desktop App and then click create.
- 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
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
- Create data class
Playlist
to access data easily
@dataclass
class Playlist:
name: str
description: str
tracks: list[str]
- 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))
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
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
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.
- Run this script
python main.py <playlist_id>
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)
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?Thank You,
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 returnsNone
. In YouTube search also, it never says no result found. Otherwise update this method toand
Yeah, got it. Thanks for the clarification. Cheers!
Nice !
I just have a problem, the process stopped after 100 items.
Why ?
Ok, I have found the solution : github.com/spotipy-dev/spotipy/blo...
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?