An Interest In:
Web News this Week
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
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.
Spotify Playlist to YouTube Playlist
A simple python script to convert Spotify playlist into YouTube playlist
Usage
- Create Google clould project and enable YouTube Data API and download the credentials file and rename it to
client_secret.json
- Create spotify app and export
CLIENT_ID
andCLIENT_SECRET
as environment variable
export CLIENT_ID="xxxxxxxxxxxxxxxxxx"export CLIENT_SECRET="xxxxxxxxxxxxxxxx"
To get more info check this
Install all requirements
pip install -r requirements.txt
- Run the Script
python main.py <playlist_id>
Contact Me
If you need more info or any support please feel free to contact me
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 dataclassimport spotipyfrom spotipy.oauth2 import SpotifyClientCredentials
- Create data class
Playlist
to access data easily
@dataclassclass 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 Searchfrom pytube.contrib.search import loggerfrom google_auth_oauthlib.flow import InstalledAppFlowfrom googleapiclient.discovery import buildlogger. 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 sysimport timefrom spotify_client import SpotifyClientfrom youtube_client import YouTubeClientspotify = 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
Original Link: https://dev.to/yogeshwaran01/from-spotify-to-youtube-how-i-built-a-python-script-to-convert-playlists-2h89
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To