Skip to content

Instantly share code, notes, and snippets.

@b1naryth1ef
Created July 13, 2015 06:25
Show Gist options
  • Save b1naryth1ef/8bf187facf9991243a61 to your computer and use it in GitHub Desktop.
Save b1naryth1ef/8bf187facf9991243a61 to your computer and use it in GitHub Desktop.
Youtube to Spotify playlist creator
# -*- coding: utf-8 -*-
import sys, os
import spotify
import logging
import time
import requests
import pafy
import re
if not len(sys.argv) >= 3:
print "Usage: ./spotty <username> <password> <spotify_playlist_name> [playlist ids...]"
sys.exit(1)
username, password = sys.argv[1:3]
playlist_name = sys.argv[3]
playlists = sys.argv[4:]
s = spotify.Session()
s.login(username, password)
time.sleep(5)
s.process_events()
def get_songs(id):
data = pafy.get_playlist(id)
return map(lambda i: i['pafy'].title, data['items'])
# added 249 songs (848 vs 599)
def filter_song(obj):
# remove [blah] my song
obj = re.sub('\[(.*?)\]', '', obj)
obj = re.sub('【(.*?)】', '', obj)
obj = re.sub('\((.*?)\)', '', obj)
# remove ft.
if 'ft' in obj:
obj = obj.split('ft', 1)[0]
return obj
def create_playlist(name):
s.playlist_container.load()
return s.playlist_container.add_new_playlist(name)
playlist = create_playlist(playlist_name)
songs = reduce(lambda a, b: a + b, map(lambda i: get_songs(i), playlists))
raw_input("About to add %s songs to playlist %s" % (len(songs), playlist_name))
fail = 0
for song in songs:
song = filter_song(song)
obj = s.search(song).load()
if not obj.track_total:
print "failed to get %s" % song
fail += 1
continue
playlist.add_tracks(obj.tracks[0])
print "added %s songs (%s vs %s)" % (len(songs) - fail, len(songs), fail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment