From Spotify to YouTube: How I Built a Python Script to Convert Playlists
Tags: python, beginners, automation
Published: 2023-04-22 09:29:47

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

{% embed https://github.com/yogeshwaran01/spotify-playlist-to-youtube-playlist %}

## Setting up environment

Install the required python packages

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

```python
from dataclasses import dataclass

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
```
- Create data class `Playlist` to access data easily

```python
@dataclass
class Playlist:
    name: str
    description: str
    tracks: list[str]
```
- Create class `SpotipyClient`

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

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

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

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